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