Game.cpp 26 KB

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