C++ modernize: Pragma once (#6264)
[oweals/minetest.git] / src / mapblock.h
1 /*
2 Minetest
3 Copyright (C) 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 <set>
23 #include "debug.h"
24 #include "irr_v3d.h"
25 #include "mapnode.h"
26 #include "exceptions.h"
27 #include "constants.h"
28 #include "staticobject.h"
29 #include "nodemetadata.h"
30 #include "nodetimer.h"
31 #include "modifiedstate.h"
32 #include "util/numeric.h" // getContainerPos
33 #include "settings.h"
34 #include "mapgen.h"
35
36 class Map;
37 class NodeMetadataList;
38 class IGameDef;
39 class MapBlockMesh;
40 class VoxelManipulator;
41
42 #define BLOCK_TIMESTAMP_UNDEFINED 0xffffffff
43
44 ////
45 //// MapBlock modified reason flags
46 ////
47
48 #define MOD_REASON_INITIAL                   (1 << 0)
49 #define MOD_REASON_REALLOCATE                (1 << 1)
50 #define MOD_REASON_SET_IS_UNDERGROUND        (1 << 2)
51 #define MOD_REASON_SET_LIGHTING_COMPLETE     (1 << 3)
52 #define MOD_REASON_SET_GENERATED             (1 << 4)
53 #define MOD_REASON_SET_NODE                  (1 << 5)
54 #define MOD_REASON_SET_NODE_NO_CHECK         (1 << 6)
55 #define MOD_REASON_SET_TIMESTAMP             (1 << 7)
56 #define MOD_REASON_REPORT_META_CHANGE        (1 << 8)
57 #define MOD_REASON_CLEAR_ALL_OBJECTS         (1 << 9)
58 #define MOD_REASON_BLOCK_EXPIRED             (1 << 10)
59 #define MOD_REASON_ADD_ACTIVE_OBJECT_RAW     (1 << 11)
60 #define MOD_REASON_REMOVE_OBJECTS_REMOVE     (1 << 12)
61 #define MOD_REASON_REMOVE_OBJECTS_DEACTIVATE (1 << 13)
62 #define MOD_REASON_TOO_MANY_OBJECTS          (1 << 14)
63 #define MOD_REASON_STATIC_DATA_ADDED         (1 << 15)
64 #define MOD_REASON_STATIC_DATA_REMOVED       (1 << 16)
65 #define MOD_REASON_STATIC_DATA_CHANGED       (1 << 17)
66 #define MOD_REASON_EXPIRE_DAYNIGHTDIFF       (1 << 18)
67 #define MOD_REASON_UNKNOWN                   (1 << 19)
68
69 ////
70 //// MapBlock itself
71 ////
72
73 class MapBlock
74 {
75 public:
76         MapBlock(Map *parent, v3s16 pos, IGameDef *gamedef, bool dummy=false);
77         ~MapBlock();
78
79         /*virtual u16 nodeContainerId() const
80         {
81                 return NODECONTAINER_ID_MAPBLOCK;
82         }*/
83
84         Map * getParent()
85         {
86                 return m_parent;
87         }
88
89         void reallocate()
90         {
91                 delete[] data;
92                 data = new MapNode[nodecount];
93                 for (u32 i = 0; i < nodecount; i++)
94                         data[i] = MapNode(CONTENT_IGNORE);
95
96                 raiseModified(MOD_STATE_WRITE_NEEDED, MOD_REASON_REALLOCATE);
97         }
98
99         MapNode* getData()
100         {
101                 return data;
102         }
103
104         ////
105         //// Modification tracking methods
106         ////
107         void raiseModified(u32 mod, u32 reason=MOD_REASON_UNKNOWN)
108         {
109                 if (mod > m_modified) {
110                         m_modified = mod;
111                         m_modified_reason = reason;
112                         if (m_modified >= MOD_STATE_WRITE_AT_UNLOAD)
113                                 m_disk_timestamp = m_timestamp;
114                 } else if (mod == m_modified) {
115                         m_modified_reason |= reason;
116                 }
117         }
118
119         inline u32 getModified()
120         {
121                 return m_modified;
122         }
123
124         inline u32 getModifiedReason()
125         {
126                 return m_modified_reason;
127         }
128
129         std::string getModifiedReasonString();
130
131         inline void resetModified()
132         {
133                 m_modified = MOD_STATE_CLEAN;
134                 m_modified_reason = 0;
135         }
136
137         ////
138         //// Flags
139         ////
140
141         inline bool isDummy()
142         {
143                 return !data;
144         }
145
146         inline void unDummify()
147         {
148                 assert(isDummy()); // Pre-condition
149                 reallocate();
150         }
151
152         // is_underground getter/setter
153         inline bool getIsUnderground()
154         {
155                 return is_underground;
156         }
157
158         inline void setIsUnderground(bool a_is_underground)
159         {
160                 is_underground = a_is_underground;
161                 raiseModified(MOD_STATE_WRITE_NEEDED, MOD_REASON_SET_IS_UNDERGROUND);
162         }
163
164         inline void setLightingComplete(u16 newflags)
165         {
166                 if (newflags != m_lighting_complete) {
167                         m_lighting_complete = newflags;
168                         raiseModified(MOD_STATE_WRITE_NEEDED, MOD_REASON_SET_LIGHTING_COMPLETE);
169                 }
170         }
171
172         inline u16 getLightingComplete()
173         {
174                 return m_lighting_complete;
175         }
176
177         inline void setLightingComplete(LightBank bank, u8 direction,
178                 bool is_complete)
179         {
180                 assert(direction >= 0 && direction <= 5);
181                 if (bank == LIGHTBANK_NIGHT) {
182                         direction += 6;
183                 }
184                 u16 newflags = m_lighting_complete;
185                 if (is_complete) {
186                         newflags |= 1 << direction;
187                 } else {
188                         newflags &= ~(1 << direction);
189                 }
190                 setLightingComplete(newflags);
191         }
192
193         inline bool isLightingComplete(LightBank bank, u8 direction)
194         {
195                 assert(direction >= 0 && direction <= 5);
196                 if (bank == LIGHTBANK_NIGHT) {
197                         direction += 6;
198                 }
199                 return (m_lighting_complete & (1 << direction)) != 0;
200         }
201
202         inline bool isGenerated()
203         {
204                 return m_generated;
205         }
206
207         inline void setGenerated(bool b)
208         {
209                 if (b != m_generated) {
210                         raiseModified(MOD_STATE_WRITE_NEEDED, MOD_REASON_SET_GENERATED);
211                         m_generated = b;
212                 }
213         }
214
215         ////
216         //// Position stuff
217         ////
218
219         inline v3s16 getPos()
220         {
221                 return m_pos;
222         }
223
224         inline v3s16 getPosRelative()
225         {
226                 return m_pos_relative;
227         }
228
229         inline core::aabbox3d<s16> getBox()
230         {
231                 return core::aabbox3d<s16>(getPosRelative(),
232                                 getPosRelative()
233                                 + v3s16(MAP_BLOCKSIZE, MAP_BLOCKSIZE, MAP_BLOCKSIZE)
234                                 - v3s16(1,1,1));
235         }
236
237         ////
238         //// Regular MapNode get-setters
239         ////
240
241         inline bool isValidPosition(s16 x, s16 y, s16 z)
242         {
243                 return data
244                         && x >= 0 && x < MAP_BLOCKSIZE
245                         && y >= 0 && y < MAP_BLOCKSIZE
246                         && z >= 0 && z < MAP_BLOCKSIZE;
247         }
248
249         inline bool isValidPosition(v3s16 p)
250         {
251                 return isValidPosition(p.X, p.Y, p.Z);
252         }
253
254         inline MapNode getNode(s16 x, s16 y, s16 z, bool *valid_position)
255         {
256                 *valid_position = isValidPosition(x, y, z);
257
258                 if (!*valid_position)
259                         return MapNode(CONTENT_IGNORE);
260
261                 return data[z * zstride + y * ystride + x];
262         }
263
264         inline MapNode getNode(v3s16 p, bool *valid_position)
265         {
266                 return getNode(p.X, p.Y, p.Z, valid_position);
267         }
268
269         inline MapNode getNodeNoEx(v3s16 p)
270         {
271                 bool is_valid;
272                 return getNode(p.X, p.Y, p.Z, &is_valid);
273         }
274
275         inline void setNode(s16 x, s16 y, s16 z, MapNode & n)
276         {
277                 if (!isValidPosition(x, y, z))
278                         throw InvalidPositionException();
279
280                 data[z * zstride + y * ystride + x] = n;
281                 raiseModified(MOD_STATE_WRITE_NEEDED, MOD_REASON_SET_NODE);
282         }
283
284         inline void setNode(v3s16 p, MapNode & n)
285         {
286                 setNode(p.X, p.Y, p.Z, n);
287         }
288
289         ////
290         //// Non-checking variants of the above
291         ////
292
293         inline MapNode getNodeNoCheck(s16 x, s16 y, s16 z, bool *valid_position)
294         {
295                 *valid_position = data != nullptr;
296                 if (!valid_position)
297                         return MapNode(CONTENT_IGNORE);
298
299                 return data[z * zstride + y * ystride + x];
300         }
301
302         inline MapNode getNodeNoCheck(v3s16 p, bool *valid_position)
303         {
304                 return getNodeNoCheck(p.X, p.Y, p.Z, valid_position);
305         }
306
307         ////
308         //// Non-checking, unsafe variants of the above
309         //// MapBlock must be loaded by another function in the same scope/function
310         //// Caller must ensure that this is not a dummy block (by calling isDummy())
311         ////
312
313         inline const MapNode &getNodeUnsafe(s16 x, s16 y, s16 z)
314         {
315                 return data[z * zstride + y * ystride + x];
316         }
317
318         inline const MapNode &getNodeUnsafe(v3s16 &p)
319         {
320                 return getNodeUnsafe(p.X, p.Y, p.Z);
321         }
322
323         inline void setNodeNoCheck(s16 x, s16 y, s16 z, MapNode & n)
324         {
325                 if (!data)
326                         throw InvalidPositionException();
327
328                 data[z * zstride + y * ystride + x] = n;
329                 raiseModified(MOD_STATE_WRITE_NEEDED, MOD_REASON_SET_NODE_NO_CHECK);
330         }
331
332         inline void setNodeNoCheck(v3s16 p, MapNode & n)
333         {
334                 setNodeNoCheck(p.X, p.Y, p.Z, n);
335         }
336
337         // These functions consult the parent container if the position
338         // is not valid on this MapBlock.
339         bool isValidPositionParent(v3s16 p);
340         MapNode getNodeParent(v3s16 p, bool *is_valid_position = NULL);
341         void setNodeParent(v3s16 p, MapNode & n);
342
343         inline void drawbox(s16 x0, s16 y0, s16 z0, s16 w, s16 h, s16 d, MapNode node)
344         {
345                 for (u16 z = 0; z < d; z++)
346                 for (u16 y = 0; y < h; y++)
347                 for (u16 x = 0; x < w; x++)
348                         setNode(x0 + x, y0 + y, z0 + z, node);
349         }
350
351         // See comments in mapblock.cpp
352         bool propagateSunlight(std::set<v3s16> &light_sources,
353                 bool remove_light=false, bool *black_air_left=NULL);
354
355         // Copies data to VoxelManipulator to getPosRelative()
356         void copyTo(VoxelManipulator &dst);
357
358         // Copies data from VoxelManipulator getPosRelative()
359         void copyFrom(VoxelManipulator &dst);
360
361         // Update day-night lighting difference flag.
362         // Sets m_day_night_differs to appropriate value.
363         // These methods don't care about neighboring blocks.
364         void actuallyUpdateDayNightDiff();
365
366         // Call this to schedule what the previous function does to be done
367         // when the value is actually needed.
368         void expireDayNightDiff();
369
370         inline bool getDayNightDiff()
371         {
372                 if (m_day_night_differs_expired)
373                         actuallyUpdateDayNightDiff();
374                 return m_day_night_differs;
375         }
376
377         ////
378         //// Miscellaneous stuff
379         ////
380
381         /*
382                 Tries to measure ground level.
383                 Return value:
384                         -1 = only air
385                         -2 = only ground
386                         -3 = random fail
387                         0...MAP_BLOCKSIZE-1 = ground level
388         */
389         s16 getGroundLevel(v2s16 p2d);
390
391         ////
392         //// Timestamp (see m_timestamp)
393         ////
394
395         // NOTE: BLOCK_TIMESTAMP_UNDEFINED=0xffffffff means there is no timestamp.
396
397         inline void setTimestamp(u32 time)
398         {
399                 m_timestamp = time;
400                 raiseModified(MOD_STATE_WRITE_AT_UNLOAD, MOD_REASON_SET_TIMESTAMP);
401         }
402
403         inline void setTimestampNoChangedFlag(u32 time)
404         {
405                 m_timestamp = time;
406         }
407
408         inline u32 getTimestamp()
409         {
410                 return m_timestamp;
411         }
412
413         inline u32 getDiskTimestamp()
414         {
415                 return m_disk_timestamp;
416         }
417
418         ////
419         //// Usage timer (see m_usage_timer)
420         ////
421
422         inline void resetUsageTimer()
423         {
424                 m_usage_timer = 0;
425         }
426
427         inline void incrementUsageTimer(float dtime)
428         {
429                 m_usage_timer += dtime;
430         }
431
432         inline float getUsageTimer()
433         {
434                 return m_usage_timer;
435         }
436
437         ////
438         //// Reference counting (see m_refcount)
439         ////
440
441         inline void refGrab()
442         {
443                 m_refcount++;
444         }
445
446         inline void refDrop()
447         {
448                 m_refcount--;
449         }
450
451         inline int refGet()
452         {
453                 return m_refcount;
454         }
455
456         ////
457         //// Node Timers
458         ////
459
460         inline NodeTimer getNodeTimer(v3s16 p)
461         {
462                 return m_node_timers.get(p);
463         }
464
465         inline void removeNodeTimer(v3s16 p)
466         {
467                 m_node_timers.remove(p);
468         }
469
470         inline void setNodeTimer(const NodeTimer &t)
471         {
472                 m_node_timers.set(t);
473         }
474
475         inline void clearNodeTimers()
476         {
477                 m_node_timers.clear();
478         }
479
480         ////
481         //// Serialization
482         ///
483
484         // These don't write or read version by itself
485         // Set disk to true for on-disk format, false for over-the-network format
486         // Precondition: version >= SER_FMT_VER_LOWEST_WRITE
487         void serialize(std::ostream &os, u8 version, bool disk);
488         // If disk == true: In addition to doing other things, will add
489         // unknown blocks from id-name mapping to wndef
490         void deSerialize(std::istream &is, u8 version, bool disk);
491
492         void serializeNetworkSpecific(std::ostream &os);
493         void deSerializeNetworkSpecific(std::istream &is);
494 private:
495         /*
496                 Private methods
497         */
498
499         void deSerialize_pre22(std::istream &is, u8 version, bool disk);
500
501         /*
502                 Used only internally, because changes can't be tracked
503         */
504
505         inline MapNode &getNodeRef(s16 x, s16 y, s16 z)
506         {
507                 if (!isValidPosition(x, y, z))
508                         throw InvalidPositionException();
509
510                 return data[z * zstride + y * ystride + x];
511         }
512
513         inline MapNode &getNodeRef(v3s16 &p)
514         {
515                 return getNodeRef(p.X, p.Y, p.Z);
516         }
517
518 public:
519         /*
520                 Public member variables
521         */
522
523 #ifndef SERVER // Only on client
524         MapBlockMesh *mesh = nullptr;
525 #endif
526
527         NodeMetadataList m_node_metadata;
528         NodeTimerList m_node_timers;
529         StaticObjectList m_static_objects;
530
531         static const u32 ystride = MAP_BLOCKSIZE;
532         static const u32 zstride = MAP_BLOCKSIZE * MAP_BLOCKSIZE;
533
534         static const u32 nodecount = MAP_BLOCKSIZE * MAP_BLOCKSIZE * MAP_BLOCKSIZE;
535
536 private:
537         /*
538                 Private member variables
539         */
540
541         // NOTE: Lots of things rely on this being the Map
542         Map *m_parent;
543         // Position in blocks on parent
544         v3s16 m_pos;
545
546         /* This is the precalculated m_pos_relative value
547         * This caches the value, improving performance by removing 3 s16 multiplications
548         * at runtime on each getPosRelative call
549         * For a 5 minutes runtime with valgrind this removes 3 * 19M s16 multiplications
550         * The gain can be estimated in Release Build to 3 * 100M multiply operations for 5 mins
551         */
552         v3s16 m_pos_relative;
553
554         IGameDef *m_gamedef;
555
556         /*
557                 If NULL, block is a dummy block.
558                 Dummy blocks are used for caching not-found-on-disk blocks.
559         */
560         MapNode *data = nullptr;
561
562         /*
563                 - On the server, this is used for telling whether the
564                   block has been modified from the one on disk.
565                 - On the client, this is used for nothing.
566         */
567         u32 m_modified = MOD_STATE_WRITE_NEEDED;
568         u32 m_modified_reason = MOD_REASON_INITIAL;
569
570         /*
571                 When propagating sunlight and the above block doesn't exist,
572                 sunlight is assumed if this is false.
573
574                 In practice this is set to true if the block is completely
575                 undeground with nothing visible above the ground except
576                 caves.
577         */
578         bool is_underground = false;
579
580         /*!
581          * Each bit indicates if light spreading was finished
582          * in a direction. (Because the neighbor could also be unloaded.)
583          * Bits (most significant first):
584          * nothing,  nothing,  nothing,  nothing,
585          * night X-, night Y-, night Z-, night Z+, night Y+, night X+,
586          * day X-,   day Y-,   day Z-,   day Z+,   day Y+,   day X+.
587         */
588         u16 m_lighting_complete = 0xFFFF;
589
590         // Whether day and night lighting differs
591         bool m_day_night_differs = false;
592         bool m_day_night_differs_expired = true;
593
594         bool m_generated = false;
595
596         /*
597                 When block is removed from active blocks, this is set to gametime.
598                 Value BLOCK_TIMESTAMP_UNDEFINED=0xffffffff means there is no timestamp.
599         */
600         u32 m_timestamp = BLOCK_TIMESTAMP_UNDEFINED;
601         // The on-disk (or to-be on-disk) timestamp value
602         u32 m_disk_timestamp = BLOCK_TIMESTAMP_UNDEFINED;
603
604         /*
605                 When the block is accessed, this is set to 0.
606                 Map will unload the block when this reaches a timeout.
607         */
608         float m_usage_timer = 0;
609
610         /*
611                 Reference count; currently used for determining if this block is in
612                 the list of blocks to be drawn.
613         */
614         int m_refcount = 0;
615 };
616
617 typedef std::vector<MapBlock*> MapBlockVect;
618
619 inline bool objectpos_over_limit(v3f p)
620 {
621         const float max_limit_bs = MAX_MAP_GENERATION_LIMIT * BS;
622         return p.X < -max_limit_bs ||
623                 p.X >  max_limit_bs ||
624                 p.Y < -max_limit_bs ||
625                 p.Y >  max_limit_bs ||
626                 p.Z < -max_limit_bs ||
627                 p.Z >  max_limit_bs;
628 }
629
630 inline bool blockpos_over_max_limit(v3s16 p)
631 {
632         const s16 max_limit_bp = MAX_MAP_GENERATION_LIMIT / MAP_BLOCKSIZE;
633         return p.X < -max_limit_bp ||
634                 p.X >  max_limit_bp ||
635                 p.Y < -max_limit_bp ||
636                 p.Y >  max_limit_bp ||
637                 p.Z < -max_limit_bp ||
638                 p.Z >  max_limit_bp;
639 }
640
641 /*
642         Returns the position of the block where the node is located
643 */
644 inline v3s16 getNodeBlockPos(v3s16 p)
645 {
646         return getContainerPos(p, MAP_BLOCKSIZE);
647 }
648
649 inline v2s16 getNodeSectorPos(v2s16 p)
650 {
651         return getContainerPos(p, MAP_BLOCKSIZE);
652 }
653
654 inline s16 getNodeBlockY(s16 y)
655 {
656         return getContainerPos(y, MAP_BLOCKSIZE);
657 }
658
659 inline void getNodeBlockPosWithOffset(const v3s16 &p, v3s16 &block, v3s16 &offset)
660 {
661         getContainerPosWithOffset(p, MAP_BLOCKSIZE, block, offset);
662 }
663
664 inline void getNodeSectorPosWithOffset(const v2s16 &p, v2s16 &block, v2s16 &offset)
665 {
666         getContainerPosWithOffset(p, MAP_BLOCKSIZE, block, offset);
667 }
668
669 /*
670         Get a quick string to describe what a block actually contains
671 */
672 std::string analyze_block(MapBlock *block);