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