15725f00e73ac6d725d46eb520195c15ea4d8137
[oweals/minetest.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 #include "database.h"
37
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         void setNodeMetadata(v3s16 p, NodeMetadata *meta);
311         void removeNodeMetadata(v3s16 p);
312
313         /*
314                 Node Timers
315                 These are basically coordinate wrappers to MapBlock
316         */
317
318         NodeTimer getNodeTimer(v3s16 p);
319         void setNodeTimer(v3s16 p, NodeTimer t);
320         void removeNodeTimer(v3s16 p);
321
322         /*
323                 Misc.
324         */
325         std::map<v2s16, MapSector*> *getSectorsPtr(){return &m_sectors;}
326
327         /*
328                 Variables
329         */
330
331         void transforming_liquid_add(v3s16 p);
332         s32 transforming_liquid_size();
333
334         virtual s16 getHeat(v3s16 p);
335         virtual s16 getHumidity(v3s16 p);
336
337 protected:
338         friend class LuaVoxelManip;
339
340         std::ostream &m_dout; // A bit deprecated, could be removed
341
342         IGameDef *m_gamedef;
343
344         std::set<MapEventReceiver*> m_event_receivers;
345
346         std::map<v2s16, MapSector*> m_sectors;
347
348         // Be sure to set this to NULL when the cached sector is deleted
349         MapSector *m_sector_cache;
350         v2s16 m_sector_cache_p;
351
352         // Queued transforming water nodes
353         UniqueQueue<v3s16> m_transforming_liquid;
354 };
355
356 /*
357         ServerMap
358
359         This is the only map class that is able to generate map.
360 */
361
362 class ServerMap : public Map
363 {
364 public:
365         /*
366                 savedir: directory to which map data should be saved
367         */
368         ServerMap(std::string savedir, IGameDef *gamedef, EmergeManager *emerge);
369         ~ServerMap();
370
371         s32 mapType() const
372         {
373                 return MAPTYPE_SERVER;
374         }
375
376         /*
377                 Get a sector from somewhere.
378                 - Check memory
379                 - Check disk (doesn't load blocks)
380                 - Create blank one
381         */
382         ServerMapSector * createSector(v2s16 p);
383
384         /*
385                 Blocks are generated by using these and makeBlock().
386         */
387         bool initBlockMake(BlockMakeData *data, v3s16 blockpos);
388         MapBlock *finishBlockMake(BlockMakeData *data,
389                         std::map<v3s16, MapBlock*> &changed_blocks);
390
391         /*
392                 Get a block from somewhere.
393                 - Memory
394                 - Create blank
395         */
396         MapBlock * createBlock(v3s16 p);
397
398         /*
399                 Forcefully get a block from somewhere.
400                 - Memory
401                 - Load from disk
402                 - Create blank filled with CONTENT_IGNORE
403
404         */
405         MapBlock * emergeBlock(v3s16 p, bool create_blank=true);
406
407         // Helper for placing objects on ground level
408         s16 findGroundLevel(v2s16 p2d);
409
410         /*
411                 Misc. helper functions for fiddling with directory and file
412                 names when saving
413         */
414         void createDirs(std::string path);
415         // returns something like "map/sectors/xxxxxxxx"
416         std::string getSectorDir(v2s16 pos, int layout = 2);
417         // dirname: final directory name
418         v2s16 getSectorPos(std::string dirname);
419         v3s16 getBlockPos(std::string sectordir, std::string blockfile);
420         static std::string getBlockFilename(v3s16 p);
421
422         /*
423                 Database functions
424         */
425         // Verify we can read/write to the database
426         void verifyDatabase();
427
428         // Returns true if the database file does not exist
429         bool loadFromFolders();
430
431         // Call these before and after saving of blocks
432         void beginSave();
433         void endSave();
434
435         void save(ModifiedState save_level);
436         void listAllLoadableBlocks(std::list<v3s16> &dst);
437         void listAllLoadedBlocks(std::list<v3s16> &dst);
438         // Saves map seed and possibly other stuff
439         void saveMapMeta();
440         void loadMapMeta();
441
442         /*void saveChunkMeta();
443         void loadChunkMeta();*/
444
445         // The sector mutex should be locked when calling most of these
446
447         // This only saves sector-specific data such as the heightmap
448         // (no MapBlocks)
449         // DEPRECATED? Sectors have no metadata anymore.
450         void saveSectorMeta(ServerMapSector *sector);
451         MapSector* loadSectorMeta(std::string dirname, bool save_after_load);
452         bool loadSectorMeta(v2s16 p2d);
453
454         // Full load of a sector including all blocks.
455         // returns true on success, false on failure.
456         bool loadSectorFull(v2s16 p2d);
457         // If sector is not found in memory, try to load it from disk.
458         // Returns true if sector now resides in memory
459         //bool deFlushSector(v2s16 p2d);
460
461         void saveBlock(MapBlock *block);
462         // This will generate a sector with getSector if not found.
463         void loadBlock(std::string sectordir, std::string blockfile, MapSector *sector, bool save_after_load=false);
464         MapBlock* loadBlock(v3s16 p);
465         // Database version
466         void loadBlock(std::string *blob, v3s16 p3d, MapSector *sector, bool save_after_load=false);
467
468         // For debug printing
469         virtual void PrintInfo(std::ostream &out);
470
471         bool isSavingEnabled(){ return m_map_saving_enabled; }
472
473         u64 getSeed(){ return m_seed; }
474
475         MapgenParams *getMapgenParams(){ return m_mgparams; }
476
477         // Parameters fed to the Mapgen
478         MapgenParams *m_mgparams;
479
480         virtual s16 getHeat(ServerEnvironment *env, v3s16 p, MapBlock *block = NULL);
481         virtual s16 getHumidity(ServerEnvironment *env, v3s16 p, MapBlock *block = NULL);
482
483 private:
484         // Seed used for all kinds of randomness in generation
485         u64 m_seed;
486         
487         // Emerge manager
488         EmergeManager *m_emerge;
489
490         std::string m_savedir;
491         bool m_map_saving_enabled;
492
493 #if 0
494         // Chunk size in MapSectors
495         // If 0, chunks are disabled.
496         s16 m_chunksize;
497         // Chunks
498         core::map<v2s16, MapChunk*> m_chunks;
499 #endif
500
501         /*
502                 Metadata is re-written on disk only if this is true.
503                 This is reset to false when written on disk.
504         */
505         bool m_map_metadata_changed;
506         Database *dbase;
507 };
508
509 #define VMANIP_BLOCK_DATA_INEXIST     1
510 #define VMANIP_BLOCK_CONTAINS_CIGNORE 2
511
512 class MapVoxelManipulator : public VoxelManipulator
513 {
514 public:
515         MapVoxelManipulator(Map *map);
516         virtual ~MapVoxelManipulator();
517
518         virtual void clear()
519         {
520                 VoxelManipulator::clear();
521                 m_loaded_blocks.clear();
522         }
523
524         virtual void emerge(VoxelArea a, s32 caller_id=-1);
525
526         void blitBack(std::map<v3s16, MapBlock*> & modified_blocks);
527
528 protected:
529         Map *m_map;
530         /*
531                 key = blockpos
532                 value = flags describing the block
533         */
534         std::map<v3s16, u8> m_loaded_blocks;
535 };
536
537 class ManualMapVoxelManipulator : public MapVoxelManipulator
538 {
539 public:
540         ManualMapVoxelManipulator(Map *map);
541         virtual ~ManualMapVoxelManipulator();
542
543         void setMap(Map *map)
544         {m_map = map;}
545
546         virtual void emerge(VoxelArea a, s32 caller_id=-1);
547
548         void initialEmerge(v3s16 blockpos_min, v3s16 blockpos_max,
549                                                 bool load_if_inexistent = true);
550
551         // This is much faster with big chunks of generated data
552         void blitBackAll(std::map<v3s16, MapBlock*> * modified_blocks);
553
554 protected:
555         bool m_create_area;
556 };
557
558 #endif
559