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