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