map.cpp 54 KB

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