Dimension.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. #include "Dimension.h"
  2. #include "Constants.h"
  3. #include "Datei.h"
  4. #include "Game.h"
  5. #include "NoBlock.h"
  6. using namespace Framework;
  7. Dimension::Dimension(int id)
  8. : Thread(),
  9. dimensionId(id),
  10. gravity(9.8f),
  11. chunks(new Trie<Chunk>()),
  12. entities(new RCArray<Entity>())
  13. {
  14. start();
  15. }
  16. Dimension::~Dimension()
  17. {
  18. entities->release();
  19. chunks->release();
  20. }
  21. void Dimension::api(Framework::InMemoryBuffer* zRequest, NetworkMessage* zResponse, Entity* zSource)
  22. {
  23. char type;
  24. zRequest->lese(&type, 1);
  25. switch (type)
  26. {
  27. case 0: // chunk message
  28. {
  29. Punkt center;
  30. zRequest->lese((char*)&center.x, 4);
  31. zRequest->lese((char*)&center.y, 4);
  32. cs.lock();
  33. Chunk* cC = zChunk(center);
  34. if (!cC)
  35. {
  36. // TODO: have a max amount of waiting requests per player
  37. waitingRequests.add({ dynamic_cast<InMemoryBuffer*>(zRequest->getThis()), center, zSource->getId() });
  38. Game::INSTANCE->requestArea({ center.x - CHUNK_SIZE / 2, center.y - CHUNK_SIZE / 2, center.x + CHUNK_SIZE / 2 - 1, center.y + CHUNK_SIZE / 2 - 1, dimensionId });
  39. }
  40. else
  41. {
  42. cC->api(zRequest, zSource);
  43. }
  44. cs.unlock();
  45. break;
  46. }
  47. }
  48. }
  49. void Dimension::tickEntities()
  50. {
  51. for (auto entity : *entities)
  52. {
  53. if (!entity->isRemoved() && zChunk(Punkt((int)entity->getPosition().x, (int)entity->getPosition().y)))
  54. entity->prepareTick(this);
  55. }
  56. int index = 0;
  57. for (auto entity : *entities)
  58. {
  59. if (!entity->isRemoved() && zChunk(Punkt((int)entity->getPosition().x, (int)entity->getPosition().y)))
  60. entity->tick(this);
  61. index++;
  62. }
  63. }
  64. void Dimension::thread()
  65. {
  66. // light calculation
  67. int index = 0;
  68. ZeitMesser messer;
  69. messer.messungStart();
  70. double time = 0;
  71. while (true)
  72. {
  73. lightCs.lock();
  74. if (!lightUpdateQueue.getEintragAnzahl())
  75. {
  76. lightCs.unlock();
  77. messer.messungEnde();
  78. time += messer.getSekunden();
  79. Sleep(500);
  80. messer.messungStart();
  81. continue;
  82. }
  83. Vec3<int> position = lightUpdateQueue.get(0);
  84. lightUpdateQueue.remove(0);
  85. lightCs.unlock();
  86. // TODO: do not remove chunks while light calculation
  87. Chunk* chunk = zChunk(Game::INSTANCE->getChunkCenter(position.x, position.y));
  88. if (position.z >= 0 && position.z < WORLD_HEIGHT)
  89. {
  90. if (chunk)
  91. {
  92. int x = position.x % CHUNK_SIZE;
  93. int y = position.y % CHUNK_SIZE;
  94. if (x < 0)
  95. x += CHUNK_SIZE;
  96. if (y < 0)
  97. y += CHUNK_SIZE;
  98. unsigned char* light = chunk->getLightData(Vec3<int>(x, y, position.z));
  99. unsigned char dayLight[6] = { 255, 255, 255, 0, 0, 0 };
  100. unsigned char noLight[6] = { 0, 0, 0, 0, 0, 0 };
  101. unsigned char newLight[6] = { 0, 0, 0, 0, 0, 0 };
  102. // add neighbor light emission
  103. for (int i = 0; i < 6; i++)
  104. {
  105. unsigned char* neighborLeight;
  106. Vec3<int> neighborPos = position + getDirection(getDirectionFromIndex(i));
  107. if (neighborPos.z < 0)
  108. {
  109. neighborLeight = noLight;
  110. }
  111. else if (neighborPos.z >= WORLD_HEIGHT)
  112. {
  113. neighborLeight = dayLight;
  114. }
  115. else
  116. {
  117. Chunk* neighborChunk = zChunk(Game::INSTANCE->getChunkCenter(neighborPos.x, neighborPos.y));
  118. int x = neighborPos.x % CHUNK_SIZE;
  119. int y = neighborPos.y % CHUNK_SIZE;
  120. if (x < 0)
  121. x += CHUNK_SIZE;
  122. if (y < 0)
  123. y += CHUNK_SIZE;
  124. if (neighborChunk)
  125. neighborLeight = neighborChunk->getLightData(Vec3<int>(x, y, neighborPos.z));
  126. else
  127. neighborLeight = noLight;
  128. }
  129. for (int j = 0; j < 3; j++)
  130. newLight[j] = (unsigned char)MAX(newLight[j], i == getDirectionIndex(TOP) ? neighborLeight[j] : neighborLeight[j] - 16);
  131. for (int j = 3; j < 6; j++)
  132. newLight[j] = (unsigned char)MAX(newLight[j], neighborLeight[j] - 16);
  133. }
  134. const Block* current = zBlockOrDefault(position);
  135. if (!current)
  136. current = &NoBlock::INSTANCE;
  137. // add own light emission
  138. for (int j = 3; j < 6; j++)
  139. newLight[j] = (unsigned char)MAX(newLight[j], current->getLightEmisionColor()[j - 3]);
  140. current->filterPassingLight(newLight);
  141. current->filterPassingLight(newLight + 3);
  142. for (int i = 0; i < 6; i++)
  143. {
  144. if (newLight[i] != light[i])
  145. {
  146. chunk->setLightData(Vec3<int>(x, y, position.z), newLight);
  147. for (int j = 0; j < 6; j++)
  148. updateLightning(position + getDirection(getDirectionFromIndex(j)));
  149. break;
  150. }
  151. }
  152. }
  153. }
  154. index++;
  155. if (index > 100000)
  156. {
  157. messer.messungEnde();
  158. time += messer.getSekunden();
  159. std::cout << "100000 light updates needed " << time << " seconds\n";
  160. time = 0;
  161. index = 0;
  162. Sleep(250);
  163. messer.messungStart();
  164. }
  165. }
  166. }
  167. void Dimension::getAddrOf(Punkt cPos, char* addr) const
  168. {
  169. *(int*)addr = cPos.x;
  170. *((int*)addr + 1) = cPos.y;
  171. }
  172. void Dimension::getAddrOfWorld(Punkt wPos, char* addr) const
  173. {
  174. if (wPos.x < 0)
  175. wPos.x -= CHUNK_SIZE;
  176. if (wPos.y < 0) // needed because otherwise would (-8, -8) have the same adress as (8, 8)
  177. wPos.y -= CHUNK_SIZE;
  178. wPos /= CHUNK_SIZE;
  179. getAddrOf(wPos, addr);
  180. }
  181. Chunk* Dimension::zChunk(Punkt wPos) const
  182. {
  183. char addr[8];
  184. getAddrOfWorld(wPos, addr);
  185. return chunks->z(addr, 8);
  186. }
  187. Framework::Either<Block*, int> Dimension::zBlock(Vec3<int> location)
  188. {
  189. Chunk* c = zChunk(Game::INSTANCE->getChunkCenter(location.x, location.y));
  190. if (c)
  191. {
  192. int x = location.x % CHUNK_SIZE;
  193. int y = location.y % CHUNK_SIZE;
  194. if (x < 0)
  195. x += CHUNK_SIZE;
  196. if (y < 0)
  197. y += CHUNK_SIZE;
  198. return c->zBlockAt(Vec3<int>(x, y, location.z));
  199. }
  200. return 0;
  201. }
  202. Block* Dimension::zRealBlockInstance(Framework::Vec3<int> location)
  203. {
  204. Chunk* c = zChunk(Game::INSTANCE->getChunkCenter(location.x, location.y));
  205. if (c)
  206. {
  207. int x = location.x % CHUNK_SIZE;
  208. int y = location.y % CHUNK_SIZE;
  209. if (x < 0)
  210. x += CHUNK_SIZE;
  211. if (y < 0)
  212. y += CHUNK_SIZE;
  213. c->instantiateBlock(Vec3<int>(x, y, location.z));
  214. auto result = c->zBlockAt(Vec3<int>(x, y, location.z));
  215. return result.isA() ? result.getA() : 0;
  216. }
  217. return 0;
  218. }
  219. const Block* Dimension::zBlockOrDefault(Framework::Vec3<int> location)
  220. {
  221. Chunk* c = zChunk(Game::INSTANCE->getChunkCenter(location.x, location.y));
  222. if (c)
  223. {
  224. int x = location.x % CHUNK_SIZE;
  225. int y = location.y % CHUNK_SIZE;
  226. if (x < 0)
  227. x += CHUNK_SIZE;
  228. if (y < 0)
  229. y += CHUNK_SIZE;
  230. return c->zBlockConst(Vec3<int>(x, y, location.z));
  231. }
  232. return 0;
  233. }
  234. void Dimension::placeBlock(Framework::Vec3<int> location, Framework::Either<Block*, int> block)
  235. {
  236. Chunk* c = zChunk(Game::getChunkCenter(location.x, location.y));
  237. if (c)
  238. {
  239. int x = location.x % CHUNK_SIZE;
  240. int y = location.y % CHUNK_SIZE;
  241. if (x < 0)
  242. x += CHUNK_SIZE;
  243. if (y < 0)
  244. y += CHUNK_SIZE;
  245. if (block.isA())
  246. c->putBlockAt(Vec3<int>(x, y, location.z), block);
  247. else
  248. {
  249. c->putBlockAt(Vec3<int>(x, y, location.z), 0);
  250. c->putBlockTypeAt(Vec3<int>(x, y, location.z), block);
  251. }
  252. }
  253. else if (block.isA())
  254. block.getA()->release();
  255. }
  256. void Dimension::addEntity(Entity* entity)
  257. {
  258. entities->add(entity);
  259. }
  260. void Dimension::setChunk(Chunk* chunk, Punkt center)
  261. {
  262. chunkCs.lock();
  263. char addr[8];
  264. getAddrOfWorld(center, addr);
  265. Chunk* old = chunks->z(addr, 8);
  266. if (old)
  267. {
  268. for (int i = 0; i < chunkList.getEintragAnzahl(); i++)
  269. {
  270. if (chunkList.get(i) == old)
  271. {
  272. chunkList.remove(i);
  273. break;
  274. }
  275. }
  276. }
  277. chunks->set(addr, 8, chunk);
  278. if (chunk)
  279. {
  280. chunkList.add(chunk);
  281. chunk->setAdded();
  282. if (chunkList.getEintragAnzahl() == 0)
  283. {
  284. updateLightning(Vec3<int>(chunk->getCenter().x, chunk->getCenter().y, WORLD_HEIGHT - 1));
  285. }
  286. }
  287. getAddrOfWorld(center + Punkt(CHUNK_SIZE, 0), addr);
  288. Chunk* zChunk = chunks->z(addr, 8);
  289. if (zChunk)
  290. {
  291. zChunk->setNeighbor(WEST, chunk);
  292. if (chunk)
  293. {
  294. chunk->setNeighbor(EAST, zChunk);
  295. }
  296. }
  297. getAddrOfWorld(center + Punkt(-CHUNK_SIZE, 0), addr);
  298. zChunk = chunks->z(addr, 8);
  299. if (zChunk)
  300. {
  301. zChunk->setNeighbor(EAST, chunk);
  302. if (chunk)
  303. chunk->setNeighbor(WEST, zChunk);
  304. }
  305. getAddrOfWorld(center + Punkt(0, CHUNK_SIZE), addr);
  306. zChunk = chunks->z(addr, 8);
  307. if (zChunk)
  308. {
  309. zChunk->setNeighbor(NORTH, chunk);
  310. if (chunk)
  311. chunk->setNeighbor(SOUTH, zChunk);
  312. }
  313. getAddrOfWorld(center + Punkt(0, -CHUNK_SIZE), addr);
  314. zChunk = chunks->z(addr, 8);
  315. if (zChunk)
  316. {
  317. zChunk->setNeighbor(SOUTH, chunk);
  318. if (chunk)
  319. chunk->setNeighbor(NORTH, zChunk);
  320. }
  321. updateLightAtChunkBorders(center);
  322. if (chunk)
  323. {
  324. cs.lock();
  325. int index = 0;
  326. for (Iterator<RequestQueue> iterator = waitingRequests.begin(); iterator; )
  327. {
  328. Entity* zE = Game::INSTANCE->zEntity(iterator.val().sourceId);
  329. if (zE)
  330. {
  331. if (iterator.val().chunkCenter == chunk->getCenter())
  332. {
  333. chunk->api(iterator.val().request, zE);
  334. iterator.val().request->release();
  335. iterator.remove();
  336. continue;
  337. }
  338. }
  339. else
  340. {
  341. iterator.val().request->release();
  342. iterator.remove();
  343. continue;
  344. }
  345. iterator++;
  346. index++;
  347. }
  348. cs.unlock();
  349. }
  350. chunkCs.unlock();
  351. }
  352. void Dimension::save(Text worldDir) const
  353. {
  354. for (auto chunk = chunks->getIterator(); chunk; chunk++)
  355. {
  356. if (!chunk._)
  357. continue;
  358. Datei* file = new Datei();
  359. Text filePath = worldDir + "/dim/" + dimensionId + "/";
  360. filePath.appendHex(chunk->getCenter().x);
  361. filePath += "_";
  362. filePath.appendHex(chunk->getCenter().y);
  363. filePath += ".chunk";
  364. file->setDatei(filePath);
  365. if (file->open(Datei::Style::schreiben))
  366. chunk->save(file);
  367. file->close();
  368. file->release();
  369. }
  370. Text filePath = worldDir + "/dim/" + dimensionId + "/entities";
  371. Datei* file = new Datei();
  372. file->setDatei(filePath);
  373. if (file->open(Datei::Style::schreiben))
  374. {
  375. for (Entity* entity : *entities)
  376. {
  377. if (entity->zType()->getId() != PlayerEntityType::ID)
  378. {
  379. if (!entity->isRemoved())
  380. {
  381. int type = entity->zType()->getId();
  382. file->schreibe((char*)&type, 4);
  383. StaticRegistry<EntityType>::INSTANCE.zElement(type)->saveEntity(entity, file);
  384. }
  385. }
  386. else
  387. {
  388. Datei pFile;
  389. pFile.setDatei(worldDir + "/player/" + ((Player*)entity)->getName());
  390. if (pFile.open(Datei::Style::schreiben))
  391. PlayerEntityType::INSTANCE->saveEntity(entity, &pFile);
  392. }
  393. }
  394. file->close();
  395. }
  396. }
  397. int Dimension::getDimensionId() const
  398. {
  399. return dimensionId;
  400. }
  401. bool Dimension::hasChunck(int x, int y) const
  402. {
  403. return zChunk(Punkt(x, y));
  404. }
  405. float Dimension::getGravity() const
  406. {
  407. return gravity;
  408. }
  409. void Dimension::removeOldChunks()
  410. {
  411. chunkCs.lock();
  412. Array<int> removed;
  413. int index = 0;
  414. for (Chunk* chunk : chunkList)
  415. {
  416. if (!chunk->hasObservers())
  417. removed.add(index, 0);
  418. index++;
  419. }
  420. for (int i : removed)
  421. {
  422. Chunk* chunk = chunkList.get(i);
  423. // TODO: save chunk in a seperate thread?
  424. Text filePath = Game::INSTANCE->getWorldDirectory() + "/dim/" + getDimensionId() + "/";
  425. filePath.appendHex(chunk->getCenter().x);
  426. filePath += "_";
  427. filePath.appendHex(chunk->getCenter().y);
  428. filePath += ".chunk";
  429. Datei d;
  430. d.setDatei(filePath);
  431. d.open(Datei::Style::schreiben);
  432. chunk->save(&d);
  433. d.close();
  434. chunk->prepareRemove();
  435. setChunk(0, chunk->getCenter());
  436. }
  437. chunkCs.unlock();
  438. }
  439. Entity* Dimension::zEntity(int id)
  440. {
  441. for (auto entity : *entities)
  442. {
  443. if (!entity->isRemoved() && entity->getId() == id)
  444. return entity;
  445. }
  446. return 0;
  447. }
  448. Entity* Dimension::zNearestEntity(Framework::Vec3<float> pos, std::function<bool(Entity*)> filter)
  449. {
  450. Entity* result = 0;
  451. float sqDist = 0;
  452. for (auto entity : *entities)
  453. {
  454. if (!entity->isRemoved() && filter(entity))
  455. {
  456. float d = pos.abstandSq(entity->getPosition());
  457. if (!result || d < sqDist)
  458. {
  459. result = entity;
  460. sqDist = d;
  461. }
  462. }
  463. }
  464. return result;
  465. }
  466. void Dimension::removeEntity(int id)
  467. {
  468. int index = 0;
  469. for (auto entity : *entities)
  470. {
  471. if (entity->getId() == id)
  472. {
  473. entities->remove(index);
  474. return;
  475. }
  476. index++;
  477. }
  478. }
  479. void Dimension::removeSubscriptions(Entity* zEntity)
  480. {
  481. for (Chunk* chunk : chunkList)
  482. chunk->removeObserver(zEntity);
  483. }
  484. void Dimension::updateLightning(Vec3<int> location)
  485. {
  486. lightCs.lock();
  487. lightUpdateQueue.add(location, 0);
  488. lightCs.unlock();
  489. }
  490. void Dimension::updateLightAtChunkBorders(Punkt chunkCenter)
  491. {
  492. lightCs.lock();
  493. if (lightUpdateQueue.getEintragAnzahl() > 300000)
  494. {
  495. std::cout << "warning: light calculation queue is over 300000 blocks long";
  496. }
  497. for (int i = WORLD_HEIGHT - 1; i >= 0; i--)
  498. {
  499. for (int j = 0; j < CHUNK_SIZE; j++)
  500. {
  501. updateLightning(Vec3<int>(chunkCenter.x - CHUNK_SIZE / 8 - 1, chunkCenter.y - CHUNK_SIZE / 8 + j, i));
  502. updateLightning(Vec3<int>(chunkCenter.x - CHUNK_SIZE / 8, chunkCenter.y - CHUNK_SIZE / 8 + j, i));
  503. updateLightning(Vec3<int>(chunkCenter.x + CHUNK_SIZE / 8 - 1, chunkCenter.y - CHUNK_SIZE / 8 + j, i));
  504. updateLightning(Vec3<int>(chunkCenter.x + CHUNK_SIZE / 8, chunkCenter.y - CHUNK_SIZE / 8 + j, i));
  505. updateLightning(Vec3<int>(chunkCenter.x - CHUNK_SIZE / 8 + j, chunkCenter.y - CHUNK_SIZE / 8 - 1, i));
  506. updateLightning(Vec3<int>(chunkCenter.x - CHUNK_SIZE / 8 + j, chunkCenter.y - CHUNK_SIZE / 8, i));
  507. updateLightning(Vec3<int>(chunkCenter.x - CHUNK_SIZE / 8 + j, chunkCenter.y + CHUNK_SIZE / 8 - 1, i));
  508. updateLightning(Vec3<int>(chunkCenter.x - CHUNK_SIZE / 8 + j, chunkCenter.y + CHUNK_SIZE / 8, i));
  509. }
  510. }
  511. lightCs.unlock();
  512. }