Game.cpp 20 KB

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