Game.cpp 14 KB

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