Game.cpp 27 KB

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