Game.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. #include "Game.h"
  2. #include "Zeit.h"
  3. #include "Player.h"
  4. #include "OverworldDimension.h"
  5. #include "AddChunkUpdate.h"
  6. #include "NoBlock.h"
  7. #include "AsynchronCall.h"
  8. #include "Entity.h"
  9. #include "AddEntityUpdate.h"
  10. using namespace Framework;
  11. GameClient::GameClient(Player* zPlayer, FCKlient* client)
  12. : ReferenceCounter(),
  13. zPlayer(zPlayer),
  14. client(client),
  15. viewDistance(DEFAULT_VIEW_DISTANCE),
  16. first(1),
  17. online(1),
  18. finished(0)
  19. {
  20. new AsynchronCall("Game Client", [this]()
  21. {
  22. while (online)
  23. {
  24. other.lock();
  25. if (updateQueue.hat(0))
  26. {
  27. WorldUpdate* update = updateQueue.get(0);
  28. updateQueue.remove(0);
  29. other.unlock();
  30. background.lock();
  31. this->client->zBackgroundWriter()->schreibe((char*)&Message::WORLD_UPDATE, 1);
  32. update->writeAndCheck(this->client->zBackgroundWriter());
  33. background.unlock();
  34. update->release();
  35. }
  36. else
  37. {
  38. other.unlock();
  39. updateSync.wait();
  40. }
  41. }
  42. finished = 1;
  43. });
  44. }
  45. GameClient::~GameClient()
  46. {
  47. online = 0;
  48. updateSync.notify();
  49. while (!finished)
  50. Sleep(100);
  51. client->release();
  52. }
  53. void GameClient::sendWorldUpdate(WorldUpdate* update)
  54. {
  55. bool add = 0;
  56. if (zPlayer->getCurrentDimensionId() == update->getAffectedDimension())
  57. {
  58. auto pos = (Vec3<int>)zPlayer->getPosition();
  59. int dist = update->distanceTo(pos.x, pos.y);
  60. if (dist < viewDistance * CHUNK_SIZE)
  61. {
  62. other.lock();
  63. int index = 0;
  64. for (auto update2 : updateQueue)
  65. {
  66. int dist2 = update2->distanceTo(pos.x, pos.y);
  67. if (dist2 > dist)
  68. break;
  69. index++;
  70. }
  71. if (update->getType() == AddChunkUpdateType::ID)
  72. ((AddChunkUpdate*)update)->zChunk()->addView(zPlayer);
  73. updateQueue.add(update, index);
  74. other.unlock();
  75. updateSync.notify();
  76. add = 1;
  77. }
  78. }
  79. if (!add)
  80. update->release();
  81. }
  82. void GameClient::reply()
  83. {
  84. other.lock();
  85. for (auto req : requests)
  86. Game::INSTANCE->api(req, this);
  87. requests.leeren();
  88. other.unlock();
  89. int x = (int)floor(zPlayer->getPosition().x);
  90. int y = (int)floor(zPlayer->getPosition().y);
  91. int d = zPlayer->getCurrentDimensionId();
  92. // send world to client
  93. if (first)
  94. {
  95. foreground.lock();
  96. int id = zPlayer->getId();
  97. client->zForegroundWriter()->schreibe((char*)&Message::POSITION_UPDATE, 1);
  98. client->zForegroundWriter()->schreibe((char*)&id, 4);
  99. foreground.unlock();
  100. first = 0;
  101. Dimension* dim = Game::INSTANCE->zDimension(d);
  102. if (dim)
  103. {
  104. for (int xP = x - CHUNK_SIZE * viewDistance; xP <= x + CHUNK_SIZE * viewDistance; xP += CHUNK_SIZE)
  105. {
  106. for (int yP = y - CHUNK_SIZE * viewDistance; yP <= y + CHUNK_SIZE * viewDistance; yP += CHUNK_SIZE)
  107. {
  108. Chunk* chunk = dim->zChunk(Game::INSTANCE->getChunkCenter(xP, yP));
  109. if (chunk)
  110. sendWorldUpdate(new AddChunkUpdate(dynamic_cast<Chunk*>(chunk->getThis())));
  111. }
  112. }
  113. }
  114. Game::INSTANCE->requestArea({ x - CHUNK_SIZE * viewDistance, y - CHUNK_SIZE * viewDistance, x + CHUNK_SIZE * viewDistance, y + CHUNK_SIZE * viewDistance, d });
  115. }
  116. else
  117. {
  118. Punkt lastMin = Game::INSTANCE->getChunkCenter((int)floor(lastPos.x) - CHUNK_SIZE * viewDistance, (int)floor(lastPos.y) - CHUNK_SIZE * viewDistance);
  119. Punkt curMin = Game::INSTANCE->getChunkCenter(x - CHUNK_SIZE * viewDistance, y - CHUNK_SIZE * viewDistance);
  120. Punkt lastMax = Game::INSTANCE->getChunkCenter((int)floor(lastPos.x) + CHUNK_SIZE * viewDistance, (int)floor(lastPos.y) + CHUNK_SIZE * viewDistance);
  121. Punkt curMax = Game::INSTANCE->getChunkCenter(x + CHUNK_SIZE * viewDistance, y + CHUNK_SIZE * viewDistance);
  122. Dimension* dim = Game::INSTANCE->zDimension(d);
  123. if (dim)
  124. {
  125. for (int xP = curMin.x; xP <= curMax.x; xP += CHUNK_SIZE)
  126. {
  127. for (int yP = curMin.y; yP <= curMax.y; yP += CHUNK_SIZE)
  128. {
  129. if (xP < lastMin.x || xP > lastMax.x || yP < lastMin.y || yP > lastMax.y)
  130. {
  131. Chunk* chunk = dim->zChunk(Game::INSTANCE->getChunkCenter(xP, yP));
  132. if (chunk)
  133. sendWorldUpdate(new AddChunkUpdate(dynamic_cast<Chunk*>(chunk->getThis())));
  134. else
  135. Game::INSTANCE->requestArea(Game::INSTANCE->getChunckArea(Game::INSTANCE->getChunkCenter(xP, yP)));
  136. }
  137. }
  138. }
  139. for (int xP = lastMin.x; xP <= lastMax.x; xP += CHUNK_SIZE)
  140. {
  141. for (int yP = lastMin.y; yP <= lastMax.y; yP += CHUNK_SIZE)
  142. {
  143. if (xP < curMin.x || xP > curMax.x || yP < curMin.y || yP > curMax.y)
  144. {
  145. Chunk* chunk = dim->zChunk(Game::INSTANCE->getChunkCenter(xP, yP));
  146. if (chunk)
  147. chunk->removeView(zPlayer);
  148. }
  149. }
  150. }
  151. }
  152. }
  153. lastPos = zPlayer->getPosition();
  154. }
  155. void GameClient::logout()
  156. {
  157. online = 0;
  158. }
  159. void GameClient::addMessage(StreamReader* reader)
  160. {
  161. short len = 0;
  162. reader->lese((char*)&len, 2);
  163. InMemoryBuffer* buffer = new InMemoryBuffer();
  164. char* tmp = new char[len];
  165. reader->lese(tmp, len);
  166. buffer->schreibe(tmp, len);
  167. delete[]tmp;
  168. other.lock();
  169. requests.add(buffer);
  170. other.unlock();
  171. }
  172. bool GameClient::isOnline() const
  173. {
  174. return online;
  175. }
  176. void GameClient::sendResponse(NetworkResponse* zResponse)
  177. {
  178. if (zResponse->isAreaAffected({ lastPos.x - (float)CHUNK_SIZE * (float)viewDistance, lastPos.y - (float)CHUNK_SIZE * (float)viewDistance, 0.f }, { lastPos.x + (float)CHUNK_SIZE * (float)viewDistance, lastPos.y + (float)CHUNK_SIZE * (float)viewDistance, (float)WORLD_HEIGHT }))
  179. {
  180. if (zResponse->isUseBackground())
  181. {
  182. background.unlock();
  183. client->zBackgroundWriter()->schreibe((char*)&Message::API_MESSAGE, 1);
  184. zResponse->writeTo(client->zBackgroundWriter());
  185. background.unlock();
  186. }
  187. else
  188. {
  189. foreground.unlock();
  190. client->zForegroundWriter()->schreibe((char*)&Message::API_MESSAGE, 1);
  191. zResponse->writeTo(client->zForegroundWriter());
  192. foreground.unlock();
  193. }
  194. }
  195. }
  196. Player* GameClient::zEntity() const
  197. {
  198. return zPlayer;
  199. }
  200. Game::Game(Framework::Text name, Framework::Text worldsDir)
  201. : Thread(),
  202. name(name),
  203. dimensions(new RCArray<Dimension>()),
  204. updates(new RCArray<WorldUpdate>()),
  205. clients(new RCArray<GameClient>()),
  206. ticker(new TickOrganizer()),
  207. path((const char*)(worldsDir + "/" + name)),
  208. stop(0),
  209. tickId(0),
  210. nextEntityId(0),
  211. generator(0),
  212. loader(0)
  213. {
  214. if (!DateiExistiert(worldsDir + "/" + name))
  215. DateiPfadErstellen(worldsDir + "/" + name + "/");
  216. Datei d;
  217. d.setDatei(path + "/eid");
  218. if (d.existiert())
  219. {
  220. d.open(Datei::Style::lesen);
  221. d.lese((char*)&nextEntityId, 4);
  222. d.close();
  223. }
  224. start();
  225. }
  226. Game::~Game()
  227. {
  228. dimensions->release();
  229. updates->release();
  230. clients->release();
  231. generator->release();
  232. loader->release();
  233. }
  234. void Game::initialize()
  235. {
  236. int seed = 0;
  237. int index = 0;
  238. for (char* n = name; *n; n++)
  239. seed += (int)pow((float)*n * 31, (float)++index);
  240. generator = new WorldGenerator(seed);
  241. loader = new WorldLoader();
  242. recipies.loadRecipies("data/recipies");
  243. }
  244. void Game::thread()
  245. {
  246. ZeitMesser m;
  247. while (!stop)
  248. {
  249. m.messungStart();
  250. ticker->nextTick();
  251. Array<int> removed;
  252. cs.lock();
  253. int index = 0;
  254. for (auto player : *clients)
  255. {
  256. if (!player->isOnline())
  257. {
  258. Datei pFile;
  259. pFile.setDatei(path + "/player/" + player->zEntity()->getName());
  260. if (pFile.open(Datei::Style::schreiben))
  261. PlayerEntityType::INSTANCE->saveEntity(player->zEntity(), &pFile);
  262. removed.add(index, 0);
  263. }
  264. index++;
  265. }
  266. for (auto i : removed)
  267. clients->remove(i);
  268. cs.unlock();
  269. for (auto dim : *dimensions)
  270. dim->tickEntities();
  271. cs.lock();
  272. while (updates->hat(0))
  273. {
  274. WorldUpdate* update = updates->z(0);
  275. for (auto client : *clients)
  276. client->sendWorldUpdate(dynamic_cast<WorldUpdate*>(update->getThis()));
  277. if (!zDimension(update->getAffectedDimension()))
  278. addDimension(new Dimension(update->getAffectedDimension()));
  279. update->onUpdate(zDimension(update->getAffectedDimension()));
  280. updates->remove(0);
  281. }
  282. cs.unlock();
  283. for (auto client : *clients)
  284. client->reply();
  285. cs.lock();
  286. for (auto dim : *dimensions)
  287. dim->removeOldChunks();
  288. cs.unlock();
  289. m.messungEnde();
  290. double sec = m.getSekunden();
  291. if (sec < 0.05)
  292. Sleep((int)((0.05 - sec) * 1000));
  293. else
  294. {
  295. std::cout << "WARNING: tick needed " << sec << " seconds. The game will run sower then normal.\n";
  296. }
  297. }
  298. save();
  299. }
  300. void Game::api(Framework::StreamReader* zRequest, GameClient* zOrigin)
  301. {
  302. char type;
  303. zRequest->lese(&type, 1);
  304. NetworkResponse response;
  305. switch (type)
  306. {
  307. case 1: // world
  308. {
  309. int dimensionId;
  310. zRequest->lese((char*)&dimensionId, 4);
  311. Dimension* dim = zDimension(dimensionId);
  312. if (!dim)
  313. {
  314. dim = new Dimension(dimensionId);
  315. addDimension(dim);
  316. }
  317. dim->api(zRequest, &response);
  318. break;
  319. }
  320. case 2: // player
  321. zOrigin->zEntity()->playerApi(zRequest, &response);
  322. break;
  323. case 3: // entity
  324. {
  325. int id;
  326. zRequest->lese((char*)&id, 4);
  327. for (Dimension* dim : *dimensions)
  328. {
  329. Entity* entity = dim->zEntity(id);
  330. if (entity)
  331. {
  332. entity->api(zRequest, &response);
  333. break;
  334. }
  335. }
  336. break;
  337. }
  338. default:
  339. std::cout << "received unknown api request in game with type " << (int)type << "\n";
  340. }
  341. if (!response.isEmpty())
  342. {
  343. if (response.isBroadcast())
  344. distributeResponse(&response);
  345. else
  346. zOrigin->sendResponse(&response);
  347. }
  348. }
  349. void Game::distributeResponse(NetworkResponse* zResponse)
  350. {
  351. for (auto client : *clients)
  352. client->sendResponse(zResponse);
  353. }
  354. bool Game::requestWorldUpdate(WorldUpdate* update)
  355. {
  356. cs.lock();
  357. for (WorldUpdate* u : *updates)
  358. {
  359. if (u->getMaxAffectedPoint().x >= update->getMinAffectedPoint().x && u->getMinAffectedPoint().x <= update->getMaxAffectedPoint().x &&
  360. u->getMaxAffectedPoint().y >= update->getMinAffectedPoint().y && u->getMinAffectedPoint().y <= update->getMaxAffectedPoint().y &&
  361. u->getMaxAffectedPoint().z >= update->getMinAffectedPoint().z && u->getMinAffectedPoint().z <= update->getMaxAffectedPoint().z && u->getType() == update->getType())
  362. {
  363. cs.unlock();
  364. update->release();
  365. return 0;
  366. }
  367. }
  368. updates->add(update);
  369. cs.unlock();
  370. return 1;
  371. }
  372. GameClient* Game::addPlayer(FCKlient* client, Framework::Text name)
  373. {
  374. cs.lock();
  375. Datei pFile;
  376. pFile.setDatei(path + "/player/" + name);
  377. Player* player;
  378. bool isNew = 0;
  379. if (!pFile.existiert() || !pFile.open(Datei::Style::lesen))
  380. {
  381. player = (Player*)PlayerEntityType::INSTANCE->createEntityAt(Vec3<float>(0.5, 0.5, 0), OverworldDimension::ID);
  382. player->setName(name);
  383. isNew = 1;
  384. }
  385. else
  386. {
  387. player = (Player*)PlayerEntityType::INSTANCE->loadEntity(&pFile);
  388. pFile.close();
  389. }
  390. GameClient* gameClient = new GameClient(player, client);
  391. clients->add(gameClient);
  392. requestArea(getChunckArea(getChunkCenter((int)player->getPosition().x, (int)player->getPosition().y)));
  393. while (!zDimension(player->getCurrentDimensionId()) || (isNew && !zDimension(player->getCurrentDimensionId())->zChunk(getChunkCenter((int)player->getPosition().x, (int)player->getPosition().y))))
  394. {
  395. cs.unlock();
  396. Sleep(1000);
  397. cs.lock();
  398. }
  399. if (isNew)
  400. {
  401. Either<Block*, int> b = AirBlockBlockType::ID;
  402. int h = WORLD_HEIGHT;
  403. while (((b.isA() && (!(Block*)b || ((Block*)b)->isPassable())) || (b.isB() && StaticRegistry<BlockType>::INSTANCE.zElement(b)->zDefault()->isPassable())) && h > 0)
  404. b = zBlockAt({ (int)player->getPosition().x, (int)player->getPosition().y, --h }, player->getCurrentDimensionId());
  405. player->setPosition({ player->getPosition().x, player->getPosition().y, (float)h + 1.f });
  406. }
  407. requestWorldUpdate(new AddEntityUpdate(player, player->getCurrentDimensionId()));
  408. cs.unlock();
  409. return dynamic_cast<GameClient*>(gameClient->getThis());
  410. }
  411. bool Game::isChunkLoaded(int x, int y, int dimension) const
  412. {
  413. Dimension* dim = zDimension(dimension);
  414. return (dim && dim->hasChunck(x, y));
  415. }
  416. bool Game::doesChunkExist(int x, int y, int dimension)
  417. {
  418. cs.lock();
  419. bool result = isChunkLoaded(x, y, dimension) || loader->existsChunk(x, y, dimension);
  420. if (!result)
  421. {
  422. for (WorldUpdate* update : *updates)
  423. {
  424. if (update->getType() == AddChunkUpdateType::ID)
  425. result |= ((AddChunkUpdate*)update)->zChunk()->getCenter() == Framework::Punkt(x, y);
  426. }
  427. }
  428. cs.unlock();
  429. return result;
  430. }
  431. Framework::Either<Block*, int> Game::zBlockAt(Framework::Vec3<int> location, int dimension) const
  432. {
  433. Dimension* dim = zDimension(dimension);
  434. if (dim)
  435. return dim->zBlock(location);
  436. return 0;
  437. }
  438. Block* Game::zRealBlockInstance(Framework::Vec3<int> location, int dimension)
  439. {
  440. Dimension* dim = zDimension(dimension);
  441. if (dim)
  442. return dim->zRealBlockInstance(location);
  443. return 0;
  444. }
  445. Dimension* Game::zDimension(int id) const
  446. {
  447. for (auto dim : *dimensions)
  448. {
  449. if (dim->getDimensionId() == id)
  450. return dim;
  451. }
  452. return 0;
  453. }
  454. Framework::Punkt Game::getChunkCenter(int x, int y)
  455. {
  456. return Punkt(((x < 0 ? x + 1 : x) / CHUNK_SIZE) * CHUNK_SIZE + (x < 0 ? -CHUNK_SIZE : CHUNK_SIZE) / 2, ((y < 0 ? y + 1 : y) / CHUNK_SIZE) * CHUNK_SIZE + (y < 0 ? -CHUNK_SIZE : CHUNK_SIZE) / 2);
  457. }
  458. Area Game::getChunckArea(Punkt center) const
  459. {
  460. return { center.x - CHUNK_SIZE / 2, center.y - CHUNK_SIZE / 2, center.x + CHUNK_SIZE / 2 - 1, center.y + CHUNK_SIZE / 2 - 1, 0 };
  461. }
  462. Framework::Text Game::getWorldDirectory() const
  463. {
  464. return path;
  465. }
  466. void Game::requestArea(Area area)
  467. {
  468. generator->requestGeneration(area);
  469. loader->requestLoading(area);
  470. }
  471. void Game::save() const
  472. {
  473. Datei d;
  474. d.setDatei(path + "/eid");
  475. d.open(Datei::Style::schreiben);
  476. d.schreibe((char*)&nextEntityId, 4);
  477. d.close();
  478. for (auto dim : *dimensions)
  479. dim->save(path);
  480. }
  481. void Game::requestStop()
  482. {
  483. stop = 1;
  484. warteAufThread(1000000);
  485. }
  486. void Game::addDimension(Dimension* d)
  487. {
  488. dimensions->add(d);
  489. }
  490. int Game::getNextEntityId()
  491. {
  492. cs.lock();
  493. int result = nextEntityId++;
  494. cs.unlock();
  495. return result;
  496. }
  497. WorldGenerator* Game::zGenerator() const
  498. {
  499. return generator;
  500. }
  501. Game* Game::INSTANCE = 0;
  502. void Game::initialize(Framework::Text name, Framework::Text worldsDir)
  503. {
  504. if (!Game::INSTANCE)
  505. {
  506. Game::INSTANCE = new Game(name, worldsDir);
  507. Game::INSTANCE->initialize();
  508. }
  509. }
  510. Entity* Game::zEntity(int id, int dimensionId) const
  511. {
  512. Dimension* d = zDimension(dimensionId);
  513. if (d)
  514. return d->zEntity(id);
  515. return 0;
  516. }
  517. Entity* Game::zNearestEntity(int dimensionId, Framework::Vec3<float> pos, std::function<bool(Entity*)> filter)
  518. {
  519. Dimension* d = zDimension(dimensionId);
  520. if (!d)
  521. return 0;
  522. return d->zNearestEntity(pos, filter);
  523. }