map.cpp 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146
  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. #if 0
  444. /* If liquid_loop_max is not keeping up with the queue size increase
  445. * loop_max up to a maximum of liquid_loop_max * dedicated_server_step.
  446. */
  447. if (m_transforming_liquid.size() > loop_max * 2) {
  448. // "Burst" mode
  449. float server_step = g_settings->getFloat("dedicated_server_step");
  450. if (m_transforming_liquid_loop_count_multiplier - 1.0 < server_step)
  451. m_transforming_liquid_loop_count_multiplier *= 1.0 + server_step / 10;
  452. } else {
  453. m_transforming_liquid_loop_count_multiplier = 1.0;
  454. }
  455. loop_max *= m_transforming_liquid_loop_count_multiplier;
  456. #endif
  457. while (m_transforming_liquid.size() != 0)
  458. {
  459. // This should be done here so that it is done when continue is used
  460. if (loopcount >= initial_size || loopcount >= loop_max)
  461. break;
  462. loopcount++;
  463. /*
  464. Get a queued transforming liquid node
  465. */
  466. v3s16 p0 = m_transforming_liquid.front();
  467. m_transforming_liquid.pop_front();
  468. MapNode n0 = getNode(p0);
  469. /*
  470. Collect information about current node
  471. */
  472. s8 liquid_level = -1;
  473. // The liquid node which will be placed there if
  474. // the liquid flows into this node.
  475. content_t liquid_kind = CONTENT_IGNORE;
  476. // The node which will be placed there if liquid
  477. // can't flow into this node.
  478. content_t floodable_node = CONTENT_AIR;
  479. const ContentFeatures &cf = m_nodedef->get(n0);
  480. LiquidType liquid_type = cf.liquid_type;
  481. switch (liquid_type) {
  482. case LIQUID_SOURCE:
  483. liquid_level = LIQUID_LEVEL_SOURCE;
  484. liquid_kind = cf.liquid_alternative_flowing_id;
  485. break;
  486. case LIQUID_FLOWING:
  487. liquid_level = (n0.param2 & LIQUID_LEVEL_MASK);
  488. liquid_kind = n0.getContent();
  489. break;
  490. case LIQUID_NONE:
  491. // if this node is 'floodable', it *could* be transformed
  492. // into a liquid, otherwise, continue with the next node.
  493. if (!cf.floodable)
  494. continue;
  495. floodable_node = n0.getContent();
  496. liquid_kind = CONTENT_AIR;
  497. break;
  498. }
  499. /*
  500. Collect information about the environment
  501. */
  502. NodeNeighbor sources[6]; // surrounding sources
  503. int num_sources = 0;
  504. NodeNeighbor flows[6]; // surrounding flowing liquid nodes
  505. int num_flows = 0;
  506. NodeNeighbor airs[6]; // surrounding air
  507. int num_airs = 0;
  508. NodeNeighbor neutrals[6]; // nodes that are solid or another kind of liquid
  509. int num_neutrals = 0;
  510. bool flowing_down = false;
  511. bool ignored_sources = false;
  512. for (u16 i = 0; i < 6; i++) {
  513. NeighborType nt = NEIGHBOR_SAME_LEVEL;
  514. switch (i) {
  515. case 0:
  516. nt = NEIGHBOR_UPPER;
  517. break;
  518. case 5:
  519. nt = NEIGHBOR_LOWER;
  520. break;
  521. default:
  522. break;
  523. }
  524. v3s16 npos = p0 + liquid_6dirs[i];
  525. NodeNeighbor nb(getNode(npos), nt, npos);
  526. const ContentFeatures &cfnb = m_nodedef->get(nb.n);
  527. switch (m_nodedef->get(nb.n.getContent()).liquid_type) {
  528. case LIQUID_NONE:
  529. if (cfnb.floodable) {
  530. airs[num_airs++] = nb;
  531. // if the current node is a water source the neighbor
  532. // should be enqueded for transformation regardless of whether the
  533. // current node changes or not.
  534. if (nb.t != NEIGHBOR_UPPER && liquid_type != LIQUID_NONE)
  535. m_transforming_liquid.push_back(npos);
  536. // if the current node happens to be a flowing node, it will start to flow down here.
  537. if (nb.t == NEIGHBOR_LOWER)
  538. flowing_down = true;
  539. } else {
  540. neutrals[num_neutrals++] = nb;
  541. if (nb.n.getContent() == CONTENT_IGNORE) {
  542. // If node below is ignore prevent water from
  543. // spreading outwards and otherwise prevent from
  544. // flowing away as ignore node might be the source
  545. if (nb.t == NEIGHBOR_LOWER)
  546. flowing_down = true;
  547. else
  548. ignored_sources = true;
  549. }
  550. }
  551. break;
  552. case LIQUID_SOURCE:
  553. // if this node is not (yet) of a liquid type, choose the first liquid type we encounter
  554. if (liquid_kind == CONTENT_AIR)
  555. liquid_kind = cfnb.liquid_alternative_flowing_id;
  556. if (cfnb.liquid_alternative_flowing_id != liquid_kind) {
  557. neutrals[num_neutrals++] = nb;
  558. } else {
  559. // Do not count bottom source, it will screw things up
  560. if(nt != NEIGHBOR_LOWER)
  561. sources[num_sources++] = nb;
  562. }
  563. break;
  564. case LIQUID_FLOWING:
  565. if (nb.t != NEIGHBOR_SAME_LEVEL ||
  566. (nb.n.param2 & LIQUID_FLOW_DOWN_MASK) != LIQUID_FLOW_DOWN_MASK) {
  567. // if this node is not (yet) of a liquid type, choose the first liquid type we encounter
  568. // but exclude falling liquids on the same level, they cannot flow here anyway
  569. if (liquid_kind == CONTENT_AIR)
  570. liquid_kind = cfnb.liquid_alternative_flowing_id;
  571. }
  572. if (cfnb.liquid_alternative_flowing_id != liquid_kind) {
  573. neutrals[num_neutrals++] = nb;
  574. } else {
  575. flows[num_flows++] = nb;
  576. if (nb.t == NEIGHBOR_LOWER)
  577. flowing_down = true;
  578. }
  579. break;
  580. }
  581. }
  582. /*
  583. decide on the type (and possibly level) of the current node
  584. */
  585. content_t new_node_content;
  586. s8 new_node_level = -1;
  587. s8 max_node_level = -1;
  588. u8 range = m_nodedef->get(liquid_kind).liquid_range;
  589. if (range > LIQUID_LEVEL_MAX + 1)
  590. range = LIQUID_LEVEL_MAX + 1;
  591. if ((num_sources >= 2 && m_nodedef->get(liquid_kind).liquid_renewable) || liquid_type == LIQUID_SOURCE) {
  592. // liquid_kind will be set to either the flowing alternative of the node (if it's a liquid)
  593. // or the flowing alternative of the first of the surrounding sources (if it's air), so
  594. // it's perfectly safe to use liquid_kind here to determine the new node content.
  595. new_node_content = m_nodedef->get(liquid_kind).liquid_alternative_source_id;
  596. } else if (num_sources >= 1 && sources[0].t != NEIGHBOR_LOWER) {
  597. // liquid_kind is set properly, see above
  598. max_node_level = new_node_level = LIQUID_LEVEL_MAX;
  599. if (new_node_level >= (LIQUID_LEVEL_MAX + 1 - range))
  600. new_node_content = liquid_kind;
  601. else
  602. new_node_content = floodable_node;
  603. } else if (ignored_sources && liquid_level >= 0) {
  604. // Maybe there are neighbouring sources that aren't loaded yet
  605. // so prevent flowing away.
  606. new_node_level = liquid_level;
  607. new_node_content = liquid_kind;
  608. } else {
  609. // no surrounding sources, so get the maximum level that can flow into this node
  610. for (u16 i = 0; i < num_flows; i++) {
  611. u8 nb_liquid_level = (flows[i].n.param2 & LIQUID_LEVEL_MASK);
  612. switch (flows[i].t) {
  613. case NEIGHBOR_UPPER:
  614. if (nb_liquid_level + WATER_DROP_BOOST > max_node_level) {
  615. max_node_level = LIQUID_LEVEL_MAX;
  616. if (nb_liquid_level + WATER_DROP_BOOST < LIQUID_LEVEL_MAX)
  617. max_node_level = nb_liquid_level + WATER_DROP_BOOST;
  618. } else if (nb_liquid_level > max_node_level) {
  619. max_node_level = nb_liquid_level;
  620. }
  621. break;
  622. case NEIGHBOR_LOWER:
  623. break;
  624. case NEIGHBOR_SAME_LEVEL:
  625. if ((flows[i].n.param2 & LIQUID_FLOW_DOWN_MASK) != LIQUID_FLOW_DOWN_MASK &&
  626. nb_liquid_level > 0 && nb_liquid_level - 1 > max_node_level)
  627. max_node_level = nb_liquid_level - 1;
  628. break;
  629. }
  630. }
  631. u8 viscosity = m_nodedef->get(liquid_kind).liquid_viscosity;
  632. if (viscosity > 1 && max_node_level != liquid_level) {
  633. // amount to gain, limited by viscosity
  634. // must be at least 1 in absolute value
  635. s8 level_inc = max_node_level - liquid_level;
  636. if (level_inc < -viscosity || level_inc > viscosity)
  637. new_node_level = liquid_level + level_inc/viscosity;
  638. else if (level_inc < 0)
  639. new_node_level = liquid_level - 1;
  640. else if (level_inc > 0)
  641. new_node_level = liquid_level + 1;
  642. if (new_node_level != max_node_level)
  643. must_reflow.push_back(p0);
  644. } else {
  645. new_node_level = max_node_level;
  646. }
  647. if (max_node_level >= (LIQUID_LEVEL_MAX + 1 - range))
  648. new_node_content = liquid_kind;
  649. else
  650. new_node_content = floodable_node;
  651. }
  652. /*
  653. check if anything has changed. if not, just continue with the next node.
  654. */
  655. if (new_node_content == n0.getContent() &&
  656. (m_nodedef->get(n0.getContent()).liquid_type != LIQUID_FLOWING ||
  657. ((n0.param2 & LIQUID_LEVEL_MASK) == (u8)new_node_level &&
  658. ((n0.param2 & LIQUID_FLOW_DOWN_MASK) == LIQUID_FLOW_DOWN_MASK)
  659. == flowing_down)))
  660. continue;
  661. /*
  662. update the current node
  663. */
  664. MapNode n00 = n0;
  665. //bool flow_down_enabled = (flowing_down && ((n0.param2 & LIQUID_FLOW_DOWN_MASK) != LIQUID_FLOW_DOWN_MASK));
  666. if (m_nodedef->get(new_node_content).liquid_type == LIQUID_FLOWING) {
  667. // set level to last 3 bits, flowing down bit to 4th bit
  668. n0.param2 = (flowing_down ? LIQUID_FLOW_DOWN_MASK : 0x00) | (new_node_level & LIQUID_LEVEL_MASK);
  669. } else {
  670. // set the liquid level and flow bits to 0
  671. n0.param2 &= ~(LIQUID_LEVEL_MASK | LIQUID_FLOW_DOWN_MASK);
  672. }
  673. // change the node.
  674. n0.setContent(new_node_content);
  675. // on_flood() the node
  676. if (floodable_node != CONTENT_AIR) {
  677. if (env->getScriptIface()->node_on_flood(p0, n00, n0))
  678. continue;
  679. }
  680. // Ignore light (because calling voxalgo::update_lighting_nodes)
  681. n0.setLight(LIGHTBANK_DAY, 0, m_nodedef);
  682. n0.setLight(LIGHTBANK_NIGHT, 0, m_nodedef);
  683. // Find out whether there is a suspect for this action
  684. std::string suspect;
  685. if (m_gamedef->rollback())
  686. suspect = m_gamedef->rollback()->getSuspect(p0, 83, 1);
  687. if (m_gamedef->rollback() && !suspect.empty()) {
  688. // Blame suspect
  689. RollbackScopeActor rollback_scope(m_gamedef->rollback(), suspect, true);
  690. // Get old node for rollback
  691. RollbackNode rollback_oldnode(this, p0, m_gamedef);
  692. // Set node
  693. setNode(p0, n0);
  694. // Report
  695. RollbackNode rollback_newnode(this, p0, m_gamedef);
  696. RollbackAction action;
  697. action.setSetNode(p0, rollback_oldnode, rollback_newnode);
  698. m_gamedef->rollback()->reportAction(action);
  699. } else {
  700. // Set node
  701. setNode(p0, n0);
  702. }
  703. v3s16 blockpos = getNodeBlockPos(p0);
  704. MapBlock *block = getBlockNoCreateNoEx(blockpos);
  705. if (block != NULL) {
  706. modified_blocks[blockpos] = block;
  707. changed_nodes.emplace_back(p0, n00);
  708. }
  709. /*
  710. enqueue neighbors for update if neccessary
  711. */
  712. switch (m_nodedef->get(n0.getContent()).liquid_type) {
  713. case LIQUID_SOURCE:
  714. case LIQUID_FLOWING:
  715. // make sure source flows into all neighboring nodes
  716. for (u16 i = 0; i < num_flows; i++)
  717. if (flows[i].t != NEIGHBOR_UPPER)
  718. m_transforming_liquid.push_back(flows[i].p);
  719. for (u16 i = 0; i < num_airs; i++)
  720. if (airs[i].t != NEIGHBOR_UPPER)
  721. m_transforming_liquid.push_back(airs[i].p);
  722. break;
  723. case LIQUID_NONE:
  724. // this flow has turned to air; neighboring flows might need to do the same
  725. for (u16 i = 0; i < num_flows; i++)
  726. m_transforming_liquid.push_back(flows[i].p);
  727. break;
  728. }
  729. }
  730. //infostream<<"Map::transformLiquids(): loopcount="<<loopcount<<std::endl;
  731. for (auto &iter : must_reflow)
  732. m_transforming_liquid.push_back(iter);
  733. voxalgo::update_lighting_nodes(this, changed_nodes, modified_blocks);
  734. /* ----------------------------------------------------------------------
  735. * Manage the queue so that it does not grow indefinately
  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->m_node_timers.get(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->m_node_timers.set(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->m_node_timers.remove(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->get(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(g_settings, 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("minetest_core_map_save_time", "Map save time (in nanoseconds)");
  1070. m_map_compression_level = rangelim(g_settings->getS16("map_compression_level_disk"), -1, 9);
  1071. try {
  1072. // If directory exists, check contents and load if possible
  1073. if (fs::PathExists(m_savedir)) {
  1074. // If directory is empty, it is safe to save into it.
  1075. if (fs::GetDirListing(m_savedir).empty()) {
  1076. infostream<<"ServerMap: Empty save directory is valid."
  1077. <<std::endl;
  1078. m_map_saving_enabled = true;
  1079. }
  1080. else
  1081. {
  1082. if (settings_mgr.loadMapMeta()) {
  1083. infostream << "ServerMap: Metadata loaded from "
  1084. << savedir << std::endl;
  1085. } else {
  1086. infostream << "ServerMap: Metadata could not be loaded "
  1087. "from " << savedir << ", assuming valid save "
  1088. "directory." << std::endl;
  1089. }
  1090. m_map_saving_enabled = true;
  1091. // Map loaded, not creating new one
  1092. return;
  1093. }
  1094. }
  1095. // If directory doesn't exist, it is safe to save to it
  1096. else{
  1097. m_map_saving_enabled = true;
  1098. }
  1099. }
  1100. catch(std::exception &e)
  1101. {
  1102. warningstream<<"ServerMap: Failed to load map from "<<savedir
  1103. <<", exception: "<<e.what()<<std::endl;
  1104. infostream<<"Please remove the map or fix it."<<std::endl;
  1105. warningstream<<"Map saving will be disabled."<<std::endl;
  1106. }
  1107. }
  1108. ServerMap::~ServerMap()
  1109. {
  1110. verbosestream<<FUNCTION_NAME<<std::endl;
  1111. try
  1112. {
  1113. if (m_map_saving_enabled) {
  1114. // Save only changed parts
  1115. save(MOD_STATE_WRITE_AT_UNLOAD);
  1116. infostream << "ServerMap: Saved map to " << m_savedir << std::endl;
  1117. } else {
  1118. infostream << "ServerMap: Map not saved" << std::endl;
  1119. }
  1120. }
  1121. catch(std::exception &e)
  1122. {
  1123. infostream<<"ServerMap: Failed to save map to "<<m_savedir
  1124. <<", exception: "<<e.what()<<std::endl;
  1125. }
  1126. /*
  1127. Close database if it was opened
  1128. */
  1129. delete dbase;
  1130. delete dbase_ro;
  1131. #if 0
  1132. /*
  1133. Free all MapChunks
  1134. */
  1135. core::map<v2s16, MapChunk*>::Iterator i = m_chunks.getIterator();
  1136. for(; i.atEnd() == false; i++)
  1137. {
  1138. MapChunk *chunk = i.getNode()->getValue();
  1139. delete chunk;
  1140. }
  1141. #endif
  1142. }
  1143. MapgenParams *ServerMap::getMapgenParams()
  1144. {
  1145. // getMapgenParams() should only ever be called after Server is initialized
  1146. assert(settings_mgr.mapgen_params != NULL);
  1147. return settings_mgr.mapgen_params;
  1148. }
  1149. u64 ServerMap::getSeed()
  1150. {
  1151. return getMapgenParams()->seed;
  1152. }
  1153. bool ServerMap::blockpos_over_mapgen_limit(v3s16 p)
  1154. {
  1155. const s16 mapgen_limit_bp = rangelim(
  1156. getMapgenParams()->mapgen_limit, 0, MAX_MAP_GENERATION_LIMIT) /
  1157. MAP_BLOCKSIZE;
  1158. return p.X < -mapgen_limit_bp ||
  1159. p.X > mapgen_limit_bp ||
  1160. p.Y < -mapgen_limit_bp ||
  1161. p.Y > mapgen_limit_bp ||
  1162. p.Z < -mapgen_limit_bp ||
  1163. p.Z > mapgen_limit_bp;
  1164. }
  1165. bool ServerMap::initBlockMake(v3s16 blockpos, BlockMakeData *data)
  1166. {
  1167. s16 csize = getMapgenParams()->chunksize;
  1168. v3s16 bpmin = EmergeManager::getContainingChunk(blockpos, csize);
  1169. v3s16 bpmax = bpmin + v3s16(1, 1, 1) * (csize - 1);
  1170. if (!m_chunks_in_progress.insert(bpmin).second)
  1171. return false;
  1172. bool enable_mapgen_debug_info = m_emerge->enable_mapgen_debug_info;
  1173. EMERGE_DBG_OUT("initBlockMake(): " PP(bpmin) " - " PP(bpmax));
  1174. v3s16 extra_borders(1, 1, 1);
  1175. v3s16 full_bpmin = bpmin - extra_borders;
  1176. v3s16 full_bpmax = bpmax + extra_borders;
  1177. // Do nothing if not inside mapgen limits (+-1 because of neighbors)
  1178. if (blockpos_over_mapgen_limit(full_bpmin) ||
  1179. blockpos_over_mapgen_limit(full_bpmax))
  1180. return false;
  1181. data->seed = getSeed();
  1182. data->blockpos_min = bpmin;
  1183. data->blockpos_max = bpmax;
  1184. data->nodedef = m_nodedef;
  1185. /*
  1186. Create the whole area of this and the neighboring blocks
  1187. */
  1188. for (s16 x = full_bpmin.X; x <= full_bpmax.X; x++)
  1189. for (s16 z = full_bpmin.Z; z <= full_bpmax.Z; z++) {
  1190. v2s16 sectorpos(x, z);
  1191. // Sector metadata is loaded from disk if not already loaded.
  1192. MapSector *sector = createSector(sectorpos);
  1193. FATAL_ERROR_IF(sector == NULL, "createSector() failed");
  1194. for (s16 y = full_bpmin.Y; y <= full_bpmax.Y; y++) {
  1195. v3s16 p(x, y, z);
  1196. MapBlock *block = emergeBlock(p, false);
  1197. if (block == NULL) {
  1198. block = createBlock(p);
  1199. // Block gets sunlight if this is true.
  1200. // Refer to the map generator heuristics.
  1201. bool ug = m_emerge->isBlockUnderground(p);
  1202. block->setIsUnderground(ug);
  1203. }
  1204. }
  1205. }
  1206. /*
  1207. Now we have a big empty area.
  1208. Make a ManualMapVoxelManipulator that contains this and the
  1209. neighboring blocks
  1210. */
  1211. data->vmanip = new MMVManip(this);
  1212. data->vmanip->initialEmerge(full_bpmin, full_bpmax);
  1213. // Note: we may need this again at some point.
  1214. #if 0
  1215. // Ensure none of the blocks to be generated were marked as
  1216. // containing CONTENT_IGNORE
  1217. for (s16 z = blockpos_min.Z; z <= blockpos_max.Z; z++) {
  1218. for (s16 y = blockpos_min.Y; y <= blockpos_max.Y; y++) {
  1219. for (s16 x = blockpos_min.X; x <= blockpos_max.X; x++) {
  1220. core::map<v3s16, u8>::Node *n;
  1221. n = data->vmanip->m_loaded_blocks.find(v3s16(x, y, z));
  1222. if (n == NULL)
  1223. continue;
  1224. u8 flags = n->getValue();
  1225. flags &= ~VMANIP_BLOCK_CONTAINS_CIGNORE;
  1226. n->setValue(flags);
  1227. }
  1228. }
  1229. }
  1230. #endif
  1231. // Data is ready now.
  1232. return true;
  1233. }
  1234. void ServerMap::finishBlockMake(BlockMakeData *data,
  1235. std::map<v3s16, MapBlock*> *changed_blocks)
  1236. {
  1237. v3s16 bpmin = data->blockpos_min;
  1238. v3s16 bpmax = data->blockpos_max;
  1239. v3s16 extra_borders(1, 1, 1);
  1240. bool enable_mapgen_debug_info = m_emerge->enable_mapgen_debug_info;
  1241. EMERGE_DBG_OUT("finishBlockMake(): " PP(bpmin) " - " PP(bpmax));
  1242. /*
  1243. Blit generated stuff to map
  1244. NOTE: blitBackAll adds nearly everything to changed_blocks
  1245. */
  1246. data->vmanip->blitBackAll(changed_blocks);
  1247. EMERGE_DBG_OUT("finishBlockMake: changed_blocks.size()="
  1248. << changed_blocks->size());
  1249. /*
  1250. Copy transforming liquid information
  1251. */
  1252. while (data->transforming_liquid.size()) {
  1253. m_transforming_liquid.push_back(data->transforming_liquid.front());
  1254. data->transforming_liquid.pop_front();
  1255. }
  1256. for (auto &changed_block : *changed_blocks) {
  1257. MapBlock *block = changed_block.second;
  1258. if (!block)
  1259. continue;
  1260. /*
  1261. Update day/night difference cache of the MapBlocks
  1262. */
  1263. block->expireDayNightDiff();
  1264. /*
  1265. Set block as modified
  1266. */
  1267. block->raiseModified(MOD_STATE_WRITE_NEEDED,
  1268. MOD_REASON_EXPIRE_DAYNIGHTDIFF);
  1269. }
  1270. /*
  1271. Set central blocks as generated
  1272. */
  1273. for (s16 x = bpmin.X; x <= bpmax.X; x++)
  1274. for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
  1275. for (s16 y = bpmin.Y; y <= bpmax.Y; y++) {
  1276. MapBlock *block = getBlockNoCreateNoEx(v3s16(x, y, z));
  1277. if (!block)
  1278. continue;
  1279. block->setGenerated(true);
  1280. }
  1281. /*
  1282. Save changed parts of map
  1283. NOTE: Will be saved later.
  1284. */
  1285. //save(MOD_STATE_WRITE_AT_UNLOAD);
  1286. m_chunks_in_progress.erase(bpmin);
  1287. }
  1288. MapSector *ServerMap::createSector(v2s16 p2d)
  1289. {
  1290. /*
  1291. Check if it exists already in memory
  1292. */
  1293. MapSector *sector = getSectorNoGenerate(p2d);
  1294. if (sector)
  1295. return sector;
  1296. /*
  1297. Do not create over max mapgen limit
  1298. */
  1299. const s16 max_limit_bp = MAX_MAP_GENERATION_LIMIT / MAP_BLOCKSIZE;
  1300. if (p2d.X < -max_limit_bp ||
  1301. p2d.X > max_limit_bp ||
  1302. p2d.Y < -max_limit_bp ||
  1303. p2d.Y > max_limit_bp)
  1304. throw InvalidPositionException("createSector(): pos. over max mapgen limit");
  1305. /*
  1306. Generate blank sector
  1307. */
  1308. sector = new MapSector(this, p2d, m_gamedef);
  1309. // Sector position on map in nodes
  1310. //v2s16 nodepos2d = p2d * MAP_BLOCKSIZE;
  1311. /*
  1312. Insert to container
  1313. */
  1314. m_sectors[p2d] = sector;
  1315. return sector;
  1316. }
  1317. #if 0
  1318. /*
  1319. This is a quick-hand function for calling makeBlock().
  1320. */
  1321. MapBlock * ServerMap::generateBlock(
  1322. v3s16 p,
  1323. std::map<v3s16, MapBlock*> &modified_blocks
  1324. )
  1325. {
  1326. bool enable_mapgen_debug_info = g_settings->getBool("enable_mapgen_debug_info");
  1327. TimeTaker timer("generateBlock");
  1328. //MapBlock *block = original_dummy;
  1329. v2s16 p2d(p.X, p.Z);
  1330. v2s16 p2d_nodes = p2d * MAP_BLOCKSIZE;
  1331. /*
  1332. Do not generate over-limit
  1333. */
  1334. if(blockpos_over_limit(p))
  1335. {
  1336. infostream<<FUNCTION_NAME<<": Block position over limit"<<std::endl;
  1337. throw InvalidPositionException("generateBlock(): pos. over limit");
  1338. }
  1339. /*
  1340. Create block make data
  1341. */
  1342. BlockMakeData data;
  1343. initBlockMake(&data, p);
  1344. /*
  1345. Generate block
  1346. */
  1347. {
  1348. TimeTaker t("mapgen::make_block()");
  1349. mapgen->makeChunk(&data);
  1350. //mapgen::make_block(&data);
  1351. if(enable_mapgen_debug_info == false)
  1352. t.stop(true); // Hide output
  1353. }
  1354. /*
  1355. Blit data back on map, update lighting, add mobs and whatever this does
  1356. */
  1357. finishBlockMake(&data, modified_blocks);
  1358. /*
  1359. Get central block
  1360. */
  1361. MapBlock *block = getBlockNoCreateNoEx(p);
  1362. #if 0
  1363. /*
  1364. Check result
  1365. */
  1366. if(block)
  1367. {
  1368. bool erroneus_content = false;
  1369. for(s16 z0=0; z0<MAP_BLOCKSIZE; z0++)
  1370. for(s16 y0=0; y0<MAP_BLOCKSIZE; y0++)
  1371. for(s16 x0=0; x0<MAP_BLOCKSIZE; x0++)
  1372. {
  1373. v3s16 p(x0,y0,z0);
  1374. MapNode n = block->getNode(p);
  1375. if(n.getContent() == CONTENT_IGNORE)
  1376. {
  1377. infostream<<"CONTENT_IGNORE at "
  1378. <<"("<<p.X<<","<<p.Y<<","<<p.Z<<")"
  1379. <<std::endl;
  1380. erroneus_content = true;
  1381. assert(0);
  1382. }
  1383. }
  1384. if(erroneus_content)
  1385. {
  1386. assert(0);
  1387. }
  1388. }
  1389. #endif
  1390. #if 0
  1391. /*
  1392. Generate a completely empty block
  1393. */
  1394. if(block)
  1395. {
  1396. for(s16 z0=0; z0<MAP_BLOCKSIZE; z0++)
  1397. for(s16 x0=0; x0<MAP_BLOCKSIZE; x0++)
  1398. {
  1399. for(s16 y0=0; y0<MAP_BLOCKSIZE; y0++)
  1400. {
  1401. MapNode n;
  1402. n.setContent(CONTENT_AIR);
  1403. block->setNode(v3s16(x0,y0,z0), n);
  1404. }
  1405. }
  1406. }
  1407. #endif
  1408. if(enable_mapgen_debug_info == false)
  1409. timer.stop(true); // Hide output
  1410. return block;
  1411. }
  1412. #endif
  1413. MapBlock * ServerMap::createBlock(v3s16 p)
  1414. {
  1415. /*
  1416. Do not create over max mapgen limit
  1417. */
  1418. if (blockpos_over_max_limit(p))
  1419. throw InvalidPositionException("createBlock(): pos. over max mapgen limit");
  1420. v2s16 p2d(p.X, p.Z);
  1421. s16 block_y = p.Y;
  1422. /*
  1423. This will create or load a sector if not found in memory.
  1424. If block exists on disk, it will be loaded.
  1425. NOTE: On old save formats, this will be slow, as it generates
  1426. lighting on blocks for them.
  1427. */
  1428. MapSector *sector;
  1429. try {
  1430. sector = createSector(p2d);
  1431. } catch (InvalidPositionException &e) {
  1432. infostream<<"createBlock: createSector() failed"<<std::endl;
  1433. throw e;
  1434. }
  1435. /*
  1436. Try to get a block from the sector
  1437. */
  1438. MapBlock *block = sector->getBlockNoCreateNoEx(block_y);
  1439. if (block) {
  1440. if(block->isDummy())
  1441. block->unDummify();
  1442. return block;
  1443. }
  1444. // Create blank
  1445. block = sector->createBlankBlock(block_y);
  1446. return block;
  1447. }
  1448. MapBlock * ServerMap::emergeBlock(v3s16 p, bool create_blank)
  1449. {
  1450. {
  1451. MapBlock *block = getBlockNoCreateNoEx(p);
  1452. if (block && !block->isDummy())
  1453. return block;
  1454. }
  1455. {
  1456. MapBlock *block = loadBlock(p);
  1457. if(block)
  1458. return block;
  1459. }
  1460. if (create_blank) {
  1461. MapSector *sector = createSector(v2s16(p.X, p.Z));
  1462. MapBlock *block = sector->createBlankBlock(p.Y);
  1463. return block;
  1464. }
  1465. return NULL;
  1466. }
  1467. MapBlock *ServerMap::getBlockOrEmerge(v3s16 p3d)
  1468. {
  1469. MapBlock *block = getBlockNoCreateNoEx(p3d);
  1470. if (block == NULL)
  1471. m_emerge->enqueueBlockEmerge(PEER_ID_INEXISTENT, p3d, false);
  1472. return block;
  1473. }
  1474. // N.B. This requires no synchronization, since data will not be modified unless
  1475. // the VoxelManipulator being updated belongs to the same thread.
  1476. void ServerMap::updateVManip(v3s16 pos)
  1477. {
  1478. Mapgen *mg = m_emerge->getCurrentMapgen();
  1479. if (!mg)
  1480. return;
  1481. MMVManip *vm = mg->vm;
  1482. if (!vm)
  1483. return;
  1484. if (!vm->m_area.contains(pos))
  1485. return;
  1486. s32 idx = vm->m_area.index(pos);
  1487. vm->m_data[idx] = getNode(pos);
  1488. vm->m_flags[idx] &= ~VOXELFLAG_NO_DATA;
  1489. vm->m_is_dirty = true;
  1490. }
  1491. void ServerMap::save(ModifiedState save_level)
  1492. {
  1493. if (!m_map_saving_enabled) {
  1494. warningstream<<"Not saving map, saving disabled."<<std::endl;
  1495. return;
  1496. }
  1497. u64 start_time = porting::getTimeNs();
  1498. if(save_level == MOD_STATE_CLEAN)
  1499. infostream<<"ServerMap: Saving whole map, this can take time."
  1500. <<std::endl;
  1501. if (m_map_metadata_changed || save_level == MOD_STATE_CLEAN) {
  1502. if (settings_mgr.saveMapMeta())
  1503. m_map_metadata_changed = false;
  1504. }
  1505. // Profile modified reasons
  1506. Profiler modprofiler;
  1507. u32 block_count = 0;
  1508. u32 block_count_all = 0; // Number of blocks in memory
  1509. // Don't do anything with sqlite unless something is really saved
  1510. bool save_started = false;
  1511. for (auto &sector_it : m_sectors) {
  1512. MapSector *sector = sector_it.second;
  1513. MapBlockVect blocks;
  1514. sector->getBlocks(blocks);
  1515. for (MapBlock *block : blocks) {
  1516. block_count_all++;
  1517. if(block->getModified() >= (u32)save_level) {
  1518. // Lazy beginSave()
  1519. if(!save_started) {
  1520. beginSave();
  1521. save_started = true;
  1522. }
  1523. modprofiler.add(block->getModifiedReasonString(), 1);
  1524. saveBlock(block);
  1525. block_count++;
  1526. }
  1527. }
  1528. }
  1529. if(save_started)
  1530. endSave();
  1531. /*
  1532. Only print if something happened or saved whole map
  1533. */
  1534. if(save_level == MOD_STATE_CLEAN
  1535. || block_count != 0) {
  1536. infostream << "ServerMap: Written: "
  1537. << block_count << " blocks"
  1538. << ", " << block_count_all << " blocks in memory."
  1539. << std::endl;
  1540. PrintInfo(infostream); // ServerMap/ClientMap:
  1541. infostream<<"Blocks modified by: "<<std::endl;
  1542. modprofiler.print(infostream);
  1543. }
  1544. auto end_time = porting::getTimeNs();
  1545. m_save_time_counter->increment(end_time - start_time);
  1546. }
  1547. void ServerMap::listAllLoadableBlocks(std::vector<v3s16> &dst)
  1548. {
  1549. dbase->listAllLoadableBlocks(dst);
  1550. if (dbase_ro)
  1551. dbase_ro->listAllLoadableBlocks(dst);
  1552. }
  1553. void ServerMap::listAllLoadedBlocks(std::vector<v3s16> &dst)
  1554. {
  1555. for (auto &sector_it : m_sectors) {
  1556. MapSector *sector = sector_it.second;
  1557. MapBlockVect blocks;
  1558. sector->getBlocks(blocks);
  1559. for (MapBlock *block : blocks) {
  1560. v3s16 p = block->getPos();
  1561. dst.push_back(p);
  1562. }
  1563. }
  1564. }
  1565. MapDatabase *ServerMap::createDatabase(
  1566. const std::string &name,
  1567. const std::string &savedir,
  1568. Settings &conf)
  1569. {
  1570. if (name == "sqlite3")
  1571. return new MapDatabaseSQLite3(savedir);
  1572. if (name == "dummy")
  1573. return new Database_Dummy();
  1574. #if USE_LEVELDB
  1575. if (name == "leveldb")
  1576. return new Database_LevelDB(savedir);
  1577. #endif
  1578. #if USE_REDIS
  1579. if (name == "redis")
  1580. return new Database_Redis(conf);
  1581. #endif
  1582. #if USE_POSTGRESQL
  1583. if (name == "postgresql") {
  1584. std::string connect_string;
  1585. conf.getNoEx("pgsql_connection", connect_string);
  1586. return new MapDatabasePostgreSQL(connect_string);
  1587. }
  1588. #endif
  1589. throw BaseException(std::string("Database backend ") + name + " not supported.");
  1590. }
  1591. void ServerMap::beginSave()
  1592. {
  1593. dbase->beginSave();
  1594. }
  1595. void ServerMap::endSave()
  1596. {
  1597. dbase->endSave();
  1598. }
  1599. bool ServerMap::saveBlock(MapBlock *block)
  1600. {
  1601. return saveBlock(block, dbase, m_map_compression_level);
  1602. }
  1603. bool ServerMap::saveBlock(MapBlock *block, MapDatabase *db, int compression_level)
  1604. {
  1605. v3s16 p3d = block->getPos();
  1606. // Dummy blocks are not written
  1607. if (block->isDummy()) {
  1608. warningstream << "saveBlock: Not writing dummy block "
  1609. << PP(p3d) << std::endl;
  1610. return true;
  1611. }
  1612. // Format used for writing
  1613. u8 version = SER_FMT_VER_HIGHEST_WRITE;
  1614. /*
  1615. [0] u8 serialization version
  1616. [1] data
  1617. */
  1618. std::ostringstream o(std::ios_base::binary);
  1619. o.write((char*) &version, 1);
  1620. block->serialize(o, version, true, compression_level);
  1621. bool ret = db->saveBlock(p3d, o.str());
  1622. if (ret) {
  1623. // We just wrote it to the disk so clear modified flag
  1624. block->resetModified();
  1625. }
  1626. return ret;
  1627. }
  1628. void ServerMap::loadBlock(std::string *blob, v3s16 p3d, MapSector *sector, bool save_after_load)
  1629. {
  1630. try {
  1631. std::istringstream is(*blob, std::ios_base::binary);
  1632. u8 version = SER_FMT_VER_INVALID;
  1633. is.read((char*)&version, 1);
  1634. if(is.fail())
  1635. throw SerializationError("ServerMap::loadBlock(): Failed"
  1636. " to read MapBlock version");
  1637. MapBlock *block = NULL;
  1638. bool created_new = false;
  1639. block = sector->getBlockNoCreateNoEx(p3d.Y);
  1640. if(block == NULL)
  1641. {
  1642. block = sector->createBlankBlockNoInsert(p3d.Y);
  1643. created_new = true;
  1644. }
  1645. // Read basic data
  1646. block->deSerialize(is, version, true);
  1647. // If it's a new block, insert it to the map
  1648. if (created_new) {
  1649. sector->insertBlock(block);
  1650. ReflowScan scanner(this, m_emerge->ndef);
  1651. scanner.scan(block, &m_transforming_liquid);
  1652. }
  1653. /*
  1654. Save blocks loaded in old format in new format
  1655. */
  1656. //if(version < SER_FMT_VER_HIGHEST_READ || save_after_load)
  1657. // Only save if asked to; no need to update version
  1658. if(save_after_load)
  1659. saveBlock(block);
  1660. // We just loaded it from, so it's up-to-date.
  1661. block->resetModified();
  1662. }
  1663. catch(SerializationError &e)
  1664. {
  1665. errorstream<<"Invalid block data in database"
  1666. <<" ("<<p3d.X<<","<<p3d.Y<<","<<p3d.Z<<")"
  1667. <<" (SerializationError): "<<e.what()<<std::endl;
  1668. // TODO: Block should be marked as invalid in memory so that it is
  1669. // not touched but the game can run
  1670. if(g_settings->getBool("ignore_world_load_errors")){
  1671. errorstream<<"Ignoring block load error. Duck and cover! "
  1672. <<"(ignore_world_load_errors)"<<std::endl;
  1673. } else {
  1674. throw SerializationError("Invalid block data in database");
  1675. }
  1676. }
  1677. }
  1678. MapBlock* ServerMap::loadBlock(v3s16 blockpos)
  1679. {
  1680. bool created_new = (getBlockNoCreateNoEx(blockpos) == NULL);
  1681. v2s16 p2d(blockpos.X, blockpos.Z);
  1682. std::string ret;
  1683. dbase->loadBlock(blockpos, &ret);
  1684. if (!ret.empty()) {
  1685. loadBlock(&ret, blockpos, createSector(p2d), false);
  1686. } else if (dbase_ro) {
  1687. dbase_ro->loadBlock(blockpos, &ret);
  1688. if (!ret.empty()) {
  1689. loadBlock(&ret, blockpos, createSector(p2d), false);
  1690. }
  1691. } else {
  1692. return NULL;
  1693. }
  1694. MapBlock *block = getBlockNoCreateNoEx(blockpos);
  1695. if (created_new && (block != NULL)) {
  1696. std::map<v3s16, MapBlock*> modified_blocks;
  1697. // Fix lighting if necessary
  1698. voxalgo::update_block_border_lighting(this, block, modified_blocks);
  1699. if (!modified_blocks.empty()) {
  1700. //Modified lighting, send event
  1701. MapEditEvent event;
  1702. event.type = MEET_OTHER;
  1703. std::map<v3s16, MapBlock *>::iterator it;
  1704. for (it = modified_blocks.begin();
  1705. it != modified_blocks.end(); ++it)
  1706. event.modified_blocks.insert(it->first);
  1707. dispatchEvent(event);
  1708. }
  1709. }
  1710. return block;
  1711. }
  1712. bool ServerMap::deleteBlock(v3s16 blockpos)
  1713. {
  1714. if (!dbase->deleteBlock(blockpos))
  1715. return false;
  1716. MapBlock *block = getBlockNoCreateNoEx(blockpos);
  1717. if (block) {
  1718. v2s16 p2d(blockpos.X, blockpos.Z);
  1719. MapSector *sector = getSectorNoGenerate(p2d);
  1720. if (!sector)
  1721. return false;
  1722. sector->deleteBlock(block);
  1723. }
  1724. return true;
  1725. }
  1726. void ServerMap::PrintInfo(std::ostream &out)
  1727. {
  1728. out<<"ServerMap: ";
  1729. }
  1730. bool ServerMap::repairBlockLight(v3s16 blockpos,
  1731. std::map<v3s16, MapBlock *> *modified_blocks)
  1732. {
  1733. MapBlock *block = emergeBlock(blockpos, false);
  1734. if (!block || !block->isGenerated())
  1735. return false;
  1736. voxalgo::repair_block_light(this, block, modified_blocks);
  1737. return true;
  1738. }
  1739. MMVManip::MMVManip(Map *map):
  1740. VoxelManipulator(),
  1741. m_map(map)
  1742. {
  1743. }
  1744. void MMVManip::initialEmerge(v3s16 blockpos_min, v3s16 blockpos_max,
  1745. bool load_if_inexistent)
  1746. {
  1747. TimeTaker timer1("initialEmerge", &emerge_time);
  1748. // Units of these are MapBlocks
  1749. v3s16 p_min = blockpos_min;
  1750. v3s16 p_max = blockpos_max;
  1751. VoxelArea block_area_nodes
  1752. (p_min*MAP_BLOCKSIZE, (p_max+1)*MAP_BLOCKSIZE-v3s16(1,1,1));
  1753. u32 size_MB = block_area_nodes.getVolume()*4/1000000;
  1754. if(size_MB >= 1)
  1755. {
  1756. infostream<<"initialEmerge: area: ";
  1757. block_area_nodes.print(infostream);
  1758. infostream<<" ("<<size_MB<<"MB)";
  1759. infostream<<std::endl;
  1760. }
  1761. addArea(block_area_nodes);
  1762. for(s32 z=p_min.Z; z<=p_max.Z; z++)
  1763. for(s32 y=p_min.Y; y<=p_max.Y; y++)
  1764. for(s32 x=p_min.X; x<=p_max.X; x++)
  1765. {
  1766. u8 flags = 0;
  1767. MapBlock *block;
  1768. v3s16 p(x,y,z);
  1769. std::map<v3s16, u8>::iterator n;
  1770. n = m_loaded_blocks.find(p);
  1771. if(n != m_loaded_blocks.end())
  1772. continue;
  1773. bool block_data_inexistent = false;
  1774. {
  1775. TimeTaker timer2("emerge load", &emerge_load_time);
  1776. block = m_map->getBlockNoCreateNoEx(p);
  1777. if (!block || block->isDummy())
  1778. block_data_inexistent = true;
  1779. else
  1780. block->copyTo(*this);
  1781. }
  1782. if(block_data_inexistent)
  1783. {
  1784. if (load_if_inexistent && !blockpos_over_max_limit(p)) {
  1785. ServerMap *svrmap = (ServerMap *)m_map;
  1786. block = svrmap->emergeBlock(p, false);
  1787. if (block == NULL)
  1788. block = svrmap->createBlock(p);
  1789. block->copyTo(*this);
  1790. } else {
  1791. flags |= VMANIP_BLOCK_DATA_INEXIST;
  1792. /*
  1793. Mark area inexistent
  1794. */
  1795. VoxelArea a(p*MAP_BLOCKSIZE, (p+1)*MAP_BLOCKSIZE-v3s16(1,1,1));
  1796. // Fill with VOXELFLAG_NO_DATA
  1797. for(s32 z=a.MinEdge.Z; z<=a.MaxEdge.Z; z++)
  1798. for(s32 y=a.MinEdge.Y; y<=a.MaxEdge.Y; y++)
  1799. {
  1800. s32 i = m_area.index(a.MinEdge.X,y,z);
  1801. memset(&m_flags[i], VOXELFLAG_NO_DATA, MAP_BLOCKSIZE);
  1802. }
  1803. }
  1804. }
  1805. /*else if (block->getNode(0, 0, 0).getContent() == CONTENT_IGNORE)
  1806. {
  1807. // Mark that block was loaded as blank
  1808. flags |= VMANIP_BLOCK_CONTAINS_CIGNORE;
  1809. }*/
  1810. m_loaded_blocks[p] = flags;
  1811. }
  1812. m_is_dirty = false;
  1813. }
  1814. void MMVManip::blitBackAll(std::map<v3s16, MapBlock*> *modified_blocks,
  1815. bool overwrite_generated)
  1816. {
  1817. if(m_area.getExtent() == v3s16(0,0,0))
  1818. return;
  1819. /*
  1820. Copy data of all blocks
  1821. */
  1822. for (auto &loaded_block : m_loaded_blocks) {
  1823. v3s16 p = loaded_block.first;
  1824. MapBlock *block = m_map->getBlockNoCreateNoEx(p);
  1825. bool existed = !(loaded_block.second & VMANIP_BLOCK_DATA_INEXIST);
  1826. if (!existed || (block == NULL) ||
  1827. (!overwrite_generated && block->isGenerated()))
  1828. continue;
  1829. block->copyFrom(*this);
  1830. block->raiseModified(MOD_STATE_WRITE_NEEDED, MOD_REASON_VMANIP);
  1831. if(modified_blocks)
  1832. (*modified_blocks)[p] = block;
  1833. }
  1834. }
  1835. //END