Update changelog and call this 0.3.3
[oweals/minetest.git] / src / mapblock.h
1 /*
2 Minetest-c55
3 Copyright (C) 2010 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 General Public License as published by
7 the Free Software Foundation; either version 2 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 General Public License for more details.
14
15 You should have received a copy of the GNU 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 MAPBLOCK_HEADER
21 #define MAPBLOCK_HEADER
22
23 #include <jmutex.h>
24 #include <jmutexautolock.h>
25 #include <exception>
26 #include "debug.h"
27 #include "common_irrlicht.h"
28 #include "mapnode.h"
29 #include "exceptions.h"
30 #include "serialization.h"
31 #include "constants.h"
32 #include "voxel.h"
33 #include "nodemetadata.h"
34 #include "staticobject.h"
35 #include "mapblock_nodemod.h"
36 #ifndef SERVER
37         #include "mapblock_mesh.h"
38 #endif
39
40 class Map;
41
42 #define BLOCK_TIMESTAMP_UNDEFINED 0xffffffff
43
44 /*// Named by looking towards z+
45 enum{
46         FACE_BACK=0,
47         FACE_TOP,
48         FACE_RIGHT,
49         FACE_FRONT,
50         FACE_BOTTOM,
51         FACE_LEFT
52 };*/
53
54 enum ModifiedState
55 {
56         // Has not been modified.
57         MOD_STATE_CLEAN = 0,
58         MOD_RESERVED1 = 1,
59         // Has been modified, and will be saved when being unloaded.
60         MOD_STATE_WRITE_AT_UNLOAD = 2,
61         MOD_RESERVED3 = 3,
62         // Has been modified, and will be saved as soon as possible.
63         MOD_STATE_WRITE_NEEDED = 4,
64         MOD_RESERVED5 = 5,
65 };
66
67 // NOTE: If this is enabled, set MapBlock to be initialized with
68 //       CONTENT_IGNORE.
69 /*enum BlockGenerationStatus
70 {
71         // Completely non-generated (filled with CONTENT_IGNORE).
72         BLOCKGEN_UNTOUCHED=0,
73         // Trees or similar might have been blitted from other blocks to here.
74         // Otherwise, the block contains CONTENT_IGNORE
75         BLOCKGEN_FROM_NEIGHBORS=2,
76         // Has been generated, but some neighbors might put some stuff in here
77         // when they are generated.
78         // Does not contain any CONTENT_IGNORE
79         BLOCKGEN_SELF_GENERATED=4,
80         // The block and all its neighbors have been generated
81         BLOCKGEN_FULLY_GENERATED=6
82 };*/
83
84 #if 0
85 enum
86 {
87         NODECONTAINER_ID_MAPBLOCK,
88         NODECONTAINER_ID_MAPSECTOR,
89         NODECONTAINER_ID_MAP,
90         NODECONTAINER_ID_MAPBLOCKCACHE,
91         NODECONTAINER_ID_VOXELMANIPULATOR,
92 };
93
94 class NodeContainer
95 {
96 public:
97         virtual bool isValidPosition(v3s16 p) = 0;
98         virtual MapNode getNode(v3s16 p) = 0;
99         virtual void setNode(v3s16 p, MapNode & n) = 0;
100         virtual u16 nodeContainerId() const = 0;
101
102         MapNode getNodeNoEx(v3s16 p)
103         {
104                 try{
105                         return getNode(p);
106                 }
107                 catch(InvalidPositionException &e){
108                         return MapNode(CONTENT_IGNORE);
109                 }
110         }
111 };
112 #endif
113
114 /*
115         MapBlock itself
116 */
117
118 class MapBlock /*: public NodeContainer*/
119 {
120 public:
121         MapBlock(Map *parent, v3s16 pos, bool dummy=false);
122         ~MapBlock();
123         
124         /*virtual u16 nodeContainerId() const
125         {
126                 return NODECONTAINER_ID_MAPBLOCK;
127         }*/
128         
129         Map * getParent()
130         {
131                 return m_parent;
132         }
133
134         void reallocate()
135         {
136                 if(data != NULL)
137                         delete[] data;
138                 u32 l = MAP_BLOCKSIZE * MAP_BLOCKSIZE * MAP_BLOCKSIZE;
139                 data = new MapNode[l];
140                 for(u32 i=0; i<l; i++){
141                         //data[i] = MapNode();
142                         data[i] = MapNode(CONTENT_IGNORE);
143                 }
144                 raiseModified(MOD_STATE_WRITE_NEEDED);
145         }
146
147         /*
148                 Flags
149         */
150
151         bool isDummy()
152         {
153                 return (data == NULL);
154         }
155         void unDummify()
156         {
157                 assert(isDummy());
158                 reallocate();
159         }
160         
161         /*
162                 This is called internally or externally after the block is
163                 modified, so that the block is saved and possibly not deleted from
164                 memory.
165         */
166         // DEPRECATED, use *Modified()
167         void setChangedFlag()
168         {
169                 //dstream<<"Deprecated setChangedFlag() called"<<std::endl;
170                 raiseModified(MOD_STATE_WRITE_NEEDED);
171         }
172         // DEPRECATED, use *Modified()
173         void resetChangedFlag()
174         {
175                 //dstream<<"Deprecated resetChangedFlag() called"<<std::endl;
176                 resetModified();
177         }
178         // DEPRECATED, use *Modified()
179         bool getChangedFlag()
180         {
181                 //dstream<<"Deprecated getChangedFlag() called"<<std::endl;
182                 if(getModified() == MOD_STATE_CLEAN)
183                         return false;
184                 else
185                         return true;
186         }
187         
188         // m_modified methods
189         void raiseModified(u32 mod)
190         {
191                 m_modified = MYMAX(m_modified, mod);
192         }
193         u32 getModified()
194         {
195                 return m_modified;
196         }
197         void resetModified()
198         {
199                 m_modified = MOD_STATE_CLEAN;
200         }
201         
202         // is_underground getter/setter
203         bool getIsUnderground()
204         {
205                 return is_underground;
206         }
207         void setIsUnderground(bool a_is_underground)
208         {
209                 is_underground = a_is_underground;
210                 raiseModified(MOD_STATE_WRITE_NEEDED);
211         }
212
213 #ifndef SERVER
214         void setMeshExpired(bool expired)
215         {
216                 m_mesh_expired = expired;
217         }
218         
219         bool getMeshExpired()
220         {
221                 return m_mesh_expired;
222         }
223 #endif
224
225         void setLightingExpired(bool expired)
226         {
227                 if(expired != m_lighting_expired){
228                         m_lighting_expired = expired;
229                         raiseModified(MOD_STATE_WRITE_NEEDED);
230                 }
231         }
232         bool getLightingExpired()
233         {
234                 return m_lighting_expired;
235         }
236
237         bool isGenerated()
238         {
239                 return m_generated;
240         }
241         void setGenerated(bool b)
242         {
243                 if(b != m_generated){
244                         raiseModified(MOD_STATE_WRITE_NEEDED);
245                         m_generated = b;
246                 }
247         }
248
249         bool isValid()
250         {
251                 if(m_lighting_expired)
252                         return false;
253                 if(data == NULL)
254                         return false;
255                 return true;
256         }
257
258         /*
259                 Position stuff
260         */
261
262         v3s16 getPos()
263         {
264                 return m_pos;
265         }
266                 
267         v3s16 getPosRelative()
268         {
269                 return m_pos * MAP_BLOCKSIZE;
270         }
271                 
272         core::aabbox3d<s16> getBox()
273         {
274                 return core::aabbox3d<s16>(getPosRelative(),
275                                 getPosRelative()
276                                 + v3s16(MAP_BLOCKSIZE, MAP_BLOCKSIZE, MAP_BLOCKSIZE)
277                                 - v3s16(1,1,1));
278         }
279
280         /*
281                 Regular MapNode get-setters
282         */
283         
284         bool isValidPosition(v3s16 p)
285         {
286                 if(data == NULL)
287                         return false;
288                 return (p.X >= 0 && p.X < MAP_BLOCKSIZE
289                                 && p.Y >= 0 && p.Y < MAP_BLOCKSIZE
290                                 && p.Z >= 0 && p.Z < MAP_BLOCKSIZE);
291         }
292
293         MapNode getNode(s16 x, s16 y, s16 z)
294         {
295                 if(data == NULL)
296                         throw InvalidPositionException();
297                 if(x < 0 || x >= MAP_BLOCKSIZE) throw InvalidPositionException();
298                 if(y < 0 || y >= MAP_BLOCKSIZE) throw InvalidPositionException();
299                 if(z < 0 || z >= MAP_BLOCKSIZE) throw InvalidPositionException();
300                 return data[z*MAP_BLOCKSIZE*MAP_BLOCKSIZE + y*MAP_BLOCKSIZE + x];
301         }
302         
303         MapNode getNode(v3s16 p)
304         {
305                 return getNode(p.X, p.Y, p.Z);
306         }
307         
308         MapNode getNodeNoEx(v3s16 p)
309         {
310                 try{
311                         return getNode(p.X, p.Y, p.Z);
312                 }catch(InvalidPositionException &e){
313                         return MapNode(CONTENT_IGNORE);
314                 }
315         }
316         
317         void setNode(s16 x, s16 y, s16 z, MapNode & n)
318         {
319                 if(data == NULL)
320                         throw InvalidPositionException();
321                 if(x < 0 || x >= MAP_BLOCKSIZE) throw InvalidPositionException();
322                 if(y < 0 || y >= MAP_BLOCKSIZE) throw InvalidPositionException();
323                 if(z < 0 || z >= MAP_BLOCKSIZE) throw InvalidPositionException();
324                 data[z*MAP_BLOCKSIZE*MAP_BLOCKSIZE + y*MAP_BLOCKSIZE + x] = n;
325                 raiseModified(MOD_STATE_WRITE_NEEDED);
326         }
327         
328         void setNode(v3s16 p, MapNode & n)
329         {
330                 setNode(p.X, p.Y, p.Z, n);
331         }
332
333         /*
334                 Non-checking variants of the above
335         */
336
337         MapNode getNodeNoCheck(s16 x, s16 y, s16 z)
338         {
339                 if(data == NULL)
340                         throw InvalidPositionException();
341                 return data[z*MAP_BLOCKSIZE*MAP_BLOCKSIZE + y*MAP_BLOCKSIZE + x];
342         }
343         
344         MapNode getNodeNoCheck(v3s16 p)
345         {
346                 return getNodeNoCheck(p.X, p.Y, p.Z);
347         }
348         
349         void setNodeNoCheck(s16 x, s16 y, s16 z, MapNode & n)
350         {
351                 if(data == NULL)
352                         throw InvalidPositionException();
353                 data[z*MAP_BLOCKSIZE*MAP_BLOCKSIZE + y*MAP_BLOCKSIZE + x] = n;
354                 raiseModified(MOD_STATE_WRITE_NEEDED);
355         }
356         
357         void setNodeNoCheck(v3s16 p, MapNode & n)
358         {
359                 setNodeNoCheck(p.X, p.Y, p.Z, n);
360         }
361
362         /*
363                 These functions consult the parent container if the position
364                 is not valid on this MapBlock.
365         */
366         bool isValidPositionParent(v3s16 p);
367         MapNode getNodeParent(v3s16 p);
368         void setNodeParent(v3s16 p, MapNode & n);
369         MapNode getNodeParentNoEx(v3s16 p);
370
371         void drawbox(s16 x0, s16 y0, s16 z0, s16 w, s16 h, s16 d, MapNode node)
372         {
373                 for(u16 z=0; z<d; z++)
374                         for(u16 y=0; y<h; y++)
375                                 for(u16 x=0; x<w; x++)
376                                         setNode(x0+x, y0+y, z0+z, node);
377         }
378
379         /*
380                 Graphics-related methods
381         */
382         
383         /*// A quick version with nodes passed as parameters
384         u8 getFaceLight(u32 daynight_ratio, MapNode n, MapNode n2,
385                         v3s16 face_dir);*/
386         /*// A more convenient version
387         u8 getFaceLight(u32 daynight_ratio, v3s16 p, v3s16 face_dir)
388         {
389                 return getFaceLight(daynight_ratio,
390                                 getNodeParentNoEx(p),
391                                 getNodeParentNoEx(p + face_dir),
392                                 face_dir);
393         }*/
394         u8 getFaceLight2(u32 daynight_ratio, v3s16 p, v3s16 face_dir)
395         {
396                 return getFaceLight(daynight_ratio,
397                                 getNodeParentNoEx(p),
398                                 getNodeParentNoEx(p + face_dir),
399                                 face_dir);
400         }
401         
402 #ifndef SERVER // Only on client
403
404 #if 1
405         /*
406                 Thread-safely updates the whole mesh of the mapblock.
407                 NOTE: Prefer generating the mesh separately and then using
408                 replaceMesh().
409         */
410         void updateMesh(u32 daynight_ratio);
411 #endif
412         // Replace the mesh with a new one
413         void replaceMesh(scene::SMesh *mesh_new);
414 #endif
415         
416         // See comments in mapblock.cpp
417         bool propagateSunlight(core::map<v3s16, bool> & light_sources,
418                         bool remove_light=false, bool *black_air_left=NULL);
419         
420         // Copies data to VoxelManipulator to getPosRelative()
421         void copyTo(VoxelManipulator &dst);
422         // Copies data from VoxelManipulator getPosRelative()
423         void copyFrom(VoxelManipulator &dst);
424
425 #ifndef SERVER // Only on client
426         /*
427                 Methods for setting temporary modifications to nodes for
428                 drawing
429
430                 returns true if the mod was different last time
431         */
432         bool setTempMod(v3s16 p, const NodeMod &mod)
433         {
434                 /*dstream<<"setTempMod called on block"
435                                 <<" ("<<p.X<<","<<p.Y<<","<<p.Z<<")"
436                                 <<", mod.type="<<mod.type
437                                 <<", mod.param="<<mod.param
438                                 <<std::endl;*/
439                 JMutexAutoLock lock(m_temp_mods_mutex);
440
441                 return m_temp_mods.set(p, mod);
442         }
443         // Returns true if there was one
444         bool getTempMod(v3s16 p, NodeMod *mod)
445         {
446                 JMutexAutoLock lock(m_temp_mods_mutex);
447
448                 return m_temp_mods.get(p, mod);
449         }
450         bool clearTempMod(v3s16 p)
451         {
452                 JMutexAutoLock lock(m_temp_mods_mutex);
453
454                 return m_temp_mods.clear(p);
455         }
456         bool clearTempMods()
457         {
458                 JMutexAutoLock lock(m_temp_mods_mutex);
459                 
460                 return m_temp_mods.clear();
461         }
462         void copyTempMods(NodeModMap &dst)
463         {
464                 JMutexAutoLock lock(m_temp_mods_mutex);
465                 m_temp_mods.copy(dst);
466         }
467 #endif
468
469         /*
470                 Update day-night lighting difference flag.
471                 
472                 Sets m_day_night_differs to appropriate value.
473                 
474                 These methods don't care about neighboring blocks.
475                 It means that to know if a block really doesn't need a mesh
476                 update between day and night, the neighboring blocks have
477                 to be taken into account. Use Map::dayNightDiffed().
478         */
479         void updateDayNightDiff();
480
481         bool dayNightDiffed()
482         {
483                 return m_day_night_differs;
484         }
485
486         /*
487                 Miscellaneous stuff
488         */
489         
490         /*
491                 Tries to measure ground level.
492                 Return value:
493                         -1 = only air
494                         -2 = only ground
495                         -3 = random fail
496                         0...MAP_BLOCKSIZE-1 = ground level
497         */
498         s16 getGroundLevel(v2s16 p2d);
499
500         /*
501                 Timestamp (see m_timestamp)
502                 NOTE: BLOCK_TIMESTAMP_UNDEFINED=0xffffffff means there is no timestamp.
503         */
504         void setTimestamp(u32 time)
505         {
506                 m_timestamp = time;
507                 raiseModified(MOD_STATE_WRITE_AT_UNLOAD);
508         }
509         void setTimestampNoChangedFlag(u32 time)
510         {
511                 m_timestamp = time;
512         }
513         u32 getTimestamp()
514         {
515                 return m_timestamp;
516         }
517         
518         /*
519                 See m_usage_timer
520         */
521         void resetUsageTimer()
522         {
523                 m_usage_timer = 0;
524         }
525         void incrementUsageTimer(float dtime)
526         {
527                 m_usage_timer += dtime;
528         }
529         u32 getUsageTimer()
530         {
531                 return m_usage_timer;
532         }
533
534         /*
535                 Serialization
536         */
537         
538         // These don't write or read version by itself
539         void serialize(std::ostream &os, u8 version);
540         void deSerialize(std::istream &is, u8 version);
541         // Used after the basic ones when writing on disk (serverside)
542         void serializeDiskExtra(std::ostream &os, u8 version);
543         void deSerializeDiskExtra(std::istream &is, u8 version);
544
545 private:
546         /*
547                 Private methods
548         */
549
550         /*
551                 Used only internally, because changes can't be tracked
552         */
553
554         MapNode & getNodeRef(s16 x, s16 y, s16 z)
555         {
556                 if(data == NULL)
557                         throw InvalidPositionException();
558                 if(x < 0 || x >= MAP_BLOCKSIZE) throw InvalidPositionException();
559                 if(y < 0 || y >= MAP_BLOCKSIZE) throw InvalidPositionException();
560                 if(z < 0 || z >= MAP_BLOCKSIZE) throw InvalidPositionException();
561                 return data[z*MAP_BLOCKSIZE*MAP_BLOCKSIZE + y*MAP_BLOCKSIZE + x];
562         }
563         MapNode & getNodeRef(v3s16 &p)
564         {
565                 return getNodeRef(p.X, p.Y, p.Z);
566         }
567
568 public:
569         /*
570                 Public member variables
571         */
572
573 #ifndef SERVER // Only on client
574         scene::SMesh *mesh;
575         JMutex mesh_mutex;
576 #endif
577         
578         NodeMetadataList m_node_metadata;
579         StaticObjectList m_static_objects;
580         
581 private:
582         /*
583                 Private member variables
584         */
585
586         // NOTE: Lots of things rely on this being the Map
587         Map *m_parent;
588         // Position in blocks on parent
589         v3s16 m_pos;
590         
591         /*
592                 If NULL, block is a dummy block.
593                 Dummy blocks are used for caching not-found-on-disk blocks.
594         */
595         MapNode * data;
596
597         /*
598                 - On the server, this is used for telling whether the
599                   block has been modified from the one on disk.
600                 - On the client, this is used for nothing.
601         */
602         u32 m_modified;
603
604         /*
605                 When propagating sunlight and the above block doesn't exist,
606                 sunlight is assumed if this is false.
607
608                 In practice this is set to true if the block is completely
609                 undeground with nothing visible above the ground except
610                 caves.
611         */
612         bool is_underground;
613
614         /*
615                 Set to true if changes has been made that make the old lighting
616                 values wrong but the lighting hasn't been actually updated.
617
618                 If this is false, lighting is exactly right.
619                 If this is true, lighting might be wrong or right.
620         */
621         bool m_lighting_expired;
622         
623         // Whether day and night lighting differs
624         bool m_day_night_differs;
625
626         bool m_generated;
627         
628 #ifndef SERVER // Only on client
629         /*
630                 Set to true if the mesh has been ordered to be updated
631                 sometime in the background.
632                 In practice this is set when the day/night lighting switches.
633         */
634         bool m_mesh_expired;
635         
636         // Temporary modifications to nodes
637         // These are only used when drawing
638         NodeModMap m_temp_mods;
639         JMutex m_temp_mods_mutex;
640 #endif
641         
642         /*
643                 When block is removed from active blocks, this is set to gametime.
644                 Value BLOCK_TIMESTAMP_UNDEFINED=0xffffffff means there is no timestamp.
645         */
646         u32 m_timestamp;
647
648         /*
649                 When the block is accessed, this is set to 0.
650                 Map will unload the block when this reaches a timeout.
651         */
652         float m_usage_timer;
653 };
654
655 inline bool blockpos_over_limit(v3s16 p)
656 {
657         return
658           (p.X < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
659         || p.X >  MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
660         || p.Y < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
661         || p.Y >  MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
662         || p.Z < -MAP_GENERATION_LIMIT / MAP_BLOCKSIZE
663         || p.Z >  MAP_GENERATION_LIMIT / MAP_BLOCKSIZE);
664 }
665
666 /*
667         Returns the position of the block where the node is located
668 */
669 inline v3s16 getNodeBlockPos(v3s16 p)
670 {
671         return getContainerPos(p, MAP_BLOCKSIZE);
672 }
673
674 inline v2s16 getNodeSectorPos(v2s16 p)
675 {
676         return getContainerPos(p, MAP_BLOCKSIZE);
677 }
678
679 inline s16 getNodeBlockY(s16 y)
680 {
681         return getContainerPos(y, MAP_BLOCKSIZE);
682 }
683
684 /*
685         Get a quick string to describe what a block actually contains
686 */
687 std::string analyze_block(MapBlock *block);
688
689 #endif
690