Game.cpp 25 KB

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