Game.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002
  1. #include "Game.h"
  2. #include "AddEntityUpdate.h"
  3. #include "AsynchronCall.h"
  4. #include "Entity.h"
  5. #include "EntityRemovedUpdate.h"
  6. #include "ItemEntity.h"
  7. #include "NetworkMessage.h"
  8. #include "NoBlock.h"
  9. #include "OverworldDimension.h"
  10. #include "Player.h"
  11. #include "Zeit.h"
  12. using namespace Framework;
  13. GameClient::GameClient(Player* zPlayer, FCKlient* client)
  14. : Thread(),
  15. zPlayer(zPlayer),
  16. client(client),
  17. viewDistance(DEFAULT_VIEW_DISTANCE),
  18. first(1),
  19. online(1),
  20. finished(0),
  21. backgroundFinished(0),
  22. foregroundFinished(0)
  23. {
  24. new AsynchronCall("Game Client Updates", [this]() {
  25. while (online)
  26. {
  27. other.lock();
  28. if (updateQueue.hat(0))
  29. {
  30. WorldUpdate* update = updateQueue.get(0);
  31. updateQueue.remove(0);
  32. other.unlock();
  33. background.lock();
  34. this->client->zBackgroundWriter()->schreibe(
  35. (char*)&Message::WORLD_UPDATE, 1);
  36. update->writeAndCheck(this->client->zBackgroundWriter());
  37. background.unlock();
  38. update->release();
  39. }
  40. else
  41. {
  42. other.unlock();
  43. updateSync.wait();
  44. }
  45. }
  46. finished = 1;
  47. });
  48. start();
  49. }
  50. GameClient::~GameClient()
  51. {
  52. online = 0;
  53. updateSync.notify();
  54. emptyForegroundQueueSync.notifyAll();
  55. emptyBackgroundQueueSync.notifyAll();
  56. foregroundQueueSync.notify();
  57. backgroundQueueSync.notify();
  58. while (!finished || !foregroundFinished || !backgroundFinished)
  59. Sleep(100);
  60. client->release();
  61. }
  62. void GameClient::thread()
  63. {
  64. new AsynchronCall("Game Client Background", [this]() {
  65. while (online)
  66. {
  67. queueCs.lock();
  68. if (backgroundQueue.hat(0))
  69. {
  70. NetworkMessage* message = backgroundQueue.get(0);
  71. backgroundQueue.remove(0);
  72. queueCs.unlock();
  73. background.lock();
  74. message->writeTo(client->zBackgroundWriter());
  75. background.unlock();
  76. message->release();
  77. }
  78. else
  79. {
  80. queueCs.unlock();
  81. emptyBackgroundQueueSync.notifyAll();
  82. backgroundQueueSync.wait();
  83. }
  84. }
  85. backgroundFinished = 1;
  86. });
  87. while (online)
  88. {
  89. queueCs.lock();
  90. if (foregroundQueue.hat(0))
  91. {
  92. NetworkMessage* message = foregroundQueue.get(0);
  93. foregroundQueue.remove(0);
  94. queueCs.unlock();
  95. foreground.lock();
  96. message->writeTo(client->zForegroundWriter());
  97. foreground.unlock();
  98. message->release();
  99. }
  100. else
  101. {
  102. queueCs.unlock();
  103. emptyForegroundQueueSync.notifyAll();
  104. foregroundQueueSync.wait();
  105. }
  106. }
  107. foregroundFinished = 1;
  108. }
  109. void GameClient::sendWorldUpdate(WorldUpdate* update)
  110. {
  111. bool add = 0;
  112. if (zPlayer->getDimensionId() == update->getAffectedDimension())
  113. {
  114. auto pos = (Vec3<int>)zPlayer->getPosition();
  115. int dist = update->distanceTo(pos.x, pos.y);
  116. if (dist < viewDistance * CHUNK_SIZE)
  117. {
  118. other.lock();
  119. int index = 0;
  120. for (auto update2 : updateQueue)
  121. {
  122. int dist2 = update2->distanceTo(pos.x, pos.y);
  123. if (dist2 > dist) break;
  124. index++;
  125. }
  126. updateQueue.add(update, index);
  127. other.unlock();
  128. updateSync.notify();
  129. add = 1;
  130. }
  131. }
  132. if (!add) update->release();
  133. }
  134. void GameClient::reply()
  135. {
  136. other.lock();
  137. for (auto req : requests)
  138. Game::INSTANCE->api(req, this);
  139. requests.leeren();
  140. other.unlock();
  141. if (first)
  142. {
  143. foreground.lock();
  144. int id = zPlayer->getId();
  145. client->zForegroundWriter()->schreibe(
  146. (char*)&Message::POSITION_UPDATE, 1);
  147. client->zForegroundWriter()->schreibe((char*)&id, 4);
  148. id = zPlayer->getDimensionId();
  149. client->zForegroundWriter()->schreibe((char*)&id, 4);
  150. foreground.unlock();
  151. first = 0;
  152. }
  153. }
  154. void GameClient::logout()
  155. {
  156. online = 0;
  157. updateSync.notify();
  158. emptyForegroundQueueSync.notifyAll();
  159. emptyBackgroundQueueSync.notifyAll();
  160. foregroundQueueSync.notify();
  161. backgroundQueueSync.notify();
  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. while (foregroundQueue.getEintragAnzahl() > 0)
  205. {
  206. emptyForegroundQueueSync.wait(100);
  207. }
  208. m.messungEnde();
  209. std::cout << "WARNING: Game resumed after " << m.getSekunden()
  210. << " seconds.\n";
  211. queueCs.lock();
  212. }
  213. foregroundQueue.add(response);
  214. queueCs.unlock();
  215. foregroundQueueSync.notify();
  216. }
  217. }
  218. Player* GameClient::zEntity() const
  219. {
  220. return zPlayer;
  221. }
  222. void GameClient::sendTypes()
  223. {
  224. foreground.lock();
  225. int count = StaticRegistry<BlockType>::INSTANCE.getCount();
  226. client->zForegroundWriter()->schreibe((char*)&count, 4);
  227. for (int i = 0; i < count; i++)
  228. {
  229. BlockType* t = StaticRegistry<BlockType>::INSTANCE.zElement(i);
  230. t->writeTypeInfo(client->zForegroundWriter());
  231. }
  232. count = 0;
  233. for (int i = 0; i < StaticRegistry<ItemType>::INSTANCE.getCount(); i++)
  234. {
  235. if (StaticRegistry<ItemType>::INSTANCE.zElement(i)) count++;
  236. }
  237. client->zForegroundWriter()->schreibe((char*)&count, 4);
  238. for (int i = 0; i < StaticRegistry<ItemType>::INSTANCE.getCount(); i++)
  239. {
  240. if (StaticRegistry<ItemType>::INSTANCE.zElement(i))
  241. {
  242. ItemType* t = StaticRegistry<ItemType>::INSTANCE.zElement(i);
  243. int id = t->getId();
  244. client->zForegroundWriter()->schreibe((char*)&id, 4);
  245. char len = (char)t->getName().getLength();
  246. client->zForegroundWriter()->schreibe((char*)&len, 1);
  247. client->zForegroundWriter()->schreibe(t->getName().getText(), len);
  248. short tlen = (short)t->getTooltipUIML().getLength();
  249. client->zForegroundWriter()->schreibe((char*)&tlen, 2);
  250. client->zForegroundWriter()->schreibe(
  251. t->getTooltipUIML().getText(), tlen);
  252. t->getModel().writeTo(client->zForegroundWriter());
  253. }
  254. }
  255. count = StaticRegistry<EntityType>::INSTANCE.getCount();
  256. client->zForegroundWriter()->schreibe((char*)&count, 4);
  257. for (int i = 0; i < count; i++)
  258. {
  259. EntityType* t = StaticRegistry<EntityType>::INSTANCE.zElement(i);
  260. int id = t->getId();
  261. client->zForegroundWriter()->schreibe((char*)&id, 4);
  262. t->getModel().writeTo(client->zForegroundWriter());
  263. }
  264. foreground.unlock();
  265. }
  266. Game::Game(Framework::Text name, Framework::Text worldsDir)
  267. : Thread(),
  268. name(name),
  269. dimensions(new RCArray<Dimension>()),
  270. updates(new RCArray<WorldUpdate>()),
  271. clients(new RCArray<GameClient>()),
  272. ticker(new TickOrganizer()),
  273. path((const char*)(worldsDir + "/" + name)),
  274. stop(0),
  275. tickId(0),
  276. nextEntityId(0),
  277. generator(0),
  278. loader(0),
  279. chat(0),
  280. playerRegister(new PlayerRegister(path)),
  281. totalTickTime(0),
  282. tickCounter(0),
  283. averageTickTime(0),
  284. ticksPerSecond(0),
  285. totalTime(0)
  286. {
  287. if (!DateiExistiert(worldsDir + "/" + name))
  288. DateiPfadErstellen(worldsDir + "/" + name + "/");
  289. Datei d;
  290. d.setDatei(path + "/eid");
  291. if (d.existiert())
  292. {
  293. d.open(Datei::Style::lesen);
  294. d.lese((char*)&nextEntityId, 4);
  295. d.close();
  296. }
  297. start();
  298. }
  299. Game::~Game()
  300. {
  301. dimensions->release();
  302. updates->release();
  303. clients->release();
  304. generator->release();
  305. loader->release();
  306. chat->release();
  307. playerRegister->release();
  308. }
  309. void Game::initialize()
  310. {
  311. int seed = 0;
  312. int index = 0;
  313. for (const char* n = name; *n; n++)
  314. seed += (int)pow((float)*n * 31, (float)++index);
  315. generator = new WorldGenerator(seed);
  316. loader = new WorldLoader();
  317. recipies.loadRecipies("data/recipies");
  318. chat = new Chat();
  319. }
  320. void Game::thread()
  321. {
  322. ZeitMesser waitForLock;
  323. ZeitMesser removeOldClients;
  324. ZeitMesser tickEntities;
  325. ZeitMesser worldUpdates;
  326. ZeitMesser clientReply;
  327. ZeitMesser removeOldChunks;
  328. ZeitMesser m;
  329. ZeitMesser total;
  330. total.messungStart();
  331. double tickTime = 0;
  332. double sleepTime = 0;
  333. while (!stop)
  334. {
  335. m.messungStart();
  336. ticker->nextTick();
  337. actionsCs.lock();
  338. while (actions.getEintragAnzahl() > 0)
  339. {
  340. actions.get(0)();
  341. actions.remove(0);
  342. }
  343. actionsCs.unlock();
  344. Array<int> removed;
  345. double waitTotal = 0;
  346. waitForLock.messungStart();
  347. cs.lock();
  348. waitForLock.messungEnde();
  349. waitTotal += waitForLock.getSekunden();
  350. removeOldClients.messungStart();
  351. int index = 0;
  352. for (auto player : *clients)
  353. {
  354. if (!player->isOnline())
  355. {
  356. chat->removeObserver(player->zEntity()->getId());
  357. chat->broadcastMessage(
  358. Framework::Text(player->zEntity()->getName())
  359. + " left the game.",
  360. Chat::CHANNEL_INFO);
  361. Datei pFile;
  362. pFile.setDatei(path + "/player/"
  363. + getPlayerId(player->zEntity()->getName()));
  364. pFile.erstellen();
  365. if (pFile.open(Datei::Style::schreiben))
  366. StaticRegistry<EntityType>::INSTANCE
  367. .zElement(EntityTypeEnum::PLAYER)
  368. ->saveEntity(player->zEntity(), &pFile);
  369. pFile.close();
  370. removed.add(index, 0);
  371. Dimension* dim
  372. = zDimension(player->zEntity()->getDimensionId());
  373. dim->removeSubscriptions(player->zEntity());
  374. this->requestWorldUpdate(
  375. new EntityRemovedUpdate(player->zEntity()->getId(),
  376. player->zEntity()->getDimensionId(),
  377. player->zEntity()->getPosition()));
  378. }
  379. index++;
  380. }
  381. for (auto i : removed)
  382. clients->remove(i);
  383. removeOldClients.messungEnde();
  384. cs.unlock();
  385. tickEntities.messungStart();
  386. for (auto dim : *dimensions)
  387. dim->tickEntities();
  388. tickEntities.messungEnde();
  389. waitForLock.messungStart();
  390. cs.lock();
  391. waitForLock.messungEnde();
  392. waitTotal += waitForLock.getSekunden();
  393. worldUpdates.messungStart();
  394. while (updates->hat(0))
  395. {
  396. WorldUpdate* update = updates->z(0);
  397. for (auto client : *clients)
  398. client->sendWorldUpdate(
  399. dynamic_cast<WorldUpdate*>(update->getThis()));
  400. if (!zDimension(update->getAffectedDimension()))
  401. addDimension(new Dimension(update->getAffectedDimension()));
  402. update->onUpdate(zDimension(update->getAffectedDimension()));
  403. updates->remove(0);
  404. }
  405. worldUpdates.messungEnde();
  406. cs.unlock();
  407. clientReply.messungStart();
  408. for (auto client : *clients)
  409. client->reply();
  410. clientReply.messungEnde();
  411. waitForLock.messungStart();
  412. cs.lock();
  413. waitForLock.messungEnde();
  414. waitTotal += waitForLock.getSekunden();
  415. removeOldChunks.messungStart();
  416. for (auto dim : *dimensions)
  417. dim->removeOldChunks();
  418. removeOldChunks.messungEnde();
  419. cs.unlock();
  420. m.messungEnde();
  421. double sec = m.getSekunden();
  422. tickCounter++;
  423. totalTickTime += sec;
  424. sleepTime += 1.0 / 20 - tickTime;
  425. if (sleepTime > 0)
  426. {
  427. Sleep((int)(sleepTime * 1000));
  428. }
  429. total.messungEnde();
  430. total.messungStart();
  431. tickTime = total.getSekunden();
  432. totalTime += tickTime;
  433. if (totalTime >= 1)
  434. {
  435. averageTickTime = totalTickTime / tickCounter;
  436. ticksPerSecond = tickCounter;
  437. totalTickTime = 0;
  438. tickCounter = 0;
  439. totalTime = 0;
  440. std::cout << std::flush; // update info in console
  441. }
  442. else if (sec > 1)
  443. {
  444. std::cout << "WARNING: tick needed " << sec
  445. << " seconds. The game will run sower then normal.\n";
  446. std::cout << "waiting: " << waitTotal << "\nremoveOldClients: "
  447. << removeOldClients.getSekunden()
  448. << "\ntickEntities:" << tickEntities.getSekunden()
  449. << "\nworldUpdates: " << worldUpdates.getSekunden()
  450. << "\nclientReply: " << clientReply.getSekunden()
  451. << "\nremoveOldChunks:" << removeOldChunks.getSekunden()
  452. << "\n";
  453. }
  454. }
  455. save();
  456. generator->exitAndWait();
  457. loader->exitAndWait();
  458. ticker->exitAndWait();
  459. for (Dimension* dim : *dimensions)
  460. dim->requestStopAndWait();
  461. std::cout << "Game thread exited\n";
  462. }
  463. void Game::api(Framework::InMemoryBuffer* zRequest, GameClient* zOrigin)
  464. {
  465. char type;
  466. zRequest->lese(&type, 1);
  467. NetworkMessage* response = new NetworkMessage();
  468. switch (type)
  469. {
  470. case 1: // world
  471. {
  472. Dimension* dim = zDimension(zOrigin->zEntity()->getDimensionId());
  473. if (!dim)
  474. {
  475. dim = new Dimension(zOrigin->zEntity()->getDimensionId());
  476. addDimension(dim);
  477. }
  478. dim->api(zRequest, response, zOrigin->zEntity());
  479. break;
  480. }
  481. case 2: // player
  482. zOrigin->zEntity()->playerApi(zRequest, response);
  483. break;
  484. case 3: // entity
  485. {
  486. int id;
  487. zRequest->lese((char*)&id, 4);
  488. for (Dimension* dim : *dimensions)
  489. {
  490. Entity* entity = dim->zEntity(id);
  491. if (entity)
  492. {
  493. entity->api(zRequest, response, zOrigin->zEntity());
  494. break;
  495. }
  496. }
  497. break;
  498. }
  499. case 4:
  500. { // inventory
  501. bool isEntity;
  502. zRequest->lese((char*)&isEntity, 1);
  503. Inventory* target;
  504. if (isEntity)
  505. {
  506. int id;
  507. zRequest->lese((char*)&id, 4);
  508. target = zEntity(id);
  509. }
  510. else
  511. {
  512. int dim;
  513. Vec3<int> pos;
  514. zRequest->lese((char*)&dim, 4);
  515. zRequest->lese((char*)&pos.x, 4);
  516. zRequest->lese((char*)&pos.y, 4);
  517. zRequest->lese((char*)&pos.z, 4);
  518. target = zBlockAt(pos, dim);
  519. }
  520. if (target)
  521. target->inventoryApi(zRequest, response, zOrigin->zEntity());
  522. break;
  523. }
  524. case 5:
  525. { // crafting uiml request
  526. int id;
  527. zRequest->lese((char*)&id, 4);
  528. Text uiml = recipies.getCrafingUIML(
  529. StaticRegistry<ItemType>::INSTANCE.zElement(id));
  530. Text dialogId = "crafting_";
  531. dialogId += id;
  532. response->openDialog(dialogId);
  533. int msgSize = 4 + uiml.getLength();
  534. char* msg = new char[msgSize];
  535. *(int*)msg = uiml.getLength();
  536. memcpy(msg + 4, uiml.getText(), uiml.getLength());
  537. response->setMessage(msg, msgSize);
  538. break;
  539. }
  540. case 6:
  541. { // chat message
  542. chat->chatApi(zRequest, zOrigin->zEntity(), response);
  543. break;
  544. }
  545. case 7: // other dimension
  546. {
  547. int dimensionId;
  548. zRequest->lese((char*)&dimensionId, 4);
  549. Dimension* dim = zDimension(dimensionId);
  550. if (dim)
  551. {
  552. dim->api(zRequest, response, zOrigin->zEntity());
  553. }
  554. break;
  555. }
  556. default:
  557. std::cout << "received unknown api request in game with type "
  558. << (int)type << "\n";
  559. }
  560. if (!response->isEmpty())
  561. {
  562. if (response->isBroadcast())
  563. broadcastMessage(response);
  564. else
  565. zOrigin->sendResponse(response);
  566. }
  567. else
  568. {
  569. response->release();
  570. }
  571. }
  572. void Game::updateLightning(int dimensionId, Vec3<int> location)
  573. {
  574. Dimension* zDim = zDimension(dimensionId);
  575. if (zDim) zDim->updateLightning(location);
  576. }
  577. void Game::updateLightningWithoutWait(int dimensionId, Vec3<int> location)
  578. {
  579. Dimension* zDim = zDimension(dimensionId);
  580. if (zDim) zDim->updateLightningWithoutWait(location);
  581. }
  582. void Game::broadcastMessage(NetworkMessage* response)
  583. {
  584. for (auto client : *clients)
  585. client->sendResponse(
  586. dynamic_cast<NetworkMessage*>(response->getThis()));
  587. }
  588. void Game::sendMessage(NetworkMessage* response, Entity* zTargetPlayer)
  589. {
  590. for (auto client : *clients)
  591. {
  592. if (client->zEntity()->getId() == zTargetPlayer->getId())
  593. {
  594. client->sendResponse(response);
  595. return;
  596. }
  597. }
  598. response->release();
  599. }
  600. bool Game::requestWorldUpdate(WorldUpdate* update)
  601. {
  602. cs.lock();
  603. for (WorldUpdate* u : *updates)
  604. {
  605. if (u->getMaxAffectedPoint().x >= update->getMinAffectedPoint().x
  606. && u->getMinAffectedPoint().x <= update->getMaxAffectedPoint().x
  607. && u->getMaxAffectedPoint().y >= update->getMinAffectedPoint().y
  608. && u->getMinAffectedPoint().y <= update->getMaxAffectedPoint().y
  609. && u->getMaxAffectedPoint().z >= update->getMinAffectedPoint().z
  610. && u->getMinAffectedPoint().z <= update->getMaxAffectedPoint().z
  611. && u->getType() == update->getType())
  612. {
  613. cs.unlock();
  614. update->release();
  615. return 0;
  616. }
  617. }
  618. updates->add(update);
  619. cs.unlock();
  620. return 1;
  621. }
  622. bool Game::checkPlayer(Framework::Text name, Framework::Text secret)
  623. {
  624. if (playerRegister->checkSecret(name, secret))
  625. return 1;
  626. else
  627. {
  628. std::cout << "player " << name.getText()
  629. << " tryed to connect with an invalid secret.\n";
  630. return 0;
  631. }
  632. }
  633. bool Game::existsPlayer(Framework::Text name)
  634. {
  635. return playerRegister->hasPlayer(name);
  636. }
  637. Framework::Text Game::createPlayer(Framework::Text name)
  638. {
  639. return playerRegister->addPlayer(name);
  640. }
  641. GameClient* Game::addPlayer(FCKlient* client, Framework::Text name)
  642. {
  643. cs.lock();
  644. int id = playerRegister->getPlayerId(name);
  645. Datei pFile;
  646. pFile.setDatei(path + "/player/" + id);
  647. Player* player;
  648. bool isNew = 0;
  649. if (!pFile.existiert() || !pFile.open(Datei::Style::lesen))
  650. {
  651. player = (Player*)StaticRegistry<EntityType>::INSTANCE
  652. .zElement(EntityTypeEnum::PLAYER)
  653. ->createEntityAt(
  654. Vec3<float>(0.5, 0.5, 0), DimensionEnum::OVERWORLD);
  655. player->setName(name);
  656. isNew = 1;
  657. }
  658. else
  659. {
  660. player = (Player*)StaticRegistry<EntityType>::INSTANCE
  661. .zElement(EntityTypeEnum::PLAYER)
  662. ->loadEntity(&pFile);
  663. pFile.close();
  664. }
  665. if (player->getId() >= nextEntityId)
  666. {
  667. nextEntityId = player->getId() + 1;
  668. }
  669. GameClient* gameClient = new GameClient(player, client);
  670. gameClient->sendTypes();
  671. clients->add(gameClient);
  672. if (!zDimension(player->getDimensionId()))
  673. {
  674. this->addDimension(new Dimension(player->getDimensionId()));
  675. }
  676. // subscribe the new player as an observer of the new chunk
  677. Dimension* dim = zDimension(player->getDimensionId());
  678. InMemoryBuffer* buffer = new InMemoryBuffer();
  679. buffer->schreibe("\0", 1);
  680. Punkt center = getChunkCenter(
  681. (int)player->getPosition().x, (int)player->getPosition().y);
  682. buffer->schreibe((char*)&center.x, 4);
  683. buffer->schreibe((char*)&center.y, 4);
  684. buffer->schreibe("\0", 1);
  685. dim->api(buffer, 0, player);
  686. buffer->release();
  687. while (isNew
  688. && !dim->zChunk(getChunkCenter(
  689. (int)player->getPosition().x, (int)player->getPosition().y)))
  690. {
  691. cs.unlock();
  692. Sleep(1000);
  693. cs.lock();
  694. }
  695. if (isNew)
  696. {
  697. Either<Block*, int> b = BlockTypeEnum::AIR;
  698. int h = WORLD_HEIGHT;
  699. while (((b.isA() && (!(Block*)b || ((Block*)b)->isPassable()))
  700. || (b.isB()
  701. && StaticRegistry<BlockType>::INSTANCE.zElement(b)
  702. ->zDefault()
  703. ->isPassable()))
  704. && h > 0)
  705. b = zBlockAt({(int)player->getPosition().x,
  706. (int)player->getPosition().y,
  707. --h},
  708. player->getDimensionId());
  709. player->setPosition(
  710. {player->getPosition().x, player->getPosition().y, (float)h + 1.f});
  711. }
  712. requestWorldUpdate(new AddEntityUpdate(player, player->getDimensionId()));
  713. chat->addObserver(gameClient->zEntity()->getId());
  714. chat->broadcastMessage(name + " joined the game.", Chat::CHANNEL_INFO);
  715. cs.unlock();
  716. return dynamic_cast<GameClient*>(gameClient->getThis());
  717. }
  718. bool Game::isChunkLoaded(int x, int y, int dimension) const
  719. {
  720. Dimension* dim = zDimension(dimension);
  721. return (dim && dim->hasChunck(x, y));
  722. }
  723. bool Game::doesChunkExist(int x, int y, int dimension)
  724. {
  725. cs.lock();
  726. bool result = isChunkLoaded(x, y, dimension)
  727. || loader->existsChunk(x, y, dimension);
  728. cs.unlock();
  729. return result;
  730. }
  731. void Game::blockTargetChanged(Block* zBlock)
  732. {
  733. for (GameClient* client : *this->clients)
  734. {
  735. if (client->zEntity()->zTarget()
  736. && client->zEntity()->zTarget()->isBlock(
  737. zBlock->getPos(), NO_DIRECTION))
  738. {
  739. client->zEntity()->onTargetChange();
  740. }
  741. }
  742. }
  743. void Game::entityTargetChanged(Entity* zEntity)
  744. {
  745. for (GameClient* client : *this->clients)
  746. {
  747. if (client->zEntity()->zTarget()
  748. && client->zEntity()->zTarget()->isEntity(zEntity->getId()))
  749. {
  750. client->zEntity()->onTargetChange();
  751. }
  752. }
  753. }
  754. void Game::spawnItem(
  755. Framework::Vec3<float> location, int dimensionId, Item* stack)
  756. {
  757. spawnItem(location, dimensionId, new ItemStack(stack, 1));
  758. }
  759. void Game::spawnItem(
  760. Framework::Vec3<float> location, int dimensionId, ItemStack* stack)
  761. {
  762. ItemEntity* itemEntity
  763. = (ItemEntity*)StaticRegistry<EntityType>::INSTANCE
  764. .zElement(EntityTypeEnum::ITEM)
  765. ->createEntity(
  766. location, dimensionId, Game::INSTANCE->getNextEntityId());
  767. itemEntity->unsaveAddItem(stack, NO_DIRECTION, 0);
  768. stack->release();
  769. requestWorldUpdate(new AddEntityUpdate(itemEntity, dimensionId));
  770. }
  771. Framework::Either<Block*, int> Game::zBlockAt(
  772. Framework::Vec3<int> location, int dimension) const
  773. {
  774. Dimension* dim = zDimension(dimension);
  775. if (dim) return dim->zBlock(location);
  776. return 0;
  777. }
  778. Block* Game::zRealBlockInstance(Framework::Vec3<int> location, int dimension)
  779. {
  780. Dimension* dim = zDimension(dimension);
  781. if (dim) return dim->zRealBlockInstance(location);
  782. return 0;
  783. }
  784. Dimension* Game::zDimension(int id) const
  785. {
  786. for (auto dim : *dimensions)
  787. {
  788. if (dim->getDimensionId() == id) return dim;
  789. }
  790. return 0;
  791. }
  792. Framework::Punkt Game::getChunkCenter(int x, int y)
  793. {
  794. return Punkt(((x < 0 ? x + 1 : x) / CHUNK_SIZE) * CHUNK_SIZE
  795. + (x < 0 ? -CHUNK_SIZE : CHUNK_SIZE) / 2,
  796. ((y < 0 ? y + 1 : y) / CHUNK_SIZE) * CHUNK_SIZE
  797. + (y < 0 ? -CHUNK_SIZE : CHUNK_SIZE) / 2);
  798. }
  799. Area Game::getChunckArea(Punkt center) const
  800. {
  801. return {center.x - CHUNK_SIZE / 2,
  802. center.y - CHUNK_SIZE / 2,
  803. center.x + CHUNK_SIZE / 2 - 1,
  804. center.y + CHUNK_SIZE / 2 - 1,
  805. 0};
  806. }
  807. Framework::Text Game::getWorldDirectory() const
  808. {
  809. return path;
  810. }
  811. void Game::requestArea(Area area)
  812. {
  813. generator->requestGeneration(area);
  814. loader->requestLoading(area);
  815. }
  816. void Game::save() const
  817. {
  818. Datei d;
  819. d.setDatei(path + "/eid");
  820. d.open(Datei::Style::schreiben);
  821. d.schreibe((char*)&nextEntityId, 4);
  822. d.close();
  823. playerRegister->save();
  824. for (auto dim : *dimensions)
  825. dim->save(path);
  826. chat->save();
  827. std::cout << "Game was saved\n";
  828. }
  829. void Game::requestStop()
  830. {
  831. stop = 1;
  832. warteAufThread(1000000);
  833. }
  834. void Game::addDimension(Dimension* d)
  835. {
  836. dimensions->add(d);
  837. }
  838. int Game::getNextEntityId()
  839. {
  840. cs.lock();
  841. int result = nextEntityId++;
  842. cs.unlock();
  843. return result;
  844. }
  845. WorldGenerator* Game::zGenerator() const
  846. {
  847. return generator;
  848. }
  849. Game* Game::INSTANCE = 0;
  850. void Game::initialize(Framework::Text name, Framework::Text worldsDir)
  851. {
  852. if (!Game::INSTANCE)
  853. {
  854. Game::INSTANCE = new Game(name, worldsDir);
  855. Game::INSTANCE->initialize();
  856. }
  857. }
  858. Entity* Game::zEntity(int id, int dimensionId) const
  859. {
  860. Dimension* d = zDimension(dimensionId);
  861. if (d) return d->zEntity(id);
  862. return 0;
  863. }
  864. Entity* Game::zEntity(int id) const
  865. {
  866. for (Dimension* d : *dimensions)
  867. {
  868. Entity* e = d->zEntity(id);
  869. if (e) return e;
  870. }
  871. // for new players that are currently loading
  872. for (GameClient* client : *clients)
  873. {
  874. if (client->zEntity()->getId() == id)
  875. {
  876. return client->zEntity();
  877. }
  878. }
  879. return 0;
  880. }
  881. Entity* Game::zNearestEntity(int dimensionId,
  882. Framework::Vec3<float> pos,
  883. std::function<bool(Entity*)> filter)
  884. {
  885. Dimension* d = zDimension(dimensionId);
  886. if (!d) return 0;
  887. return d->zNearestEntity(pos, filter);
  888. }
  889. const RecipieLoader& Game::getRecipies() const
  890. {
  891. return recipies;
  892. }
  893. void Game::doLater(std::function<void()> action)
  894. {
  895. actionsCs.lock();
  896. actions.add(action);
  897. actionsCs.unlock();
  898. }
  899. TickOrganizer* Game::zTickOrganizer() const
  900. {
  901. return ticker;
  902. }
  903. Chat* Game::zChat() const
  904. {
  905. return chat;
  906. }
  907. Player* Game::zPlayerByName(const char* name) const
  908. {
  909. for (GameClient* client : *clients)
  910. {
  911. if (strcmp(client->zEntity()->getName(), name) == 0)
  912. {
  913. return client->zEntity();
  914. }
  915. }
  916. return 0;
  917. }
  918. int Game::getPlayerId(const char* name) const
  919. {
  920. return playerRegister->getPlayerId(name);
  921. }
  922. double Game::getAverageTickTime() const
  923. {
  924. return averageTickTime;
  925. }
  926. int Game::getTicksPerSecond() const
  927. {
  928. return ticksPerSecond;
  929. }
  930. int Game::getPlayerCount() const
  931. {
  932. return clients->getEintragAnzahl();
  933. }
  934. int Game::getChunkCount() const
  935. {
  936. int result = 0;
  937. for (Dimension* dim : *dimensions)
  938. {
  939. result += dim->getChunkCount();
  940. }
  941. return result;
  942. }