map.h 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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. #pragma once
  17. #include <iostream>
  18. #include <sstream>
  19. #include <set>
  20. #include <map>
  21. #include <list>
  22. #include "irrlichttypes_bloated.h"
  23. #include "mapnode.h"
  24. #include "constants.h"
  25. #include "voxel.h"
  26. #include "modifiedstate.h"
  27. #include "util/container.h"
  28. #include "util/metricsbackend.h"
  29. #include "nodetimer.h"
  30. #include "map_settings_manager.h"
  31. #include "debug.h"
  32. class Settings;
  33. class MapDatabase;
  34. class ClientMap;
  35. class MapSector;
  36. class ServerMapSector;
  37. class MapBlock;
  38. class NodeMetadata;
  39. class IGameDef;
  40. class IRollbackManager;
  41. class EmergeManager;
  42. class MetricsBackend;
  43. class ServerEnvironment;
  44. struct BlockMakeData;
  45. /*
  46. MapEditEvent
  47. */
  48. enum MapEditEventType{
  49. // Node added (changed from air or something else to something)
  50. MEET_ADDNODE,
  51. // Node removed (changed to air)
  52. MEET_REMOVENODE,
  53. // Node swapped (changed without metadata change)
  54. MEET_SWAPNODE,
  55. // Node metadata changed
  56. MEET_BLOCK_NODE_METADATA_CHANGED,
  57. // Anything else (modified_blocks are set unsent)
  58. MEET_OTHER
  59. };
  60. struct MapEditEvent
  61. {
  62. MapEditEventType type = MEET_OTHER;
  63. v3s16 p;
  64. MapNode n = CONTENT_AIR;
  65. std::set<v3s16> modified_blocks;
  66. bool is_private_change = false;
  67. MapEditEvent() = default;
  68. VoxelArea getArea() const
  69. {
  70. switch(type){
  71. case MEET_ADDNODE:
  72. return VoxelArea(p);
  73. case MEET_REMOVENODE:
  74. return VoxelArea(p);
  75. case MEET_SWAPNODE:
  76. return VoxelArea(p);
  77. case MEET_BLOCK_NODE_METADATA_CHANGED:
  78. {
  79. v3s16 np1 = p*MAP_BLOCKSIZE;
  80. v3s16 np2 = np1 + v3s16(1,1,1)*MAP_BLOCKSIZE - v3s16(1,1,1);
  81. return VoxelArea(np1, np2);
  82. }
  83. case MEET_OTHER:
  84. {
  85. VoxelArea a;
  86. for (v3s16 p : modified_blocks) {
  87. v3s16 np1 = p*MAP_BLOCKSIZE;
  88. v3s16 np2 = np1 + v3s16(1,1,1)*MAP_BLOCKSIZE - v3s16(1,1,1);
  89. a.addPoint(np1);
  90. a.addPoint(np2);
  91. }
  92. return a;
  93. }
  94. }
  95. return VoxelArea();
  96. }
  97. };
  98. class MapEventReceiver
  99. {
  100. public:
  101. // event shall be deleted by caller after the call.
  102. virtual void onMapEditEvent(const MapEditEvent &event) = 0;
  103. };
  104. class Map /*: public NodeContainer*/
  105. {
  106. public:
  107. Map(IGameDef *gamedef);
  108. virtual ~Map();
  109. DISABLE_CLASS_COPY(Map);
  110. /*
  111. Drop (client) or delete (server) the map.
  112. */
  113. virtual void drop()
  114. {
  115. delete this;
  116. }
  117. void addEventReceiver(MapEventReceiver *event_receiver);
  118. void removeEventReceiver(MapEventReceiver *event_receiver);
  119. // event shall be deleted by caller after the call.
  120. void dispatchEvent(const MapEditEvent &event);
  121. // On failure returns NULL
  122. MapSector * getSectorNoGenerateNoLock(v2s16 p2d);
  123. // Same as the above (there exists no lock anymore)
  124. MapSector * getSectorNoGenerate(v2s16 p2d);
  125. /*
  126. This is overloaded by ClientMap and ServerMap to allow
  127. their differing fetch methods.
  128. */
  129. virtual MapSector * emergeSector(v2s16 p){ return NULL; }
  130. // Returns InvalidPositionException if not found
  131. MapBlock * getBlockNoCreate(v3s16 p);
  132. // Returns NULL if not found
  133. MapBlock * getBlockNoCreateNoEx(v3s16 p);
  134. /* Server overrides */
  135. virtual MapBlock * emergeBlock(v3s16 p, bool create_blank=true)
  136. { return getBlockNoCreateNoEx(p); }
  137. inline const NodeDefManager * getNodeDefManager() { return m_nodedef; }
  138. bool isValidPosition(v3s16 p);
  139. // throws InvalidPositionException if not found
  140. void setNode(v3s16 p, MapNode & n);
  141. // Returns a CONTENT_IGNORE node if not found
  142. // If is_valid_position is not NULL then this will be set to true if the
  143. // position is valid, otherwise false
  144. MapNode getNode(v3s16 p, bool *is_valid_position = NULL);
  145. /*
  146. These handle lighting but not faces.
  147. */
  148. virtual void addNodeAndUpdate(v3s16 p, MapNode n,
  149. std::map<v3s16, MapBlock*> &modified_blocks,
  150. bool remove_metadata = true);
  151. void removeNodeAndUpdate(v3s16 p,
  152. std::map<v3s16, MapBlock*> &modified_blocks);
  153. /*
  154. Wrappers for the latter ones.
  155. These emit events.
  156. Return true if succeeded, false if not.
  157. */
  158. bool addNodeWithEvent(v3s16 p, MapNode n, bool remove_metadata = true);
  159. bool removeNodeWithEvent(v3s16 p);
  160. // Call these before and after saving of many blocks
  161. virtual void beginSave() {}
  162. virtual void endSave() {}
  163. virtual void save(ModifiedState save_level) { FATAL_ERROR("FIXME"); }
  164. /*
  165. Return true unless the map definitely cannot save blocks.
  166. */
  167. virtual bool maySaveBlocks() { return true; }
  168. // Server implements these.
  169. // Client leaves them as no-op.
  170. virtual bool saveBlock(MapBlock *block) { return false; }
  171. virtual bool deleteBlock(v3s16 blockpos) { return false; }
  172. /*
  173. Updates usage timers and unloads unused blocks and sectors.
  174. Saves modified blocks before unloading if possible.
  175. */
  176. void timerUpdate(float dtime, float unload_timeout, u32 max_loaded_blocks,
  177. std::vector<v3s16> *unloaded_blocks=NULL);
  178. /*
  179. Unloads all blocks with a zero refCount().
  180. Saves modified blocks before unloading if possible.
  181. */
  182. void unloadUnreferencedBlocks(std::vector<v3s16> *unloaded_blocks=NULL);
  183. // Deletes sectors and their blocks from memory
  184. // Takes cache into account
  185. // If deleted sector is in sector cache, clears cache
  186. void deleteSectors(std::vector<v2s16> &list);
  187. // For debug printing. Prints "Map: ", "ServerMap: " or "ClientMap: "
  188. virtual void PrintInfo(std::ostream &out);
  189. /*
  190. Node metadata
  191. These are basically coordinate wrappers to MapBlock
  192. */
  193. std::vector<v3s16> findNodesWithMetadata(v3s16 p1, v3s16 p2);
  194. NodeMetadata *getNodeMetadata(v3s16 p);
  195. /**
  196. * Sets metadata for a node.
  197. * This method sets the metadata for a given node.
  198. * On success, it returns @c true and the object pointed to
  199. * by @p meta is then managed by the system and should
  200. * not be deleted by the caller.
  201. *
  202. * In case of failure, the method returns @c false and the
  203. * caller is still responsible for deleting the object!
  204. *
  205. * @param p node coordinates
  206. * @param meta pointer to @c NodeMetadata object
  207. * @return @c true on success, false on failure
  208. */
  209. bool setNodeMetadata(v3s16 p, NodeMetadata *meta);
  210. void removeNodeMetadata(v3s16 p);
  211. /*
  212. Node Timers
  213. These are basically coordinate wrappers to MapBlock
  214. */
  215. NodeTimer getNodeTimer(v3s16 p);
  216. void setNodeTimer(const NodeTimer &t);
  217. void removeNodeTimer(v3s16 p);
  218. /*
  219. Variables
  220. */
  221. bool isBlockOccluded(MapBlock *block, v3s16 cam_pos_nodes);
  222. protected:
  223. IGameDef *m_gamedef;
  224. std::set<MapEventReceiver*> m_event_receivers;
  225. std::unordered_map<v2s16, MapSector*> m_sectors;
  226. // Be sure to set this to NULL when the cached sector is deleted
  227. MapSector *m_sector_cache = nullptr;
  228. v2s16 m_sector_cache_p;
  229. // This stores the properties of the nodes on the map.
  230. const NodeDefManager *m_nodedef;
  231. // Can be implemented by child class
  232. virtual void reportMetrics(u64 save_time_us, u32 saved_blocks, u32 all_blocks) {}
  233. bool determineAdditionalOcclusionCheck(const v3s16 &pos_camera,
  234. const core::aabbox3d<s16> &block_bounds, v3s16 &check);
  235. bool isOccluded(const v3s16 &pos_camera, const v3s16 &pos_target,
  236. float step, float stepfac, float start_offset, float end_offset,
  237. u32 needed_count);
  238. };
  239. /*
  240. ServerMap
  241. This is the only map class that is able to generate map.
  242. */
  243. class ServerMap : public Map
  244. {
  245. public:
  246. /*
  247. savedir: directory to which map data should be saved
  248. */
  249. ServerMap(const std::string &savedir, IGameDef *gamedef, EmergeManager *emerge, MetricsBackend *mb);
  250. ~ServerMap();
  251. /*
  252. Get a sector from somewhere.
  253. - Check memory
  254. - Check disk (doesn't load blocks)
  255. - Create blank one
  256. */
  257. MapSector *createSector(v2s16 p);
  258. /*
  259. Blocks are generated by using these and makeBlock().
  260. */
  261. bool blockpos_over_mapgen_limit(v3s16 p);
  262. bool initBlockMake(v3s16 blockpos, BlockMakeData *data);
  263. void finishBlockMake(BlockMakeData *data,
  264. std::map<v3s16, MapBlock*> *changed_blocks);
  265. /*
  266. Get a block from somewhere.
  267. - Memory
  268. - Create blank
  269. */
  270. MapBlock *createBlock(v3s16 p);
  271. /*
  272. Forcefully get a block from somewhere.
  273. - Memory
  274. - Load from disk
  275. - Create blank filled with CONTENT_IGNORE
  276. */
  277. MapBlock *emergeBlock(v3s16 p, bool create_blank=true) override;
  278. /*
  279. Try to get a block.
  280. If it does not exist in memory, add it to the emerge queue.
  281. - Memory
  282. - Emerge Queue (deferred disk or generate)
  283. */
  284. MapBlock *getBlockOrEmerge(v3s16 p3d);
  285. bool isBlockInQueue(v3s16 pos);
  286. void addNodeAndUpdate(v3s16 p, MapNode n,
  287. std::map<v3s16, MapBlock*> &modified_blocks,
  288. bool remove_metadata) override;
  289. /*
  290. Database functions
  291. */
  292. static MapDatabase *createDatabase(const std::string &name, const std::string &savedir, Settings &conf);
  293. // Call these before and after saving of blocks
  294. void beginSave() override;
  295. void endSave() override;
  296. void save(ModifiedState save_level) override;
  297. void listAllLoadableBlocks(std::vector<v3s16> &dst);
  298. void listAllLoadedBlocks(std::vector<v3s16> &dst);
  299. MapgenParams *getMapgenParams();
  300. bool saveBlock(MapBlock *block) override;
  301. static bool saveBlock(MapBlock *block, MapDatabase *db, int compression_level = -1);
  302. MapBlock* loadBlock(v3s16 p);
  303. // Database version
  304. void loadBlock(std::string *blob, v3s16 p3d, MapSector *sector, bool save_after_load=false);
  305. bool deleteBlock(v3s16 blockpos) override;
  306. void updateVManip(v3s16 pos);
  307. // For debug printing
  308. void PrintInfo(std::ostream &out) override;
  309. bool isSavingEnabled(){ return m_map_saving_enabled; }
  310. u64 getSeed();
  311. /*!
  312. * Fixes lighting in one map block.
  313. * May modify other blocks as well, as light can spread
  314. * out of the specified block.
  315. * Returns false if the block is not generated (so nothing
  316. * changed), true otherwise.
  317. */
  318. bool repairBlockLight(v3s16 blockpos,
  319. std::map<v3s16, MapBlock *> *modified_blocks);
  320. void transformLiquids(std::map<v3s16, MapBlock*> & modified_blocks,
  321. ServerEnvironment *env);
  322. void transforming_liquid_add(v3s16 p);
  323. MapSettingsManager settings_mgr;
  324. protected:
  325. void reportMetrics(u64 save_time_us, u32 saved_blocks, u32 all_blocks) override;
  326. private:
  327. friend class LuaVoxelManip;
  328. // Emerge manager
  329. EmergeManager *m_emerge;
  330. std::string m_savedir;
  331. bool m_map_saving_enabled;
  332. int m_map_compression_level;
  333. std::set<v3s16> m_chunks_in_progress;
  334. // Queued transforming water nodes
  335. UniqueQueue<v3s16> m_transforming_liquid;
  336. f32 m_transforming_liquid_loop_count_multiplier = 1.0f;
  337. u32 m_unprocessed_count = 0;
  338. u64 m_inc_trending_up_start_time = 0; // milliseconds
  339. bool m_queue_size_timer_started = false;
  340. /*
  341. Metadata is re-written on disk only if this is true.
  342. This is reset to false when written on disk.
  343. */
  344. bool m_map_metadata_changed = true;
  345. MapDatabase *dbase = nullptr;
  346. MapDatabase *dbase_ro = nullptr;
  347. // Map metrics
  348. MetricGaugePtr m_loaded_blocks_gauge;
  349. MetricCounterPtr m_save_time_counter;
  350. MetricCounterPtr m_save_count_counter;
  351. };
  352. #define VMANIP_BLOCK_DATA_INEXIST 1
  353. #define VMANIP_BLOCK_CONTAINS_CIGNORE 2
  354. class MMVManip : public VoxelManipulator
  355. {
  356. public:
  357. MMVManip(Map *map);
  358. virtual ~MMVManip() = default;
  359. virtual void clear()
  360. {
  361. VoxelManipulator::clear();
  362. m_loaded_blocks.clear();
  363. }
  364. void initialEmerge(v3s16 blockpos_min, v3s16 blockpos_max,
  365. bool load_if_inexistent = true);
  366. // This is much faster with big chunks of generated data
  367. void blitBackAll(std::map<v3s16, MapBlock*> * modified_blocks,
  368. bool overwrite_generated = true);
  369. /*
  370. Creates a copy of this VManip including contents, the copy will not be
  371. associated with a Map.
  372. */
  373. MMVManip *clone() const;
  374. // Reassociates a copied VManip to a map
  375. void reparent(Map *map);
  376. // Is it impossible to call initialEmerge / blitBackAll?
  377. inline bool isOrphan() const { return !m_map; }
  378. bool m_is_dirty = false;
  379. protected:
  380. MMVManip() {};
  381. // may be null
  382. Map *m_map = nullptr;
  383. /*
  384. key = blockpos
  385. value = flags describing the block
  386. */
  387. std::map<v3s16, u8> m_loaded_blocks;
  388. };