Dimension.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074
  1. #include "Dimension.h"
  2. #include <AsynchronCall.h>
  3. #include <Logging.h>
  4. #include "ChunkMap.h"
  5. #include "Constants.h"
  6. #include "DimensionMap.h"
  7. #include "Entity.h"
  8. #include "EntityType.h"
  9. #include "File.h"
  10. #include "Game.h"
  11. #include "NoBlock.h"
  12. #include "Player.h"
  13. #include "TickOrganizer.h"
  14. #include "WorldGenerator.h"
  15. using namespace Framework;
  16. Dimension::Dimension(int id)
  17. : Thread(),
  18. nextStructureId(1),
  19. dimensionId(id),
  20. gravity(9.8f),
  21. chunks(new RCTrie<Chunk>()),
  22. entities(new RCArray<Entity>()),
  23. structureManager(new MultiblockStructureManager(id)),
  24. map(new DimensionMap(id)),
  25. stop(0),
  26. currentDayTime(0.0),
  27. nightDuration(300.0),
  28. nightTransitionDuration(30.0),
  29. dayDuration(600.0)
  30. {
  31. File d;
  32. d.setFile(
  33. Game::INSTANCE->getWorldDirectory() + "/dim/" + Text(id) + "/meta.dim");
  34. if (d.exists())
  35. {
  36. d.open(File::Style::read);
  37. d.read((char*)&nextStructureId, 8);
  38. d.read((char*)&currentDayTime, 8);
  39. d.close();
  40. }
  41. start();
  42. new AsynchronCall([this]() { this->entityTickLoop(); });
  43. }
  44. Dimension::~Dimension()
  45. {
  46. entities->release();
  47. chunks->release();
  48. map->release();
  49. delete structureManager;
  50. }
  51. void Dimension::configureDayNightCyncle(
  52. double nightDuration, double nightTransitionDuration, double dayDuration)
  53. {
  54. this->nightDuration = nightDuration;
  55. this->nightTransitionDuration = nightTransitionDuration;
  56. this->dayDuration = dayDuration;
  57. }
  58. void Dimension::api(Framework::InMemoryBuffer* zRequest,
  59. NetworkMessage* zResponse,
  60. Entity* zSource)
  61. {
  62. DoLaterHandler laterHandler;
  63. char type;
  64. zRequest->read(&type, 1);
  65. switch (type)
  66. {
  67. case 0: // chunk message
  68. {
  69. Point center;
  70. zRequest->read((char*)&center.x, 4);
  71. zRequest->read((char*)&center.y, 4);
  72. cs.lock();
  73. Chunk* cC = zChunk(Game::getChunkCenter(center.x, center.y));
  74. if (!cC)
  75. {
  76. // TODO: have a max amount of waiting requests per player
  77. waitingRequests.add(
  78. {dynamic_cast<InMemoryBuffer*>(zRequest->getThis()),
  79. center,
  80. zSource->getId()});
  81. Game::INSTANCE->requestArea({center.x - CHUNK_SIZE / 2,
  82. center.y - CHUNK_SIZE / 2,
  83. center.x + CHUNK_SIZE / 2 - 1,
  84. center.y + CHUNK_SIZE / 2 - 1,
  85. dimensionId});
  86. }
  87. else
  88. {
  89. cC->api(zRequest, zSource, laterHandler);
  90. }
  91. cs.unlock();
  92. break;
  93. }
  94. case 1: // block message
  95. {
  96. Vec3<int> location;
  97. zRequest->read((char*)&location.x, 4);
  98. zRequest->read((char*)&location.y, 4);
  99. zRequest->read((char*)&location.z, 4);
  100. Framework::Either<Block*, int> block = zBlock(location, 0);
  101. if (block.isA())
  102. {
  103. block.getA()->api(zRequest, zResponse, zSource);
  104. }
  105. break;
  106. }
  107. case 2: // map request
  108. {
  109. map->api(zRequest, zResponse, zSource, this);
  110. break;
  111. }
  112. }
  113. }
  114. void Dimension::tick()
  115. {
  116. this->currentDayTime += 1.0 / MAX_TICKS_PER_SECOND;
  117. if (this->currentDayTime
  118. > dayDuration + nightDuration + nightTransitionDuration * 2)
  119. {
  120. this->currentDayTime
  121. -= dayDuration + nightDuration + nightTransitionDuration * 2;
  122. }
  123. }
  124. void Dimension::thread()
  125. {
  126. // light calculation
  127. int index = 0;
  128. Timer messer;
  129. messer.measureStart();
  130. double time = 0;
  131. bool isForeground = 0;
  132. Framework::Array<Framework::Vec3<int>> internalLightUpdateQueue;
  133. unsigned char tmp[3];
  134. while (!stop)
  135. {
  136. Vec3<int> position;
  137. if (internalLightUpdateQueue.getEntryCount())
  138. {
  139. position = internalLightUpdateQueue.get(0);
  140. internalLightUpdateQueue.remove(0);
  141. }
  142. else
  143. {
  144. removedChunksCs.lock();
  145. if (removedChunks.getEntryCount() > 0)
  146. {
  147. Chunk* removedChunk = removedChunks.z(0);
  148. removedChunksCs.unlock();
  149. Array<Framework::Point> chunksToSave;
  150. Text filePath = Game::INSTANCE->getWorldDirectory() + "/dim/"
  151. + getDimensionId() + "/";
  152. filePath.appendHex(removedChunk->getCenter().x);
  153. filePath += "_";
  154. filePath.appendHex(removedChunk->getCenter().y);
  155. filePath += ".chunk";
  156. File d;
  157. d.setFile(filePath);
  158. d.create();
  159. d.open(File::Style::write);
  160. removedChunk->save(&d, chunksToSave);
  161. char addr[8];
  162. getAddrOfWorld(removedChunk->getCenter(), addr);
  163. map->removeMap(addr, 8);
  164. d.close();
  165. removedChunksCs.lock();
  166. removedChunks.remove(0);
  167. while (chunksToSave.getEntryCount() > 0)
  168. {
  169. Point cPos = chunksToSave.get(0);
  170. chunksToSave.remove(0);
  171. Chunk* c = zChunk(cPos);
  172. if (c)
  173. {
  174. Text filePath = Game::INSTANCE->getWorldDirectory()
  175. + "/dim/" + getDimensionId() + "/";
  176. filePath.appendHex(cPos.x);
  177. filePath += "_";
  178. filePath.appendHex(cPos.y);
  179. filePath += ".chunk";
  180. File d;
  181. d.setFile(filePath);
  182. d.create();
  183. d.open(File::Style::write);
  184. c->save(&d, chunksToSave);
  185. d.close();
  186. }
  187. }
  188. }
  189. removedChunksCs.unlock();
  190. if (priorizedLightUpdateQueue.getEntryCount())
  191. {
  192. prioLightCs.lock();
  193. position = priorizedLightUpdateQueue.get(0);
  194. priorizedLightUpdateQueue.remove(0);
  195. prioLightCs.unlock();
  196. isForeground = 1;
  197. }
  198. else
  199. {
  200. if (!lightUpdateQueue.getEntryCount())
  201. {
  202. messer.measureEnd();
  203. time += messer.getSekunden();
  204. Sleep(500);
  205. messer.measureStart();
  206. continue;
  207. }
  208. lightCs.lock();
  209. position = lightUpdateQueue.get(0);
  210. lightUpdateQueue.remove(0);
  211. lightCs.unlock();
  212. isForeground = 0;
  213. }
  214. }
  215. Chunk* chunk
  216. = zChunk(Game::INSTANCE->getChunkCenter(position.x, position.y));
  217. if (position.z >= 0 && position.z < WORLD_HEIGHT)
  218. {
  219. if (chunk)
  220. {
  221. Vec3<int> chunkPos = chunkCoordinates(position);
  222. unsigned char* light = chunk->getLightData(chunkPos);
  223. unsigned char dayLight[6] = {255, 255, 255, 0, 0, 0};
  224. unsigned char noLight[6] = {0, 0, 0, 0, 0, 0};
  225. unsigned char newLight[6] = {0, 0, 0, 0, 0, 0};
  226. // add neighbor light emission
  227. for (int i = 0; i < 6; i++)
  228. {
  229. unsigned char* neighborLeight;
  230. Vec3<int> neighborPos
  231. = position + getDirection(getDirectionFromIndex(i));
  232. if (neighborPos.z < 0)
  233. {
  234. neighborLeight = noLight;
  235. }
  236. else if (neighborPos.z >= WORLD_HEIGHT)
  237. {
  238. neighborLeight = dayLight;
  239. }
  240. else
  241. {
  242. Chunk* neighborChunk
  243. = zChunk(Game::INSTANCE->getChunkCenter(
  244. neighborPos.x, neighborPos.y));
  245. if (neighborChunk)
  246. neighborLeight = neighborChunk->getLightData(
  247. chunkCoordinates(neighborPos));
  248. else
  249. neighborLeight = noLight;
  250. }
  251. for (int j = 0; j < 3; j++)
  252. newLight[j] = (unsigned char)MAX(newLight[j],
  253. i == getDirectionIndex(TOP)
  254. ? neighborLeight[j]
  255. : (unsigned char)((float)neighborLeight[j]
  256. * 0.8f));
  257. for (int j = 3; j < 6; j++)
  258. newLight[j] = (unsigned char)MAX(newLight[j],
  259. (unsigned char)((float)neighborLeight[j] * 0.85f));
  260. }
  261. const Block* current = zBlockOrDefault(position);
  262. // add own light emission
  263. current->getLightEmisionColor(tmp);
  264. for (int j = 3; j < 6; j++)
  265. newLight[j] = (unsigned char)MAX(newLight[j], tmp[j - 3]);
  266. current->filterPassingLight(newLight);
  267. current->filterPassingLight(newLight + 3);
  268. for (int i = 0; i < 6; i++)
  269. {
  270. if (newLight[i] != light[i])
  271. {
  272. chunk->setLightData(chunkPos, newLight, isForeground);
  273. for (int j = 0; j < 6; j++)
  274. internalLightUpdateQueue.add(
  275. position
  276. + getDirection(getDirectionFromIndex(j)),
  277. 0);
  278. break;
  279. }
  280. }
  281. }
  282. }
  283. index++;
  284. if (index > 100000)
  285. {
  286. messer.measureEnd();
  287. time += messer.getSekunden();
  288. Logging::debug()
  289. << "100000 light updates needed " << time << " seconds";
  290. time = 0;
  291. index = 0;
  292. messer.measureStart();
  293. }
  294. }
  295. Logging::info() << Text("Dimension ") + this->getDimensionId()
  296. + " update Thread exited.";
  297. }
  298. void Dimension::getAddrOf(Point cPos, char* addr) const
  299. {
  300. *(int*)addr = cPos.x;
  301. *((int*)addr + 1) = cPos.y;
  302. }
  303. void Dimension::getAddrOfWorld(Point wPos, char* addr) const
  304. {
  305. if (wPos.x < 0) wPos.x -= CHUNK_SIZE;
  306. if (wPos.y < 0) // needed because otherwise would (-8, -8) have the same
  307. // adress as (8, 8)
  308. wPos.y -= CHUNK_SIZE;
  309. wPos /= CHUNK_SIZE;
  310. getAddrOf(wPos, addr);
  311. }
  312. void Dimension::saveStructure(MultiblockStructure* zStructure) const
  313. {
  314. structureManager->saveStructure(zStructure);
  315. }
  316. void Dimension::entityTickLoop()
  317. {
  318. Timer zm;
  319. double ausgleich = 0.0;
  320. zm.measureStart();
  321. Sleep(16);
  322. int etps = 0;
  323. double secondSum = 0.0;
  324. while (!stop)
  325. {
  326. zm.measureEnd();
  327. double seconds = zm.getSekunden();
  328. zm.measureStart();
  329. {
  330. Framework::StackLock* lock
  331. = new Framework::StackLock({&entityCs, &chunkCs});
  332. auto iterator = entities->begin();
  333. auto end = entities->end();
  334. while (iterator != end)
  335. {
  336. if (!iterator->isRemoved())
  337. {
  338. iterator->prepareTick(this, seconds);
  339. iterator++;
  340. }
  341. else
  342. {
  343. auto chunk = zChunk(
  344. Game::getChunkCenter((int)iterator->getPosition().x,
  345. (int)iterator->getPosition().y));
  346. if (chunk)
  347. {
  348. chunk->onEntityLeaves(iterator, 0);
  349. }
  350. iterator.remove();
  351. }
  352. }
  353. int index = 0;
  354. for (auto entity : *entities)
  355. {
  356. if (!entity->isRemoved())
  357. {
  358. entity->tick(this, seconds);
  359. }
  360. index++;
  361. }
  362. delete lock;
  363. } // end of LOCK entityCs, chunkCs
  364. ausgleich += 1.0 / 30 - seconds;
  365. etps++;
  366. secondSum += seconds;
  367. if (secondSum > 1.0)
  368. {
  369. if (etps < 29)
  370. {
  371. Framework::Logging::warning()
  372. << "Only " << etps << " entity ticks per second!";
  373. }
  374. etps = 0;
  375. secondSum -= 1.0;
  376. }
  377. if (ausgleich > 0) Sleep((int)(ausgleich * 1000));
  378. }
  379. }
  380. Chunk* Dimension::zChunk(Point wPos) const
  381. {
  382. char addr[8];
  383. getAddrOfWorld(wPos, addr);
  384. return chunks->z(addr, 8);
  385. }
  386. Framework::Either<Block*, int> Dimension::zBlock(
  387. Vec3<int> location, OUT Chunk** zChunk) const
  388. {
  389. Chunk* c
  390. = this->zChunk(Game::INSTANCE->getChunkCenter(location.x, location.y));
  391. if (zChunk)
  392. {
  393. *zChunk = c;
  394. }
  395. if (c)
  396. {
  397. location = chunkCoordinates(location);
  398. return c->zBlockAt(location);
  399. }
  400. return 0;
  401. }
  402. Block* Dimension::zRealBlockInstance(Framework::Vec3<int> location) const
  403. {
  404. Chunk* c = zChunk(Game::INSTANCE->getChunkCenter(location.x, location.y));
  405. if (c)
  406. {
  407. location = chunkCoordinates(location);
  408. c->instantiateBlock(location);
  409. auto result = c->zBlockAt(location);
  410. return result.isA() ? result.getA() : 0;
  411. }
  412. return 0;
  413. }
  414. const Block* Dimension::zBlockOrDefault(Framework::Vec3<int> location) const
  415. {
  416. Chunk* c = zChunk(Game::INSTANCE->getChunkCenter(location.x, location.y));
  417. if (c)
  418. {
  419. location = chunkCoordinates(location);
  420. return c->zBlockConst(location);
  421. }
  422. return &NoBlock::INSTANCE;
  423. }
  424. int Dimension::getBlockType(Framework::Vec3<int> location) const
  425. {
  426. Chunk* c = zChunk(Game::INSTANCE->getChunkCenter(location.x, location.y));
  427. if (c)
  428. {
  429. location = chunkCoordinates(location);
  430. return c->getBlockTypeAt(location);
  431. }
  432. return BlockTypeEnum::NO_BLOCK;
  433. }
  434. void Dimension::placeBlock(
  435. Framework::Vec3<int> location, Framework::Either<Block*, int> block)
  436. {
  437. if (block.isB() && block.getB() == BlockTypeEnum::NO_BLOCK) return;
  438. Chunk* c = zChunk(Game::getChunkCenter(location.x, location.y));
  439. if (c)
  440. {
  441. location = chunkCoordinates(location);
  442. if (block.isA())
  443. c->putBlockAt(location, block);
  444. else
  445. {
  446. c->putBlockAt(location, 0);
  447. c->putBlockTypeAt(location, block);
  448. }
  449. }
  450. else if (block.isA())
  451. block.getA()->release();
  452. }
  453. void Dimension::sendBlockInfo(Framework::Vec3<int> location)
  454. {
  455. Chunk* c = zChunk(Game::getChunkCenter(location.x, location.y));
  456. if (c)
  457. {
  458. location = chunkCoordinates(location);
  459. c->sendBlockInfo(location);
  460. }
  461. }
  462. void Dimension::addEntity(Entity* entity)
  463. {
  464. entityCs.lock();
  465. entities->add(entity);
  466. entityCs.unlock();
  467. }
  468. void Dimension::setChunk(Chunk* chunk, Point center)
  469. {
  470. char addr[8];
  471. getAddrOfWorld(center, addr);
  472. if (chunk) map->loadMap(addr, 8, chunk);
  473. chunkCs.lock();
  474. Chunk* old = chunks->get(addr, 8);
  475. if (old)
  476. {
  477. Game::INSTANCE->zTickOrganizer()->removeTickSource(old);
  478. old->prepareRemove();
  479. for (int i = 0; i < chunkList.getEntryCount(); i++)
  480. {
  481. if (chunkList.get(i) == old)
  482. {
  483. chunkList.remove(i);
  484. break;
  485. }
  486. }
  487. for (Entity* entity : old->getEntitiesInChunk())
  488. {
  489. removeEntity(entity->getId());
  490. }
  491. }
  492. chunks->set(addr, 8, chunk);
  493. if (chunk)
  494. {
  495. chunkList.add(chunk);
  496. }
  497. getAddrOfWorld(center + Point(CHUNK_SIZE, 0), addr);
  498. Chunk* zChunk = chunks->z(addr, 8);
  499. if (zChunk)
  500. {
  501. zChunk->setNeighbor(WEST, chunk);
  502. if (chunk)
  503. {
  504. chunk->setNeighbor(EAST, zChunk);
  505. Game::INSTANCE->zGenerator()->postprocessChunk(zChunk);
  506. }
  507. }
  508. getAddrOfWorld(center + Point(-CHUNK_SIZE, 0), addr);
  509. zChunk = chunks->z(addr, 8);
  510. if (zChunk)
  511. {
  512. zChunk->setNeighbor(EAST, chunk);
  513. if (chunk)
  514. {
  515. chunk->setNeighbor(WEST, zChunk);
  516. Game::INSTANCE->zGenerator()->postprocessChunk(zChunk);
  517. }
  518. }
  519. getAddrOfWorld(center + Point(0, CHUNK_SIZE), addr);
  520. zChunk = chunks->z(addr, 8);
  521. if (zChunk)
  522. {
  523. zChunk->setNeighbor(NORTH, chunk);
  524. if (chunk)
  525. {
  526. chunk->setNeighbor(SOUTH, zChunk);
  527. Game::INSTANCE->zGenerator()->postprocessChunk(zChunk);
  528. }
  529. }
  530. getAddrOfWorld(center + Point(0, -CHUNK_SIZE), addr);
  531. zChunk = chunks->z(addr, 8);
  532. if (zChunk)
  533. {
  534. zChunk->setNeighbor(SOUTH, chunk);
  535. if (chunk)
  536. {
  537. chunk->setNeighbor(NORTH, zChunk);
  538. Game::INSTANCE->zGenerator()->postprocessChunk(zChunk);
  539. }
  540. }
  541. DoLaterHandler laterHandler;
  542. if (chunk)
  543. {
  544. chunkCs.unlock();
  545. Game::INSTANCE->zGenerator()->postprocessChunk(chunk);
  546. chunk->setAdded();
  547. for (Entity* entity : chunk->getEntitiesInChunk())
  548. {
  549. addEntity(dynamic_cast<Entity*>(entity->getThis()));
  550. }
  551. cs.lock();
  552. int index = 0;
  553. for (ArrayIterator<RequestQueue> iterator = waitingRequests.begin();
  554. iterator;)
  555. {
  556. Entity* zE = Game::INSTANCE->zEntity(iterator.val().sourceId);
  557. if (zE)
  558. {
  559. if (iterator.val().chunkCenter == chunk->getCenter())
  560. {
  561. chunk->api(iterator.val().request, zE, laterHandler);
  562. iterator.val().request->release();
  563. iterator.remove();
  564. continue;
  565. }
  566. }
  567. else
  568. {
  569. iterator.val().request->release();
  570. iterator.remove();
  571. continue;
  572. }
  573. iterator++;
  574. index++;
  575. }
  576. cs.unlock();
  577. Game::INSTANCE->zTickOrganizer()->addTickSource(chunk);
  578. }
  579. else
  580. {
  581. chunkCs.unlock();
  582. }
  583. if (old)
  584. {
  585. old->onUnloaded();
  586. removedChunksCs.lock();
  587. removedChunks.add(old);
  588. removedChunksCs.unlock();
  589. }
  590. if (chunk) chunk->onLoaded();
  591. laterHandler.execute();
  592. if (chunk)
  593. {
  594. updateLightAtChunkBorders(chunk);
  595. chunk->updateLightSources();
  596. }
  597. }
  598. void Dimension::save(Text worldDir) const
  599. {
  600. File d;
  601. d.setFile(Game::INSTANCE->getWorldDirectory() + "/dim/" + Text(dimensionId)
  602. + "/meta.dim");
  603. d.create();
  604. d.open(File::Style::write);
  605. d.write((char*)&nextStructureId, 8);
  606. d.write((char*)&currentDayTime, 8);
  607. d.close();
  608. Array<Framework::Point> otherChunks;
  609. for (auto chunk = chunkList.begin(); chunk; chunk++)
  610. {
  611. if (!chunk._) continue;
  612. File* file = new File();
  613. Text filePath = worldDir + "/dim/" + dimensionId + "/";
  614. filePath.appendHex(chunk->getCenter().x);
  615. filePath += "_";
  616. filePath.appendHex(chunk->getCenter().y);
  617. filePath += ".chunk";
  618. file->setFile(filePath);
  619. if (file->open(File::Style::write)) chunk->save(file, otherChunks);
  620. file->close();
  621. file->release();
  622. char addr[8];
  623. getAddrOfWorld(chunk->getCenter(), addr);
  624. map->saveMap(addr, 8);
  625. }
  626. // since all chunks were saved otherChunks can be ignored
  627. entityCs.lock();
  628. for (Entity* entity : *entities)
  629. {
  630. if (entity->zType()->getId() == EntityTypeEnum::PLAYER)
  631. {
  632. File pFile;
  633. pFile.setFile(
  634. worldDir + "/player/"
  635. + Game::INSTANCE->getPlayerId(((Player*)entity)->getName()));
  636. pFile.create();
  637. if (pFile.open(File::Style::write))
  638. {
  639. Game::INSTANCE->zEntityType(EntityTypeEnum::PLAYER)
  640. ->saveEntity(entity, &pFile);
  641. pFile.close();
  642. }
  643. }
  644. }
  645. entityCs.unlock();
  646. for (MultiblockStructure* structure : structures)
  647. {
  648. saveStructure(structure);
  649. }
  650. }
  651. int Dimension::getDimensionId() const
  652. {
  653. return dimensionId;
  654. }
  655. bool Dimension::hasChunck(int x, int y) const
  656. {
  657. if (zChunk(Point(x, y))) return 1;
  658. removedChunksCs.lock();
  659. for (Chunk* c : removedChunks)
  660. {
  661. if (c->getCenter().x == x && c->getCenter().y == y)
  662. {
  663. removedChunksCs.unlock();
  664. return 1;
  665. }
  666. }
  667. removedChunksCs.unlock();
  668. return 0;
  669. }
  670. bool Dimension::reviveChunk(int x, int y)
  671. {
  672. chunkCs.lock();
  673. if (zChunk(Point(x, y)))
  674. {
  675. chunkCs.unlock();
  676. return 1;
  677. }
  678. removedChunksCs.lock();
  679. int index = 0;
  680. for (ArrayIterator<Chunk*> i = removedChunks.begin(); i; i++)
  681. {
  682. if (i->getCenter().x == x && i->getCenter().y == y)
  683. {
  684. setChunk(dynamic_cast<Chunk*>(i->getThis()), Point(x, y));
  685. if (index > 0) i.remove();
  686. removedChunksCs.unlock();
  687. chunkCs.unlock();
  688. return 1;
  689. }
  690. index++;
  691. }
  692. removedChunksCs.unlock();
  693. chunkCs.unlock();
  694. return 0;
  695. }
  696. float Dimension::getGravity() const
  697. {
  698. return gravity;
  699. }
  700. void Dimension::removeOldChunks()
  701. {
  702. chunkCs.lock();
  703. int index = 0;
  704. for (Chunk* chunk : chunkList)
  705. {
  706. if (!chunk->hasObservers()) setChunk(0, chunk->getCenter());
  707. index++;
  708. }
  709. chunkCs.unlock();
  710. structurCs.lock();
  711. ArrayIterator<MultiblockStructure*> i = structures.begin();
  712. while (i)
  713. {
  714. if (i->isEmpty())
  715. {
  716. i.remove();
  717. continue;
  718. }
  719. else if (i->isFullyUnloaded())
  720. {
  721. saveStructure(i);
  722. i.remove();
  723. continue;
  724. }
  725. i++;
  726. }
  727. structurCs.unlock();
  728. }
  729. Entity* Dimension::zTarget(Framework::Vec3<float> pos,
  730. Vec3<float> direction,
  731. float maxDistanceSq) const
  732. {
  733. double minDist = 0;
  734. Entity* closestEntity = 0;
  735. entityCs.lock();
  736. for (auto entity : *entities)
  737. {
  738. if (!entity->isRemoved()
  739. && entity->getPosition().distanceSq(pos) <= maxDistanceSq)
  740. {
  741. double dist = entity->getHitDistance(pos, direction);
  742. if (!isnan(dist))
  743. {
  744. if (!closestEntity || dist < minDist)
  745. {
  746. closestEntity = entity;
  747. minDist = dist;
  748. }
  749. }
  750. }
  751. }
  752. entityCs.unlock();
  753. return closestEntity;
  754. }
  755. Entity* Dimension::zEntity(int id) const
  756. {
  757. entityCs.lock();
  758. for (auto entity : *entities)
  759. {
  760. if (!entity->isRemoved() && entity->getId() == id)
  761. {
  762. entityCs.unlock();
  763. return entity;
  764. }
  765. }
  766. entityCs.unlock();
  767. return 0;
  768. }
  769. Entity* Dimension::zNearestEntity(
  770. Framework::Vec3<float> pos, std::function<bool(Entity*)> filter) const
  771. {
  772. Entity* result = 0;
  773. float sqDist = 0;
  774. entityCs.lock();
  775. for (auto entity : *entities)
  776. {
  777. if (!entity->isRemoved() && filter(entity))
  778. {
  779. float d = pos.distanceSq(entity->getPosition());
  780. if (!result || d < sqDist)
  781. {
  782. result = entity;
  783. sqDist = d;
  784. }
  785. }
  786. }
  787. entityCs.unlock();
  788. return result;
  789. }
  790. void Dimension::removeEntity(int id)
  791. {
  792. int index = 0;
  793. entityCs.lock();
  794. for (auto entity : *entities)
  795. {
  796. if (entity->getId() == id)
  797. {
  798. entities->remove(index);
  799. entityCs.unlock();
  800. return;
  801. }
  802. index++;
  803. }
  804. entityCs.unlock();
  805. }
  806. void Dimension::removeSubscriptions(Entity* zEntity)
  807. {
  808. for (Chunk* chunk : chunkList)
  809. chunk->removeObserver(zEntity);
  810. }
  811. void Dimension::updateLightning(Vec3<int> location)
  812. {
  813. lightCs.lock();
  814. lightUpdateQueue.add(location, 0);
  815. lightCs.unlock();
  816. }
  817. void Dimension::updateLightningWithoutWait(Framework::Vec3<int> location)
  818. {
  819. prioLightCs.lock();
  820. priorizedLightUpdateQueue.add(location, 0);
  821. prioLightCs.unlock();
  822. }
  823. void Dimension::updateLightAtChunkBorders(Chunk* zChunk)
  824. {
  825. if (lightUpdateQueue.getEntryCount() > 300000)
  826. {
  827. Logging::warning()
  828. << "light calculation queue is over 300000 blocks long";
  829. }
  830. Point center = zChunk->getCenter();
  831. Chunk* xn = this->zChunk(center - Point(CHUNK_SIZE, 0));
  832. Chunk* xp = this->zChunk(center + Point(CHUNK_SIZE, 0));
  833. Chunk* yn = this->zChunk(center - Point(0, CHUNK_SIZE));
  834. Chunk* yp = this->zChunk(center + Point(0, CHUNK_SIZE));
  835. for (int i = WORLD_HEIGHT - 1; i >= 0; i--)
  836. {
  837. for (int j = 0; j < CHUNK_SIZE; j++)
  838. {
  839. if (xn)
  840. {
  841. unsigned char* light
  842. = xn->getLightData(Vec3<int>(CHUNK_SIZE - 1, j, i));
  843. unsigned char* light2
  844. = zChunk->getLightData(Vec3<int>(0, j, i));
  845. if (*(int*)light != *(int*)light2
  846. || *(int*)(light + 2) != *(int*)(light2 + 2))
  847. {
  848. updateLightning(Vec3<int>(center.x - CHUNK_SIZE / 2 - 1,
  849. center.y - CHUNK_SIZE / 2 + j,
  850. i));
  851. updateLightning(Vec3<int>(center.x - CHUNK_SIZE / 2,
  852. center.y - CHUNK_SIZE / 2 + j,
  853. i));
  854. }
  855. }
  856. if (xp)
  857. {
  858. unsigned char* light = xp->getLightData(Vec3<int>(0, j, i));
  859. unsigned char* light2
  860. = zChunk->getLightData(Vec3<int>(CHUNK_SIZE - 1, j, i));
  861. if (*(int*)light != *(int*)light2
  862. || *(int*)(light + 2) != *(int*)(light2 + 2))
  863. {
  864. updateLightning(Vec3<int>(center.x + CHUNK_SIZE / 2 - 1,
  865. center.y - CHUNK_SIZE / 2 + j,
  866. i));
  867. updateLightning(Vec3<int>(center.x + CHUNK_SIZE / 2,
  868. center.y - CHUNK_SIZE / 2 + j,
  869. i));
  870. }
  871. }
  872. if (yn)
  873. {
  874. unsigned char* light
  875. = yn->getLightData(Vec3<int>(j, CHUNK_SIZE - 1, i));
  876. unsigned char* light2
  877. = zChunk->getLightData(Vec3<int>(j, 0, i));
  878. if (*(int*)light != *(int*)light2
  879. || *(int*)(light + 2) != *(int*)(light2 + 2))
  880. {
  881. updateLightning(Vec3<int>(center.x - CHUNK_SIZE / 2 + j,
  882. center.y - CHUNK_SIZE / 2 - 1,
  883. i));
  884. updateLightning(Vec3<int>(center.x - CHUNK_SIZE / 2 + j,
  885. center.y - CHUNK_SIZE / 2,
  886. i));
  887. }
  888. }
  889. if (yp)
  890. {
  891. unsigned char* light = yp->getLightData(Vec3<int>(j, 0, i));
  892. unsigned char* light2
  893. = zChunk->getLightData(Vec3<int>(j, CHUNK_SIZE - 1, i));
  894. if (*(int*)light != *(int*)light2
  895. || *(int*)(light + 2) != *(int*)(light2 + 2))
  896. {
  897. updateLightning(Vec3<int>(center.x - CHUNK_SIZE / 2 + j,
  898. center.y + CHUNK_SIZE / 2 - 1,
  899. i));
  900. updateLightning(Vec3<int>(center.x - CHUNK_SIZE / 2 + j,
  901. center.y + CHUNK_SIZE / 2,
  902. i));
  903. }
  904. }
  905. }
  906. }
  907. }
  908. __int64 Dimension::getNextStructureId()
  909. {
  910. return nextStructureId++;
  911. }
  912. void Dimension::addStructure(MultiblockStructure* structure)
  913. {
  914. structurCs.lock();
  915. structures.add(structure);
  916. structurCs.unlock();
  917. }
  918. MultiblockStructure* Dimension::zStructureByPosition(
  919. Framework::Vec3<int> uniquePosition)
  920. {
  921. __int64 id = structureManager->getStructureId(uniquePosition);
  922. if (id > 0)
  923. {
  924. return zStructureById(id);
  925. }
  926. return 0;
  927. }
  928. MultiblockStructure* Dimension::zStructureById(__int64 id)
  929. {
  930. structurCs.lock();
  931. for (MultiblockStructure* str : structures)
  932. {
  933. if (str->getStructureId() == id)
  934. {
  935. structurCs.unlock();
  936. return str;
  937. }
  938. }
  939. MultiblockStructure* structure = structureManager->loadStructure(id);
  940. if (structure)
  941. {
  942. structures.add(structure);
  943. structurCs.unlock();
  944. return structure;
  945. }
  946. Logging::warning() << "did not find Structure information file '"
  947. << std::hex << id << "'.";
  948. structurCs.unlock();
  949. return 0;
  950. }
  951. void Dimension::requestStopAndWait()
  952. {
  953. stop = 1;
  954. waitForThread(1000000);
  955. }
  956. void Dimension::updateMap(int x, int y, int height)
  957. {
  958. chunkCs.lock();
  959. int h1 = height % 2 == 0 ? height : height - 1;
  960. int h2 = h1 + 1;
  961. const Block* b1 = zBlockOrDefault({x, y, h1});
  962. const Block* b2 = zBlockOrDefault({x, y, h2});
  963. bool visible = 1;
  964. if (h2 != WORLD_HEIGHT - 1)
  965. {
  966. const Block* b3 = zBlockOrDefault({x, y, h2 + 1});
  967. visible = b3->isPassable() || b3->isTransparent();
  968. }
  969. int color1
  970. = (b2->isPassable() || b2->isTransparent()) ? b1->getMapColor() : 0;
  971. int color2 = visible ? b2->getMapColor() : 0;
  972. int color1m = 0;
  973. int color2m = 0;
  974. if (h1 > 0)
  975. {
  976. const Block* b1m = zBlockOrDefault({x, y, h1 - 2});
  977. const Block* b2m = zBlockOrDefault({x, y, h1 - 1});
  978. color1m = (b2m->isPassable() || b2m->isTransparent())
  979. ? b1m->getMapColor()
  980. : 0;
  981. color2m = (b1->isPassable() || b1->isTransparent()) ? b2m->getMapColor()
  982. : 0;
  983. }
  984. char addr[8];
  985. Point center = Game::INSTANCE->getChunkCenter(x, y);
  986. getAddrOfWorld(center, addr);
  987. ChunkMap* cMap = map->getMap(addr, 8, center);
  988. if (cMap)
  989. {
  990. Framework::Vec3<int> chunkLocation = chunkCoordinates({x, y, height});
  991. if (cMap->update((char)chunkLocation.x,
  992. (char)chunkLocation.y,
  993. (unsigned char)(chunkLocation.z / 2),
  994. color1,
  995. color2)
  996. || (h1 > 0
  997. && cMap->update((char)chunkLocation.x,
  998. (char)chunkLocation.y,
  999. (unsigned char)(chunkLocation.z / 2 - 1),
  1000. color1m,
  1001. color2m)))
  1002. {
  1003. map->onMapUpdated(addr, 8);
  1004. }
  1005. }
  1006. chunkCs.unlock();
  1007. }
  1008. int Dimension::getChunkCount() const
  1009. {
  1010. return chunkList.getEntryCount();
  1011. }
  1012. double Dimension::getCurrentDayTime() const
  1013. {
  1014. return currentDayTime;
  1015. }
  1016. double Dimension::getNightDuration() const
  1017. {
  1018. return nightDuration;
  1019. }
  1020. double Dimension::getNightTransitionDuration() const
  1021. {
  1022. return nightTransitionDuration;
  1023. }
  1024. double Dimension::getDayDuration() const
  1025. {
  1026. return dayDuration;
  1027. }