Game.cpp 28 KB

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