Performance fix + SAO factorization
[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 "util/cpp11_container.h"
36 #include "nodetimer.h"
37 #include "map_settings_manager.h"
38
39 class Settings;
40 class Database;
41 class ClientMap;
42 class MapSector;
43 class ServerMapSector;
44 class MapBlock;
45 class NodeMetadata;
46 class IGameDef;
47 class IRollbackManager;
48 class EmergeManager;
49 class ServerEnvironment;
50 struct BlockMakeData;
51
52 /*
53         MapEditEvent
54 */
55
56 #define MAPTYPE_BASE 0
57 #define MAPTYPE_SERVER 1
58 #define MAPTYPE_CLIENT 2
59
60 enum MapEditEventType{
61         // Node added (changed from air or something else to something)
62         MEET_ADDNODE,
63         // Node removed (changed to air)
64         MEET_REMOVENODE,
65         // Node swapped (changed without metadata change)
66         MEET_SWAPNODE,
67         // Node metadata of block changed (not knowing which node exactly)
68         // p stores block coordinate
69         MEET_BLOCK_NODE_METADATA_CHANGED,
70         // Anything else (modified_blocks are set unsent)
71         MEET_OTHER
72 };
73
74 struct MapEditEvent
75 {
76         MapEditEventType type;
77         v3s16 p;
78         MapNode n;
79         std::set<v3s16> modified_blocks;
80         u16 already_known_by_peer;
81
82         MapEditEvent():
83                 type(MEET_OTHER),
84                 n(CONTENT_AIR),
85                 already_known_by_peer(0)
86         { }
87
88         MapEditEvent * clone()
89         {
90                 MapEditEvent *event = new MapEditEvent();
91                 event->type = type;
92                 event->p = p;
93                 event->n = n;
94                 event->modified_blocks = modified_blocks;
95                 return event;
96         }
97
98         VoxelArea getArea()
99         {
100                 switch(type){
101                 case MEET_ADDNODE:
102                         return VoxelArea(p);
103                 case MEET_REMOVENODE:
104                         return VoxelArea(p);
105                 case MEET_SWAPNODE:
106                         return VoxelArea(p);
107                 case MEET_BLOCK_NODE_METADATA_CHANGED:
108                 {
109                         v3s16 np1 = p*MAP_BLOCKSIZE;
110                         v3s16 np2 = np1 + v3s16(1,1,1)*MAP_BLOCKSIZE - v3s16(1,1,1);
111                         return VoxelArea(np1, np2);
112                 }
113                 case MEET_OTHER:
114                 {
115                         VoxelArea a;
116                         for(std::set<v3s16>::iterator
117                                         i = modified_blocks.begin();
118                                         i != modified_blocks.end(); ++i)
119                         {
120                                 v3s16 p = *i;
121                                 v3s16 np1 = p*MAP_BLOCKSIZE;
122                                 v3s16 np2 = np1 + v3s16(1,1,1)*MAP_BLOCKSIZE - v3s16(1,1,1);
123                                 a.addPoint(np1);
124                                 a.addPoint(np2);
125                         }
126                         return a;
127                 }
128                 }
129                 return VoxelArea();
130         }
131 };
132
133 class MapEventReceiver
134 {
135 public:
136         // event shall be deleted by caller after the call.
137         virtual void onMapEditEvent(MapEditEvent *event) = 0;
138 };
139
140 class Map /*: public NodeContainer*/
141 {
142 public:
143
144         Map(std::ostream &dout, IGameDef *gamedef);
145         virtual ~Map();
146
147         /*virtual u16 nodeContainerId() const
148         {
149                 return NODECONTAINER_ID_MAP;
150         }*/
151
152         virtual s32 mapType() const
153         {
154                 return MAPTYPE_BASE;
155         }
156
157         /*
158                 Drop (client) or delete (server) the map.
159         */
160         virtual void drop()
161         {
162                 delete this;
163         }
164
165         void addEventReceiver(MapEventReceiver *event_receiver);
166         void removeEventReceiver(MapEventReceiver *event_receiver);
167         // event shall be deleted by caller after the call.
168         void dispatchEvent(MapEditEvent *event);
169
170         // On failure returns NULL
171         MapSector * getSectorNoGenerateNoExNoLock(v2s16 p2d);
172         // Same as the above (there exists no lock anymore)
173         MapSector * getSectorNoGenerateNoEx(v2s16 p2d);
174         // On failure throws InvalidPositionException
175         MapSector * getSectorNoGenerate(v2s16 p2d);
176         // Gets an existing sector or creates an empty one
177         //MapSector * getSectorCreate(v2s16 p2d);
178
179         /*
180                 This is overloaded by ClientMap and ServerMap to allow
181                 their differing fetch methods.
182         */
183         virtual MapSector * emergeSector(v2s16 p){ return NULL; }
184         virtual MapSector * emergeSector(v2s16 p,
185                         std::map<v3s16, MapBlock*> &changed_blocks){ return NULL; }
186
187         // Returns InvalidPositionException if not found
188         MapBlock * getBlockNoCreate(v3s16 p);
189         // Returns NULL if not found
190         MapBlock * getBlockNoCreateNoEx(v3s16 p);
191
192         /* Server overrides */
193         virtual MapBlock * emergeBlock(v3s16 p, bool create_blank=true)
194         { return getBlockNoCreateNoEx(p); }
195
196         inline INodeDefManager * getNodeDefManager() { return m_nodedef; }
197
198         // Returns InvalidPositionException if not found
199         bool isNodeUnderground(v3s16 p);
200
201         bool isValidPosition(v3s16 p);
202
203         // throws InvalidPositionException if not found
204         void setNode(v3s16 p, MapNode & n);
205
206         // Returns a CONTENT_IGNORE node if not found
207         // If is_valid_position is not NULL then this will be set to true if the
208         // position is valid, otherwise false
209         MapNode getNodeNoEx(v3s16 p, bool *is_valid_position = NULL);
210
211         void unspreadLight(enum LightBank bank,
212                         std::map<v3s16, u8> & from_nodes,
213                         std::set<v3s16> & light_sources,
214                         std::map<v3s16, MapBlock*> & modified_blocks);
215
216         void spreadLight(enum LightBank bank,
217                         std::set<v3s16> & from_nodes,
218                         std::map<v3s16, MapBlock*> & modified_blocks);
219         
220         void updateLighting(enum LightBank bank,
221                         std::map<v3s16, MapBlock*>  & a_blocks,
222                         std::map<v3s16, MapBlock*> & modified_blocks);
223
224         void updateLighting(std::map<v3s16, MapBlock*>  & a_blocks,
225                         std::map<v3s16, MapBlock*> & modified_blocks);
226
227         /*
228                 These handle lighting but not faces.
229         */
230         void addNodeAndUpdate(v3s16 p, MapNode n,
231                         std::map<v3s16, MapBlock*> &modified_blocks,
232                         bool remove_metadata = true);
233         void removeNodeAndUpdate(v3s16 p,
234                         std::map<v3s16, MapBlock*> &modified_blocks);
235
236         /*
237                 Wrappers for the latter ones.
238                 These emit events.
239                 Return true if succeeded, false if not.
240         */
241         bool addNodeWithEvent(v3s16 p, MapNode n, bool remove_metadata = true);
242         bool removeNodeWithEvent(v3s16 p);
243
244         /*
245                 Takes the blocks at the edges into account
246         */
247         bool getDayNightDiff(v3s16 blockpos);
248
249         //core::aabbox3d<s16> getDisplayedBlockArea();
250
251         //bool updateChangedVisibleArea();
252
253         // Call these before and after saving of many blocks
254         virtual void beginSave() { return; }
255         virtual void endSave() { return; }
256
257         virtual void save(ModifiedState save_level) { FATAL_ERROR("FIXME"); }
258
259         // Server implements these.
260         // Client leaves them as no-op.
261         virtual bool saveBlock(MapBlock *block) { return false; }
262         virtual bool deleteBlock(v3s16 blockpos) { return false; }
263
264         /*
265                 Updates usage timers and unloads unused blocks and sectors.
266                 Saves modified blocks before unloading on MAPTYPE_SERVER.
267         */
268         void timerUpdate(float dtime, float unload_timeout, u32 max_loaded_blocks,
269                         std::vector<v3s16> *unloaded_blocks=NULL);
270
271         /*
272                 Unloads all blocks with a zero refCount().
273                 Saves modified blocks before unloading on MAPTYPE_SERVER.
274         */
275         void unloadUnreferencedBlocks(std::vector<v3s16> *unloaded_blocks=NULL);
276
277         // Deletes sectors and their blocks from memory
278         // Takes cache into account
279         // If deleted sector is in sector cache, clears cache
280         void deleteSectors(std::vector<v2s16> &list);
281
282         // For debug printing. Prints "Map: ", "ServerMap: " or "ClientMap: "
283         virtual void PrintInfo(std::ostream &out);
284
285         void transformLiquids(std::map<v3s16, MapBlock*> & modified_blocks);
286
287         /*
288                 Node metadata
289                 These are basically coordinate wrappers to MapBlock
290         */
291
292         std::vector<v3s16> findNodesWithMetadata(v3s16 p1, v3s16 p2);
293         NodeMetadata *getNodeMetadata(v3s16 p);
294
295         /**
296          * Sets metadata for a node.
297          * This method sets the metadata for a given node.
298          * On success, it returns @c true and the object pointed to
299          * by @p meta is then managed by the system and should
300          * not be deleted by the caller.
301          *
302          * In case of failure, the method returns @c false and the
303          * caller is still responsible for deleting the object!
304          *
305          * @param p node coordinates
306          * @param meta pointer to @c NodeMetadata object
307          * @return @c true on success, false on failure
308          */
309         bool setNodeMetadata(v3s16 p, NodeMetadata *meta);
310         void removeNodeMetadata(v3s16 p);
311
312         /*
313                 Node Timers
314                 These are basically coordinate wrappers to MapBlock
315         */
316
317         NodeTimer getNodeTimer(v3s16 p);
318         void setNodeTimer(const NodeTimer &t);
319         void removeNodeTimer(v3s16 p);
320
321         /*
322                 Misc.
323         */
324         std::map<v2s16, MapSector*> *getSectorsPtr(){return &m_sectors;}
325
326         /*
327                 Variables
328         */
329
330         void transforming_liquid_add(v3s16 p);
331         s32 transforming_liquid_size();
332
333 protected:
334         friend class LuaVoxelManip;
335
336         std::ostream &m_dout; // A bit deprecated, could be removed
337
338         IGameDef *m_gamedef;
339
340         std::set<MapEventReceiver*> m_event_receivers;
341
342         std::map<v2s16, MapSector*> m_sectors;
343
344         // Be sure to set this to NULL when the cached sector is deleted
345         MapSector *m_sector_cache;
346         v2s16 m_sector_cache_p;
347
348         // Queued transforming water nodes
349         UniqueQueue<v3s16> m_transforming_liquid;
350
351         // This stores the properties of the nodes on the map.
352         INodeDefManager *m_nodedef;
353
354 private:
355         f32 m_transforming_liquid_loop_count_multiplier;
356         u32 m_unprocessed_count;
357         u32 m_inc_trending_up_start_time; // milliseconds
358         bool m_queue_size_timer_started;
359
360         DISABLE_CLASS_COPY(Map);
361 };
362
363 /*
364         ServerMap
365
366         This is the only map class that is able to generate map.
367 */
368
369 class ServerMap : public Map
370 {
371 public:
372         /*
373                 savedir: directory to which map data should be saved
374         */
375         ServerMap(std::string savedir, IGameDef *gamedef, EmergeManager *emerge);
376         ~ServerMap();
377
378         s32 mapType() const
379         {
380                 return MAPTYPE_SERVER;
381         }
382
383         /*
384                 Get a sector from somewhere.
385                 - Check memory
386                 - Check disk (doesn't load blocks)
387                 - Create blank one
388         */
389         ServerMapSector *createSector(v2s16 p);
390
391         /*
392                 Blocks are generated by using these and makeBlock().
393         */
394         bool initBlockMake(v3s16 blockpos, BlockMakeData *data);
395         void finishBlockMake(BlockMakeData *data,
396                 std::map<v3s16, MapBlock*> *changed_blocks);
397
398         /*
399                 Get a block from somewhere.
400                 - Memory
401                 - Create blank
402         */
403         MapBlock *createBlock(v3s16 p);
404
405         /*
406                 Forcefully get a block from somewhere.
407                 - Memory
408                 - Load from disk
409                 - Create blank filled with CONTENT_IGNORE
410
411         */
412         MapBlock *emergeBlock(v3s16 p, bool create_blank=true);
413
414         /*
415                 Try to get a block.
416                 If it does not exist in memory, add it to the emerge queue.
417                 - Memory
418                 - Emerge Queue (deferred disk or generate)
419         */
420         MapBlock *getBlockOrEmerge(v3s16 p3d);
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         static Database *createDatabase(const std::string &name, const std::string &savedir, Settings &conf);
444         // Verify we can read/write to the database
445         void verifyDatabase();
446
447         // Returns true if the database file does not exist
448         bool loadFromFolders();
449
450         // Call these before and after saving of blocks
451         void beginSave();
452         void endSave();
453
454         void save(ModifiedState save_level);
455         void listAllLoadableBlocks(std::vector<v3s16> &dst);
456         void listAllLoadedBlocks(std::vector<v3s16> &dst);
457
458         MapgenParams *getMapgenParams();
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         bool saveBlock(MapBlock *block);
480         static bool saveBlock(MapBlock *block, Database *db);
481         // This will generate a sector with getSector if not found.
482         void loadBlock(std::string sectordir, std::string blockfile, MapSector *sector, bool save_after_load=false);
483         MapBlock* loadBlock(v3s16 p);
484         // Database version
485         void loadBlock(std::string *blob, v3s16 p3d, MapSector *sector, bool save_after_load=false);
486
487         bool deleteBlock(v3s16 blockpos);
488
489         void updateVManip(v3s16 pos);
490
491         // For debug printing
492         virtual void PrintInfo(std::ostream &out);
493
494         bool isSavingEnabled(){ return m_map_saving_enabled; }
495
496         u64 getSeed();
497         s16 getWaterLevel();
498
499         MapSettingsManager settings_mgr;
500
501 private:
502         // Emerge manager
503         EmergeManager *m_emerge;
504
505         std::string m_savedir;
506         bool m_map_saving_enabled;
507
508 #if 0
509         // Chunk size in MapSectors
510         // If 0, chunks are disabled.
511         s16 m_chunksize;
512         // Chunks
513         core::map<v2s16, MapChunk*> m_chunks;
514 #endif
515
516         /*
517                 Metadata is re-written on disk only if this is true.
518                 This is reset to false when written on disk.
519         */
520         bool m_map_metadata_changed;
521         Database *dbase;
522 };
523
524
525 #define VMANIP_BLOCK_DATA_INEXIST     1
526 #define VMANIP_BLOCK_CONTAINS_CIGNORE 2
527
528 class MMVManip : public VoxelManipulator
529 {
530 public:
531         MMVManip(Map *map);
532         virtual ~MMVManip();
533
534         virtual void clear()
535         {
536                 VoxelManipulator::clear();
537                 m_loaded_blocks.clear();
538         }
539
540         void setMap(Map *map)
541         {m_map = map;}
542
543         void initialEmerge(v3s16 blockpos_min, v3s16 blockpos_max,
544                 bool load_if_inexistent = true);
545
546         // This is much faster with big chunks of generated data
547         void blitBackAll(std::map<v3s16, MapBlock*> * modified_blocks,
548                 bool overwrite_generated = true);
549
550         bool m_is_dirty;
551
552 protected:
553         bool m_create_area;
554         Map *m_map;
555         /*
556                 key = blockpos
557                 value = flags describing the block
558         */
559         std::map<v3s16, u8> m_loaded_blocks;
560 };
561
562 #endif