]> git.lizzy.rs Git - dragonfireclient.git/blob - src/map.h
Check node updates whether the blocks are known (#7568)
[dragonfireclient.git] / src / map.h
1 /*
2 Minetest
3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 GNU Lesser General Public License for more details.
14
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #pragma once
21
22 #include <iostream>
23 #include <sstream>
24 #include <set>
25 #include <map>
26 #include <list>
27
28 #include "irrlichttypes_bloated.h"
29 #include "mapnode.h"
30 #include "constants.h"
31 #include "voxel.h"
32 #include "modifiedstate.h"
33 #include "util/container.h"
34 #include "nodetimer.h"
35 #include "map_settings_manager.h"
36 #include "debug.h"
37
38 class Settings;
39 class MapDatabase;
40 class ClientMap;
41 class MapSector;
42 class ServerMapSector;
43 class MapBlock;
44 class NodeMetadata;
45 class IGameDef;
46 class IRollbackManager;
47 class EmergeManager;
48 class ServerEnvironment;
49 struct BlockMakeData;
50
51 /*
52         MapEditEvent
53 */
54
55 #define MAPTYPE_BASE 0
56 #define MAPTYPE_SERVER 1
57 #define MAPTYPE_CLIENT 2
58
59 enum MapEditEventType{
60         // Node added (changed from air or something else to something)
61         MEET_ADDNODE,
62         // Node removed (changed to air)
63         MEET_REMOVENODE,
64         // Node swapped (changed without metadata change)
65         MEET_SWAPNODE,
66         // Node metadata of block changed (not knowing which node exactly)
67         // p stores block coordinate
68         MEET_BLOCK_NODE_METADATA_CHANGED,
69         // Anything else (modified_blocks are set unsent)
70         MEET_OTHER
71 };
72
73 struct MapEditEvent
74 {
75         MapEditEventType type = MEET_OTHER;
76         v3s16 p;
77         MapNode n = CONTENT_AIR;
78         std::set<v3s16> modified_blocks;
79
80         MapEditEvent() = default;
81
82         MapEditEvent * clone()
83         {
84                 MapEditEvent *event = new MapEditEvent();
85                 event->type = type;
86                 event->p = p;
87                 event->n = n;
88                 event->modified_blocks = modified_blocks;
89                 return event;
90         }
91
92         VoxelArea getArea()
93         {
94                 switch(type){
95                 case MEET_ADDNODE:
96                         return VoxelArea(p);
97                 case MEET_REMOVENODE:
98                         return VoxelArea(p);
99                 case MEET_SWAPNODE:
100                         return VoxelArea(p);
101                 case MEET_BLOCK_NODE_METADATA_CHANGED:
102                 {
103                         v3s16 np1 = p*MAP_BLOCKSIZE;
104                         v3s16 np2 = np1 + v3s16(1,1,1)*MAP_BLOCKSIZE - v3s16(1,1,1);
105                         return VoxelArea(np1, np2);
106                 }
107                 case MEET_OTHER:
108                 {
109                         VoxelArea a;
110                         for (v3s16 p : modified_blocks) {
111                                 v3s16 np1 = p*MAP_BLOCKSIZE;
112                                 v3s16 np2 = np1 + v3s16(1,1,1)*MAP_BLOCKSIZE - v3s16(1,1,1);
113                                 a.addPoint(np1);
114                                 a.addPoint(np2);
115                         }
116                         return a;
117                 }
118                 }
119                 return VoxelArea();
120         }
121 };
122
123 class MapEventReceiver
124 {
125 public:
126         // event shall be deleted by caller after the call.
127         virtual void onMapEditEvent(MapEditEvent *event) = 0;
128 };
129
130 class Map /*: public NodeContainer*/
131 {
132 public:
133
134         Map(std::ostream &dout, IGameDef *gamedef);
135         virtual ~Map();
136         DISABLE_CLASS_COPY(Map);
137
138         virtual s32 mapType() const
139         {
140                 return MAPTYPE_BASE;
141         }
142
143         /*
144                 Drop (client) or delete (server) the map.
145         */
146         virtual void drop()
147         {
148                 delete this;
149         }
150
151         void addEventReceiver(MapEventReceiver *event_receiver);
152         void removeEventReceiver(MapEventReceiver *event_receiver);
153         // event shall be deleted by caller after the call.
154         void dispatchEvent(MapEditEvent *event);
155
156         // On failure returns NULL
157         MapSector * getSectorNoGenerateNoExNoLock(v2s16 p2d);
158         // Same as the above (there exists no lock anymore)
159         MapSector * getSectorNoGenerateNoEx(v2s16 p2d);
160         // On failure throws InvalidPositionException
161         MapSector * getSectorNoGenerate(v2s16 p2d);
162         // Gets an existing sector or creates an empty one
163         //MapSector * getSectorCreate(v2s16 p2d);
164
165         /*
166                 This is overloaded by ClientMap and ServerMap to allow
167                 their differing fetch methods.
168         */
169         virtual MapSector * emergeSector(v2s16 p){ return NULL; }
170
171         // Returns InvalidPositionException if not found
172         MapBlock * getBlockNoCreate(v3s16 p);
173         // Returns NULL if not found
174         MapBlock * getBlockNoCreateNoEx(v3s16 p);
175
176         /* Server overrides */
177         virtual MapBlock * emergeBlock(v3s16 p, bool create_blank=true)
178         { return getBlockNoCreateNoEx(p); }
179
180         inline const NodeDefManager * getNodeDefManager() { return m_nodedef; }
181
182         // Returns InvalidPositionException if not found
183         bool isNodeUnderground(v3s16 p);
184
185         bool isValidPosition(v3s16 p);
186
187         // throws InvalidPositionException if not found
188         void setNode(v3s16 p, MapNode & n);
189
190         // Returns a CONTENT_IGNORE node if not found
191         // If is_valid_position is not NULL then this will be set to true if the
192         // position is valid, otherwise false
193         MapNode getNodeNoEx(v3s16 p, bool *is_valid_position = NULL);
194
195         /*
196                 These handle lighting but not faces.
197         */
198         void addNodeAndUpdate(v3s16 p, MapNode n,
199                         std::map<v3s16, MapBlock*> &modified_blocks,
200                         bool remove_metadata = true);
201         void removeNodeAndUpdate(v3s16 p,
202                         std::map<v3s16, MapBlock*> &modified_blocks);
203
204         /*
205                 Wrappers for the latter ones.
206                 These emit events.
207                 Return true if succeeded, false if not.
208         */
209         bool addNodeWithEvent(v3s16 p, MapNode n, bool remove_metadata = true);
210         bool removeNodeWithEvent(v3s16 p);
211
212         // Call these before and after saving of many blocks
213         virtual void beginSave() {}
214         virtual void endSave() {}
215
216         virtual void save(ModifiedState save_level) { FATAL_ERROR("FIXME"); }
217
218         // Server implements these.
219         // Client leaves them as no-op.
220         virtual bool saveBlock(MapBlock *block) { return false; }
221         virtual bool deleteBlock(v3s16 blockpos) { return false; }
222
223         /*
224                 Updates usage timers and unloads unused blocks and sectors.
225                 Saves modified blocks before unloading on MAPTYPE_SERVER.
226         */
227         void timerUpdate(float dtime, float unload_timeout, u32 max_loaded_blocks,
228                         std::vector<v3s16> *unloaded_blocks=NULL);
229
230         /*
231                 Unloads all blocks with a zero refCount().
232                 Saves modified blocks before unloading on MAPTYPE_SERVER.
233         */
234         void unloadUnreferencedBlocks(std::vector<v3s16> *unloaded_blocks=NULL);
235
236         // Deletes sectors and their blocks from memory
237         // Takes cache into account
238         // If deleted sector is in sector cache, clears cache
239         void deleteSectors(std::vector<v2s16> &list);
240
241         // For debug printing. Prints "Map: ", "ServerMap: " or "ClientMap: "
242         virtual void PrintInfo(std::ostream &out);
243
244         void transformLiquids(std::map<v3s16, MapBlock*> & modified_blocks,
245                         ServerEnvironment *env);
246
247         /*
248                 Node metadata
249                 These are basically coordinate wrappers to MapBlock
250         */
251
252         std::vector<v3s16> findNodesWithMetadata(v3s16 p1, v3s16 p2);
253         NodeMetadata *getNodeMetadata(v3s16 p);
254
255         /**
256          * Sets metadata for a node.
257          * This method sets the metadata for a given node.
258          * On success, it returns @c true and the object pointed to
259          * by @p meta is then managed by the system and should
260          * not be deleted by the caller.
261          *
262          * In case of failure, the method returns @c false and the
263          * caller is still responsible for deleting the object!
264          *
265          * @param p node coordinates
266          * @param meta pointer to @c NodeMetadata object
267          * @return @c true on success, false on failure
268          */
269         bool setNodeMetadata(v3s16 p, NodeMetadata *meta);
270         void removeNodeMetadata(v3s16 p);
271
272         /*
273                 Node Timers
274                 These are basically coordinate wrappers to MapBlock
275         */
276
277         NodeTimer getNodeTimer(v3s16 p);
278         void setNodeTimer(const NodeTimer &t);
279         void removeNodeTimer(v3s16 p);
280
281         /*
282                 Misc.
283         */
284         std::map<v2s16, MapSector*> *getSectorsPtr(){return &m_sectors;}
285
286         /*
287                 Variables
288         */
289
290         void transforming_liquid_add(v3s16 p);
291
292         bool isBlockOccluded(MapBlock *block, v3s16 cam_pos_nodes);
293 protected:
294         friend class LuaVoxelManip;
295
296         std::ostream &m_dout; // A bit deprecated, could be removed
297
298         IGameDef *m_gamedef;
299
300         std::set<MapEventReceiver*> m_event_receivers;
301
302         std::map<v2s16, MapSector*> m_sectors;
303
304         // Be sure to set this to NULL when the cached sector is deleted
305         MapSector *m_sector_cache = nullptr;
306         v2s16 m_sector_cache_p;
307
308         // Queued transforming water nodes
309         UniqueQueue<v3s16> m_transforming_liquid;
310
311         // This stores the properties of the nodes on the map.
312         const NodeDefManager *m_nodedef;
313
314         bool isOccluded(v3s16 p0, v3s16 p1, float step, float stepfac,
315                         float start_off, float end_off, u32 needed_count);
316
317 private:
318         f32 m_transforming_liquid_loop_count_multiplier = 1.0f;
319         u32 m_unprocessed_count = 0;
320         u64 m_inc_trending_up_start_time = 0; // milliseconds
321         bool m_queue_size_timer_started = false;
322 };
323
324 /*
325         ServerMap
326
327         This is the only map class that is able to generate map.
328 */
329
330 class ServerMap : public Map
331 {
332 public:
333         /*
334                 savedir: directory to which map data should be saved
335         */
336         ServerMap(const std::string &savedir, IGameDef *gamedef, EmergeManager *emerge);
337         ~ServerMap();
338
339         s32 mapType() const
340         {
341                 return MAPTYPE_SERVER;
342         }
343
344         /*
345                 Get a sector from somewhere.
346                 - Check memory
347                 - Check disk (doesn't load blocks)
348                 - Create blank one
349         */
350         MapSector *createSector(v2s16 p);
351
352         /*
353                 Blocks are generated by using these and makeBlock().
354         */
355         bool blockpos_over_mapgen_limit(v3s16 p);
356         bool initBlockMake(v3s16 blockpos, BlockMakeData *data);
357         void finishBlockMake(BlockMakeData *data,
358                 std::map<v3s16, MapBlock*> *changed_blocks);
359
360         /*
361                 Get a block from somewhere.
362                 - Memory
363                 - Create blank
364         */
365         MapBlock *createBlock(v3s16 p);
366
367         /*
368                 Forcefully get a block from somewhere.
369                 - Memory
370                 - Load from disk
371                 - Create blank filled with CONTENT_IGNORE
372
373         */
374         MapBlock *emergeBlock(v3s16 p, bool create_blank=true);
375
376         /*
377                 Try to get a block.
378                 If it does not exist in memory, add it to the emerge queue.
379                 - Memory
380                 - Emerge Queue (deferred disk or generate)
381         */
382         MapBlock *getBlockOrEmerge(v3s16 p3d);
383
384         // Helper for placing objects on ground level
385         s16 findGroundLevel(v2s16 p2d);
386
387         /*
388                 Misc. helper functions for fiddling with directory and file
389                 names when saving
390         */
391         void createDirs(std::string path);
392         // returns something like "map/sectors/xxxxxxxx"
393         std::string getSectorDir(v2s16 pos, int layout = 2);
394         // dirname: final directory name
395         v2s16 getSectorPos(const std::string &dirname);
396         v3s16 getBlockPos(const std::string &sectordir, const std::string &blockfile);
397         static std::string getBlockFilename(v3s16 p);
398
399         /*
400                 Database functions
401         */
402         static MapDatabase *createDatabase(const std::string &name, const std::string &savedir, Settings &conf);
403
404         // Returns true if the database file does not exist
405         bool loadFromFolders();
406
407         // Call these before and after saving of blocks
408         void beginSave();
409         void endSave();
410
411         void save(ModifiedState save_level);
412         void listAllLoadableBlocks(std::vector<v3s16> &dst);
413         void listAllLoadedBlocks(std::vector<v3s16> &dst);
414
415         MapgenParams *getMapgenParams();
416
417         bool saveBlock(MapBlock *block);
418         static bool saveBlock(MapBlock *block, MapDatabase *db);
419         // This will generate a sector with getSector if not found.
420         void loadBlock(const std::string &sectordir, const std::string &blockfile,
421                         MapSector *sector, bool save_after_load=false);
422         MapBlock* loadBlock(v3s16 p);
423         // Database version
424         void loadBlock(std::string *blob, v3s16 p3d, MapSector *sector, bool save_after_load=false);
425
426         bool deleteBlock(v3s16 blockpos);
427
428         void updateVManip(v3s16 pos);
429
430         // For debug printing
431         virtual void PrintInfo(std::ostream &out);
432
433         bool isSavingEnabled(){ return m_map_saving_enabled; }
434
435         u64 getSeed();
436         s16 getWaterLevel();
437
438         /*!
439          * Fixes lighting in one map block.
440          * May modify other blocks as well, as light can spread
441          * out of the specified block.
442          * Returns false if the block is not generated (so nothing
443          * changed), true otherwise.
444          */
445         bool repairBlockLight(v3s16 blockpos,
446                 std::map<v3s16, MapBlock *> *modified_blocks);
447
448         MapSettingsManager settings_mgr;
449
450 private:
451         // Emerge manager
452         EmergeManager *m_emerge;
453
454         std::string m_savedir;
455         bool m_map_saving_enabled;
456
457 #if 0
458         // Chunk size in MapSectors
459         // If 0, chunks are disabled.
460         s16 m_chunksize;
461         // Chunks
462         core::map<v2s16, MapChunk*> m_chunks;
463 #endif
464
465         /*
466                 Metadata is re-written on disk only if this is true.
467                 This is reset to false when written on disk.
468         */
469         bool m_map_metadata_changed = true;
470         MapDatabase *dbase = nullptr;
471         MapDatabase *dbase_ro = nullptr;
472 };
473
474
475 #define VMANIP_BLOCK_DATA_INEXIST     1
476 #define VMANIP_BLOCK_CONTAINS_CIGNORE 2
477
478 class MMVManip : public VoxelManipulator
479 {
480 public:
481         MMVManip(Map *map);
482         virtual ~MMVManip() = default;
483
484         virtual void clear()
485         {
486                 VoxelManipulator::clear();
487                 m_loaded_blocks.clear();
488         }
489
490         void initialEmerge(v3s16 blockpos_min, v3s16 blockpos_max,
491                 bool load_if_inexistent = true);
492
493         // This is much faster with big chunks of generated data
494         void blitBackAll(std::map<v3s16, MapBlock*> * modified_blocks,
495                 bool overwrite_generated = true);
496
497         bool m_is_dirty = false;
498
499 protected:
500         Map *m_map;
501         /*
502                 key = blockpos
503                 value = flags describing the block
504         */
505         std::map<v3s16, u8> m_loaded_blocks;
506 };