Game.cpp 26 KB

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