Game.cpp 25 KB

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