Game.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  1. #include "Game.h"
  2. #include "Zeit.h"
  3. #include "Player.h"
  4. #include "OverworldDimension.h"
  5. #include "NoBlock.h"
  6. #include "AsynchronCall.h"
  7. #include "Entity.h"
  8. #include "AddEntityUpdate.h"
  9. #include "EntityRemovedUpdate.h"
  10. #include "NetworkMessage.h"
  11. using namespace Framework;
  12. GameClient::GameClient(Player* zPlayer, FCKlient* client)
  13. : Thread(),
  14. zPlayer(zPlayer),
  15. client(client),
  16. viewDistance(DEFAULT_VIEW_DISTANCE),
  17. first(1),
  18. online(1),
  19. finished(0)
  20. {
  21. new AsynchronCall("Game Client Updates", [this]()
  22. {
  23. while (online)
  24. {
  25. other.lock();
  26. if (updateQueue.hat(0))
  27. {
  28. WorldUpdate* update = updateQueue.get(0);
  29. updateQueue.remove(0);
  30. other.unlock();
  31. background.lock();
  32. this->client->zBackgroundWriter()->schreibe((char*)&Message::WORLD_UPDATE, 1);
  33. update->writeAndCheck(this->client->zBackgroundWriter());
  34. background.unlock();
  35. update->release();
  36. }
  37. else
  38. {
  39. other.unlock();
  40. updateSync.wait();
  41. }
  42. }
  43. finished = 1;
  44. });
  45. start();
  46. }
  47. GameClient::~GameClient()
  48. {
  49. online = 0;
  50. updateSync.notify();
  51. emptyForegroundQueueSync.notifyAll();
  52. emptyBackgroundQueueSync.notifyAll();
  53. foregroundQueueSync.notify();
  54. backgroundQueueSync.notify();
  55. while (!finished)
  56. Sleep(100);
  57. client->release();
  58. }
  59. void GameClient::thread()
  60. {
  61. new AsynchronCall("Game Client Background", [this]()
  62. {
  63. while (online)
  64. {
  65. queueCs.lock();
  66. if (backgroundQueue.hat(0))
  67. {
  68. NetworkMessage* message = backgroundQueue.get(0);
  69. backgroundQueue.remove(0);
  70. queueCs.unlock();
  71. background.lock();
  72. message->writeTo(client->zBackgroundWriter());
  73. background.unlock();
  74. message->release();
  75. }
  76. else
  77. {
  78. queueCs.unlock();
  79. emptyBackgroundQueueSync.notifyAll();
  80. backgroundQueueSync.wait();
  81. }
  82. }
  83. finished = 1;
  84. });
  85. while (online)
  86. {
  87. queueCs.lock();
  88. if (foregroundQueue.hat(0))
  89. {
  90. NetworkMessage* message = foregroundQueue.get(0);
  91. foregroundQueue.remove(0);
  92. queueCs.unlock();
  93. foreground.lock();
  94. message->writeTo(client->zForegroundWriter());
  95. foreground.unlock();
  96. message->release();
  97. }
  98. else
  99. {
  100. queueCs.unlock();
  101. emptyForegroundQueueSync.notifyAll();
  102. foregroundQueueSync.wait();
  103. }
  104. }
  105. }
  106. void GameClient::sendWorldUpdate(WorldUpdate* update)
  107. {
  108. bool add = 0;
  109. if (zPlayer->getCurrentDimensionId() == update->getAffectedDimension())
  110. {
  111. auto pos = (Vec3<int>)zPlayer->getPosition();
  112. int dist = update->distanceTo(pos.x, pos.y);
  113. if (dist < viewDistance * CHUNK_SIZE)
  114. {
  115. other.lock();
  116. int index = 0;
  117. for (auto update2 : updateQueue)
  118. {
  119. int dist2 = update2->distanceTo(pos.x, pos.y);
  120. if (dist2 > dist)
  121. break;
  122. index++;
  123. }
  124. updateQueue.add(update, index);
  125. other.unlock();
  126. updateSync.notify();
  127. add = 1;
  128. }
  129. }
  130. if (!add)
  131. update->release();
  132. }
  133. void GameClient::reply()
  134. {
  135. other.lock();
  136. for (auto req : requests)
  137. Game::INSTANCE->api(req, this);
  138. requests.leeren();
  139. other.unlock();
  140. if (first)
  141. {
  142. foreground.lock();
  143. int id = zPlayer->getId();
  144. client->zForegroundWriter()->schreibe((char*)&Message::POSITION_UPDATE, 1);
  145. client->zForegroundWriter()->schreibe((char*)&id, 4);
  146. foreground.unlock();
  147. first = 0;
  148. }
  149. }
  150. void GameClient::logout()
  151. {
  152. online = 0;
  153. }
  154. void GameClient::addMessage(StreamReader* reader)
  155. {
  156. short len = 0;
  157. reader->lese((char*)&len, 2);
  158. InMemoryBuffer* buffer = new InMemoryBuffer();
  159. char* tmp = new char[len];
  160. reader->lese(tmp, len);
  161. buffer->schreibe(tmp, len);
  162. delete[]tmp;
  163. other.lock();
  164. requests.add(buffer);
  165. other.unlock();
  166. }
  167. bool GameClient::isOnline() const
  168. {
  169. return online;
  170. }
  171. void GameClient::sendResponse(NetworkMessage* response)
  172. {
  173. queueCs.lock();
  174. if (response->isUseBackground())
  175. {
  176. if (backgroundQueue.getEintragAnzahl() > 20)
  177. {
  178. queueCs.unlock();
  179. emptyBackgroundQueueSync.wait();
  180. queueCs.lock();
  181. }
  182. backgroundQueue.add(response);
  183. queueCs.unlock();
  184. backgroundQueueSync.notify();
  185. }
  186. else
  187. {
  188. if (foregroundQueue.getEintragAnzahl() > 100)
  189. {
  190. queueCs.unlock();
  191. std::cout << "WARNING: Game paused because nework connection to " << zPlayer->getName() << " is to slow.\n";
  192. ZeitMesser m;
  193. m.messungStart();
  194. emptyForegroundQueueSync.wait();
  195. m.messungEnde();
  196. std::cout << "WARNING: Game resumed after " << m.getSekunden() << " seconds.\n";
  197. queueCs.lock();
  198. }
  199. foregroundQueue.add(response);
  200. queueCs.unlock();
  201. foregroundQueueSync.notify();
  202. }
  203. }
  204. Player* GameClient::zEntity() const
  205. {
  206. return zPlayer;
  207. }
  208. void GameClient::sendTypes()
  209. {
  210. foreground.lock();
  211. int count = StaticRegistry<BlockType>::INSTANCE.getCount();
  212. client->zForegroundWriter()->schreibe((char*)&count, 4);
  213. for (int i = 0; i < count; i++)
  214. {
  215. BlockType* t = StaticRegistry<BlockType>::INSTANCE.zElement(i);
  216. int id = t->getId();
  217. client->zForegroundWriter()->schreibe((char*)&id, 4);
  218. bool inst = t->doesNeedClientInstance();
  219. client->zForegroundWriter()->schreibe((char*)&inst, 1);
  220. int maxHp = t->getInitialMaxHP();
  221. client->zForegroundWriter()->schreibe((char*)&maxHp, 4);
  222. t->getModel().writeTo(client->zForegroundWriter());
  223. }
  224. count = StaticRegistry<ItemType>::INSTANCE.getCount();
  225. client->zForegroundWriter()->schreibe((char*)&count, 4);
  226. for (int i = 0; i < count; i++)
  227. {
  228. ItemType* t = StaticRegistry<ItemType>::INSTANCE.zElement(i);
  229. int id = t->getId();
  230. client->zForegroundWriter()->schreibe((char*)&id, 4);
  231. t->getModel().writeTo(client->zForegroundWriter());
  232. }
  233. count = StaticRegistry<EntityType>::INSTANCE.getCount();
  234. client->zForegroundWriter()->schreibe((char*)&count, 4);
  235. for (int i = 0; i < count; i++)
  236. {
  237. EntityType* t = StaticRegistry<EntityType>::INSTANCE.zElement(i);
  238. int id = t->getId();
  239. client->zForegroundWriter()->schreibe((char*)&id, 4);
  240. t->getModel().writeTo(client->zForegroundWriter());
  241. }
  242. foreground.unlock();
  243. }
  244. Game::Game(Framework::Text name, Framework::Text worldsDir)
  245. : Thread(),
  246. name(name),
  247. dimensions(new RCArray<Dimension>()),
  248. updates(new RCArray<WorldUpdate>()),
  249. clients(new RCArray<GameClient>()),
  250. ticker(new TickOrganizer()),
  251. path((const char*)(worldsDir + "/" + name)),
  252. stop(0),
  253. tickId(0),
  254. nextEntityId(0),
  255. generator(0),
  256. loader(0),
  257. totalTickTime(0),
  258. tickCounter(0)
  259. {
  260. if (!DateiExistiert(worldsDir + "/" + name))
  261. DateiPfadErstellen(worldsDir + "/" + name + "/");
  262. Datei d;
  263. d.setDatei(path + "/eid");
  264. if (d.existiert())
  265. {
  266. d.open(Datei::Style::lesen);
  267. d.lese((char*)&nextEntityId, 4);
  268. d.close();
  269. }
  270. start();
  271. }
  272. Game::~Game()
  273. {
  274. dimensions->release();
  275. updates->release();
  276. clients->release();
  277. generator->release();
  278. loader->release();
  279. }
  280. void Game::initialize()
  281. {
  282. int seed = 0;
  283. int index = 0;
  284. for (char* n = name; *n; n++)
  285. seed += (int)pow((float)*n * 31, (float)++index);
  286. generator = new WorldGenerator(seed);
  287. loader = new WorldLoader();
  288. recipies.loadRecipies("data/recipies");
  289. }
  290. void Game::thread()
  291. {
  292. ZeitMesser waitForLock;
  293. ZeitMesser removeOldClients;
  294. ZeitMesser tickEntities;
  295. ZeitMesser worldUpdates;
  296. ZeitMesser clientReply;
  297. ZeitMesser removeOldChunks;
  298. ZeitMesser m;
  299. while (!stop)
  300. {
  301. m.messungStart();
  302. ticker->nextTick();
  303. Array<int> removed;
  304. double waitTotal = 0;
  305. waitForLock.messungStart();
  306. cs.lock();
  307. waitForLock.messungEnde();
  308. waitTotal += waitForLock.getSekunden();
  309. removeOldClients.messungStart();
  310. int index = 0;
  311. for (auto player : *clients)
  312. {
  313. if (!player->isOnline())
  314. {
  315. std::cout << "player " << player->zEntity()->getName() << " disconnected.\n";
  316. Datei pFile;
  317. pFile.setDatei(path + "/player/" + player->zEntity()->getName());
  318. pFile.erstellen();
  319. if (pFile.open(Datei::Style::schreiben))
  320. PlayerEntityType::INSTANCE->saveEntity(player->zEntity(), &pFile);
  321. pFile.close();
  322. removed.add(index, 0);
  323. Dimension* dim = zDimension(player->zEntity()->getCurrentDimensionId());
  324. dim->removeSubscriptions(player->zEntity());
  325. this->requestWorldUpdate(new EntityRemovedUpdate(player->zEntity()->getId(), player->zEntity()->getCurrentDimensionId(), player->zEntity()->getPosition()));
  326. }
  327. index++;
  328. }
  329. for (auto i : removed)
  330. clients->remove(i);
  331. removeOldClients.messungEnde();
  332. cs.unlock();
  333. tickEntities.messungStart();
  334. for (auto dim : *dimensions)
  335. dim->tickEntities();
  336. tickEntities.messungEnde();
  337. waitForLock.messungStart();
  338. cs.lock();
  339. waitForLock.messungEnde();
  340. waitTotal += waitForLock.getSekunden();
  341. worldUpdates.messungStart();
  342. while (updates->hat(0))
  343. {
  344. WorldUpdate* update = updates->z(0);
  345. for (auto client : *clients)
  346. client->sendWorldUpdate(dynamic_cast<WorldUpdate*>(update->getThis()));
  347. if (!zDimension(update->getAffectedDimension()))
  348. addDimension(new Dimension(update->getAffectedDimension()));
  349. update->onUpdate(zDimension(update->getAffectedDimension()));
  350. updates->remove(0);
  351. }
  352. worldUpdates.messungEnde();
  353. cs.unlock();
  354. clientReply.messungStart();
  355. for (auto client : *clients)
  356. client->reply();
  357. clientReply.messungEnde();
  358. waitForLock.messungStart();
  359. cs.lock();
  360. waitForLock.messungEnde();
  361. waitTotal += waitForLock.getSekunden();
  362. removeOldChunks.messungStart();
  363. for (auto dim : *dimensions)
  364. dim->removeOldChunks();
  365. removeOldChunks.messungEnde();
  366. cs.unlock();
  367. m.messungEnde();
  368. double sec = m.getSekunden();
  369. tickCounter++;
  370. totalTickTime += sec;
  371. if (tickCounter >= 1000)
  372. {
  373. std::cout << "Average Tick time: " << (totalTickTime / 1000) << "\n";
  374. if ((totalTickTime / 1000) * 20 > 1)
  375. {
  376. std::cout << "The game runns slower than normal.\n";
  377. }
  378. else
  379. {
  380. std::cout << "No performance issues detected.\n";
  381. }
  382. totalTickTime = 0;
  383. tickCounter = 0;
  384. }
  385. if (sec < 0.05)
  386. Sleep((int)((0.05 - sec) * 1000));
  387. else
  388. {
  389. std::cout << "WARNING: tick needed " << sec << " seconds. The game will run sower then normal.\n";
  390. std::cout << "waiting: " << waitTotal << "\nremoveOldClients: " << removeOldClients.getSekunden() << "\ntickEntities:" << tickEntities.getSekunden() << "\nworldUpdates: " << worldUpdates.getSekunden() << "\nclientReply: " << clientReply.getSekunden() << "\nremoveOldChunks:" << removeOldChunks.getSekunden() << "\n";
  391. }
  392. }
  393. save();
  394. }
  395. void Game::api(Framework::InMemoryBuffer* zRequest, GameClient* zOrigin)
  396. {
  397. char type;
  398. zRequest->lese(&type, 1);
  399. NetworkMessage* response = new NetworkMessage();
  400. switch (type)
  401. {
  402. case 1: // world
  403. {
  404. Dimension* dim = zDimension(zOrigin->zEntity()->getCurrentDimensionId());
  405. if (!dim)
  406. {
  407. dim = new Dimension(zOrigin->zEntity()->getCurrentDimensionId());
  408. addDimension(dim);
  409. }
  410. dim->api(zRequest, response, zOrigin->zEntity());
  411. break;
  412. }
  413. case 2: // player
  414. zOrigin->zEntity()->playerApi(zRequest, response);
  415. break;
  416. case 3: // entity
  417. {
  418. int id;
  419. zRequest->lese((char*)&id, 4);
  420. for (Dimension* dim : *dimensions)
  421. {
  422. Entity* entity = dim->zEntity(id);
  423. if (entity)
  424. {
  425. entity->api(zRequest, response);
  426. break;
  427. }
  428. }
  429. break;
  430. }
  431. case 4:
  432. { // inventory
  433. bool isEntity;
  434. zRequest->lese((char*)&isEntity, 1);
  435. Inventory* target;
  436. if (isEntity)
  437. {
  438. int id;
  439. zRequest->lese((char*)&id, 4);
  440. target = zEntity(id);
  441. }
  442. else
  443. {
  444. int dim;
  445. Vec3<int> pos;
  446. zRequest->lese((char*)&dim, 4);
  447. zRequest->lese((char*)&pos.x, 4);
  448. zRequest->lese((char*)&pos.y, 4);
  449. zRequest->lese((char*)&pos.z, 4);
  450. target = zBlockAt(pos, dim);
  451. }
  452. if (target)
  453. target->inventoryApi(zRequest, response, zOrigin->zEntity());
  454. break;
  455. }
  456. default:
  457. std::cout << "received unknown api request in game with type " << (int)type << "\n";
  458. }
  459. if (!response->isEmpty())
  460. {
  461. if (response->isBroadcast())
  462. broadcastMessage(response);
  463. else
  464. zOrigin->sendResponse(response);
  465. }
  466. else
  467. {
  468. response->release();
  469. }
  470. }
  471. void Game::updateLightning(int dimensionId, Vec3<int> location)
  472. {
  473. Dimension* zDim = zDimension(dimensionId);
  474. if (zDim)
  475. zDim->updateLightning(location);
  476. }
  477. void Game::updateLightningWithoutWait(int dimensionId, Vec3<int> location)
  478. {
  479. Dimension* zDim = zDimension(dimensionId);
  480. if (zDim)
  481. zDim->updateLightningWithoutWait(location);
  482. }
  483. void Game::broadcastMessage(NetworkMessage* response)
  484. {
  485. for (auto client : *clients)
  486. client->sendResponse(dynamic_cast<NetworkMessage*>(response->getThis()));
  487. }
  488. void Game::sendMessage(NetworkMessage* response, Entity* zTargetPlayer)
  489. {
  490. for (auto client : *clients)
  491. {
  492. if (client->zEntity()->getId() == zTargetPlayer->getId())
  493. {
  494. client->sendResponse(response);
  495. return;
  496. }
  497. }
  498. response->release();
  499. }
  500. bool Game::requestWorldUpdate(WorldUpdate* update)
  501. {
  502. cs.lock();
  503. for (WorldUpdate* u : *updates)
  504. {
  505. if (u->getMaxAffectedPoint().x >= update->getMinAffectedPoint().x && u->getMinAffectedPoint().x <= update->getMaxAffectedPoint().x &&
  506. u->getMaxAffectedPoint().y >= update->getMinAffectedPoint().y && u->getMinAffectedPoint().y <= update->getMaxAffectedPoint().y &&
  507. u->getMaxAffectedPoint().z >= update->getMinAffectedPoint().z && u->getMinAffectedPoint().z <= update->getMaxAffectedPoint().z && u->getType() == update->getType())
  508. {
  509. cs.unlock();
  510. update->release();
  511. return 0;
  512. }
  513. }
  514. updates->add(update);
  515. cs.unlock();
  516. return 1;
  517. }
  518. GameClient* Game::addPlayer(FCKlient* client, Framework::Text name)
  519. {
  520. cs.lock();
  521. Datei pFile;
  522. pFile.setDatei(path + "/player/" + name);
  523. std::cout << "player " << name.getText() << " connected.\n";
  524. Player* player;
  525. bool isNew = 0;
  526. if (!pFile.existiert() || !pFile.open(Datei::Style::lesen))
  527. {
  528. player = (Player*)PlayerEntityType::INSTANCE->createEntityAt(Vec3<float>(0.5, 0.5, 0), OverworldDimension::ID);
  529. player->setName(name);
  530. isNew = 1;
  531. }
  532. else
  533. {
  534. player = (Player*)PlayerEntityType::INSTANCE->loadEntity(&pFile);
  535. pFile.close();
  536. }
  537. GameClient* gameClient = new GameClient(player, client);
  538. gameClient->sendTypes();
  539. clients->add(gameClient);
  540. if (!zDimension(player->getCurrentDimensionId()))
  541. {
  542. this->addDimension(new Dimension(player->getCurrentDimensionId()));
  543. }
  544. // subscribe the new player as an observer of the new chunk
  545. Dimension* dim = zDimension(player->getCurrentDimensionId());
  546. InMemoryBuffer* buffer = new InMemoryBuffer();
  547. buffer->schreibe("\0", 1);
  548. Punkt center = getChunkCenter((int)player->getPosition().x, (int)player->getPosition().y);
  549. buffer->schreibe((char*)&center.x, 4);
  550. buffer->schreibe((char*)&center.y, 4);
  551. buffer->schreibe("\0", 1);
  552. dim->api(buffer, 0, player);
  553. buffer->release();
  554. while (isNew && !dim->zChunk(getChunkCenter((int)player->getPosition().x, (int)player->getPosition().y)))
  555. {
  556. cs.unlock();
  557. Sleep(1000);
  558. cs.lock();
  559. }
  560. if (isNew)
  561. {
  562. Either<Block*, int> b = AirBlockBlockType::ID;
  563. int h = WORLD_HEIGHT;
  564. while (((b.isA() && (!(Block*)b || ((Block*)b)->isPassable())) || (b.isB() && StaticRegistry<BlockType>::INSTANCE.zElement(b)->zDefault()->isPassable())) && h > 0)
  565. b = zBlockAt({ (int)player->getPosition().x, (int)player->getPosition().y, --h }, player->getCurrentDimensionId());
  566. player->setPosition({ player->getPosition().x, player->getPosition().y, (float)h + 1.f });
  567. }
  568. requestWorldUpdate(new AddEntityUpdate(player, player->getCurrentDimensionId()));
  569. cs.unlock();
  570. return dynamic_cast<GameClient*>(gameClient->getThis());
  571. }
  572. bool Game::isChunkLoaded(int x, int y, int dimension) const
  573. {
  574. Dimension* dim = zDimension(dimension);
  575. return (dim && dim->hasChunck(x, y));
  576. }
  577. bool Game::doesChunkExist(int x, int y, int dimension)
  578. {
  579. cs.lock();
  580. bool result = isChunkLoaded(x, y, dimension) || loader->existsChunk(x, y, dimension);
  581. cs.unlock();
  582. return result;
  583. }
  584. Framework::Either<Block*, int> Game::zBlockAt(Framework::Vec3<int> location, int dimension) const
  585. {
  586. Dimension* dim = zDimension(dimension);
  587. if (dim)
  588. return dim->zBlock(location);
  589. return 0;
  590. }
  591. Block* Game::zRealBlockInstance(Framework::Vec3<int> location, int dimension)
  592. {
  593. Dimension* dim = zDimension(dimension);
  594. if (dim)
  595. return dim->zRealBlockInstance(location);
  596. return 0;
  597. }
  598. Dimension* Game::zDimension(int id) const
  599. {
  600. for (auto dim : *dimensions)
  601. {
  602. if (dim->getDimensionId() == id)
  603. return dim;
  604. }
  605. return 0;
  606. }
  607. Framework::Punkt Game::getChunkCenter(int x, int y)
  608. {
  609. 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);
  610. }
  611. Area Game::getChunckArea(Punkt center) const
  612. {
  613. return { center.x - CHUNK_SIZE / 2, center.y - CHUNK_SIZE / 2, center.x + CHUNK_SIZE / 2 - 1, center.y + CHUNK_SIZE / 2 - 1, 0 };
  614. }
  615. Framework::Text Game::getWorldDirectory() const
  616. {
  617. return path;
  618. }
  619. void Game::requestArea(Area area)
  620. {
  621. generator->requestGeneration(area);
  622. loader->requestLoading(area);
  623. }
  624. void Game::save() const
  625. {
  626. Datei d;
  627. d.setDatei(path + "/eid");
  628. d.open(Datei::Style::schreiben);
  629. d.schreibe((char*)&nextEntityId, 4);
  630. d.close();
  631. for (auto dim : *dimensions)
  632. dim->save(path);
  633. }
  634. void Game::requestStop()
  635. {
  636. stop = 1;
  637. warteAufThread(1000000);
  638. }
  639. void Game::addDimension(Dimension* d)
  640. {
  641. dimensions->add(d);
  642. }
  643. int Game::getNextEntityId()
  644. {
  645. cs.lock();
  646. int result = nextEntityId++;
  647. cs.unlock();
  648. return result;
  649. }
  650. WorldGenerator* Game::zGenerator() const
  651. {
  652. return generator;
  653. }
  654. Game* Game::INSTANCE = 0;
  655. void Game::initialize(Framework::Text name, Framework::Text worldsDir)
  656. {
  657. if (!Game::INSTANCE)
  658. {
  659. Game::INSTANCE = new Game(name, worldsDir);
  660. Game::INSTANCE->initialize();
  661. }
  662. }
  663. Entity* Game::zEntity(int id, int dimensionId) const
  664. {
  665. Dimension* d = zDimension(dimensionId);
  666. if (d)
  667. return d->zEntity(id);
  668. return 0;
  669. }
  670. Entity* Game::zEntity(int id) const
  671. {
  672. for (Dimension* d : *dimensions)
  673. {
  674. Entity* e = d->zEntity(id);
  675. if (e)
  676. return e;
  677. }
  678. // for new players that are currently loading
  679. for (GameClient* client : *clients)
  680. {
  681. if (client->zEntity()->getId() == id)
  682. {
  683. return client->zEntity();
  684. }
  685. }
  686. return 0;
  687. }
  688. Entity* Game::zNearestEntity(int dimensionId, Framework::Vec3<float> pos, std::function<bool(Entity*)> filter)
  689. {
  690. Dimension* d = zDimension(dimensionId);
  691. if (!d)
  692. return 0;
  693. return d->zNearestEntity(pos, filter);
  694. }
  695. const RecipieLoader& Game::getRecipies() const
  696. {
  697. return recipies;
  698. }