Game.cpp 27 KB

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