Game.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599
  1. #include "Game.h"
  2. #include "Zeit.h"
  3. #include "Player.h"
  4. #include "OverworldDimension.h"
  5. #include "AddChunkUpdate.h"
  6. #include "NoBlock.h"
  7. #include "AsynchronCall.h"
  8. #include "Entity.h"
  9. #include "AddEntityUpdate.h"
  10. using namespace Framework;
  11. GameClient::GameClient(Player* zPlayer, FCKlient* client)
  12. : ReferenceCounter(),
  13. zPlayer(zPlayer),
  14. client(client),
  15. viewDistance(DEFAULT_VIEW_DISTANCE),
  16. first(1),
  17. online(1),
  18. finished(0)
  19. {
  20. new AsynchronCall("Game Client", [this]()
  21. {
  22. while (online)
  23. {
  24. other.lock();
  25. if (updateQueue.hat(0))
  26. {
  27. WorldUpdate* update = updateQueue.get(0);
  28. updateQueue.remove(0);
  29. other.unlock();
  30. background.lock();
  31. this->client->zBackgroundWriter()->schreibe((char*)&Message::WORLD_UPDATE, 1);
  32. update->writeAndCheck(this->client->zBackgroundWriter());
  33. background.unlock();
  34. update->release();
  35. }
  36. else
  37. {
  38. other.unlock();
  39. updateSync.wait();
  40. }
  41. }
  42. finished = 1;
  43. });
  44. }
  45. GameClient::~GameClient()
  46. {
  47. online = 0;
  48. updateSync.notify();
  49. while (!finished)
  50. Sleep(100);
  51. client->release();
  52. }
  53. void GameClient::sendWorldUpdate(WorldUpdate* update)
  54. {
  55. bool add = 0;
  56. if (zPlayer->getCurrentDimensionId() == update->getAffectedDimension())
  57. {
  58. auto pos = (Vec3<int>)zPlayer->getPosition();
  59. int dist = update->distanceTo(pos.x, pos.y);
  60. if (dist < viewDistance * CHUNK_SIZE)
  61. {
  62. other.lock();
  63. int index = 0;
  64. for (auto update2 : updateQueue)
  65. {
  66. int dist2 = update2->distanceTo(pos.x, pos.y);
  67. if (dist2 > dist)
  68. break;
  69. index++;
  70. }
  71. if (update->getType() == AddChunkUpdateType::ID)
  72. ((AddChunkUpdate*)update)->zChunk()->addView(zPlayer);
  73. updateQueue.add(update, index);
  74. other.unlock();
  75. updateSync.notify();
  76. add = 1;
  77. }
  78. }
  79. if (!add)
  80. update->release();
  81. }
  82. void GameClient::reply()
  83. {
  84. other.lock();
  85. for (auto req : requests)
  86. Game::INSTANCE->api(req, this);
  87. requests.leeren();
  88. other.unlock();
  89. int x = (int)floor(zPlayer->getPosition().x);
  90. int y = (int)floor(zPlayer->getPosition().y);
  91. int d = zPlayer->getCurrentDimensionId();
  92. // send world to client
  93. if (first)
  94. {
  95. foreground.lock();
  96. int id = zPlayer->getId();
  97. client->zForegroundWriter()->schreibe((char*)&Message::POSITION_UPDATE, 1);
  98. client->zForegroundWriter()->schreibe((char*)&id, 4);
  99. foreground.unlock();
  100. first = 0;
  101. Dimension* dim = Game::INSTANCE->zDimension(d);
  102. if (dim)
  103. {
  104. for (int xP = x - CHUNK_SIZE * viewDistance; xP <= x + CHUNK_SIZE * viewDistance; xP += CHUNK_SIZE)
  105. {
  106. for (int yP = y - CHUNK_SIZE * viewDistance; yP <= y + CHUNK_SIZE * viewDistance; yP += CHUNK_SIZE)
  107. {
  108. Chunk* chunk = dim->zChunk(Game::INSTANCE->getChunkCenter(xP, yP));
  109. if (chunk)
  110. sendWorldUpdate(new AddChunkUpdate(dynamic_cast<Chunk*>(chunk->getThis())));
  111. }
  112. }
  113. }
  114. Game::INSTANCE->requestArea({ x - CHUNK_SIZE * viewDistance, y - CHUNK_SIZE * viewDistance, x + CHUNK_SIZE * viewDistance, y + CHUNK_SIZE * viewDistance, d });
  115. }
  116. else
  117. {
  118. Punkt lastMin = Game::INSTANCE->getChunkCenter((int)floor(lastPos.x) - CHUNK_SIZE * viewDistance, (int)floor(lastPos.y) - CHUNK_SIZE * viewDistance);
  119. Punkt curMin = Game::INSTANCE->getChunkCenter(x - CHUNK_SIZE * viewDistance, y - CHUNK_SIZE * viewDistance);
  120. Punkt lastMax = Game::INSTANCE->getChunkCenter((int)floor(lastPos.x) + CHUNK_SIZE * viewDistance, (int)floor(lastPos.y) + CHUNK_SIZE * viewDistance);
  121. Punkt curMax = Game::INSTANCE->getChunkCenter(x + CHUNK_SIZE * viewDistance, y + CHUNK_SIZE * viewDistance);
  122. Dimension* dim = Game::INSTANCE->zDimension(d);
  123. if (dim)
  124. {
  125. for (int xP = curMin.x; xP <= curMax.x; xP += CHUNK_SIZE)
  126. {
  127. for (int yP = curMin.y; yP <= curMax.y; yP += CHUNK_SIZE)
  128. {
  129. if (xP < lastMin.x || xP > lastMax.x || yP < lastMin.y || yP > lastMax.y)
  130. {
  131. Chunk* chunk = dim->zChunk(Game::INSTANCE->getChunkCenter(xP, yP));
  132. if (chunk)
  133. sendWorldUpdate(new AddChunkUpdate(dynamic_cast<Chunk*>(chunk->getThis())));
  134. else
  135. Game::INSTANCE->requestArea(Game::INSTANCE->getChunckArea(Game::INSTANCE->getChunkCenter(xP, yP)));
  136. }
  137. }
  138. }
  139. for (int xP = lastMin.x; xP <= lastMax.x; xP += CHUNK_SIZE)
  140. {
  141. for (int yP = lastMin.y; yP <= lastMax.y; yP += CHUNK_SIZE)
  142. {
  143. if (xP < curMin.x || xP > curMax.x || yP < curMin.y || yP > curMax.y)
  144. {
  145. Chunk* chunk = dim->zChunk(Game::INSTANCE->getChunkCenter(xP, yP));
  146. if (chunk)
  147. chunk->removeView(zPlayer);
  148. }
  149. }
  150. }
  151. }
  152. }
  153. lastPos = zPlayer->getPosition();
  154. }
  155. void GameClient::logout()
  156. {
  157. online = 0;
  158. }
  159. void GameClient::addMessage(StreamReader* reader)
  160. {
  161. short len = 0;
  162. reader->lese((char*)&len, 2);
  163. InMemoryBuffer* buffer = new InMemoryBuffer();
  164. char* tmp = new char[len];
  165. reader->lese(tmp, len);
  166. buffer->schreibe(tmp, len);
  167. delete[]tmp;
  168. other.lock();
  169. requests.add(buffer);
  170. other.unlock();
  171. }
  172. bool GameClient::isOnline() const
  173. {
  174. return online;
  175. }
  176. void GameClient::sendResponse(NetworkResponse* zResponse)
  177. {
  178. if (zResponse->isAreaAffected({ lastPos.x - (float)CHUNK_SIZE * (float)viewDistance, lastPos.y - (float)CHUNK_SIZE * (float)viewDistance, 0.f }, { lastPos.x + (float)CHUNK_SIZE * (float)viewDistance, lastPos.y + (float)CHUNK_SIZE * (float)viewDistance, (float)WORLD_HEIGHT }, zPlayer->getCurrentDimensionId()))
  179. {
  180. if (zResponse->isUseBackground())
  181. {
  182. background.lock();
  183. client->zBackgroundWriter()->schreibe((char*)&Message::API_MESSAGE, 1);
  184. zResponse->writeTo(client->zBackgroundWriter());
  185. background.unlock();
  186. }
  187. else
  188. {
  189. foreground.lock();
  190. client->zForegroundWriter()->schreibe((char*)&Message::API_MESSAGE, 1);
  191. zResponse->writeTo(client->zForegroundWriter());
  192. foreground.unlock();
  193. }
  194. }
  195. }
  196. Player* GameClient::zEntity() const
  197. {
  198. return zPlayer;
  199. }
  200. void GameClient::sendTypes()
  201. {
  202. foreground.lock();
  203. int count = StaticRegistry<BlockType>::INSTANCE.getCount();
  204. client->zForegroundWriter()->schreibe((char*)&count, 4);
  205. for (int i = 0; i < count; i++)
  206. {
  207. BlockType* t = StaticRegistry<BlockType>::INSTANCE.zElement(i);
  208. int id = t->getId();
  209. client->zForegroundWriter()->schreibe((char*)&id, 4);
  210. bool inst = t->doesNeedClientInstance();
  211. client->zForegroundWriter()->schreibe((char*)&inst, 1);
  212. int maxHp = t->getInitialMaxHP();
  213. client->zForegroundWriter()->schreibe((char*)&maxHp, 4);
  214. t->getModel().writeTo(client->zForegroundWriter());
  215. }
  216. count = StaticRegistry<ItemType>::INSTANCE.getCount();
  217. client->zForegroundWriter()->schreibe((char*)&count, 4);
  218. for (int i = 0; i < count; i++)
  219. {
  220. ItemType* t = StaticRegistry<ItemType>::INSTANCE.zElement(i);
  221. int id = t->getId();
  222. client->zForegroundWriter()->schreibe((char*)&id, 4);
  223. t->getModel().writeTo(client->zForegroundWriter());
  224. }
  225. count = StaticRegistry<EntityType>::INSTANCE.getCount();
  226. client->zForegroundWriter()->schreibe((char*)&count, 4);
  227. for (int i = 0; i < count; i++)
  228. {
  229. EntityType* t = StaticRegistry<EntityType>::INSTANCE.zElement(i);
  230. int id = t->getId();
  231. client->zForegroundWriter()->schreibe((char*)&id, 4);
  232. t->getModel().writeTo(client->zForegroundWriter());
  233. }
  234. foreground.unlock();
  235. }
  236. Game::Game(Framework::Text name, Framework::Text worldsDir)
  237. : Thread(),
  238. name(name),
  239. dimensions(new RCArray<Dimension>()),
  240. updates(new RCArray<WorldUpdate>()),
  241. clients(new RCArray<GameClient>()),
  242. ticker(new TickOrganizer()),
  243. path((const char*)(worldsDir + "/" + name)),
  244. stop(0),
  245. tickId(0),
  246. nextEntityId(0),
  247. generator(0),
  248. loader(0)
  249. {
  250. if (!DateiExistiert(worldsDir + "/" + name))
  251. DateiPfadErstellen(worldsDir + "/" + name + "/");
  252. Datei d;
  253. d.setDatei(path + "/eid");
  254. if (d.existiert())
  255. {
  256. d.open(Datei::Style::lesen);
  257. d.lese((char*)&nextEntityId, 4);
  258. d.close();
  259. }
  260. start();
  261. }
  262. Game::~Game()
  263. {
  264. dimensions->release();
  265. updates->release();
  266. clients->release();
  267. generator->release();
  268. loader->release();
  269. }
  270. void Game::initialize()
  271. {
  272. int seed = 0;
  273. int index = 0;
  274. for (char* n = name; *n; n++)
  275. seed += (int)pow((float)*n * 31, (float)++index);
  276. generator = new WorldGenerator(seed);
  277. loader = new WorldLoader();
  278. recipies.loadRecipies("data/recipies");
  279. }
  280. void Game::thread()
  281. {
  282. ZeitMesser m;
  283. while (!stop)
  284. {
  285. m.messungStart();
  286. ticker->nextTick();
  287. Array<int> removed;
  288. cs.lock();
  289. int index = 0;
  290. for (auto player : *clients)
  291. {
  292. if (!player->isOnline())
  293. {
  294. Datei pFile;
  295. pFile.setDatei(path + "/player/" + player->zEntity()->getName());
  296. if (pFile.open(Datei::Style::schreiben))
  297. PlayerEntityType::INSTANCE->saveEntity(player->zEntity(), &pFile);
  298. removed.add(index, 0);
  299. }
  300. index++;
  301. }
  302. for (auto i : removed)
  303. clients->remove(i);
  304. cs.unlock();
  305. for (auto dim : *dimensions)
  306. dim->tickEntities();
  307. cs.lock();
  308. while (updates->hat(0))
  309. {
  310. WorldUpdate* update = updates->z(0);
  311. for (auto client : *clients)
  312. client->sendWorldUpdate(dynamic_cast<WorldUpdate*>(update->getThis()));
  313. if (!zDimension(update->getAffectedDimension()))
  314. addDimension(new Dimension(update->getAffectedDimension()));
  315. update->onUpdate(zDimension(update->getAffectedDimension()));
  316. updates->remove(0);
  317. }
  318. cs.unlock();
  319. for (auto client : *clients)
  320. client->reply();
  321. cs.lock();
  322. for (auto dim : *dimensions)
  323. dim->removeOldChunks();
  324. cs.unlock();
  325. m.messungEnde();
  326. double sec = m.getSekunden();
  327. if (sec < 0.05)
  328. Sleep((int)((0.05 - sec) * 1000));
  329. else
  330. {
  331. std::cout << "WARNING: tick needed " << sec << " seconds. The game will run sower then normal.\n";
  332. }
  333. }
  334. save();
  335. }
  336. void Game::api(Framework::StreamReader* zRequest, GameClient* zOrigin)
  337. {
  338. char type;
  339. zRequest->lese(&type, 1);
  340. NetworkResponse response;
  341. switch (type)
  342. {
  343. case 1: // world
  344. {
  345. int dimensionId;
  346. zRequest->lese((char*)&dimensionId, 4);
  347. Dimension* dim = zDimension(dimensionId);
  348. if (!dim)
  349. {
  350. dim = new Dimension(dimensionId);
  351. addDimension(dim);
  352. }
  353. dim->api(zRequest, &response);
  354. break;
  355. }
  356. case 2: // player
  357. zOrigin->zEntity()->playerApi(zRequest, &response);
  358. break;
  359. case 3: // entity
  360. {
  361. int id;
  362. zRequest->lese((char*)&id, 4);
  363. for (Dimension* dim : *dimensions)
  364. {
  365. Entity* entity = dim->zEntity(id);
  366. if (entity)
  367. {
  368. entity->api(zRequest, &response);
  369. break;
  370. }
  371. }
  372. break;
  373. }
  374. default:
  375. std::cout << "received unknown api request in game with type " << (int)type << "\n";
  376. }
  377. if (!response.isEmpty())
  378. {
  379. if (response.isBroadcast())
  380. distributeResponse(&response);
  381. else
  382. zOrigin->sendResponse(&response);
  383. }
  384. }
  385. void Game::distributeResponse(NetworkResponse* zResponse)
  386. {
  387. for (auto client : *clients)
  388. client->sendResponse(zResponse);
  389. }
  390. bool Game::requestWorldUpdate(WorldUpdate* update)
  391. {
  392. cs.lock();
  393. for (WorldUpdate* u : *updates)
  394. {
  395. if (u->getMaxAffectedPoint().x >= update->getMinAffectedPoint().x && u->getMinAffectedPoint().x <= update->getMaxAffectedPoint().x &&
  396. u->getMaxAffectedPoint().y >= update->getMinAffectedPoint().y && u->getMinAffectedPoint().y <= update->getMaxAffectedPoint().y &&
  397. u->getMaxAffectedPoint().z >= update->getMinAffectedPoint().z && u->getMinAffectedPoint().z <= update->getMaxAffectedPoint().z && u->getType() == update->getType())
  398. {
  399. cs.unlock();
  400. update->release();
  401. return 0;
  402. }
  403. }
  404. updates->add(update);
  405. cs.unlock();
  406. return 1;
  407. }
  408. GameClient* Game::addPlayer(FCKlient* client, Framework::Text name)
  409. {
  410. cs.lock();
  411. Datei pFile;
  412. pFile.setDatei(path + "/player/" + name);
  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. if (!result)
  458. {
  459. for (WorldUpdate* update : *updates)
  460. {
  461. if (update->getType() == AddChunkUpdateType::ID)
  462. result |= ((AddChunkUpdate*)update)->zChunk()->getCenter() == Framework::Punkt(x, y);
  463. }
  464. }
  465. cs.unlock();
  466. return result;
  467. }
  468. Framework::Either<Block*, int> Game::zBlockAt(Framework::Vec3<int> location, int dimension) const
  469. {
  470. Dimension* dim = zDimension(dimension);
  471. if (dim)
  472. return dim->zBlock(location);
  473. return 0;
  474. }
  475. Block* Game::zRealBlockInstance(Framework::Vec3<int> location, int dimension)
  476. {
  477. Dimension* dim = zDimension(dimension);
  478. if (dim)
  479. return dim->zRealBlockInstance(location);
  480. return 0;
  481. }
  482. Dimension* Game::zDimension(int id) const
  483. {
  484. for (auto dim : *dimensions)
  485. {
  486. if (dim->getDimensionId() == id)
  487. return dim;
  488. }
  489. return 0;
  490. }
  491. Framework::Punkt Game::getChunkCenter(int x, int y)
  492. {
  493. 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);
  494. }
  495. Area Game::getChunckArea(Punkt center) const
  496. {
  497. return { center.x - CHUNK_SIZE / 2, center.y - CHUNK_SIZE / 2, center.x + CHUNK_SIZE / 2 - 1, center.y + CHUNK_SIZE / 2 - 1, 0 };
  498. }
  499. Framework::Text Game::getWorldDirectory() const
  500. {
  501. return path;
  502. }
  503. void Game::requestArea(Area area)
  504. {
  505. generator->requestGeneration(area);
  506. loader->requestLoading(area);
  507. }
  508. void Game::save() const
  509. {
  510. Datei d;
  511. d.setDatei(path + "/eid");
  512. d.open(Datei::Style::schreiben);
  513. d.schreibe((char*)&nextEntityId, 4);
  514. d.close();
  515. for (auto dim : *dimensions)
  516. dim->save(path);
  517. }
  518. void Game::requestStop()
  519. {
  520. stop = 1;
  521. warteAufThread(1000000);
  522. }
  523. void Game::addDimension(Dimension* d)
  524. {
  525. dimensions->add(d);
  526. }
  527. int Game::getNextEntityId()
  528. {
  529. cs.lock();
  530. int result = nextEntityId++;
  531. cs.unlock();
  532. return result;
  533. }
  534. WorldGenerator* Game::zGenerator() const
  535. {
  536. return generator;
  537. }
  538. Game* Game::INSTANCE = 0;
  539. void Game::initialize(Framework::Text name, Framework::Text worldsDir)
  540. {
  541. if (!Game::INSTANCE)
  542. {
  543. Game::INSTANCE = new Game(name, worldsDir);
  544. Game::INSTANCE->initialize();
  545. }
  546. }
  547. Entity* Game::zEntity(int id, int dimensionId) const
  548. {
  549. Dimension* d = zDimension(dimensionId);
  550. if (d)
  551. return d->zEntity(id);
  552. return 0;
  553. }
  554. Entity* Game::zNearestEntity(int dimensionId, Framework::Vec3<float> pos, std::function<bool(Entity*)> filter)
  555. {
  556. Dimension* d = zDimension(dimensionId);
  557. if (!d)
  558. return 0;
  559. return d->zNearestEntity(pos, filter);
  560. }