]> git.lizzy.rs Git - dragonfireclient.git/blob - src/map.h
Fixed potential NULL pointer and leak when setting node metadata
[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 #ifndef MAP_HEADER
21 #define MAP_HEADER
22
23 #include <iostream>
24 #include <sstream>
25 #include <set>
26 #include <map>
27 #include <list>
28
29 #include "irrlichttypes_bloated.h"
30 #include "mapnode.h"
31 #include "constants.h"
32 #include "voxel.h"
33 #include "modifiedstate.h"
34 #include "util/container.h"
35 #include "nodetimer.h"
36
37 class Database;
38 class ClientMap;
39 class MapSector;
40 class ServerMapSector;
41 class MapBlock;
42 class NodeMetadata;
43 class IGameDef;
44 class IRollbackReportSink;
45 class EmergeManager;
46 class ServerEnvironment;
47 struct BlockMakeData;
48 struct MapgenParams;
49
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 metadata of block changed (not knowing which node exactly)
65         // p stores block coordinate
66         MEET_BLOCK_NODE_METADATA_CHANGED,
67         // Anything else (modified_blocks are set unsent)
68         MEET_OTHER
69 };
70
71 struct MapEditEvent
72 {
73         MapEditEventType type;
74         v3s16 p;
75         MapNode n;
76         std::set<v3s16> modified_blocks;
77         u16 already_known_by_peer;
78
79         MapEditEvent():
80                 type(MEET_OTHER),
81                 already_known_by_peer(0)
82         {
83         }
84
85         MapEditEvent * clone()
86         {
87                 MapEditEvent *event = new MapEditEvent();
88                 event->type = type;
89                 event->p = p;
90                 event->n = n;
91                 event->modified_blocks = modified_blocks;
92                 return event;
93         }
94
95         VoxelArea getArea()
96         {
97                 switch(type){
98                 case MEET_ADDNODE:
99                         return VoxelArea(p);
100                 case MEET_REMOVENODE:
101                         return VoxelArea(p);
102                 case MEET_BLOCK_NODE_METADATA_CHANGED:
103                 {
104                         v3s16 np1 = p*MAP_BLOCKSIZE;
105                         v3s16 np2 = np1 + v3s16(1,1,1)*MAP_BLOCKSIZE - v3s16(1,1,1);
106                         return VoxelArea(np1, np2);
107                 }
108                 case MEET_OTHER:
109                 {
110                         VoxelArea a;
111                         for(std::set<v3s16>::iterator
112                                         i = modified_blocks.begin();
113                                         i != modified_blocks.end(); ++i)
114                         {
115                                 v3s16 p = *i;
116                                 v3s16 np1 = p*MAP_BLOCKSIZE;
117                                 v3s16 np2 = np1 + v3s16(1,1,1)*MAP_BLOCKSIZE - v3s16(1,1,1);
118                                 a.addPoint(np1);
119                                 a.addPoint(np2);
120                         }
121                         return a;
122                 }
123                 }
124                 return VoxelArea();
125         }
126 };
127
128 class MapEventReceiver
129 {
130 public:
131         // event shall be deleted by caller after the call.
132         virtual void onMapEditEvent(MapEditEvent *event) = 0;
133 };
134
135 class Map /*: public NodeContainer*/
136 {
137 public:
138
139         Map(std::ostream &dout, IGameDef *gamedef);
140         virtual ~Map();
141
142         /*virtual u16 nodeContainerId() const
143         {
144                 return NODECONTAINER_ID_MAP;
145         }*/
146
147         virtual s32 mapType() const
148         {
149                 return MAPTYPE_BASE;
150         }
151
152         /*
153                 Drop (client) or delete (server) the map.
154         */
155         virtual void drop()
156         {
157                 delete this;
158         }
159
160         void addEventReceiver(MapEventReceiver *event_receiver);
161         void removeEventReceiver(MapEventReceiver *event_receiver);
162         // event shall be deleted by caller after the call.
163         void dispatchEvent(MapEditEvent *event);
164
165         // On failure returns NULL
166         MapSector * getSectorNoGenerateNoExNoLock(v2s16 p2d);
167         // Same as the above (there exists no lock anymore)
168         MapSector * getSectorNoGenerateNoEx(v2s16 p2d);
169         // On failure throws InvalidPositionException
170         MapSector * getSectorNoGenerate(v2s16 p2d);
171         // Gets an existing sector or creates an empty one
172         //MapSector * getSectorCreate(v2s16 p2d);
173
174         /*
175                 This is overloaded by ClientMap and ServerMap to allow
176                 their differing fetch methods.
177         */
178         virtual MapSector * emergeSector(v2s16 p){ return NULL; }
179         virtual MapSector * emergeSector(v2s16 p,
180                         std::map<v3s16, MapBlock*> &changed_blocks){ return NULL; }
181
182         // Returns InvalidPositionException if not found
183         MapBlock * getBlockNoCreate(v3s16 p);
184         // Returns NULL if not found
185         MapBlock * getBlockNoCreateNoEx(v3s16 p);
186
187         /* Server overrides */
188         virtual MapBlock * emergeBlock(v3s16 p, bool allow_generate=true)
189         { return getBlockNoCreateNoEx(p); }
190
191         // Returns InvalidPositionException if not found
192         bool isNodeUnderground(v3s16 p);
193
194         bool isValidPosition(v3s16 p);
195
196         // throws InvalidPositionException if not found
197         MapNode getNode(v3s16 p);
198
199         // throws InvalidPositionException if not found
200         void setNode(v3s16 p, MapNode & n);
201
202         // Returns a CONTENT_IGNORE node if not found
203         MapNode getNodeNoEx(v3s16 p);
204
205         void unspreadLight(enum LightBank bank,
206                         std::map<v3s16, u8> & from_nodes,
207                         std::set<v3s16> & light_sources,
208                         std::map<v3s16, MapBlock*> & modified_blocks);
209
210         void unLightNeighbors(enum LightBank bank,
211                         v3s16 pos, u8 lightwas,
212                         std::set<v3s16> & light_sources,
213                         std::map<v3s16, MapBlock*> & modified_blocks);
214
215         void spreadLight(enum LightBank bank,
216                         std::set<v3s16> & from_nodes,
217                         std::map<v3s16, MapBlock*> & modified_blocks);
218
219         void lightNeighbors(enum LightBank bank,
220                         v3s16 pos,
221                         std::map<v3s16, MapBlock*> & modified_blocks);
222
223         v3s16 getBrightestNeighbour(enum LightBank bank, v3s16 p);
224
225         s16 propagateSunlight(v3s16 start,
226                         std::map<v3s16, MapBlock*> & modified_blocks);
227
228         void updateLighting(enum LightBank bank,
229                         std::map<v3s16, MapBlock*>  & a_blocks,
230                         std::map<v3s16, MapBlock*> & modified_blocks);
231
232         void updateLighting(std::map<v3s16, MapBlock*>  & a_blocks,
233                         std::map<v3s16, MapBlock*> & modified_blocks);
234
235         /*
236                 These handle lighting but not faces.
237         */
238         void addNodeAndUpdate(v3s16 p, MapNode n,
239                         std::map<v3s16, MapBlock*> &modified_blocks);
240         void removeNodeAndUpdate(v3s16 p,
241                         std::map<v3s16, MapBlock*> &modified_blocks);
242
243         /*
244                 Wrappers for the latter ones.
245                 These emit events.
246                 Return true if succeeded, false if not.
247         */
248         bool addNodeWithEvent(v3s16 p, MapNode n);
249         bool removeNodeWithEvent(v3s16 p);
250
251         /*
252                 Takes the blocks at the edges into account
253         */
254         bool getDayNightDiff(v3s16 blockpos);
255
256         //core::aabbox3d<s16> getDisplayedBlockArea();
257
258         //bool updateChangedVisibleArea();
259
260         // Call these before and after saving of many blocks
261         virtual void beginSave() {return;};
262         virtual void endSave() {return;};
263
264         virtual void save(ModifiedState save_level){assert(0);};
265
266         // Server implements this.
267         // Client leaves it as no-op.
268         virtual void saveBlock(MapBlock *block){};
269
270         /*
271                 Updates usage timers and unloads unused blocks and sectors.
272                 Saves modified blocks before unloading on MAPTYPE_SERVER.
273         */
274         void timerUpdate(float dtime, float unload_timeout,
275                         std::list<v3s16> *unloaded_blocks=NULL);
276
277         /*
278                 Unloads all blocks with a zero refCount().
279                 Saves modified blocks before unloading on MAPTYPE_SERVER.
280         */
281         void unloadUnreferencedBlocks(std::list<v3s16> *unloaded_blocks=NULL);
282
283         // Deletes sectors and their blocks from memory
284         // Takes cache into account
285         // If deleted sector is in sector cache, clears cache
286         void deleteSectors(std::list<v2s16> &list);
287
288 #if 0
289         /*
290                 Unload unused data
291                 = flush changed to disk and delete from memory, if usage timer of
292                   block is more than timeout
293         */
294         void unloadUnusedData(float timeout,
295                         core::list<v3s16> *deleted_blocks=NULL);
296 #endif
297
298         // For debug printing. Prints "Map: ", "ServerMap: " or "ClientMap: "
299         virtual void PrintInfo(std::ostream &out);
300
301         void transformLiquids(std::map<v3s16, MapBlock*> & modified_blocks);
302         void transformLiquidsFinite(std::map<v3s16, MapBlock*> & modified_blocks);
303
304         /*
305                 Node metadata
306                 These are basically coordinate wrappers to MapBlock
307         */
308
309         NodeMetadata* getNodeMetadata(v3s16 p);
310
311         /**
312          * Sets metadata for a node.
313          * This method sets the metadata for a given node.
314          * On success, it returns @c true and the object pointed to
315          * by @p meta is then managed by the system and should
316          * not be deleted by the caller.
317          *
318          * In case of failure, the method returns @c false and the
319          * caller is still responsible for deleting the object!
320          *
321          * @param p node coordinates
322          * @param meta pointer to @c NodeMetadata object
323          * @return @c true on success, false on failure
324          */
325         bool setNodeMetadata(v3s16 p, NodeMetadata *meta);
326         void removeNodeMetadata(v3s16 p);
327
328         /*
329                 Node Timers
330                 These are basically coordinate wrappers to MapBlock
331         */
332
333         NodeTimer getNodeTimer(v3s16 p);
334         void setNodeTimer(v3s16 p, NodeTimer t);
335         void removeNodeTimer(v3s16 p);
336
337         /*
338                 Misc.
339         */
340         std::map<v2s16, MapSector*> *getSectorsPtr(){return &m_sectors;}
341
342         /*
343                 Variables
344         */
345
346         void transforming_liquid_add(v3s16 p);
347         s32 transforming_liquid_size();
348
349         virtual s16 getHeat(v3s16 p);
350         virtual s16 getHumidity(v3s16 p);
351
352 protected:
353         friend class LuaVoxelManip;
354
355         std::ostream &m_dout; // A bit deprecated, could be removed
356
357         IGameDef *m_gamedef;
358
359         std::set<MapEventReceiver*> m_event_receivers;
360
361         std::map<v2s16, MapSector*> m_sectors;
362
363         // Be sure to set this to NULL when the cached sector is deleted
364         MapSector *m_sector_cache;
365         v2s16 m_sector_cache_p;
366
367         // Queued transforming water nodes
368         UniqueQueue<v3s16> m_transforming_liquid;
369 };
370
371 /*
372         ServerMap
373
374         This is the only map class that is able to generate map.
375 */
376
377 class ServerMap : public Map
378 {
379 public:
380         /*
381                 savedir: directory to which map data should be saved
382         */
383         ServerMap(std::string savedir, IGameDef *gamedef, EmergeManager *emerge);
384         ~ServerMap();
385
386         s32 mapType() const
387         {
388                 return MAPTYPE_SERVER;
389         }
390
391         /*
392                 Get a sector from somewhere.
393                 - Check memory
394                 - Check disk (doesn't load blocks)
395                 - Create blank one
396         */
397         ServerMapSector * createSector(v2s16 p);
398
399         /*
400                 Blocks are generated by using these and makeBlock().
401         */
402         bool initBlockMake(BlockMakeData *data, v3s16 blockpos);
403         MapBlock *finishBlockMake(BlockMakeData *data,
404                         std::map<v3s16, MapBlock*> &changed_blocks);
405
406         /*
407                 Get a block from somewhere.
408                 - Memory
409                 - Create blank
410         */
411         MapBlock * createBlock(v3s16 p);
412
413         /*
414                 Forcefully get a block from somewhere.
415                 - Memory
416                 - Load from disk
417                 - Create blank filled with CONTENT_IGNORE
418
419         */
420         MapBlock * emergeBlock(v3s16 p, bool create_blank=true);
421         
422         // Carries out any initialization necessary before block is sent
423         void prepareBlock(MapBlock *block);
424
425         // Helper for placing objects on ground level
426         s16 findGroundLevel(v2s16 p2d);
427
428         /*
429                 Misc. helper functions for fiddling with directory and file
430                 names when saving
431         */
432         void createDirs(std::string path);
433         // returns something like "map/sectors/xxxxxxxx"
434         std::string getSectorDir(v2s16 pos, int layout = 2);
435         // dirname: final directory name
436         v2s16 getSectorPos(std::string dirname);
437         v3s16 getBlockPos(std::string sectordir, std::string blockfile);
438         static std::string getBlockFilename(v3s16 p);
439
440         /*
441                 Database functions
442         */
443         // Verify we can read/write to the database
444         void verifyDatabase();
445
446         // Returns true if the database file does not exist
447         bool loadFromFolders();
448
449         // Call these before and after saving of blocks
450         void beginSave();
451         void endSave();
452
453         void save(ModifiedState save_level);
454         void listAllLoadableBlocks(std::list<v3s16> &dst);
455         void listAllLoadedBlocks(std::list<v3s16> &dst);
456         // Saves map seed and possibly other stuff
457         void saveMapMeta();
458         void loadMapMeta();
459
460         /*void saveChunkMeta();
461         void loadChunkMeta();*/
462
463         // The sector mutex should be locked when calling most of these
464
465         // This only saves sector-specific data such as the heightmap
466         // (no MapBlocks)
467         // DEPRECATED? Sectors have no metadata anymore.
468         void saveSectorMeta(ServerMapSector *sector);
469         MapSector* loadSectorMeta(std::string dirname, bool save_after_load);
470         bool loadSectorMeta(v2s16 p2d);
471
472         // Full load of a sector including all blocks.
473         // returns true on success, false on failure.
474         bool loadSectorFull(v2s16 p2d);
475         // If sector is not found in memory, try to load it from disk.
476         // Returns true if sector now resides in memory
477         //bool deFlushSector(v2s16 p2d);
478
479         void saveBlock(MapBlock *block);
480         // This will generate a sector with getSector if not found.
481         void loadBlock(std::string sectordir, std::string blockfile, MapSector *sector, bool save_after_load=false);
482         MapBlock* loadBlock(v3s16 p);
483         // Database version
484         void loadBlock(std::string *blob, v3s16 p3d, MapSector *sector, bool save_after_load=false);
485
486         // For debug printing
487         virtual void PrintInfo(std::ostream &out);
488
489         bool isSavingEnabled(){ return m_map_saving_enabled; }
490
491         u64 getSeed(){ return m_seed; }
492
493         MapgenParams *getMapgenParams(){ return m_mgparams; }
494
495         // Parameters fed to the Mapgen
496         MapgenParams *m_mgparams;
497
498         virtual s16 updateBlockHeat(ServerEnvironment *env, v3s16 p, MapBlock *block = NULL);
499         virtual s16 updateBlockHumidity(ServerEnvironment *env, v3s16 p, MapBlock *block = NULL);
500
501 private:
502         // Seed used for all kinds of randomness in generation
503         u64 m_seed;
504         
505         // Emerge manager
506         EmergeManager *m_emerge;
507
508         std::string m_savedir;
509         bool m_map_saving_enabled;
510
511 #if 0
512         // Chunk size in MapSectors
513         // If 0, chunks are disabled.
514         s16 m_chunksize;
515         // Chunks
516         core::map<v2s16, MapChunk*> m_chunks;
517 #endif
518
519         /*
520                 Metadata is re-written on disk only if this is true.
521                 This is reset to false when written on disk.
522         */
523         bool m_map_metadata_changed;
524         Database *dbase;
525 };
526
527 #define VMANIP_BLOCK_DATA_INEXIST     1
528 #define VMANIP_BLOCK_CONTAINS_CIGNORE 2
529
530 class MapVoxelManipulator : public VoxelManipulator
531 {
532 public:
533         MapVoxelManipulator(Map *map);
534         virtual ~MapVoxelManipulator();
535
536         virtual void clear()
537         {
538                 VoxelManipulator::clear();
539                 m_loaded_blocks.clear();
540         }
541
542         virtual void emerge(VoxelArea a, s32 caller_id=-1);
543
544         void blitBack(std::map<v3s16, MapBlock*> & modified_blocks);
545
546 protected:
547         Map *m_map;
548         /*
549                 key = blockpos
550                 value = flags describing the block
551         */
552         std::map<v3s16, u8> m_loaded_blocks;
553 };
554
555 class ManualMapVoxelManipulator : public MapVoxelManipulator
556 {
557 public:
558         ManualMapVoxelManipulator(Map *map);
559         virtual ~ManualMapVoxelManipulator();
560
561         void setMap(Map *map)
562         {m_map = map;}
563
564         virtual void emerge(VoxelArea a, s32 caller_id=-1);
565
566         void initialEmerge(v3s16 blockpos_min, v3s16 blockpos_max,
567                                                 bool load_if_inexistent = true);
568
569         // This is much faster with big chunks of generated data
570         void blitBackAll(std::map<v3s16, MapBlock*> * modified_blocks);
571
572 protected:
573         bool m_create_area;
574 };
575
576 #endif
577