map.cpp 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992
  1. /*
  2. Minetest
  3. Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
  4. This program is free software; you can redistribute it and/or modify
  5. it under the terms of the GNU Lesser General Public License as published by
  6. the Free Software Foundation; either version 2.1 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public License along
  13. with this program; if not, write to the Free Software Foundation, Inc.,
  14. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  15. */
  16. #include "map.h"
  17. #include "mapsector.h"
  18. #include "mapblock.h"
  19. #include "filesys.h"
  20. #include "voxel.h"
  21. #include "voxelalgorithms.h"
  22. #include "porting.h"
  23. #include "serialization.h"
  24. #include "nodemetadata.h"
  25. #include "settings.h"
  26. #include "log.h"
  27. #include "profiler.h"
  28. #include "nodedef.h"
  29. #include "gamedef.h"
  30. #include "util/directiontables.h"
  31. #include "util/basic_macros.h"
  32. #include "rollback_interface.h"
  33. #include "environment.h"
  34. #include "reflowscan.h"
  35. #include "emerge.h"
  36. #include "mapgen/mapgen_v6.h"
  37. #include "mapgen/mg_biome.h"
  38. #include "config.h"
  39. #include "server.h"
  40. #include "database/database.h"
  41. #include "database/database-dummy.h"
  42. #include "database/database-sqlite3.h"
  43. #include "script/scripting_server.h"
  44. #include <deque>
  45. #include <queue>
  46. #if USE_LEVELDB
  47. #include "database/database-leveldb.h"
  48. #endif
  49. #if USE_REDIS
  50. #include "database/database-redis.h"
  51. #endif
  52. #if USE_POSTGRESQL
  53. #include "database/database-postgresql.h"
  54. #endif
  55. /*
  56. Map
  57. */
  58. Map::Map(IGameDef *gamedef):
  59. m_gamedef(gamedef),
  60. m_nodedef(gamedef->ndef())
  61. {
  62. }
  63. Map::~Map()
  64. {
  65. /*
  66. Free all MapSectors
  67. */
  68. for (auto &sector : m_sectors) {
  69. delete sector.second;
  70. }
  71. }
  72. void Map::addEventReceiver(MapEventReceiver *event_receiver)
  73. {
  74. m_event_receivers.insert(event_receiver);
  75. }
  76. void Map::removeEventReceiver(MapEventReceiver *event_receiver)
  77. {
  78. m_event_receivers.erase(event_receiver);
  79. }
  80. void Map::dispatchEvent(const MapEditEvent &event)
  81. {
  82. for (MapEventReceiver *event_receiver : m_event_receivers) {
  83. event_receiver->onMapEditEvent(event);
  84. }
  85. }
  86. MapSector * Map::getSectorNoGenerateNoLock(v2s16 p)
  87. {
  88. if(m_sector_cache != NULL && p == m_sector_cache_p){
  89. MapSector * sector = m_sector_cache;
  90. return sector;
  91. }
  92. std::map<v2s16, MapSector*>::iterator n = m_sectors.find(p);
  93. if (n == m_sectors.end())
  94. return NULL;
  95. MapSector *sector = n->second;
  96. // Cache the last result
  97. m_sector_cache_p = p;
  98. m_sector_cache = sector;
  99. return sector;
  100. }
  101. MapSector * Map::getSectorNoGenerate(v2s16 p)
  102. {
  103. return getSectorNoGenerateNoLock(p);
  104. }
  105. MapBlock * Map::getBlockNoCreateNoEx(v3s16 p3d)
  106. {
  107. v2s16 p2d(p3d.X, p3d.Z);
  108. MapSector * sector = getSectorNoGenerate(p2d);
  109. if(sector == NULL)
  110. return NULL;
  111. MapBlock *block = sector->getBlockNoCreateNoEx(p3d.Y);
  112. return block;
  113. }
  114. MapBlock * Map::getBlockNoCreate(v3s16 p3d)
  115. {
  116. MapBlock *block = getBlockNoCreateNoEx(p3d);
  117. if(block == NULL)
  118. throw InvalidPositionException();
  119. return block;
  120. }
  121. bool Map::isNodeUnderground(v3s16 p)
  122. {
  123. v3s16 blockpos = getNodeBlockPos(p);
  124. MapBlock *block = getBlockNoCreateNoEx(blockpos);
  125. return block && block->getIsUnderground();
  126. }
  127. bool Map::isValidPosition(v3s16 p)
  128. {
  129. v3s16 blockpos = getNodeBlockPos(p);
  130. MapBlock *block = getBlockNoCreateNoEx(blockpos);
  131. return (block != NULL);
  132. }
  133. // Returns a CONTENT_IGNORE node if not found
  134. MapNode Map::getNode(v3s16 p, bool *is_valid_position)
  135. {
  136. v3s16 blockpos = getNodeBlockPos(p);
  137. MapBlock *block = getBlockNoCreateNoEx(blockpos);
  138. if (block == NULL) {
  139. if (is_valid_position != NULL)
  140. *is_valid_position = false;
  141. return {CONTENT_IGNORE};
  142. }
  143. v3s16 relpos = p - blockpos*MAP_BLOCKSIZE;
  144. bool is_valid_p;
  145. MapNode node = block->getNodeNoCheck(relpos, &is_valid_p);
  146. if (is_valid_position != NULL)
  147. *is_valid_position = is_valid_p;
  148. return node;
  149. }
  150. // throws InvalidPositionException if not found
  151. void Map::setNode(v3s16 p, MapNode & n)
  152. {
  153. v3s16 blockpos = getNodeBlockPos(p);
  154. MapBlock *block = getBlockNoCreate(blockpos);
  155. v3s16 relpos = p - blockpos*MAP_BLOCKSIZE;
  156. // Never allow placing CONTENT_IGNORE, it causes problems
  157. if(n.getContent() == CONTENT_IGNORE){
  158. bool temp_bool;
  159. errorstream<<"Map::setNode(): Not allowing to place CONTENT_IGNORE"
  160. <<" while trying to replace \""
  161. <<m_nodedef->get(block->getNodeNoCheck(relpos, &temp_bool)).name
  162. <<"\" at "<<PP(p)<<" (block "<<PP(blockpos)<<")"<<std::endl;
  163. return;
  164. }
  165. block->setNodeNoCheck(relpos, n);
  166. }
  167. void Map::addNodeAndUpdate(v3s16 p, MapNode n,
  168. std::map<v3s16, MapBlock*> &modified_blocks,
  169. bool remove_metadata)
  170. {
  171. // Collect old node for rollback
  172. RollbackNode rollback_oldnode(this, p, m_gamedef);
  173. // This is needed for updating the lighting
  174. MapNode oldnode = getNode(p);
  175. // Remove node metadata
  176. if (remove_metadata) {
  177. removeNodeMetadata(p);
  178. }
  179. // Set the node on the map
  180. // Ignore light (because calling voxalgo::update_lighting_nodes)
  181. n.setLight(LIGHTBANK_DAY, 0, m_nodedef);
  182. n.setLight(LIGHTBANK_NIGHT, 0, m_nodedef);
  183. setNode(p, n);
  184. // Update lighting
  185. std::vector<std::pair<v3s16, MapNode> > oldnodes;
  186. oldnodes.emplace_back(p, oldnode);
  187. voxalgo::update_lighting_nodes(this, oldnodes, modified_blocks);
  188. for (auto &modified_block : modified_blocks) {
  189. modified_block.second->expireDayNightDiff();
  190. }
  191. // Report for rollback
  192. if(m_gamedef->rollback())
  193. {
  194. RollbackNode rollback_newnode(this, p, m_gamedef);
  195. RollbackAction action;
  196. action.setSetNode(p, rollback_oldnode, rollback_newnode);
  197. m_gamedef->rollback()->reportAction(action);
  198. }
  199. /*
  200. Add neighboring liquid nodes and this node to transform queue.
  201. (it's vital for the node itself to get updated last, if it was removed.)
  202. */
  203. for (const v3s16 &dir : g_7dirs) {
  204. v3s16 p2 = p + dir;
  205. bool is_valid_position;
  206. MapNode n2 = getNode(p2, &is_valid_position);
  207. if(is_valid_position &&
  208. (m_nodedef->get(n2).isLiquid() ||
  209. n2.getContent() == CONTENT_AIR))
  210. m_transforming_liquid.push_back(p2);
  211. }
  212. }
  213. void Map::removeNodeAndUpdate(v3s16 p,
  214. std::map<v3s16, MapBlock*> &modified_blocks)
  215. {
  216. addNodeAndUpdate(p, MapNode(CONTENT_AIR), modified_blocks, true);
  217. }
  218. bool Map::addNodeWithEvent(v3s16 p, MapNode n, bool remove_metadata)
  219. {
  220. MapEditEvent event;
  221. event.type = remove_metadata ? MEET_ADDNODE : MEET_SWAPNODE;
  222. event.p = p;
  223. event.n = n;
  224. bool succeeded = true;
  225. try{
  226. std::map<v3s16, MapBlock*> modified_blocks;
  227. addNodeAndUpdate(p, n, modified_blocks, remove_metadata);
  228. // Copy modified_blocks to event
  229. for (auto &modified_block : modified_blocks) {
  230. event.modified_blocks.insert(modified_block.first);
  231. }
  232. }
  233. catch(InvalidPositionException &e){
  234. succeeded = false;
  235. }
  236. dispatchEvent(event);
  237. return succeeded;
  238. }
  239. bool Map::removeNodeWithEvent(v3s16 p)
  240. {
  241. MapEditEvent event;
  242. event.type = MEET_REMOVENODE;
  243. event.p = p;
  244. bool succeeded = true;
  245. try{
  246. std::map<v3s16, MapBlock*> modified_blocks;
  247. removeNodeAndUpdate(p, modified_blocks);
  248. // Copy modified_blocks to event
  249. for (auto &modified_block : modified_blocks) {
  250. event.modified_blocks.insert(modified_block.first);
  251. }
  252. }
  253. catch(InvalidPositionException &e){
  254. succeeded = false;
  255. }
  256. dispatchEvent(event);
  257. return succeeded;
  258. }
  259. struct TimeOrderedMapBlock {
  260. MapSector *sect;
  261. MapBlock *block;
  262. TimeOrderedMapBlock(MapSector *sect, MapBlock *block) :
  263. sect(sect),
  264. block(block)
  265. {}
  266. bool operator<(const TimeOrderedMapBlock &b) const
  267. {
  268. return block->getUsageTimer() < b.block->getUsageTimer();
  269. };
  270. };
  271. /*
  272. Updates usage timers
  273. */
  274. void Map::timerUpdate(float dtime, float unload_timeout, u32 max_loaded_blocks,
  275. std::vector<v3s16> *unloaded_blocks)
  276. {
  277. bool save_before_unloading = (mapType() == MAPTYPE_SERVER);
  278. // Profile modified reasons
  279. Profiler modprofiler;
  280. std::vector<v2s16> sector_deletion_queue;
  281. u32 deleted_blocks_count = 0;
  282. u32 saved_blocks_count = 0;
  283. u32 block_count_all = 0;
  284. beginSave();
  285. // If there is no practical limit, we spare creation of mapblock_queue
  286. if (max_loaded_blocks == U32_MAX) {
  287. for (auto &sector_it : m_sectors) {
  288. MapSector *sector = sector_it.second;
  289. bool all_blocks_deleted = true;
  290. MapBlockVect blocks;
  291. sector->getBlocks(blocks);
  292. for (MapBlock *block : blocks) {
  293. block->incrementUsageTimer(dtime);
  294. if (block->refGet() == 0
  295. && block->getUsageTimer() > unload_timeout) {
  296. v3s16 p = block->getPos();
  297. // Save if modified
  298. if (block->getModified() != MOD_STATE_CLEAN
  299. && save_before_unloading) {
  300. modprofiler.add(block->getModifiedReasonString(), 1);
  301. if (!saveBlock(block))
  302. continue;
  303. saved_blocks_count++;
  304. }
  305. // Delete from memory
  306. sector->deleteBlock(block);
  307. if (unloaded_blocks)
  308. unloaded_blocks->push_back(p);
  309. deleted_blocks_count++;
  310. } else {
  311. all_blocks_deleted = false;
  312. block_count_all++;
  313. }
  314. }
  315. if (all_blocks_deleted) {
  316. sector_deletion_queue.push_back(sector_it.first);
  317. }
  318. }
  319. } else {
  320. std::priority_queue<TimeOrderedMapBlock> mapblock_queue;
  321. for (auto &sector_it : m_sectors) {
  322. MapSector *sector = sector_it.second;
  323. MapBlockVect blocks;
  324. sector->getBlocks(blocks);
  325. for (MapBlock *block : blocks) {
  326. block->incrementUsageTimer(dtime);
  327. mapblock_queue.push(TimeOrderedMapBlock(sector, block));
  328. }
  329. }
  330. block_count_all = mapblock_queue.size();
  331. // Delete old blocks, and blocks over the limit from the memory
  332. while (!mapblock_queue.empty() && (mapblock_queue.size() > max_loaded_blocks
  333. || mapblock_queue.top().block->getUsageTimer() > unload_timeout)) {
  334. TimeOrderedMapBlock b = mapblock_queue.top();
  335. mapblock_queue.pop();
  336. MapBlock *block = b.block;
  337. if (block->refGet() != 0)
  338. continue;
  339. v3s16 p = block->getPos();
  340. // Save if modified
  341. if (block->getModified() != MOD_STATE_CLEAN && save_before_unloading) {
  342. modprofiler.add(block->getModifiedReasonString(), 1);
  343. if (!saveBlock(block))
  344. continue;
  345. saved_blocks_count++;
  346. }
  347. // Delete from memory
  348. b.sect->deleteBlock(block);
  349. if (unloaded_blocks)
  350. unloaded_blocks->push_back(p);
  351. deleted_blocks_count++;
  352. block_count_all--;
  353. }
  354. // Delete empty sectors
  355. for (auto &sector_it : m_sectors) {
  356. if (sector_it.second->empty()) {
  357. sector_deletion_queue.push_back(sector_it.first);
  358. }
  359. }
  360. }
  361. endSave();
  362. // Finally delete the empty sectors
  363. deleteSectors(sector_deletion_queue);
  364. if(deleted_blocks_count != 0)
  365. {
  366. PrintInfo(infostream); // ServerMap/ClientMap:
  367. infostream<<"Unloaded "<<deleted_blocks_count
  368. <<" blocks from memory";
  369. if(save_before_unloading)
  370. infostream<<", of which "<<saved_blocks_count<<" were written";
  371. infostream<<", "<<block_count_all<<" blocks in memory";
  372. infostream<<"."<<std::endl;
  373. if(saved_blocks_count != 0){
  374. PrintInfo(infostream); // ServerMap/ClientMap:
  375. infostream<<"Blocks modified by: "<<std::endl;
  376. modprofiler.print(infostream);
  377. }
  378. }
  379. }
  380. void Map::unloadUnreferencedBlocks(std::vector<v3s16> *unloaded_blocks)
  381. {
  382. timerUpdate(0.0, -1.0, 0, unloaded_blocks);
  383. }
  384. void Map::deleteSectors(std::vector<v2s16> &sectorList)
  385. {
  386. for (v2s16 j : sectorList) {
  387. MapSector *sector = m_sectors[j];
  388. // If sector is in sector cache, remove it from there
  389. if(m_sector_cache == sector)
  390. m_sector_cache = NULL;
  391. // Remove from map and delete
  392. m_sectors.erase(j);
  393. delete sector;
  394. }
  395. }
  396. void Map::PrintInfo(std::ostream &out)
  397. {
  398. out<<"Map: ";
  399. }
  400. #define WATER_DROP_BOOST 4
  401. const static v3s16 liquid_6dirs[6] = {
  402. // order: upper before same level before lower
  403. v3s16( 0, 1, 0),
  404. v3s16( 0, 0, 1),
  405. v3s16( 1, 0, 0),
  406. v3s16( 0, 0,-1),
  407. v3s16(-1, 0, 0),
  408. v3s16( 0,-1, 0)
  409. };
  410. enum NeighborType : u8 {
  411. NEIGHBOR_UPPER,
  412. NEIGHBOR_SAME_LEVEL,
  413. NEIGHBOR_LOWER
  414. };
  415. struct NodeNeighbor {
  416. MapNode n;
  417. NeighborType t;
  418. v3s16 p;
  419. NodeNeighbor()
  420. : n(CONTENT_AIR), t(NEIGHBOR_SAME_LEVEL)
  421. { }
  422. NodeNeighbor(const MapNode &node, NeighborType n_type, const v3s16 &pos)
  423. : n(node),
  424. t(n_type),
  425. p(pos)
  426. { }
  427. };
  428. void Map::transforming_liquid_add(v3s16 p) {
  429. m_transforming_liquid.push_back(p);
  430. }
  431. void Map::transformLiquids(std::map<v3s16, MapBlock*> &modified_blocks,
  432. ServerEnvironment *env)
  433. {
  434. u32 loopcount = 0;
  435. u32 initial_size = m_transforming_liquid.size();
  436. /*if(initial_size != 0)
  437. infostream<<"transformLiquids(): initial_size="<<initial_size<<std::endl;*/
  438. // list of nodes that due to viscosity have not reached their max level height
  439. std::deque<v3s16> must_reflow;
  440. std::vector<std::pair<v3s16, MapNode> > changed_nodes;
  441. u32 liquid_loop_max = g_settings->getS32("liquid_loop_max");
  442. u32 loop_max = liquid_loop_max;
  443. while (m_transforming_liquid.size() != 0)
  444. {
  445. // This should be done here so that it is done when continue is used
  446. if (loopcount >= initial_size || loopcount >= loop_max)
  447. break;
  448. loopcount++;
  449. /*
  450. Get a queued transforming liquid node
  451. */
  452. v3s16 p0 = m_transforming_liquid.front();
  453. m_transforming_liquid.pop_front();
  454. MapNode n0 = getNode(p0);
  455. /*
  456. Collect information about current node
  457. */
  458. s8 liquid_level = -1;
  459. // The liquid node which will be placed there if
  460. // the liquid flows into this node.
  461. content_t liquid_kind = CONTENT_IGNORE;
  462. // The node which will be placed there if liquid
  463. // can't flow into this node.
  464. content_t floodable_node = CONTENT_AIR;
  465. const ContentFeatures &cf = m_nodedef->get(n0);
  466. LiquidType liquid_type = cf.liquid_type;
  467. switch (liquid_type) {
  468. case LIQUID_SOURCE:
  469. liquid_level = LIQUID_LEVEL_SOURCE;
  470. liquid_kind = cf.liquid_alternative_flowing_id;
  471. break;
  472. case LIQUID_FLOWING:
  473. liquid_level = (n0.param2 & LIQUID_LEVEL_MASK);
  474. liquid_kind = n0.getContent();
  475. break;
  476. case LIQUID_NONE:
  477. // if this node is 'floodable', it *could* be transformed
  478. // into a liquid, otherwise, continue with the next node.
  479. if (!cf.floodable)
  480. continue;
  481. floodable_node = n0.getContent();
  482. liquid_kind = CONTENT_AIR;
  483. break;
  484. }
  485. /*
  486. Collect information about the environment
  487. */
  488. NodeNeighbor sources[6]; // surrounding sources
  489. int num_sources = 0;
  490. NodeNeighbor flows[6]; // surrounding flowing liquid nodes
  491. int num_flows = 0;
  492. NodeNeighbor airs[6]; // surrounding air
  493. int num_airs = 0;
  494. NodeNeighbor neutrals[6]; // nodes that are solid or another kind of liquid
  495. int num_neutrals = 0;
  496. bool flowing_down = false;
  497. bool ignored_sources = false;
  498. for (u16 i = 0; i < 6; i++) {
  499. NeighborType nt = NEIGHBOR_SAME_LEVEL;
  500. switch (i) {
  501. case 0:
  502. nt = NEIGHBOR_UPPER;
  503. break;
  504. case 5:
  505. nt = NEIGHBOR_LOWER;
  506. break;
  507. default:
  508. break;
  509. }
  510. v3s16 npos = p0 + liquid_6dirs[i];
  511. NodeNeighbor nb(getNode(npos), nt, npos);
  512. const ContentFeatures &cfnb = m_nodedef->get(nb.n);
  513. switch (m_nodedef->get(nb.n.getContent()).liquid_type) {
  514. case LIQUID_NONE:
  515. if (cfnb.floodable) {
  516. airs[num_airs++] = nb;
  517. // if the current node is a water source the neighbor
  518. // should be enqueded for transformation regardless of whether the
  519. // current node changes or not.
  520. if (nb.t != NEIGHBOR_UPPER && liquid_type != LIQUID_NONE)
  521. m_transforming_liquid.push_back(npos);
  522. // if the current node happens to be a flowing node, it will start to flow down here.
  523. if (nb.t == NEIGHBOR_LOWER)
  524. flowing_down = true;
  525. } else {
  526. neutrals[num_neutrals++] = nb;
  527. if (nb.n.getContent() == CONTENT_IGNORE) {
  528. // If node below is ignore prevent water from
  529. // spreading outwards and otherwise prevent from
  530. // flowing away as ignore node might be the source
  531. if (nb.t == NEIGHBOR_LOWER)
  532. flowing_down = true;
  533. else
  534. ignored_sources = true;
  535. }
  536. }
  537. break;
  538. case LIQUID_SOURCE:
  539. // if this node is not (yet) of a liquid type, choose the first liquid type we encounter
  540. if (liquid_kind == CONTENT_AIR)
  541. liquid_kind = cfnb.liquid_alternative_flowing_id;
  542. if (cfnb.liquid_alternative_flowing_id != liquid_kind) {
  543. neutrals[num_neutrals++] = nb;
  544. } else {
  545. // Do not count bottom source, it will screw things up
  546. if(nt != NEIGHBOR_LOWER)
  547. sources[num_sources++] = nb;
  548. }
  549. break;
  550. case LIQUID_FLOWING:
  551. if (nb.t != NEIGHBOR_SAME_LEVEL ||
  552. (nb.n.param2 & LIQUID_FLOW_DOWN_MASK) != LIQUID_FLOW_DOWN_MASK) {
  553. // if this node is not (yet) of a liquid type, choose the first liquid type we encounter
  554. // but exclude falling liquids on the same level, they cannot flow here anyway
  555. if (liquid_kind == CONTENT_AIR)
  556. liquid_kind = cfnb.liquid_alternative_flowing_id;
  557. }
  558. if (cfnb.liquid_alternative_flowing_id != liquid_kind) {
  559. neutrals[num_neutrals++] = nb;
  560. } else {
  561. flows[num_flows++] = nb;
  562. if (nb.t == NEIGHBOR_LOWER)
  563. flowing_down = true;
  564. }
  565. break;
  566. }
  567. }
  568. /*
  569. decide on the type (and possibly level) of the current node
  570. */
  571. content_t new_node_content;
  572. s8 new_node_level = -1;
  573. s8 max_node_level = -1;
  574. u8 range = m_nodedef->get(liquid_kind).liquid_range;
  575. if (range > LIQUID_LEVEL_MAX + 1)
  576. range = LIQUID_LEVEL_MAX + 1;
  577. if ((num_sources >= 2 && m_nodedef->get(liquid_kind).liquid_renewable) || liquid_type == LIQUID_SOURCE) {
  578. // liquid_kind will be set to either the flowing alternative of the node (if it's a liquid)
  579. // or the flowing alternative of the first of the surrounding sources (if it's air), so
  580. // it's perfectly safe to use liquid_kind here to determine the new node content.
  581. new_node_content = m_nodedef->get(liquid_kind).liquid_alternative_source_id;
  582. } else if (num_sources >= 1 && sources[0].t != NEIGHBOR_LOWER) {
  583. // liquid_kind is set properly, see above
  584. max_node_level = new_node_level = LIQUID_LEVEL_MAX;
  585. if (new_node_level >= (LIQUID_LEVEL_MAX + 1 - range))
  586. new_node_content = liquid_kind;
  587. else
  588. new_node_content = floodable_node;
  589. } else if (ignored_sources && liquid_level >= 0) {
  590. // Maybe there are neighbouring sources that aren't loaded yet
  591. // so prevent flowing away.
  592. new_node_level = liquid_level;
  593. new_node_content = liquid_kind;
  594. } else {
  595. // no surrounding sources, so get the maximum level that can flow into this node
  596. for (u16 i = 0; i < num_flows; i++) {
  597. u8 nb_liquid_level = (flows[i].n.param2 & LIQUID_LEVEL_MASK);
  598. switch (flows[i].t) {
  599. case NEIGHBOR_UPPER:
  600. if (nb_liquid_level + WATER_DROP_BOOST > max_node_level) {
  601. max_node_level = LIQUID_LEVEL_MAX;
  602. if (nb_liquid_level + WATER_DROP_BOOST < LIQUID_LEVEL_MAX)
  603. max_node_level = nb_liquid_level + WATER_DROP_BOOST;
  604. } else if (nb_liquid_level > max_node_level) {
  605. max_node_level = nb_liquid_level;
  606. }
  607. break;
  608. case NEIGHBOR_LOWER:
  609. break;
  610. case NEIGHBOR_SAME_LEVEL:
  611. if ((flows[i].n.param2 & LIQUID_FLOW_DOWN_MASK) != LIQUID_FLOW_DOWN_MASK &&
  612. nb_liquid_level > 0 && nb_liquid_level - 1 > max_node_level)
  613. max_node_level = nb_liquid_level - 1;
  614. break;
  615. }
  616. }
  617. u8 viscosity = m_nodedef->get(liquid_kind).liquid_viscosity;
  618. if (viscosity > 1 && max_node_level != liquid_level) {
  619. // amount to gain, limited by viscosity
  620. // must be at least 1 in absolute value
  621. s8 level_inc = max_node_level - liquid_level;
  622. if (level_inc < -viscosity || level_inc > viscosity)
  623. new_node_level = liquid_level + level_inc/viscosity;
  624. else if (level_inc < 0)
  625. new_node_level = liquid_level - 1;
  626. else if (level_inc > 0)
  627. new_node_level = liquid_level + 1;
  628. if (new_node_level != max_node_level)
  629. must_reflow.push_back(p0);
  630. } else {
  631. new_node_level = max_node_level;
  632. }
  633. if (max_node_level >= (LIQUID_LEVEL_MAX + 1 - range))
  634. new_node_content = liquid_kind;
  635. else
  636. new_node_content = floodable_node;
  637. }
  638. /*
  639. check if anything has changed. if not, just continue with the next node.
  640. */
  641. if (new_node_content == n0.getContent() &&
  642. (m_nodedef->get(n0.getContent()).liquid_type != LIQUID_FLOWING ||
  643. ((n0.param2 & LIQUID_LEVEL_MASK) == (u8)new_node_level &&
  644. ((n0.param2 & LIQUID_FLOW_DOWN_MASK) == LIQUID_FLOW_DOWN_MASK)
  645. == flowing_down)))
  646. continue;
  647. /*
  648. update the current node
  649. */
  650. MapNode n00 = n0;
  651. //bool flow_down_enabled = (flowing_down && ((n0.param2 & LIQUID_FLOW_DOWN_MASK) != LIQUID_FLOW_DOWN_MASK));
  652. if (m_nodedef->get(new_node_content).liquid_type == LIQUID_FLOWING) {
  653. // set level to last 3 bits, flowing down bit to 4th bit
  654. n0.param2 = (flowing_down ? LIQUID_FLOW_DOWN_MASK : 0x00) | (new_node_level & LIQUID_LEVEL_MASK);
  655. } else {
  656. // set the liquid level and flow bits to 0
  657. n0.param2 &= ~(LIQUID_LEVEL_MASK | LIQUID_FLOW_DOWN_MASK);
  658. }
  659. // change the node.
  660. n0.setContent(new_node_content);
  661. // on_flood() the node
  662. if (floodable_node != CONTENT_AIR) {
  663. if (env->getScriptIface()->node_on_flood(p0, n00, n0))
  664. continue;
  665. }
  666. // Ignore light (because calling voxalgo::update_lighting_nodes)
  667. n0.setLight(LIGHTBANK_DAY, 0, m_nodedef);
  668. n0.setLight(LIGHTBANK_NIGHT, 0, m_nodedef);
  669. // Find out whether there is a suspect for this action
  670. std::string suspect;
  671. if (m_gamedef->rollback())
  672. suspect = m_gamedef->rollback()->getSuspect(p0, 83, 1);
  673. if (m_gamedef->rollback() && !suspect.empty()) {
  674. // Blame suspect
  675. RollbackScopeActor rollback_scope(m_gamedef->rollback(), suspect, true);
  676. // Get old node for rollback
  677. RollbackNode rollback_oldnode(this, p0, m_gamedef);
  678. // Set node
  679. setNode(p0, n0);
  680. // Report
  681. RollbackNode rollback_newnode(this, p0, m_gamedef);
  682. RollbackAction action;
  683. action.setSetNode(p0, rollback_oldnode, rollback_newnode);
  684. m_gamedef->rollback()->reportAction(action);
  685. } else {
  686. // Set node
  687. setNode(p0, n0);
  688. }
  689. v3s16 blockpos = getNodeBlockPos(p0);
  690. MapBlock *block = getBlockNoCreateNoEx(blockpos);
  691. if (block != NULL) {
  692. modified_blocks[blockpos] = block;
  693. changed_nodes.emplace_back(p0, n00);
  694. }
  695. /*
  696. enqueue neighbors for update if neccessary
  697. */
  698. switch (m_nodedef->get(n0.getContent()).liquid_type) {
  699. case LIQUID_SOURCE:
  700. case LIQUID_FLOWING:
  701. // make sure source flows into all neighboring nodes
  702. for (u16 i = 0; i < num_flows; i++)
  703. if (flows[i].t != NEIGHBOR_UPPER)
  704. m_transforming_liquid.push_back(flows[i].p);
  705. for (u16 i = 0; i < num_airs; i++)
  706. if (airs[i].t != NEIGHBOR_UPPER)
  707. m_transforming_liquid.push_back(airs[i].p);
  708. break;
  709. case LIQUID_NONE:
  710. // this flow has turned to air; neighboring flows might need to do the same
  711. for (u16 i = 0; i < num_flows; i++)
  712. m_transforming_liquid.push_back(flows[i].p);
  713. break;
  714. }
  715. }
  716. //infostream<<"Map::transformLiquids(): loopcount="<<loopcount<<std::endl;
  717. for (auto &iter : must_reflow)
  718. m_transforming_liquid.push_back(iter);
  719. voxalgo::update_lighting_nodes(this, changed_nodes, modified_blocks);
  720. env->getScriptIface()->on_liquid_transformed(changed_nodes);
  721. /* ----------------------------------------------------------------------
  722. * Manage the queue so that it does not grow indefinately
  723. */
  724. u16 time_until_purge = g_settings->getU16("liquid_queue_purge_time");
  725. if (time_until_purge == 0)
  726. return; // Feature disabled
  727. time_until_purge *= 1000; // seconds -> milliseconds
  728. u64 curr_time = porting::getTimeMs();
  729. u32 prev_unprocessed = m_unprocessed_count;
  730. m_unprocessed_count = m_transforming_liquid.size();
  731. // if unprocessed block count is decreasing or stable
  732. if (m_unprocessed_count <= prev_unprocessed) {
  733. m_queue_size_timer_started = false;
  734. } else {
  735. if (!m_queue_size_timer_started)
  736. m_inc_trending_up_start_time = curr_time;
  737. m_queue_size_timer_started = true;
  738. }
  739. // Account for curr_time overflowing
  740. if (m_queue_size_timer_started && m_inc_trending_up_start_time > curr_time)
  741. m_queue_size_timer_started = false;
  742. /* If the queue has been growing for more than liquid_queue_purge_time seconds
  743. * and the number of unprocessed blocks is still > liquid_loop_max then we
  744. * cannot keep up; dump the oldest blocks from the queue so that the queue
  745. * has liquid_loop_max items in it
  746. */
  747. if (m_queue_size_timer_started
  748. && curr_time - m_inc_trending_up_start_time > time_until_purge
  749. && m_unprocessed_count > liquid_loop_max) {
  750. size_t dump_qty = m_unprocessed_count - liquid_loop_max;
  751. infostream << "transformLiquids(): DUMPING " << dump_qty
  752. << " blocks from the queue" << std::endl;
  753. while (dump_qty--)
  754. m_transforming_liquid.pop_front();
  755. m_queue_size_timer_started = false; // optimistically assume we can keep up now
  756. m_unprocessed_count = m_transforming_liquid.size();
  757. }
  758. }
  759. std::vector<v3s16> Map::findNodesWithMetadata(v3s16 p1, v3s16 p2)
  760. {
  761. std::vector<v3s16> positions_with_meta;
  762. sortBoxVerticies(p1, p2);
  763. v3s16 bpmin = getNodeBlockPos(p1);
  764. v3s16 bpmax = getNodeBlockPos(p2);
  765. VoxelArea area(p1, p2);
  766. for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
  767. for (s16 y = bpmin.Y; y <= bpmax.Y; y++)
  768. for (s16 x = bpmin.X; x <= bpmax.X; x++) {
  769. v3s16 blockpos(x, y, z);
  770. MapBlock *block = getBlockNoCreateNoEx(blockpos);
  771. if (!block) {
  772. verbosestream << "Map::getNodeMetadata(): Need to emerge "
  773. << PP(blockpos) << std::endl;
  774. block = emergeBlock(blockpos, false);
  775. }
  776. if (!block) {
  777. infostream << "WARNING: Map::getNodeMetadata(): Block not found"
  778. << std::endl;
  779. continue;
  780. }
  781. v3s16 p_base = blockpos * MAP_BLOCKSIZE;
  782. std::vector<v3s16> keys = block->m_node_metadata.getAllKeys();
  783. for (size_t i = 0; i != keys.size(); i++) {
  784. v3s16 p(keys[i] + p_base);
  785. if (!area.contains(p))
  786. continue;
  787. positions_with_meta.push_back(p);
  788. }
  789. }
  790. return positions_with_meta;
  791. }
  792. NodeMetadata *Map::getNodeMetadata(v3s16 p)
  793. {
  794. v3s16 blockpos = getNodeBlockPos(p);
  795. v3s16 p_rel = p - blockpos*MAP_BLOCKSIZE;
  796. MapBlock *block = getBlockNoCreateNoEx(blockpos);
  797. if(!block){
  798. infostream<<"Map::getNodeMetadata(): Need to emerge "
  799. <<PP(blockpos)<<std::endl;
  800. block = emergeBlock(blockpos, false);
  801. }
  802. if(!block){
  803. warningstream<<"Map::getNodeMetadata(): Block not found"
  804. <<std::endl;
  805. return NULL;
  806. }
  807. NodeMetadata *meta = block->m_node_metadata.get(p_rel);
  808. return meta;
  809. }
  810. bool Map::setNodeMetadata(v3s16 p, NodeMetadata *meta)
  811. {
  812. v3s16 blockpos = getNodeBlockPos(p);
  813. v3s16 p_rel = p - blockpos*MAP_BLOCKSIZE;
  814. MapBlock *block = getBlockNoCreateNoEx(blockpos);
  815. if(!block){
  816. infostream<<"Map::setNodeMetadata(): Need to emerge "
  817. <<PP(blockpos)<<std::endl;
  818. block = emergeBlock(blockpos, false);
  819. }
  820. if(!block){
  821. warningstream<<"Map::setNodeMetadata(): Block not found"
  822. <<std::endl;
  823. return false;
  824. }
  825. block->m_node_metadata.set(p_rel, meta);
  826. return true;
  827. }
  828. void Map::removeNodeMetadata(v3s16 p)
  829. {
  830. v3s16 blockpos = getNodeBlockPos(p);
  831. v3s16 p_rel = p - blockpos*MAP_BLOCKSIZE;
  832. MapBlock *block = getBlockNoCreateNoEx(blockpos);
  833. if(block == NULL)
  834. {
  835. warningstream<<"Map::removeNodeMetadata(): Block not found"
  836. <<std::endl;
  837. return;
  838. }
  839. block->m_node_metadata.remove(p_rel);
  840. }
  841. NodeTimer Map::getNodeTimer(v3s16 p)
  842. {
  843. v3s16 blockpos = getNodeBlockPos(p);
  844. v3s16 p_rel = p - blockpos*MAP_BLOCKSIZE;
  845. MapBlock *block = getBlockNoCreateNoEx(blockpos);
  846. if(!block){
  847. infostream<<"Map::getNodeTimer(): Need to emerge "
  848. <<PP(blockpos)<<std::endl;
  849. block = emergeBlock(blockpos, false);
  850. }
  851. if(!block){
  852. warningstream<<"Map::getNodeTimer(): Block not found"
  853. <<std::endl;
  854. return NodeTimer();
  855. }
  856. NodeTimer t = block->m_node_timers.get(p_rel);
  857. NodeTimer nt(t.timeout, t.elapsed, p);
  858. return nt;
  859. }
  860. void Map::setNodeTimer(const NodeTimer &t)
  861. {
  862. v3s16 p = t.position;
  863. v3s16 blockpos = getNodeBlockPos(p);
  864. v3s16 p_rel = p - blockpos*MAP_BLOCKSIZE;
  865. MapBlock *block = getBlockNoCreateNoEx(blockpos);
  866. if(!block){
  867. infostream<<"Map::setNodeTimer(): Need to emerge "
  868. <<PP(blockpos)<<std::endl;
  869. block = emergeBlock(blockpos, false);
  870. }
  871. if(!block){
  872. warningstream<<"Map::setNodeTimer(): Block not found"
  873. <<std::endl;
  874. return;
  875. }
  876. NodeTimer nt(t.timeout, t.elapsed, p_rel);
  877. block->m_node_timers.set(nt);
  878. }
  879. void Map::removeNodeTimer(v3s16 p)
  880. {
  881. v3s16 blockpos = getNodeBlockPos(p);
  882. v3s16 p_rel = p - blockpos*MAP_BLOCKSIZE;
  883. MapBlock *block = getBlockNoCreateNoEx(blockpos);
  884. if(block == NULL)
  885. {
  886. warningstream<<"Map::removeNodeTimer(): Block not found"
  887. <<std::endl;
  888. return;
  889. }
  890. block->m_node_timers.remove(p_rel);
  891. }
  892. bool Map::determineAdditionalOcclusionCheck(const v3s16 &pos_camera,
  893. const core::aabbox3d<s16> &block_bounds, v3s16 &check)
  894. {
  895. /*
  896. This functions determines the node inside the target block that is
  897. closest to the camera position. This increases the occlusion culling
  898. accuracy in straight and diagonal corridors.
  899. The returned position will be occlusion checked first in addition to the
  900. others (8 corners + center).
  901. No position is returned if
  902. - the closest node is a corner, corners are checked anyway.
  903. - the camera is inside the target block, it will never be occluded.
  904. */
  905. #define CLOSEST_EDGE(pos, bounds, axis) \
  906. ((pos).axis <= (bounds).MinEdge.axis) ? (bounds).MinEdge.axis : \
  907. (bounds).MaxEdge.axis
  908. bool x_inside = (block_bounds.MinEdge.X <= pos_camera.X) &&
  909. (pos_camera.X <= block_bounds.MaxEdge.X);
  910. bool y_inside = (block_bounds.MinEdge.Y <= pos_camera.Y) &&
  911. (pos_camera.Y <= block_bounds.MaxEdge.Y);
  912. bool z_inside = (block_bounds.MinEdge.Z <= pos_camera.Z) &&
  913. (pos_camera.Z <= block_bounds.MaxEdge.Z);
  914. if (x_inside && y_inside && z_inside)
  915. return false; // Camera inside target mapblock
  916. // straight
  917. if (x_inside && y_inside) {
  918. check = v3s16(pos_camera.X, pos_camera.Y, 0);
  919. check.Z = CLOSEST_EDGE(pos_camera, block_bounds, Z);
  920. return true;
  921. } else if (y_inside && z_inside) {
  922. check = v3s16(0, pos_camera.Y, pos_camera.Z);
  923. check.X = CLOSEST_EDGE(pos_camera, block_bounds, X);
  924. return true;
  925. } else if (x_inside && z_inside) {
  926. check = v3s16(pos_camera.X, 0, pos_camera.Z);
  927. check.Y = CLOSEST_EDGE(pos_camera, block_bounds, Y);
  928. return true;
  929. }
  930. // diagonal
  931. if (x_inside) {
  932. check = v3s16(pos_camera.X, 0, 0);
  933. check.Y = CLOSEST_EDGE(pos_camera, block_bounds, Y);
  934. check.Z = CLOSEST_EDGE(pos_camera, block_bounds, Z);
  935. return true;
  936. } else if (y_inside) {
  937. check = v3s16(0, pos_camera.Y, 0);
  938. check.X = CLOSEST_EDGE(pos_camera, block_bounds, X);
  939. check.Z = CLOSEST_EDGE(pos_camera, block_bounds, Z);
  940. return true;
  941. } else if (z_inside) {
  942. check = v3s16(0, 0, pos_camera.Z);
  943. check.X = CLOSEST_EDGE(pos_camera, block_bounds, X);
  944. check.Y = CLOSEST_EDGE(pos_camera, block_bounds, Y);
  945. return true;
  946. }
  947. // Closest node would be a corner, none returned
  948. return false;
  949. }
  950. bool Map::isOccluded(const v3s16 &pos_camera, const v3s16 &pos_target,
  951. float step, float stepfac, float offset, float end_offset, u32 needed_count)
  952. {
  953. v3f direction = intToFloat(pos_target - pos_camera, BS);
  954. float distance = direction.getLength();
  955. // Normalize direction vector
  956. if (distance > 0.0f)
  957. direction /= distance;
  958. v3f pos_origin_f = intToFloat(pos_camera, BS);
  959. u32 count = 0;
  960. bool is_valid_position;
  961. for (; offset < distance + end_offset; offset += step) {
  962. v3f pos_node_f = pos_origin_f + direction * offset;
  963. v3s16 pos_node = floatToInt(pos_node_f, BS);
  964. MapNode node = getNode(pos_node, &is_valid_position);
  965. if (is_valid_position &&
  966. !m_nodedef->get(node).light_propagates) {
  967. // Cannot see through light-blocking nodes --> occluded
  968. count++;
  969. if (count >= needed_count)
  970. return true;
  971. }
  972. step *= stepfac;
  973. }
  974. return false;
  975. }
  976. bool Map::isBlockOccluded(MapBlock *block, v3s16 cam_pos_nodes)
  977. {
  978. // Check occlusion for center and all 8 corners of the mapblock
  979. // Overshoot a little for less flickering
  980. static const s16 bs2 = MAP_BLOCKSIZE / 2 + 1;
  981. static const v3s16 dir9[9] = {
  982. v3s16( 0, 0, 0),
  983. v3s16( 1, 1, 1) * bs2,
  984. v3s16( 1, 1, -1) * bs2,
  985. v3s16( 1, -1, 1) * bs2,
  986. v3s16( 1, -1, -1) * bs2,
  987. v3s16(-1, 1, 1) * bs2,
  988. v3s16(-1, 1, -1) * bs2,
  989. v3s16(-1, -1, 1) * bs2,
  990. v3s16(-1, -1, -1) * bs2,
  991. };
  992. v3s16 pos_blockcenter = block->getPosRelative() + (MAP_BLOCKSIZE / 2);
  993. // Starting step size, value between 1m and sqrt(3)m
  994. float step = BS * 1.2f;
  995. // Multiply step by each iteraction by 'stepfac' to reduce checks in distance
  996. float stepfac = 1.05f;
  997. float start_offset = BS * 1.0f;
  998. // The occlusion search of 'isOccluded()' must stop short of the target
  999. // point by distance 'end_offset' to not enter the target mapblock.
  1000. // For the 8 mapblock corners 'end_offset' must therefore be the maximum
  1001. // diagonal of a mapblock, because we must consider all view angles.
  1002. // sqrt(1^2 + 1^2 + 1^2) = 1.732
  1003. float end_offset = -BS * MAP_BLOCKSIZE * 1.732f;
  1004. // to reduce the likelihood of falsely occluded blocks
  1005. // require at least two solid blocks
  1006. // this is a HACK, we should think of a more precise algorithm
  1007. u32 needed_count = 2;
  1008. // Additional occlusion check, see comments in that function
  1009. v3s16 check;
  1010. if (determineAdditionalOcclusionCheck(cam_pos_nodes, block->getBox(), check)) {
  1011. // node is always on a side facing the camera, end_offset can be lower
  1012. if (!isOccluded(cam_pos_nodes, check, step, stepfac, start_offset,
  1013. -1.0f, needed_count))
  1014. return false;
  1015. }
  1016. for (const v3s16 &dir : dir9) {
  1017. if (!isOccluded(cam_pos_nodes, pos_blockcenter + dir, step, stepfac,
  1018. start_offset, end_offset, needed_count))
  1019. return false;
  1020. }
  1021. return true;
  1022. }
  1023. /*
  1024. ServerMap
  1025. */
  1026. ServerMap::ServerMap(const std::string &savedir, IGameDef *gamedef,
  1027. EmergeManager *emerge, MetricsBackend *mb):
  1028. Map(gamedef),
  1029. settings_mgr(savedir + DIR_DELIM + "map_meta.txt"),
  1030. m_emerge(emerge)
  1031. {
  1032. verbosestream<<FUNCTION_NAME<<std::endl;
  1033. // Tell the EmergeManager about our MapSettingsManager
  1034. emerge->map_settings_mgr = &settings_mgr;
  1035. /*
  1036. Try to load map; if not found, create a new one.
  1037. */
  1038. // Determine which database backend to use
  1039. std::string conf_path = savedir + DIR_DELIM + "world.mt";
  1040. Settings conf;
  1041. bool succeeded = conf.readConfigFile(conf_path.c_str());
  1042. if (!succeeded || !conf.exists("backend")) {
  1043. // fall back to sqlite3
  1044. conf.set("backend", "sqlite3");
  1045. }
  1046. std::string backend = conf.get("backend");
  1047. dbase = createDatabase(backend, savedir, conf);
  1048. if (conf.exists("readonly_backend")) {
  1049. std::string readonly_dir = savedir + DIR_DELIM + "readonly";
  1050. dbase_ro = createDatabase(conf.get("readonly_backend"), readonly_dir, conf);
  1051. }
  1052. if (!conf.updateConfigFile(conf_path.c_str()))
  1053. errorstream << "ServerMap::ServerMap(): Failed to update world.mt!" << std::endl;
  1054. m_savedir = savedir;
  1055. m_map_saving_enabled = false;
  1056. m_save_time_counter = mb->addCounter("minetest_core_map_save_time", "Map save time (in nanoseconds)");
  1057. m_map_compression_level = rangelim(g_settings->getS16("map_compression_level_disk"), -1, 9);
  1058. try {
  1059. // If directory exists, check contents and load if possible
  1060. if (fs::PathExists(m_savedir)) {
  1061. // If directory is empty, it is safe to save into it.
  1062. if (fs::GetDirListing(m_savedir).empty()) {
  1063. infostream<<"ServerMap: Empty save directory is valid."
  1064. <<std::endl;
  1065. m_map_saving_enabled = true;
  1066. }
  1067. else
  1068. {
  1069. if (settings_mgr.loadMapMeta()) {
  1070. infostream << "ServerMap: Metadata loaded from "
  1071. << savedir << std::endl;
  1072. } else {
  1073. infostream << "ServerMap: Metadata could not be loaded "
  1074. "from " << savedir << ", assuming valid save "
  1075. "directory." << std::endl;
  1076. }
  1077. m_map_saving_enabled = true;
  1078. // Map loaded, not creating new one
  1079. return;
  1080. }
  1081. }
  1082. // If directory doesn't exist, it is safe to save to it
  1083. else{
  1084. m_map_saving_enabled = true;
  1085. }
  1086. }
  1087. catch(std::exception &e)
  1088. {
  1089. warningstream<<"ServerMap: Failed to load map from "<<savedir
  1090. <<", exception: "<<e.what()<<std::endl;
  1091. infostream<<"Please remove the map or fix it."<<std::endl;
  1092. warningstream<<"Map saving will be disabled."<<std::endl;
  1093. }
  1094. }
  1095. ServerMap::~ServerMap()
  1096. {
  1097. verbosestream<<FUNCTION_NAME<<std::endl;
  1098. try
  1099. {
  1100. if (m_map_saving_enabled) {
  1101. // Save only changed parts
  1102. save(MOD_STATE_WRITE_AT_UNLOAD);
  1103. infostream << "ServerMap: Saved map to " << m_savedir << std::endl;
  1104. } else {
  1105. infostream << "ServerMap: Map not saved" << std::endl;
  1106. }
  1107. }
  1108. catch(std::exception &e)
  1109. {
  1110. infostream<<"ServerMap: Failed to save map to "<<m_savedir
  1111. <<", exception: "<<e.what()<<std::endl;
  1112. }
  1113. /*
  1114. Close database if it was opened
  1115. */
  1116. delete dbase;
  1117. delete dbase_ro;
  1118. }
  1119. MapgenParams *ServerMap::getMapgenParams()
  1120. {
  1121. // getMapgenParams() should only ever be called after Server is initialized
  1122. assert(settings_mgr.mapgen_params != NULL);
  1123. return settings_mgr.mapgen_params;
  1124. }
  1125. u64 ServerMap::getSeed()
  1126. {
  1127. return getMapgenParams()->seed;
  1128. }
  1129. bool ServerMap::blockpos_over_mapgen_limit(v3s16 p)
  1130. {
  1131. const s16 mapgen_limit_bp = rangelim(
  1132. getMapgenParams()->mapgen_limit, 0, MAX_MAP_GENERATION_LIMIT) /
  1133. MAP_BLOCKSIZE;
  1134. return p.X < -mapgen_limit_bp ||
  1135. p.X > mapgen_limit_bp ||
  1136. p.Y < -mapgen_limit_bp ||
  1137. p.Y > mapgen_limit_bp ||
  1138. p.Z < -mapgen_limit_bp ||
  1139. p.Z > mapgen_limit_bp;
  1140. }
  1141. bool ServerMap::initBlockMake(v3s16 blockpos, BlockMakeData *data)
  1142. {
  1143. s16 csize = getMapgenParams()->chunksize;
  1144. v3s16 bpmin = EmergeManager::getContainingChunk(blockpos, csize);
  1145. v3s16 bpmax = bpmin + v3s16(1, 1, 1) * (csize - 1);
  1146. if (!m_chunks_in_progress.insert(bpmin).second)
  1147. return false;
  1148. bool enable_mapgen_debug_info = m_emerge->enable_mapgen_debug_info;
  1149. EMERGE_DBG_OUT("initBlockMake(): " PP(bpmin) " - " PP(bpmax));
  1150. v3s16 extra_borders(1, 1, 1);
  1151. v3s16 full_bpmin = bpmin - extra_borders;
  1152. v3s16 full_bpmax = bpmax + extra_borders;
  1153. // Do nothing if not inside mapgen limits (+-1 because of neighbors)
  1154. if (blockpos_over_mapgen_limit(full_bpmin) ||
  1155. blockpos_over_mapgen_limit(full_bpmax))
  1156. return false;
  1157. data->seed = getSeed();
  1158. data->blockpos_min = bpmin;
  1159. data->blockpos_max = bpmax;
  1160. data->nodedef = m_nodedef;
  1161. /*
  1162. Create the whole area of this and the neighboring blocks
  1163. */
  1164. for (s16 x = full_bpmin.X; x <= full_bpmax.X; x++)
  1165. for (s16 z = full_bpmin.Z; z <= full_bpmax.Z; z++) {
  1166. v2s16 sectorpos(x, z);
  1167. // Sector metadata is loaded from disk if not already loaded.
  1168. MapSector *sector = createSector(sectorpos);
  1169. FATAL_ERROR_IF(sector == NULL, "createSector() failed");
  1170. for (s16 y = full_bpmin.Y; y <= full_bpmax.Y; y++) {
  1171. v3s16 p(x, y, z);
  1172. MapBlock *block = emergeBlock(p, false);
  1173. if (block == NULL) {
  1174. block = createBlock(p);
  1175. // Block gets sunlight if this is true.
  1176. // Refer to the map generator heuristics.
  1177. bool ug = m_emerge->isBlockUnderground(p);
  1178. block->setIsUnderground(ug);
  1179. }
  1180. }
  1181. }
  1182. /*
  1183. Now we have a big empty area.
  1184. Make a ManualMapVoxelManipulator that contains this and the
  1185. neighboring blocks
  1186. */
  1187. data->vmanip = new MMVManip(this);
  1188. data->vmanip->initialEmerge(full_bpmin, full_bpmax);
  1189. // Data is ready now.
  1190. return true;
  1191. }
  1192. void ServerMap::finishBlockMake(BlockMakeData *data,
  1193. std::map<v3s16, MapBlock*> *changed_blocks)
  1194. {
  1195. v3s16 bpmin = data->blockpos_min;
  1196. v3s16 bpmax = data->blockpos_max;
  1197. bool enable_mapgen_debug_info = m_emerge->enable_mapgen_debug_info;
  1198. EMERGE_DBG_OUT("finishBlockMake(): " PP(bpmin) " - " PP(bpmax));
  1199. /*
  1200. Blit generated stuff to map
  1201. NOTE: blitBackAll adds nearly everything to changed_blocks
  1202. */
  1203. data->vmanip->blitBackAll(changed_blocks);
  1204. EMERGE_DBG_OUT("finishBlockMake: changed_blocks.size()="
  1205. << changed_blocks->size());
  1206. /*
  1207. Copy transforming liquid information
  1208. */
  1209. while (data->transforming_liquid.size()) {
  1210. m_transforming_liquid.push_back(data->transforming_liquid.front());
  1211. data->transforming_liquid.pop_front();
  1212. }
  1213. for (auto &changed_block : *changed_blocks) {
  1214. MapBlock *block = changed_block.second;
  1215. if (!block)
  1216. continue;
  1217. /*
  1218. Update day/night difference cache of the MapBlocks
  1219. */
  1220. block->expireDayNightDiff();
  1221. /*
  1222. Set block as modified
  1223. */
  1224. block->raiseModified(MOD_STATE_WRITE_NEEDED,
  1225. MOD_REASON_EXPIRE_DAYNIGHTDIFF);
  1226. }
  1227. /*
  1228. Set central blocks as generated
  1229. */
  1230. for (s16 x = bpmin.X; x <= bpmax.X; x++)
  1231. for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
  1232. for (s16 y = bpmin.Y; y <= bpmax.Y; y++) {
  1233. MapBlock *block = getBlockNoCreateNoEx(v3s16(x, y, z));
  1234. if (!block)
  1235. continue;
  1236. block->setGenerated(true);
  1237. }
  1238. /*
  1239. Save changed parts of map
  1240. NOTE: Will be saved later.
  1241. */
  1242. //save(MOD_STATE_WRITE_AT_UNLOAD);
  1243. m_chunks_in_progress.erase(bpmin);
  1244. }
  1245. MapSector *ServerMap::createSector(v2s16 p2d)
  1246. {
  1247. /*
  1248. Check if it exists already in memory
  1249. */
  1250. MapSector *sector = getSectorNoGenerate(p2d);
  1251. if (sector)
  1252. return sector;
  1253. /*
  1254. Do not create over max mapgen limit
  1255. */
  1256. const s16 max_limit_bp = MAX_MAP_GENERATION_LIMIT / MAP_BLOCKSIZE;
  1257. if (p2d.X < -max_limit_bp ||
  1258. p2d.X > max_limit_bp ||
  1259. p2d.Y < -max_limit_bp ||
  1260. p2d.Y > max_limit_bp)
  1261. throw InvalidPositionException("createSector(): pos. over max mapgen limit");
  1262. /*
  1263. Generate blank sector
  1264. */
  1265. sector = new MapSector(this, p2d, m_gamedef);
  1266. // Sector position on map in nodes
  1267. //v2s16 nodepos2d = p2d * MAP_BLOCKSIZE;
  1268. /*
  1269. Insert to container
  1270. */
  1271. m_sectors[p2d] = sector;
  1272. return sector;
  1273. }
  1274. MapBlock * ServerMap::createBlock(v3s16 p)
  1275. {
  1276. /*
  1277. Do not create over max mapgen limit
  1278. */
  1279. if (blockpos_over_max_limit(p))
  1280. throw InvalidPositionException("createBlock(): pos. over max mapgen limit");
  1281. v2s16 p2d(p.X, p.Z);
  1282. s16 block_y = p.Y;
  1283. /*
  1284. This will create or load a sector if not found in memory.
  1285. If block exists on disk, it will be loaded.
  1286. NOTE: On old save formats, this will be slow, as it generates
  1287. lighting on blocks for them.
  1288. */
  1289. MapSector *sector;
  1290. try {
  1291. sector = createSector(p2d);
  1292. } catch (InvalidPositionException &e) {
  1293. infostream<<"createBlock: createSector() failed"<<std::endl;
  1294. throw e;
  1295. }
  1296. /*
  1297. Try to get a block from the sector
  1298. */
  1299. MapBlock *block = sector->getBlockNoCreateNoEx(block_y);
  1300. if (block) {
  1301. if(block->isDummy())
  1302. block->unDummify();
  1303. return block;
  1304. }
  1305. // Create blank
  1306. block = sector->createBlankBlock(block_y);
  1307. return block;
  1308. }
  1309. MapBlock * ServerMap::emergeBlock(v3s16 p, bool create_blank)
  1310. {
  1311. {
  1312. MapBlock *block = getBlockNoCreateNoEx(p);
  1313. if (block && !block->isDummy())
  1314. return block;
  1315. }
  1316. {
  1317. MapBlock *block = loadBlock(p);
  1318. if(block)
  1319. return block;
  1320. }
  1321. if (create_blank) {
  1322. MapSector *sector = createSector(v2s16(p.X, p.Z));
  1323. MapBlock *block = sector->createBlankBlock(p.Y);
  1324. return block;
  1325. }
  1326. return NULL;
  1327. }
  1328. MapBlock *ServerMap::getBlockOrEmerge(v3s16 p3d)
  1329. {
  1330. MapBlock *block = getBlockNoCreateNoEx(p3d);
  1331. if (block == NULL)
  1332. m_emerge->enqueueBlockEmerge(PEER_ID_INEXISTENT, p3d, false);
  1333. return block;
  1334. }
  1335. bool ServerMap::isBlockInQueue(v3s16 pos)
  1336. {
  1337. return m_emerge && m_emerge->isBlockInQueue(pos);
  1338. }
  1339. // N.B. This requires no synchronization, since data will not be modified unless
  1340. // the VoxelManipulator being updated belongs to the same thread.
  1341. void ServerMap::updateVManip(v3s16 pos)
  1342. {
  1343. Mapgen *mg = m_emerge->getCurrentMapgen();
  1344. if (!mg)
  1345. return;
  1346. MMVManip *vm = mg->vm;
  1347. if (!vm)
  1348. return;
  1349. if (!vm->m_area.contains(pos))
  1350. return;
  1351. s32 idx = vm->m_area.index(pos);
  1352. vm->m_data[idx] = getNode(pos);
  1353. vm->m_flags[idx] &= ~VOXELFLAG_NO_DATA;
  1354. vm->m_is_dirty = true;
  1355. }
  1356. void ServerMap::save(ModifiedState save_level)
  1357. {
  1358. if (!m_map_saving_enabled) {
  1359. warningstream<<"Not saving map, saving disabled."<<std::endl;
  1360. return;
  1361. }
  1362. u64 start_time = porting::getTimeNs();
  1363. if(save_level == MOD_STATE_CLEAN)
  1364. infostream<<"ServerMap: Saving whole map, this can take time."
  1365. <<std::endl;
  1366. if (m_map_metadata_changed || save_level == MOD_STATE_CLEAN) {
  1367. if (settings_mgr.saveMapMeta())
  1368. m_map_metadata_changed = false;
  1369. }
  1370. // Profile modified reasons
  1371. Profiler modprofiler;
  1372. u32 block_count = 0;
  1373. u32 block_count_all = 0; // Number of blocks in memory
  1374. // Don't do anything with sqlite unless something is really saved
  1375. bool save_started = false;
  1376. for (auto &sector_it : m_sectors) {
  1377. MapSector *sector = sector_it.second;
  1378. MapBlockVect blocks;
  1379. sector->getBlocks(blocks);
  1380. for (MapBlock *block : blocks) {
  1381. block_count_all++;
  1382. if(block->getModified() >= (u32)save_level) {
  1383. // Lazy beginSave()
  1384. if(!save_started) {
  1385. beginSave();
  1386. save_started = true;
  1387. }
  1388. modprofiler.add(block->getModifiedReasonString(), 1);
  1389. saveBlock(block);
  1390. block_count++;
  1391. }
  1392. }
  1393. }
  1394. if(save_started)
  1395. endSave();
  1396. /*
  1397. Only print if something happened or saved whole map
  1398. */
  1399. if(save_level == MOD_STATE_CLEAN
  1400. || block_count != 0) {
  1401. infostream << "ServerMap: Written: "
  1402. << block_count << " blocks"
  1403. << ", " << block_count_all << " blocks in memory."
  1404. << std::endl;
  1405. PrintInfo(infostream); // ServerMap/ClientMap:
  1406. infostream<<"Blocks modified by: "<<std::endl;
  1407. modprofiler.print(infostream);
  1408. }
  1409. auto end_time = porting::getTimeNs();
  1410. m_save_time_counter->increment(end_time - start_time);
  1411. }
  1412. void ServerMap::listAllLoadableBlocks(std::vector<v3s16> &dst)
  1413. {
  1414. dbase->listAllLoadableBlocks(dst);
  1415. if (dbase_ro)
  1416. dbase_ro->listAllLoadableBlocks(dst);
  1417. }
  1418. void ServerMap::listAllLoadedBlocks(std::vector<v3s16> &dst)
  1419. {
  1420. for (auto &sector_it : m_sectors) {
  1421. MapSector *sector = sector_it.second;
  1422. MapBlockVect blocks;
  1423. sector->getBlocks(blocks);
  1424. for (MapBlock *block : blocks) {
  1425. v3s16 p = block->getPos();
  1426. dst.push_back(p);
  1427. }
  1428. }
  1429. }
  1430. MapDatabase *ServerMap::createDatabase(
  1431. const std::string &name,
  1432. const std::string &savedir,
  1433. Settings &conf)
  1434. {
  1435. if (name == "sqlite3")
  1436. return new MapDatabaseSQLite3(savedir);
  1437. if (name == "dummy")
  1438. return new Database_Dummy();
  1439. #if USE_LEVELDB
  1440. if (name == "leveldb")
  1441. return new Database_LevelDB(savedir);
  1442. #endif
  1443. #if USE_REDIS
  1444. if (name == "redis")
  1445. return new Database_Redis(conf);
  1446. #endif
  1447. #if USE_POSTGRESQL
  1448. if (name == "postgresql") {
  1449. std::string connect_string;
  1450. conf.getNoEx("pgsql_connection", connect_string);
  1451. return new MapDatabasePostgreSQL(connect_string);
  1452. }
  1453. #endif
  1454. throw BaseException(std::string("Database backend ") + name + " not supported.");
  1455. }
  1456. void ServerMap::beginSave()
  1457. {
  1458. dbase->beginSave();
  1459. }
  1460. void ServerMap::endSave()
  1461. {
  1462. dbase->endSave();
  1463. }
  1464. bool ServerMap::saveBlock(MapBlock *block)
  1465. {
  1466. return saveBlock(block, dbase, m_map_compression_level);
  1467. }
  1468. bool ServerMap::saveBlock(MapBlock *block, MapDatabase *db, int compression_level)
  1469. {
  1470. v3s16 p3d = block->getPos();
  1471. // Dummy blocks are not written
  1472. if (block->isDummy()) {
  1473. warningstream << "saveBlock: Not writing dummy block "
  1474. << PP(p3d) << std::endl;
  1475. return true;
  1476. }
  1477. // Format used for writing
  1478. u8 version = SER_FMT_VER_HIGHEST_WRITE;
  1479. /*
  1480. [0] u8 serialization version
  1481. [1] data
  1482. */
  1483. std::ostringstream o(std::ios_base::binary);
  1484. o.write((char*) &version, 1);
  1485. block->serialize(o, version, true, compression_level);
  1486. bool ret = db->saveBlock(p3d, o.str());
  1487. if (ret) {
  1488. // We just wrote it to the disk so clear modified flag
  1489. block->resetModified();
  1490. }
  1491. return ret;
  1492. }
  1493. void ServerMap::loadBlock(std::string *blob, v3s16 p3d, MapSector *sector, bool save_after_load)
  1494. {
  1495. try {
  1496. std::istringstream is(*blob, std::ios_base::binary);
  1497. u8 version = SER_FMT_VER_INVALID;
  1498. is.read((char*)&version, 1);
  1499. if(is.fail())
  1500. throw SerializationError("ServerMap::loadBlock(): Failed"
  1501. " to read MapBlock version");
  1502. MapBlock *block = NULL;
  1503. bool created_new = false;
  1504. block = sector->getBlockNoCreateNoEx(p3d.Y);
  1505. if(block == NULL)
  1506. {
  1507. block = sector->createBlankBlockNoInsert(p3d.Y);
  1508. created_new = true;
  1509. }
  1510. // Read basic data
  1511. block->deSerialize(is, version, true);
  1512. // If it's a new block, insert it to the map
  1513. if (created_new) {
  1514. sector->insertBlock(block);
  1515. ReflowScan scanner(this, m_emerge->ndef);
  1516. scanner.scan(block, &m_transforming_liquid);
  1517. }
  1518. /*
  1519. Save blocks loaded in old format in new format
  1520. */
  1521. //if(version < SER_FMT_VER_HIGHEST_READ || save_after_load)
  1522. // Only save if asked to; no need to update version
  1523. if(save_after_load)
  1524. saveBlock(block);
  1525. // We just loaded it from, so it's up-to-date.
  1526. block->resetModified();
  1527. }
  1528. catch(SerializationError &e)
  1529. {
  1530. errorstream<<"Invalid block data in database"
  1531. <<" ("<<p3d.X<<","<<p3d.Y<<","<<p3d.Z<<")"
  1532. <<" (SerializationError): "<<e.what()<<std::endl;
  1533. // TODO: Block should be marked as invalid in memory so that it is
  1534. // not touched but the game can run
  1535. if(g_settings->getBool("ignore_world_load_errors")){
  1536. errorstream<<"Ignoring block load error. Duck and cover! "
  1537. <<"(ignore_world_load_errors)"<<std::endl;
  1538. } else {
  1539. throw SerializationError("Invalid block data in database");
  1540. }
  1541. }
  1542. }
  1543. MapBlock* ServerMap::loadBlock(v3s16 blockpos)
  1544. {
  1545. bool created_new = (getBlockNoCreateNoEx(blockpos) == NULL);
  1546. v2s16 p2d(blockpos.X, blockpos.Z);
  1547. std::string ret;
  1548. dbase->loadBlock(blockpos, &ret);
  1549. if (!ret.empty()) {
  1550. loadBlock(&ret, blockpos, createSector(p2d), false);
  1551. } else if (dbase_ro) {
  1552. dbase_ro->loadBlock(blockpos, &ret);
  1553. if (!ret.empty()) {
  1554. loadBlock(&ret, blockpos, createSector(p2d), false);
  1555. }
  1556. } else {
  1557. return NULL;
  1558. }
  1559. MapBlock *block = getBlockNoCreateNoEx(blockpos);
  1560. if (created_new && (block != NULL)) {
  1561. std::map<v3s16, MapBlock*> modified_blocks;
  1562. // Fix lighting if necessary
  1563. voxalgo::update_block_border_lighting(this, block, modified_blocks);
  1564. if (!modified_blocks.empty()) {
  1565. //Modified lighting, send event
  1566. MapEditEvent event;
  1567. event.type = MEET_OTHER;
  1568. std::map<v3s16, MapBlock *>::iterator it;
  1569. for (it = modified_blocks.begin();
  1570. it != modified_blocks.end(); ++it)
  1571. event.modified_blocks.insert(it->first);
  1572. dispatchEvent(event);
  1573. }
  1574. }
  1575. return block;
  1576. }
  1577. bool ServerMap::deleteBlock(v3s16 blockpos)
  1578. {
  1579. if (!dbase->deleteBlock(blockpos))
  1580. return false;
  1581. MapBlock *block = getBlockNoCreateNoEx(blockpos);
  1582. if (block) {
  1583. v2s16 p2d(blockpos.X, blockpos.Z);
  1584. MapSector *sector = getSectorNoGenerate(p2d);
  1585. if (!sector)
  1586. return false;
  1587. sector->deleteBlock(block);
  1588. }
  1589. return true;
  1590. }
  1591. void ServerMap::PrintInfo(std::ostream &out)
  1592. {
  1593. out<<"ServerMap: ";
  1594. }
  1595. bool ServerMap::repairBlockLight(v3s16 blockpos,
  1596. std::map<v3s16, MapBlock *> *modified_blocks)
  1597. {
  1598. MapBlock *block = emergeBlock(blockpos, false);
  1599. if (!block || !block->isGenerated())
  1600. return false;
  1601. voxalgo::repair_block_light(this, block, modified_blocks);
  1602. return true;
  1603. }
  1604. MMVManip::MMVManip(Map *map):
  1605. VoxelManipulator(),
  1606. m_map(map)
  1607. {
  1608. }
  1609. void MMVManip::initialEmerge(v3s16 blockpos_min, v3s16 blockpos_max,
  1610. bool load_if_inexistent)
  1611. {
  1612. TimeTaker timer1("initialEmerge", &emerge_time);
  1613. // Units of these are MapBlocks
  1614. v3s16 p_min = blockpos_min;
  1615. v3s16 p_max = blockpos_max;
  1616. VoxelArea block_area_nodes
  1617. (p_min*MAP_BLOCKSIZE, (p_max+1)*MAP_BLOCKSIZE-v3s16(1,1,1));
  1618. u32 size_MB = block_area_nodes.getVolume()*4/1000000;
  1619. if(size_MB >= 1)
  1620. {
  1621. infostream<<"initialEmerge: area: ";
  1622. block_area_nodes.print(infostream);
  1623. infostream<<" ("<<size_MB<<"MB)";
  1624. infostream<<std::endl;
  1625. }
  1626. addArea(block_area_nodes);
  1627. for(s32 z=p_min.Z; z<=p_max.Z; z++)
  1628. for(s32 y=p_min.Y; y<=p_max.Y; y++)
  1629. for(s32 x=p_min.X; x<=p_max.X; x++)
  1630. {
  1631. u8 flags = 0;
  1632. MapBlock *block;
  1633. v3s16 p(x,y,z);
  1634. std::map<v3s16, u8>::iterator n;
  1635. n = m_loaded_blocks.find(p);
  1636. if(n != m_loaded_blocks.end())
  1637. continue;
  1638. bool block_data_inexistent = false;
  1639. {
  1640. TimeTaker timer2("emerge load", &emerge_load_time);
  1641. block = m_map->getBlockNoCreateNoEx(p);
  1642. if (!block || block->isDummy())
  1643. block_data_inexistent = true;
  1644. else
  1645. block->copyTo(*this);
  1646. }
  1647. if(block_data_inexistent)
  1648. {
  1649. if (load_if_inexistent && !blockpos_over_max_limit(p)) {
  1650. ServerMap *svrmap = (ServerMap *)m_map;
  1651. block = svrmap->emergeBlock(p, false);
  1652. if (block == NULL)
  1653. block = svrmap->createBlock(p);
  1654. block->copyTo(*this);
  1655. } else {
  1656. flags |= VMANIP_BLOCK_DATA_INEXIST;
  1657. /*
  1658. Mark area inexistent
  1659. */
  1660. VoxelArea a(p*MAP_BLOCKSIZE, (p+1)*MAP_BLOCKSIZE-v3s16(1,1,1));
  1661. // Fill with VOXELFLAG_NO_DATA
  1662. for(s32 z=a.MinEdge.Z; z<=a.MaxEdge.Z; z++)
  1663. for(s32 y=a.MinEdge.Y; y<=a.MaxEdge.Y; y++)
  1664. {
  1665. s32 i = m_area.index(a.MinEdge.X,y,z);
  1666. memset(&m_flags[i], VOXELFLAG_NO_DATA, MAP_BLOCKSIZE);
  1667. }
  1668. }
  1669. }
  1670. /*else if (block->getNode(0, 0, 0).getContent() == CONTENT_IGNORE)
  1671. {
  1672. // Mark that block was loaded as blank
  1673. flags |= VMANIP_BLOCK_CONTAINS_CIGNORE;
  1674. }*/
  1675. m_loaded_blocks[p] = flags;
  1676. }
  1677. m_is_dirty = false;
  1678. }
  1679. void MMVManip::blitBackAll(std::map<v3s16, MapBlock*> *modified_blocks,
  1680. bool overwrite_generated)
  1681. {
  1682. if(m_area.getExtent() == v3s16(0,0,0))
  1683. return;
  1684. /*
  1685. Copy data of all blocks
  1686. */
  1687. for (auto &loaded_block : m_loaded_blocks) {
  1688. v3s16 p = loaded_block.first;
  1689. MapBlock *block = m_map->getBlockNoCreateNoEx(p);
  1690. bool existed = !(loaded_block.second & VMANIP_BLOCK_DATA_INEXIST);
  1691. if (!existed || (block == NULL) ||
  1692. (!overwrite_generated && block->isGenerated()))
  1693. continue;
  1694. block->copyFrom(*this);
  1695. block->raiseModified(MOD_STATE_WRITE_NEEDED, MOD_REASON_VMANIP);
  1696. if(modified_blocks)
  1697. (*modified_blocks)[p] = block;
  1698. }
  1699. }
  1700. //END