Game.cpp 30 KB

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