Game.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  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 m;
  223. while (!stop)
  224. {
  225. m.messungStart();
  226. ticker->nextTick();
  227. Array<int> removed;
  228. cs.lock();
  229. int index = 0;
  230. for (auto player : *clients)
  231. {
  232. if (!player->isOnline())
  233. {
  234. std::cout << "player " << player->zEntity()->getName() << " disconnected.\n";
  235. Datei pFile;
  236. pFile.setDatei(path + "/player/" + player->zEntity()->getName());
  237. pFile.erstellen();
  238. if (pFile.open(Datei::Style::schreiben))
  239. PlayerEntityType::INSTANCE->saveEntity(player->zEntity(), &pFile);
  240. pFile.close();
  241. removed.add(index, 0);
  242. Dimension* dim = zDimension(player->zEntity()->getCurrentDimensionId());
  243. dim->removeSubscriptions(player->zEntity());
  244. this->requestWorldUpdate(new EntityRemovedUpdate(player->zEntity()->getId(), player->zEntity()->getCurrentDimensionId(), player->zEntity()->getPosition()));
  245. }
  246. index++;
  247. }
  248. for (auto i : removed)
  249. clients->remove(i);
  250. cs.unlock();
  251. for (auto dim : *dimensions)
  252. dim->tickEntities();
  253. cs.lock();
  254. while (updates->hat(0))
  255. {
  256. WorldUpdate* update = updates->z(0);
  257. for (auto client : *clients)
  258. client->sendWorldUpdate(dynamic_cast<WorldUpdate*>(update->getThis()));
  259. if (!zDimension(update->getAffectedDimension()))
  260. addDimension(new Dimension(update->getAffectedDimension()));
  261. update->onUpdate(zDimension(update->getAffectedDimension()));
  262. updates->remove(0);
  263. }
  264. cs.unlock();
  265. for (auto client : *clients)
  266. client->reply();
  267. cs.lock();
  268. for (auto dim : *dimensions)
  269. dim->removeOldChunks();
  270. cs.unlock();
  271. m.messungEnde();
  272. double sec = m.getSekunden();
  273. tickCounter++;
  274. totalTickTime += sec;
  275. if (tickCounter >= 1000)
  276. {
  277. std::cout << "Average Tick time: " << (totalTickTime / 1000) << "\n";
  278. if ((totalTickTime / 1000) * 20 > 1)
  279. {
  280. std::cout << "The game runns slower than normal.\n";
  281. }
  282. else
  283. {
  284. std::cout << "No performance issues detected.\n";
  285. }
  286. totalTickTime = 0;
  287. tickCounter = 0;
  288. }
  289. if (sec < 0.05)
  290. Sleep((int)((0.05 - sec) * 1000));
  291. else
  292. {
  293. std::cout << "WARNING: tick needed " << sec << " seconds. The game will run sower then normal.\n";
  294. }
  295. }
  296. save();
  297. }
  298. void Game::api(Framework::InMemoryBuffer* zRequest, GameClient* zOrigin)
  299. {
  300. char type;
  301. zRequest->lese(&type, 1);
  302. NetworkMessage response;
  303. switch (type)
  304. {
  305. case 1: // world
  306. {
  307. Dimension* dim = zDimension(zOrigin->zEntity()->getCurrentDimensionId());
  308. if (!dim)
  309. {
  310. dim = new Dimension(zOrigin->zEntity()->getCurrentDimensionId());
  311. addDimension(dim);
  312. }
  313. dim->api(zRequest, &response, zOrigin->zEntity());
  314. break;
  315. }
  316. case 2: // player
  317. zOrigin->zEntity()->playerApi(zRequest, &response);
  318. break;
  319. case 3: // entity
  320. {
  321. int id;
  322. zRequest->lese((char*)&id, 4);
  323. for (Dimension* dim : *dimensions)
  324. {
  325. Entity* entity = dim->zEntity(id);
  326. if (entity)
  327. {
  328. entity->api(zRequest, &response);
  329. break;
  330. }
  331. }
  332. break;
  333. }
  334. case 4:
  335. { // inventory
  336. bool isEntity;
  337. zRequest->lese((char*)&isEntity, 1);
  338. Inventory* target;
  339. if (isEntity)
  340. {
  341. int id;
  342. zRequest->lese((char*)&id, 4);
  343. target = zEntity(id);
  344. }
  345. else
  346. {
  347. int dim;
  348. Vec3<int> pos;
  349. zRequest->lese((char*)&dim, 4);
  350. zRequest->lese((char*)&pos.x, 4);
  351. zRequest->lese((char*)&pos.y, 4);
  352. zRequest->lese((char*)&pos.z, 4);
  353. target = zBlockAt(pos, dim);
  354. }
  355. if (target)
  356. target->inventoryApi(zRequest, &response, zOrigin->zEntity());
  357. break;
  358. }
  359. default:
  360. std::cout << "received unknown api request in game with type " << (int)type << "\n";
  361. }
  362. if (!response.isEmpty())
  363. {
  364. if (response.isBroadcast())
  365. broadcastMessage(&response);
  366. else
  367. zOrigin->sendResponse(&response);
  368. }
  369. }
  370. void Game::broadcastMessage(NetworkMessage* zResponse)
  371. {
  372. for (auto client : *clients)
  373. client->sendResponse(zResponse);
  374. }
  375. void Game::sendMessage(NetworkMessage* zResponse, Entity* zTargetPlayer)
  376. {
  377. for (auto client : *clients)
  378. {
  379. if (client->zEntity()->getId() == zTargetPlayer->getId())
  380. {
  381. client->sendResponse(zResponse);
  382. break;
  383. }
  384. }
  385. }
  386. bool Game::requestWorldUpdate(WorldUpdate* update)
  387. {
  388. cs.lock();
  389. for (WorldUpdate* u : *updates)
  390. {
  391. if (u->getMaxAffectedPoint().x >= update->getMinAffectedPoint().x && u->getMinAffectedPoint().x <= update->getMaxAffectedPoint().x &&
  392. u->getMaxAffectedPoint().y >= update->getMinAffectedPoint().y && u->getMinAffectedPoint().y <= update->getMaxAffectedPoint().y &&
  393. u->getMaxAffectedPoint().z >= update->getMinAffectedPoint().z && u->getMinAffectedPoint().z <= update->getMaxAffectedPoint().z && u->getType() == update->getType())
  394. {
  395. cs.unlock();
  396. update->release();
  397. return 0;
  398. }
  399. }
  400. updates->add(update);
  401. cs.unlock();
  402. return 1;
  403. }
  404. GameClient* Game::addPlayer(FCKlient* client, Framework::Text name)
  405. {
  406. cs.lock();
  407. Datei pFile;
  408. pFile.setDatei(path + "/player/" + name);
  409. std::cout << "player " << name.getText() << " connected.\n";
  410. Player* player;
  411. bool isNew = 0;
  412. if (!pFile.existiert() || !pFile.open(Datei::Style::lesen))
  413. {
  414. player = (Player*)PlayerEntityType::INSTANCE->createEntityAt(Vec3<float>(0.5, 0.5, 0), OverworldDimension::ID);
  415. player->setName(name);
  416. isNew = 1;
  417. }
  418. else
  419. {
  420. player = (Player*)PlayerEntityType::INSTANCE->loadEntity(&pFile);
  421. pFile.close();
  422. }
  423. GameClient* gameClient = new GameClient(player, client);
  424. gameClient->sendTypes();
  425. clients->add(gameClient);
  426. if (!zDimension(player->getCurrentDimensionId()))
  427. {
  428. this->addDimension(new Dimension(player->getCurrentDimensionId()));
  429. }
  430. // subscribe the new player as an observer of the new chunk
  431. Dimension* dim = zDimension(player->getCurrentDimensionId());
  432. InMemoryBuffer* buffer = new InMemoryBuffer();
  433. buffer->schreibe("\0", 1);
  434. Punkt center = getChunkCenter((int)player->getPosition().x, (int)player->getPosition().y);
  435. buffer->schreibe((char*)&center.x, 4);
  436. buffer->schreibe((char*)&center.y, 4);
  437. buffer->schreibe("\0", 1);
  438. dim->api(buffer, 0, player);
  439. buffer->release();
  440. while (isNew && !dim->zChunk(getChunkCenter((int)player->getPosition().x, (int)player->getPosition().y)))
  441. {
  442. cs.unlock();
  443. Sleep(1000);
  444. cs.lock();
  445. }
  446. if (isNew)
  447. {
  448. Either<Block*, int> b = AirBlockBlockType::ID;
  449. int h = WORLD_HEIGHT;
  450. while (((b.isA() && (!(Block*)b || ((Block*)b)->isPassable())) || (b.isB() && StaticRegistry<BlockType>::INSTANCE.zElement(b)->zDefault()->isPassable())) && h > 0)
  451. b = zBlockAt({ (int)player->getPosition().x, (int)player->getPosition().y, --h }, player->getCurrentDimensionId());
  452. player->setPosition({ player->getPosition().x, player->getPosition().y, (float)h + 1.f });
  453. }
  454. requestWorldUpdate(new AddEntityUpdate(player, player->getCurrentDimensionId()));
  455. cs.unlock();
  456. return dynamic_cast<GameClient*>(gameClient->getThis());
  457. }
  458. bool Game::isChunkLoaded(int x, int y, int dimension) const
  459. {
  460. Dimension* dim = zDimension(dimension);
  461. return (dim && dim->hasChunck(x, y));
  462. }
  463. bool Game::doesChunkExist(int x, int y, int dimension)
  464. {
  465. cs.lock();
  466. bool result = isChunkLoaded(x, y, dimension) || loader->existsChunk(x, y, dimension);
  467. cs.unlock();
  468. return result;
  469. }
  470. Framework::Either<Block*, int> Game::zBlockAt(Framework::Vec3<int> location, int dimension) const
  471. {
  472. Dimension* dim = zDimension(dimension);
  473. if (dim)
  474. return dim->zBlock(location);
  475. return 0;
  476. }
  477. Block* Game::zRealBlockInstance(Framework::Vec3<int> location, int dimension)
  478. {
  479. Dimension* dim = zDimension(dimension);
  480. if (dim)
  481. return dim->zRealBlockInstance(location);
  482. return 0;
  483. }
  484. Dimension* Game::zDimension(int id) const
  485. {
  486. for (auto dim : *dimensions)
  487. {
  488. if (dim->getDimensionId() == id)
  489. return dim;
  490. }
  491. return 0;
  492. }
  493. Framework::Punkt Game::getChunkCenter(int x, int y)
  494. {
  495. 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);
  496. }
  497. Area Game::getChunckArea(Punkt center) const
  498. {
  499. return { center.x - CHUNK_SIZE / 2, center.y - CHUNK_SIZE / 2, center.x + CHUNK_SIZE / 2 - 1, center.y + CHUNK_SIZE / 2 - 1, 0 };
  500. }
  501. Framework::Text Game::getWorldDirectory() const
  502. {
  503. return path;
  504. }
  505. void Game::requestArea(Area area)
  506. {
  507. generator->requestGeneration(area);
  508. loader->requestLoading(area);
  509. }
  510. void Game::save() const
  511. {
  512. Datei d;
  513. d.setDatei(path + "/eid");
  514. d.open(Datei::Style::schreiben);
  515. d.schreibe((char*)&nextEntityId, 4);
  516. d.close();
  517. for (auto dim : *dimensions)
  518. dim->save(path);
  519. }
  520. void Game::requestStop()
  521. {
  522. stop = 1;
  523. warteAufThread(1000000);
  524. }
  525. void Game::addDimension(Dimension* d)
  526. {
  527. dimensions->add(d);
  528. }
  529. int Game::getNextEntityId()
  530. {
  531. cs.lock();
  532. int result = nextEntityId++;
  533. cs.unlock();
  534. return result;
  535. }
  536. WorldGenerator* Game::zGenerator() const
  537. {
  538. return generator;
  539. }
  540. Game* Game::INSTANCE = 0;
  541. void Game::initialize(Framework::Text name, Framework::Text worldsDir)
  542. {
  543. if (!Game::INSTANCE)
  544. {
  545. Game::INSTANCE = new Game(name, worldsDir);
  546. Game::INSTANCE->initialize();
  547. }
  548. }
  549. Entity* Game::zEntity(int id, int dimensionId) const
  550. {
  551. Dimension* d = zDimension(dimensionId);
  552. if (d)
  553. return d->zEntity(id);
  554. return 0;
  555. }
  556. Entity* Game::zEntity(int id) const
  557. {
  558. for (Dimension* d : *dimensions)
  559. {
  560. Entity* e = d->zEntity(id);
  561. if (e)
  562. return e;
  563. }
  564. // for new players that are currently loading
  565. for (GameClient* client : *clients)
  566. {
  567. if (client->zEntity()->getId() == id)
  568. {
  569. return client->zEntity();
  570. }
  571. }
  572. return 0;
  573. }
  574. Entity* Game::zNearestEntity(int dimensionId, Framework::Vec3<float> pos, std::function<bool(Entity*)> filter)
  575. {
  576. Dimension* d = zDimension(dimensionId);
  577. if (!d)
  578. return 0;
  579. return d->zNearestEntity(pos, filter);
  580. }
  581. const RecipieLoader& Game::getRecipies() const
  582. {
  583. return recipies;
  584. }