Game.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660
  1. #include "Game.h"
  2. #include "Zeit.h"
  3. #include "Player.h"
  4. #include "OverworldDimension.h"
  5. #include "NoBlock.h"
  6. #include "AsynchronCall.h"
  7. #include "Entity.h"
  8. #include "AddEntityUpdate.h"
  9. #include "EntityRemovedUpdate.h"
  10. #include "NetworkMessage.h"
  11. using namespace Framework;
  12. GameClient::GameClient(Player* zPlayer, FCKlient* client)
  13. : ReferenceCounter(),
  14. zPlayer(zPlayer),
  15. client(client),
  16. viewDistance(DEFAULT_VIEW_DISTANCE),
  17. first(1),
  18. online(1),
  19. finished(0)
  20. {
  21. new AsynchronCall("Game Client", [this]()
  22. {
  23. while (online)
  24. {
  25. other.lock();
  26. if (updateQueue.hat(0))
  27. {
  28. WorldUpdate* update = updateQueue.get(0);
  29. updateQueue.remove(0);
  30. other.unlock();
  31. background.lock();
  32. this->client->zBackgroundWriter()->schreibe((char*)&Message::WORLD_UPDATE, 1);
  33. update->writeAndCheck(this->client->zBackgroundWriter());
  34. background.unlock();
  35. update->release();
  36. }
  37. else
  38. {
  39. other.unlock();
  40. updateSync.wait();
  41. }
  42. }
  43. finished = 1;
  44. });
  45. }
  46. GameClient::~GameClient()
  47. {
  48. online = 0;
  49. updateSync.notify();
  50. while (!finished)
  51. Sleep(100);
  52. client->release();
  53. }
  54. void GameClient::sendWorldUpdate(WorldUpdate* update)
  55. {
  56. bool add = 0;
  57. if (zPlayer->getCurrentDimensionId() == update->getAffectedDimension())
  58. {
  59. auto pos = (Vec3<int>)zPlayer->getPosition();
  60. int dist = update->distanceTo(pos.x, pos.y);
  61. if (dist < viewDistance * CHUNK_SIZE)
  62. {
  63. other.lock();
  64. int index = 0;
  65. for (auto update2 : updateQueue)
  66. {
  67. int dist2 = update2->distanceTo(pos.x, pos.y);
  68. if (dist2 > dist)
  69. break;
  70. index++;
  71. }
  72. updateQueue.add(update, index);
  73. other.unlock();
  74. updateSync.notify();
  75. add = 1;
  76. }
  77. }
  78. if (!add)
  79. update->release();
  80. }
  81. void GameClient::reply()
  82. {
  83. other.lock();
  84. for (auto req : requests)
  85. Game::INSTANCE->api(req, this);
  86. requests.leeren();
  87. other.unlock();
  88. if (first)
  89. {
  90. foreground.lock();
  91. int id = zPlayer->getId();
  92. client->zForegroundWriter()->schreibe((char*)&Message::POSITION_UPDATE, 1);
  93. client->zForegroundWriter()->schreibe((char*)&id, 4);
  94. foreground.unlock();
  95. first = 0;
  96. }
  97. }
  98. void GameClient::logout()
  99. {
  100. online = 0;
  101. }
  102. void GameClient::addMessage(StreamReader* reader)
  103. {
  104. short len = 0;
  105. reader->lese((char*)&len, 2);
  106. InMemoryBuffer* buffer = new InMemoryBuffer();
  107. char* tmp = new char[len];
  108. reader->lese(tmp, len);
  109. buffer->schreibe(tmp, len);
  110. delete[]tmp;
  111. other.lock();
  112. requests.add(buffer);
  113. other.unlock();
  114. }
  115. bool GameClient::isOnline() const
  116. {
  117. return online;
  118. }
  119. void GameClient::sendResponse(NetworkMessage* zResponse)
  120. {
  121. if (zResponse->isUseBackground())
  122. {
  123. background.lock();
  124. zResponse->writeTo(client->zBackgroundWriter());
  125. background.unlock();
  126. }
  127. else
  128. {
  129. foreground.lock();
  130. zResponse->writeTo(client->zForegroundWriter());
  131. foreground.unlock();
  132. }
  133. }
  134. Player* GameClient::zEntity() const
  135. {
  136. return zPlayer;
  137. }
  138. void GameClient::sendTypes()
  139. {
  140. foreground.lock();
  141. int count = StaticRegistry<BlockType>::INSTANCE.getCount();
  142. client->zForegroundWriter()->schreibe((char*)&count, 4);
  143. for (int i = 0; i < count; i++)
  144. {
  145. BlockType* t = StaticRegistry<BlockType>::INSTANCE.zElement(i);
  146. int id = t->getId();
  147. client->zForegroundWriter()->schreibe((char*)&id, 4);
  148. bool inst = t->doesNeedClientInstance();
  149. client->zForegroundWriter()->schreibe((char*)&inst, 1);
  150. int maxHp = t->getInitialMaxHP();
  151. client->zForegroundWriter()->schreibe((char*)&maxHp, 4);
  152. t->getModel().writeTo(client->zForegroundWriter());
  153. }
  154. count = StaticRegistry<ItemType>::INSTANCE.getCount();
  155. client->zForegroundWriter()->schreibe((char*)&count, 4);
  156. for (int i = 0; i < count; i++)
  157. {
  158. ItemType* t = StaticRegistry<ItemType>::INSTANCE.zElement(i);
  159. int id = t->getId();
  160. client->zForegroundWriter()->schreibe((char*)&id, 4);
  161. t->getModel().writeTo(client->zForegroundWriter());
  162. }
  163. count = StaticRegistry<EntityType>::INSTANCE.getCount();
  164. client->zForegroundWriter()->schreibe((char*)&count, 4);
  165. for (int i = 0; i < count; i++)
  166. {
  167. EntityType* t = StaticRegistry<EntityType>::INSTANCE.zElement(i);
  168. int id = t->getId();
  169. client->zForegroundWriter()->schreibe((char*)&id, 4);
  170. t->getModel().writeTo(client->zForegroundWriter());
  171. }
  172. foreground.unlock();
  173. }
  174. Game::Game(Framework::Text name, Framework::Text worldsDir)
  175. : Thread(),
  176. name(name),
  177. dimensions(new RCArray<Dimension>()),
  178. updates(new RCArray<WorldUpdate>()),
  179. clients(new RCArray<GameClient>()),
  180. ticker(new TickOrganizer()),
  181. path((const char*)(worldsDir + "/" + name)),
  182. stop(0),
  183. tickId(0),
  184. nextEntityId(0),
  185. generator(0),
  186. loader(0),
  187. totalTickTime(0),
  188. tickCounter(0)
  189. {
  190. if (!DateiExistiert(worldsDir + "/" + name))
  191. DateiPfadErstellen(worldsDir + "/" + name + "/");
  192. Datei d;
  193. d.setDatei(path + "/eid");
  194. if (d.existiert())
  195. {
  196. d.open(Datei::Style::lesen);
  197. d.lese((char*)&nextEntityId, 4);
  198. d.close();
  199. }
  200. start();
  201. }
  202. Game::~Game()
  203. {
  204. dimensions->release();
  205. updates->release();
  206. clients->release();
  207. generator->release();
  208. loader->release();
  209. }
  210. void Game::initialize()
  211. {
  212. int seed = 0;
  213. int index = 0;
  214. for (char* n = name; *n; n++)
  215. seed += (int)pow((float)*n * 31, (float)++index);
  216. generator = new WorldGenerator(seed);
  217. loader = new WorldLoader();
  218. recipies.loadRecipies("data/recipies");
  219. }
  220. void Game::thread()
  221. {
  222. ZeitMesser waitForLock;
  223. ZeitMesser removeOldClients;
  224. ZeitMesser tickEntities;
  225. ZeitMesser worldUpdates;
  226. ZeitMesser clientReply;
  227. ZeitMesser removeOldChunks;
  228. ZeitMesser m;
  229. while (!stop)
  230. {
  231. m.messungStart();
  232. ticker->nextTick();
  233. Array<int> removed;
  234. double waitTotal = 0;
  235. waitForLock.messungStart();
  236. cs.lock();
  237. waitForLock.messungEnde();
  238. waitTotal += waitForLock.getSekunden();
  239. removeOldClients.messungStart();
  240. int index = 0;
  241. for (auto player : *clients)
  242. {
  243. if (!player->isOnline())
  244. {
  245. std::cout << "player " << player->zEntity()->getName() << " disconnected.\n";
  246. Datei pFile;
  247. pFile.setDatei(path + "/player/" + player->zEntity()->getName());
  248. pFile.erstellen();
  249. if (pFile.open(Datei::Style::schreiben))
  250. PlayerEntityType::INSTANCE->saveEntity(player->zEntity(), &pFile);
  251. pFile.close();
  252. removed.add(index, 0);
  253. Dimension* dim = zDimension(player->zEntity()->getCurrentDimensionId());
  254. dim->removeSubscriptions(player->zEntity());
  255. this->requestWorldUpdate(new EntityRemovedUpdate(player->zEntity()->getId(), player->zEntity()->getCurrentDimensionId(), player->zEntity()->getPosition()));
  256. }
  257. index++;
  258. }
  259. for (auto i : removed)
  260. clients->remove(i);
  261. removeOldClients.messungEnde();
  262. cs.unlock();
  263. tickEntities.messungStart();
  264. for (auto dim : *dimensions)
  265. dim->tickEntities();
  266. tickEntities.messungEnde();
  267. waitForLock.messungStart();
  268. cs.lock();
  269. waitForLock.messungEnde();
  270. waitTotal += waitForLock.getSekunden();
  271. worldUpdates.messungStart();
  272. while (updates->hat(0))
  273. {
  274. WorldUpdate* update = updates->z(0);
  275. for (auto client : *clients)
  276. client->sendWorldUpdate(dynamic_cast<WorldUpdate*>(update->getThis()));
  277. if (!zDimension(update->getAffectedDimension()))
  278. addDimension(new Dimension(update->getAffectedDimension()));
  279. update->onUpdate(zDimension(update->getAffectedDimension()));
  280. updates->remove(0);
  281. }
  282. worldUpdates.messungEnde();
  283. cs.unlock();
  284. clientReply.messungStart();
  285. for (auto client : *clients)
  286. client->reply();
  287. clientReply.messungEnde();
  288. waitForLock.messungStart();
  289. cs.lock();
  290. waitForLock.messungEnde();
  291. waitTotal += waitForLock.getSekunden();
  292. removeOldChunks.messungStart();
  293. for (auto dim : *dimensions)
  294. dim->removeOldChunks();
  295. removeOldChunks.messungEnde();
  296. cs.unlock();
  297. m.messungEnde();
  298. double sec = m.getSekunden();
  299. tickCounter++;
  300. totalTickTime += sec;
  301. if (tickCounter >= 1000)
  302. {
  303. std::cout << "Average Tick time: " << (totalTickTime / 1000) << "\n";
  304. if ((totalTickTime / 1000) * 20 > 1)
  305. {
  306. std::cout << "The game runns slower than normal.\n";
  307. }
  308. else
  309. {
  310. std::cout << "No performance issues detected.\n";
  311. }
  312. totalTickTime = 0;
  313. tickCounter = 0;
  314. }
  315. if (sec < 0.05)
  316. Sleep((int)((0.05 - sec) * 1000));
  317. else
  318. {
  319. std::cout << "WARNING: tick needed " << sec << " seconds. The game will run sower then normal.\n";
  320. std::cout << "waiting: " << waitTotal << "\nremoveOldClients: " << removeOldClients.getSekunden() << "\ntickEntities:" << tickEntities.getSekunden() << "\nworldUpdates: " << worldUpdates.getSekunden() << "\nclientReply: " << clientReply.getSekunden() << "\nremoveOldChunks:" << removeOldChunks.getSekunden() << "\n";
  321. }
  322. }
  323. save();
  324. }
  325. void Game::api(Framework::InMemoryBuffer* zRequest, GameClient* zOrigin)
  326. {
  327. char type;
  328. zRequest->lese(&type, 1);
  329. NetworkMessage response;
  330. switch (type)
  331. {
  332. case 1: // world
  333. {
  334. Dimension* dim = zDimension(zOrigin->zEntity()->getCurrentDimensionId());
  335. if (!dim)
  336. {
  337. dim = new Dimension(zOrigin->zEntity()->getCurrentDimensionId());
  338. addDimension(dim);
  339. }
  340. dim->api(zRequest, &response, zOrigin->zEntity());
  341. break;
  342. }
  343. case 2: // player
  344. zOrigin->zEntity()->playerApi(zRequest, &response);
  345. break;
  346. case 3: // entity
  347. {
  348. int id;
  349. zRequest->lese((char*)&id, 4);
  350. for (Dimension* dim : *dimensions)
  351. {
  352. Entity* entity = dim->zEntity(id);
  353. if (entity)
  354. {
  355. entity->api(zRequest, &response);
  356. break;
  357. }
  358. }
  359. break;
  360. }
  361. case 4:
  362. { // inventory
  363. bool isEntity;
  364. zRequest->lese((char*)&isEntity, 1);
  365. Inventory* target;
  366. if (isEntity)
  367. {
  368. int id;
  369. zRequest->lese((char*)&id, 4);
  370. target = zEntity(id);
  371. }
  372. else
  373. {
  374. int dim;
  375. Vec3<int> pos;
  376. zRequest->lese((char*)&dim, 4);
  377. zRequest->lese((char*)&pos.x, 4);
  378. zRequest->lese((char*)&pos.y, 4);
  379. zRequest->lese((char*)&pos.z, 4);
  380. target = zBlockAt(pos, dim);
  381. }
  382. if (target)
  383. target->inventoryApi(zRequest, &response, zOrigin->zEntity());
  384. break;
  385. }
  386. default:
  387. std::cout << "received unknown api request in game with type " << (int)type << "\n";
  388. }
  389. if (!response.isEmpty())
  390. {
  391. if (response.isBroadcast())
  392. broadcastMessage(&response);
  393. else
  394. zOrigin->sendResponse(&response);
  395. }
  396. }
  397. void Game::updateLightning(int dimensionId, Vec3<int> location)
  398. {
  399. Dimension* zDim = zDimension(dimensionId);
  400. if (zDim)
  401. zDim->updateLightning(location);
  402. }
  403. void Game::broadcastMessage(NetworkMessage* zResponse)
  404. {
  405. for (auto client : *clients)
  406. client->sendResponse(zResponse);
  407. }
  408. void Game::sendMessage(NetworkMessage* zResponse, Entity* zTargetPlayer)
  409. {
  410. for (auto client : *clients)
  411. {
  412. if (client->zEntity()->getId() == zTargetPlayer->getId())
  413. {
  414. client->sendResponse(zResponse);
  415. break;
  416. }
  417. }
  418. }
  419. bool Game::requestWorldUpdate(WorldUpdate* update)
  420. {
  421. cs.lock();
  422. for (WorldUpdate* u : *updates)
  423. {
  424. if (u->getMaxAffectedPoint().x >= update->getMinAffectedPoint().x && u->getMinAffectedPoint().x <= update->getMaxAffectedPoint().x &&
  425. u->getMaxAffectedPoint().y >= update->getMinAffectedPoint().y && u->getMinAffectedPoint().y <= update->getMaxAffectedPoint().y &&
  426. u->getMaxAffectedPoint().z >= update->getMinAffectedPoint().z && u->getMinAffectedPoint().z <= update->getMaxAffectedPoint().z && u->getType() == update->getType())
  427. {
  428. cs.unlock();
  429. update->release();
  430. return 0;
  431. }
  432. }
  433. updates->add(update);
  434. cs.unlock();
  435. return 1;
  436. }
  437. GameClient* Game::addPlayer(FCKlient* client, Framework::Text name)
  438. {
  439. cs.lock();
  440. Datei pFile;
  441. pFile.setDatei(path + "/player/" + name);
  442. std::cout << "player " << name.getText() << " connected.\n";
  443. Player* player;
  444. bool isNew = 0;
  445. if (!pFile.existiert() || !pFile.open(Datei::Style::lesen))
  446. {
  447. player = (Player*)PlayerEntityType::INSTANCE->createEntityAt(Vec3<float>(0.5, 0.5, 0), OverworldDimension::ID);
  448. player->setName(name);
  449. isNew = 1;
  450. }
  451. else
  452. {
  453. player = (Player*)PlayerEntityType::INSTANCE->loadEntity(&pFile);
  454. pFile.close();
  455. }
  456. GameClient* gameClient = new GameClient(player, client);
  457. gameClient->sendTypes();
  458. clients->add(gameClient);
  459. if (!zDimension(player->getCurrentDimensionId()))
  460. {
  461. this->addDimension(new Dimension(player->getCurrentDimensionId()));
  462. }
  463. // subscribe the new player as an observer of the new chunk
  464. Dimension* dim = zDimension(player->getCurrentDimensionId());
  465. InMemoryBuffer* buffer = new InMemoryBuffer();
  466. buffer->schreibe("\0", 1);
  467. Punkt center = getChunkCenter((int)player->getPosition().x, (int)player->getPosition().y);
  468. buffer->schreibe((char*)&center.x, 4);
  469. buffer->schreibe((char*)&center.y, 4);
  470. buffer->schreibe("\0", 1);
  471. dim->api(buffer, 0, player);
  472. buffer->release();
  473. while (isNew && !dim->zChunk(getChunkCenter((int)player->getPosition().x, (int)player->getPosition().y)))
  474. {
  475. cs.unlock();
  476. Sleep(1000);
  477. cs.lock();
  478. }
  479. if (isNew)
  480. {
  481. Either<Block*, int> b = AirBlockBlockType::ID;
  482. int h = WORLD_HEIGHT;
  483. while (((b.isA() && (!(Block*)b || ((Block*)b)->isPassable())) || (b.isB() && StaticRegistry<BlockType>::INSTANCE.zElement(b)->zDefault()->isPassable())) && h > 0)
  484. b = zBlockAt({ (int)player->getPosition().x, (int)player->getPosition().y, --h }, player->getCurrentDimensionId());
  485. player->setPosition({ player->getPosition().x, player->getPosition().y, (float)h + 1.f });
  486. }
  487. requestWorldUpdate(new AddEntityUpdate(player, player->getCurrentDimensionId()));
  488. cs.unlock();
  489. return dynamic_cast<GameClient*>(gameClient->getThis());
  490. }
  491. bool Game::isChunkLoaded(int x, int y, int dimension) const
  492. {
  493. Dimension* dim = zDimension(dimension);
  494. return (dim && dim->hasChunck(x, y));
  495. }
  496. bool Game::doesChunkExist(int x, int y, int dimension)
  497. {
  498. cs.lock();
  499. bool result = isChunkLoaded(x, y, dimension) || loader->existsChunk(x, y, dimension);
  500. cs.unlock();
  501. return result;
  502. }
  503. Framework::Either<Block*, int> Game::zBlockAt(Framework::Vec3<int> location, int dimension) const
  504. {
  505. Dimension* dim = zDimension(dimension);
  506. if (dim)
  507. return dim->zBlock(location);
  508. return 0;
  509. }
  510. Block* Game::zRealBlockInstance(Framework::Vec3<int> location, int dimension)
  511. {
  512. Dimension* dim = zDimension(dimension);
  513. if (dim)
  514. return dim->zRealBlockInstance(location);
  515. return 0;
  516. }
  517. Dimension* Game::zDimension(int id) const
  518. {
  519. for (auto dim : *dimensions)
  520. {
  521. if (dim->getDimensionId() == id)
  522. return dim;
  523. }
  524. return 0;
  525. }
  526. Framework::Punkt Game::getChunkCenter(int x, int y)
  527. {
  528. return Punkt(((x < 0 ? x + 1 : x) / CHUNK_SIZE) * CHUNK_SIZE + (x < 0 ? -CHUNK_SIZE : CHUNK_SIZE) / 2, ((y < 0 ? y + 1 : y) / CHUNK_SIZE) * CHUNK_SIZE + (y < 0 ? -CHUNK_SIZE : CHUNK_SIZE) / 2);
  529. }
  530. Area Game::getChunckArea(Punkt center) const
  531. {
  532. return { center.x - CHUNK_SIZE / 2, center.y - CHUNK_SIZE / 2, center.x + CHUNK_SIZE / 2 - 1, center.y + CHUNK_SIZE / 2 - 1, 0 };
  533. }
  534. Framework::Text Game::getWorldDirectory() const
  535. {
  536. return path;
  537. }
  538. void Game::requestArea(Area area)
  539. {
  540. generator->requestGeneration(area);
  541. loader->requestLoading(area);
  542. }
  543. void Game::save() const
  544. {
  545. Datei d;
  546. d.setDatei(path + "/eid");
  547. d.open(Datei::Style::schreiben);
  548. d.schreibe((char*)&nextEntityId, 4);
  549. d.close();
  550. for (auto dim : *dimensions)
  551. dim->save(path);
  552. }
  553. void Game::requestStop()
  554. {
  555. stop = 1;
  556. warteAufThread(1000000);
  557. }
  558. void Game::addDimension(Dimension* d)
  559. {
  560. dimensions->add(d);
  561. }
  562. int Game::getNextEntityId()
  563. {
  564. cs.lock();
  565. int result = nextEntityId++;
  566. cs.unlock();
  567. return result;
  568. }
  569. WorldGenerator* Game::zGenerator() const
  570. {
  571. return generator;
  572. }
  573. Game* Game::INSTANCE = 0;
  574. void Game::initialize(Framework::Text name, Framework::Text worldsDir)
  575. {
  576. if (!Game::INSTANCE)
  577. {
  578. Game::INSTANCE = new Game(name, worldsDir);
  579. Game::INSTANCE->initialize();
  580. }
  581. }
  582. Entity* Game::zEntity(int id, int dimensionId) const
  583. {
  584. Dimension* d = zDimension(dimensionId);
  585. if (d)
  586. return d->zEntity(id);
  587. return 0;
  588. }
  589. Entity* Game::zEntity(int id) const
  590. {
  591. for (Dimension* d : *dimensions)
  592. {
  593. Entity* e = d->zEntity(id);
  594. if (e)
  595. return e;
  596. }
  597. // for new players that are currently loading
  598. for (GameClient* client : *clients)
  599. {
  600. if (client->zEntity()->getId() == id)
  601. {
  602. return client->zEntity();
  603. }
  604. }
  605. return 0;
  606. }
  607. Entity* Game::zNearestEntity(int dimensionId, Framework::Vec3<float> pos, std::function<bool(Entity*)> filter)
  608. {
  609. Dimension* d = zDimension(dimensionId);
  610. if (!d)
  611. return 0;
  612. return d->zNearestEntity(pos, filter);
  613. }
  614. const RecipieLoader& Game::getRecipies() const
  615. {
  616. return recipies;
  617. }