Remove unused light updating code
[oweals/minetest.git] / src / mapblock.cpp
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 #include "mapblock.h"
21
22 #include <sstream>
23 #include "map.h"
24 #include "light.h"
25 #include "nodedef.h"
26 #include "nodemetadata.h"
27 #include "gamedef.h"
28 #include "log.h"
29 #include "nameidmapping.h"
30 #include "content_mapnode.h" // For legacy name-id mapping
31 #include "content_nodemeta.h" // For legacy deserialization
32 #include "serialization.h"
33 #ifndef SERVER
34 #include "mapblock_mesh.h"
35 #endif
36 #include "util/string.h"
37 #include "util/serialize.h"
38 #include "util/basic_macros.h"
39
40 static const char *modified_reason_strings[] = {
41         "initial",
42         "reallocate",
43         "setIsUnderground",
44         "setLightingExpired",
45         "setGenerated",
46         "setNode",
47         "setNodeNoCheck",
48         "setTimestamp",
49         "NodeMetaRef::reportMetadataChange",
50         "clearAllObjects",
51         "Timestamp expired (step)",
52         "addActiveObjectRaw",
53         "removeRemovedObjects/remove",
54         "removeRemovedObjects/deactivate",
55         "Stored list cleared in activateObjects due to overflow",
56         "deactivateFarObjects: Static data moved in",
57         "deactivateFarObjects: Static data moved out",
58         "deactivateFarObjects: Static data changed considerably",
59         "finishBlockMake: expireDayNightDiff",
60         "unknown",
61 };
62
63
64 /*
65         MapBlock
66 */
67
68 MapBlock::MapBlock(Map *parent, v3s16 pos, IGameDef *gamedef, bool dummy):
69                 m_parent(parent),
70                 m_pos(pos),
71                 m_pos_relative(pos * MAP_BLOCKSIZE),
72                 m_gamedef(gamedef)
73 {
74         if (!dummy)
75                 reallocate();
76 }
77
78 MapBlock::~MapBlock()
79 {
80 #ifndef SERVER
81         {
82                 delete mesh;
83                 mesh = nullptr;
84         }
85 #endif
86
87         delete[] data;
88 }
89
90 bool MapBlock::isValidPositionParent(v3s16 p)
91 {
92         if (isValidPosition(p)) {
93                 return true;
94         }
95
96         return m_parent->isValidPosition(getPosRelative() + p);
97 }
98
99 MapNode MapBlock::getNodeParent(v3s16 p, bool *is_valid_position)
100 {
101         if (!isValidPosition(p))
102                 return m_parent->getNodeNoEx(getPosRelative() + p, is_valid_position);
103
104         if (!data) {
105                 if (is_valid_position)
106                         *is_valid_position = false;
107                 return {CONTENT_IGNORE};
108         }
109         if (is_valid_position)
110                 *is_valid_position = true;
111         return data[p.Z * zstride + p.Y * ystride + p.X];
112 }
113
114 std::string MapBlock::getModifiedReasonString()
115 {
116         std::string reason;
117
118         const u32 ubound = MYMIN(sizeof(m_modified_reason) * CHAR_BIT,
119                 ARRLEN(modified_reason_strings));
120
121         for (u32 i = 0; i != ubound; i++) {
122                 if ((m_modified_reason & (1 << i)) == 0)
123                         continue;
124
125                 reason += modified_reason_strings[i];
126                 reason += ", ";
127         }
128
129         if (reason.length() > 2)
130                 reason.resize(reason.length() - 2);
131
132         return reason;
133 }
134
135 void MapBlock::copyTo(VoxelManipulator &dst)
136 {
137         v3s16 data_size(MAP_BLOCKSIZE, MAP_BLOCKSIZE, MAP_BLOCKSIZE);
138         VoxelArea data_area(v3s16(0,0,0), data_size - v3s16(1,1,1));
139
140         // Copy from data to VoxelManipulator
141         dst.copyFrom(data, data_area, v3s16(0,0,0),
142                         getPosRelative(), data_size);
143 }
144
145 void MapBlock::copyFrom(VoxelManipulator &dst)
146 {
147         v3s16 data_size(MAP_BLOCKSIZE, MAP_BLOCKSIZE, MAP_BLOCKSIZE);
148         VoxelArea data_area(v3s16(0,0,0), data_size - v3s16(1,1,1));
149
150         // Copy from VoxelManipulator to data
151         dst.copyTo(data, data_area, v3s16(0,0,0),
152                         getPosRelative(), data_size);
153 }
154
155 void MapBlock::actuallyUpdateDayNightDiff()
156 {
157         INodeDefManager *nodemgr = m_gamedef->ndef();
158
159         // Running this function un-expires m_day_night_differs
160         m_day_night_differs_expired = false;
161
162         if (!data) {
163                 m_day_night_differs = false;
164                 return;
165         }
166
167         bool differs = false;
168
169         /*
170                 Check if any lighting value differs
171         */
172
173         MapNode previous_n(CONTENT_IGNORE);
174         for (u32 i = 0; i < nodecount; i++) {
175                 MapNode n = data[i];
176
177                 // If node is identical to previous node, don't verify if it differs
178                 if (n == previous_n)
179                         continue;
180
181                 differs = !n.isLightDayNightEq(nodemgr);
182                 if (differs)
183                         break;
184                 previous_n = n;
185         }
186
187         /*
188                 If some lighting values differ, check if the whole thing is
189                 just air. If it is just air, differs = false
190         */
191         if (differs) {
192                 bool only_air = true;
193                 for (u32 i = 0; i < nodecount; i++) {
194                         MapNode &n = data[i];
195                         if (n.getContent() != CONTENT_AIR) {
196                                 only_air = false;
197                                 break;
198                         }
199                 }
200                 if (only_air)
201                         differs = false;
202         }
203
204         // Set member variable
205         m_day_night_differs = differs;
206 }
207
208 void MapBlock::expireDayNightDiff()
209 {
210         if (!data) {
211                 m_day_night_differs = false;
212                 m_day_night_differs_expired = false;
213                 return;
214         }
215
216         m_day_night_differs_expired = true;
217 }
218
219 s16 MapBlock::getGroundLevel(v2s16 p2d)
220 {
221         if(isDummy())
222                 return -3;
223         try
224         {
225                 s16 y = MAP_BLOCKSIZE-1;
226                 for(; y>=0; y--)
227                 {
228                         MapNode n = getNodeRef(p2d.X, y, p2d.Y);
229                         if (m_gamedef->ndef()->get(n).walkable) {
230                                 if(y == MAP_BLOCKSIZE-1)
231                                         return -2;
232
233                                 return y;
234                         }
235                 }
236                 return -1;
237         }
238         catch(InvalidPositionException &e)
239         {
240                 return -3;
241         }
242 }
243
244 /*
245         Serialization
246 */
247 // List relevant id-name pairs for ids in the block using nodedef
248 // Renumbers the content IDs (starting at 0 and incrementing
249 // use static memory requires about 65535 * sizeof(int) ram in order to be
250 // sure we can handle all content ids. But it's absolutely worth it as it's
251 // a speedup of 4 for one of the major time consuming functions on storing
252 // mapblocks.
253 static content_t getBlockNodeIdMapping_mapping[USHRT_MAX + 1];
254 static void getBlockNodeIdMapping(NameIdMapping *nimap, MapNode *nodes,
255                 INodeDefManager *nodedef)
256 {
257         memset(getBlockNodeIdMapping_mapping, 0xFF, (USHRT_MAX + 1) * sizeof(content_t));
258
259         std::set<content_t> unknown_contents;
260         content_t id_counter = 0;
261         for (u32 i = 0; i < MapBlock::nodecount; i++) {
262                 content_t global_id = nodes[i].getContent();
263                 content_t id = CONTENT_IGNORE;
264
265                 // Try to find an existing mapping
266                 if (getBlockNodeIdMapping_mapping[global_id] != 0xFFFF) {
267                         id = getBlockNodeIdMapping_mapping[global_id];
268                 }
269                 else
270                 {
271                         // We have to assign a new mapping
272                         id = id_counter++;
273                         getBlockNodeIdMapping_mapping[global_id] = id;
274
275                         const ContentFeatures &f = nodedef->get(global_id);
276                         const std::string &name = f.name;
277                         if (name.empty())
278                                 unknown_contents.insert(global_id);
279                         else
280                                 nimap->set(id, name);
281                 }
282
283                 // Update the MapNode
284                 nodes[i].setContent(id);
285         }
286         for (u16 unknown_content : unknown_contents) {
287                 errorstream << "getBlockNodeIdMapping(): IGNORING ERROR: "
288                                 << "Name for node id " << unknown_content << " not known" << std::endl;
289         }
290 }
291 // Correct ids in the block to match nodedef based on names.
292 // Unknown ones are added to nodedef.
293 // Will not update itself to match id-name pairs in nodedef.
294 static void correctBlockNodeIds(const NameIdMapping *nimap, MapNode *nodes,
295                 IGameDef *gamedef)
296 {
297         INodeDefManager *nodedef = gamedef->ndef();
298         // This means the block contains incorrect ids, and we contain
299         // the information to convert those to names.
300         // nodedef contains information to convert our names to globally
301         // correct ids.
302         std::unordered_set<content_t> unnamed_contents;
303         std::unordered_set<std::string> unallocatable_contents;
304
305         bool previous_exists = false;
306         content_t previous_local_id = CONTENT_IGNORE;
307         content_t previous_global_id = CONTENT_IGNORE;
308
309         for (u32 i = 0; i < MapBlock::nodecount; i++) {
310                 content_t local_id = nodes[i].getContent();
311                 // If previous node local_id was found and same than before, don't lookup maps
312                 // apply directly previous resolved id
313                 // This permits to massively improve loading performance when nodes are similar
314                 // example: default:air, default:stone are massively present
315                 if (previous_exists && local_id == previous_local_id) {
316                         nodes[i].setContent(previous_global_id);
317                         continue;
318                 }
319
320                 std::string name;
321                 if (!nimap->getName(local_id, name)) {
322                         unnamed_contents.insert(local_id);
323                         previous_exists = false;
324                         continue;
325                 }
326
327                 content_t global_id;
328                 if (!nodedef->getId(name, global_id)) {
329                         global_id = gamedef->allocateUnknownNodeId(name);
330                         if (global_id == CONTENT_IGNORE) {
331                                 unallocatable_contents.insert(name);
332                                 previous_exists = false;
333                                 continue;
334                         }
335                 }
336                 nodes[i].setContent(global_id);
337
338                 // Save previous node local_id & global_id result
339                 previous_local_id = local_id;
340                 previous_global_id = global_id;
341                 previous_exists = true;
342         }
343
344         for (const content_t c: unnamed_contents) {
345                 errorstream << "correctBlockNodeIds(): IGNORING ERROR: "
346                                 << "Block contains id " << c
347                                 << " with no name mapping" << std::endl;
348         }
349         for (const std::string &node_name: unallocatable_contents) {
350                 errorstream << "correctBlockNodeIds(): IGNORING ERROR: "
351                                 << "Could not allocate global id for node name \""
352                                 << node_name << "\"" << std::endl;
353         }
354 }
355
356 void MapBlock::serialize(std::ostream &os, u8 version, bool disk)
357 {
358         if(!ser_ver_supported(version))
359                 throw VersionMismatchException("ERROR: MapBlock format not supported");
360
361         if (!data)
362                 throw SerializationError("ERROR: Not writing dummy block.");
363
364         FATAL_ERROR_IF(version < SER_FMT_VER_LOWEST_WRITE, "Serialisation version error");
365
366         // First byte
367         u8 flags = 0;
368         if(is_underground)
369                 flags |= 0x01;
370         if(getDayNightDiff())
371                 flags |= 0x02;
372         if (!m_generated)
373                 flags |= 0x08;
374         writeU8(os, flags);
375         if (version >= 27) {
376                 writeU16(os, m_lighting_complete);
377         }
378
379         /*
380                 Bulk node data
381         */
382         NameIdMapping nimap;
383         if(disk)
384         {
385                 MapNode *tmp_nodes = new MapNode[nodecount];
386                 for(u32 i=0; i<nodecount; i++)
387                         tmp_nodes[i] = data[i];
388                 getBlockNodeIdMapping(&nimap, tmp_nodes, m_gamedef->ndef());
389
390                 u8 content_width = 2;
391                 u8 params_width = 2;
392                 writeU8(os, content_width);
393                 writeU8(os, params_width);
394                 MapNode::serializeBulk(os, version, tmp_nodes, nodecount,
395                                 content_width, params_width, true);
396                 delete[] tmp_nodes;
397         }
398         else
399         {
400                 u8 content_width = 2;
401                 u8 params_width = 2;
402                 writeU8(os, content_width);
403                 writeU8(os, params_width);
404                 MapNode::serializeBulk(os, version, data, nodecount,
405                                 content_width, params_width, true);
406         }
407
408         /*
409                 Node metadata
410         */
411         std::ostringstream oss(std::ios_base::binary);
412         m_node_metadata.serialize(oss, version, disk);
413         compressZlib(oss.str(), os);
414
415         /*
416                 Data that goes to disk, but not the network
417         */
418         if(disk)
419         {
420                 if(version <= 24){
421                         // Node timers
422                         m_node_timers.serialize(os, version);
423                 }
424
425                 // Static objects
426                 m_static_objects.serialize(os);
427
428                 // Timestamp
429                 writeU32(os, getTimestamp());
430
431                 // Write block-specific node definition id mapping
432                 nimap.serialize(os);
433
434                 if(version >= 25){
435                         // Node timers
436                         m_node_timers.serialize(os, version);
437                 }
438         }
439 }
440
441 void MapBlock::serializeNetworkSpecific(std::ostream &os)
442 {
443         if (!data) {
444                 throw SerializationError("ERROR: Not writing dummy block.");
445         }
446
447         writeU8(os, 1); // version
448         writeF1000(os, 0); // deprecated heat
449         writeF1000(os, 0); // deprecated humidity
450 }
451
452 void MapBlock::deSerialize(std::istream &is, u8 version, bool disk)
453 {
454         if(!ser_ver_supported(version))
455                 throw VersionMismatchException("ERROR: MapBlock format not supported");
456
457         TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos())<<std::endl);
458
459         m_day_night_differs_expired = false;
460
461         if(version <= 21)
462         {
463                 deSerialize_pre22(is, version, disk);
464                 return;
465         }
466
467         u8 flags = readU8(is);
468         is_underground = (flags & 0x01) != 0;
469         m_day_night_differs = (flags & 0x02) != 0;
470         if (version < 27)
471                 m_lighting_complete = 0xFFFF;
472         else
473                 m_lighting_complete = readU16(is);
474         m_generated = (flags & 0x08) == 0;
475
476         /*
477                 Bulk node data
478         */
479         TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos())
480                         <<": Bulk node data"<<std::endl);
481         u8 content_width = readU8(is);
482         u8 params_width = readU8(is);
483         if(content_width != 1 && content_width != 2)
484                 throw SerializationError("MapBlock::deSerialize(): invalid content_width");
485         if(params_width != 2)
486                 throw SerializationError("MapBlock::deSerialize(): invalid params_width");
487         MapNode::deSerializeBulk(is, version, data, nodecount,
488                         content_width, params_width, true);
489
490         /*
491                 NodeMetadata
492         */
493         TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos())
494                         <<": Node metadata"<<std::endl);
495         // Ignore errors
496         try {
497                 std::ostringstream oss(std::ios_base::binary);
498                 decompressZlib(is, oss);
499                 std::istringstream iss(oss.str(), std::ios_base::binary);
500                 if (version >= 23)
501                         m_node_metadata.deSerialize(iss, m_gamedef->idef());
502                 else
503                         content_nodemeta_deserialize_legacy(iss,
504                                 &m_node_metadata, &m_node_timers,
505                                 m_gamedef->idef());
506         } catch(SerializationError &e) {
507                 warningstream<<"MapBlock::deSerialize(): Ignoring an error"
508                                 <<" while deserializing node metadata at ("
509                                 <<PP(getPos())<<": "<<e.what()<<std::endl;
510         }
511
512         /*
513                 Data that is only on disk
514         */
515         if(disk)
516         {
517                 // Node timers
518                 if(version == 23){
519                         // Read unused zero
520                         readU8(is);
521                 }
522                 if(version == 24){
523                         TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos())
524                                         <<": Node timers (ver==24)"<<std::endl);
525                         m_node_timers.deSerialize(is, version);
526                 }
527
528                 // Static objects
529                 TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos())
530                                 <<": Static objects"<<std::endl);
531                 m_static_objects.deSerialize(is);
532
533                 // Timestamp
534                 TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos())
535                                 <<": Timestamp"<<std::endl);
536                 setTimestamp(readU32(is));
537                 m_disk_timestamp = m_timestamp;
538
539                 // Dynamically re-set ids based on node names
540                 TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos())
541                                 <<": NameIdMapping"<<std::endl);
542                 NameIdMapping nimap;
543                 nimap.deSerialize(is);
544                 correctBlockNodeIds(&nimap, data, m_gamedef);
545
546                 if(version >= 25){
547                         TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos())
548                                         <<": Node timers (ver>=25)"<<std::endl);
549                         m_node_timers.deSerialize(is, version);
550                 }
551         }
552
553         TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos())
554                         <<": Done."<<std::endl);
555 }
556
557 void MapBlock::deSerializeNetworkSpecific(std::istream &is)
558 {
559         try {
560                 int version = readU8(is);
561                 //if(version != 1)
562                 //      throw SerializationError("unsupported MapBlock version");
563                 if(version >= 1) {
564                         readF1000(is); // deprecated heat
565                         readF1000(is); // deprecated humidity
566                 }
567         }
568         catch(SerializationError &e)
569         {
570                 warningstream<<"MapBlock::deSerializeNetworkSpecific(): Ignoring an error"
571                                 <<": "<<e.what()<<std::endl;
572         }
573 }
574
575 /*
576         Legacy serialization
577 */
578
579 void MapBlock::deSerialize_pre22(std::istream &is, u8 version, bool disk)
580 {
581         // Initialize default flags
582         is_underground = false;
583         m_day_night_differs = false;
584         m_lighting_complete = 0xFFFF;
585         m_generated = true;
586
587         // Make a temporary buffer
588         u32 ser_length = MapNode::serializedLength(version);
589         SharedBuffer<u8> databuf_nodelist(nodecount * ser_length);
590
591         // These have no compression
592         if (version <= 3 || version == 5 || version == 6) {
593                 char tmp;
594                 is.read(&tmp, 1);
595                 if (is.gcount() != 1)
596                         throw SerializationError(std::string(FUNCTION_NAME)
597                                 + ": not enough input data");
598                 is_underground = tmp;
599                 is.read((char *)*databuf_nodelist, nodecount * ser_length);
600                 if ((u32)is.gcount() != nodecount * ser_length)
601                         throw SerializationError(std::string(FUNCTION_NAME)
602                                 + ": not enough input data");
603         } else if (version <= 10) {
604                 u8 t8;
605                 is.read((char *)&t8, 1);
606                 is_underground = t8;
607
608                 {
609                         // Uncompress and set material data
610                         std::ostringstream os(std::ios_base::binary);
611                         decompress(is, os, version);
612                         std::string s = os.str();
613                         if (s.size() != nodecount)
614                                 throw SerializationError(std::string(FUNCTION_NAME)
615                                         + ": not enough input data");
616                         for (u32 i = 0; i < s.size(); i++) {
617                                 databuf_nodelist[i*ser_length] = s[i];
618                         }
619                 }
620                 {
621                         // Uncompress and set param data
622                         std::ostringstream os(std::ios_base::binary);
623                         decompress(is, os, version);
624                         std::string s = os.str();
625                         if (s.size() != nodecount)
626                                 throw SerializationError(std::string(FUNCTION_NAME)
627                                         + ": not enough input data");
628                         for (u32 i = 0; i < s.size(); i++) {
629                                 databuf_nodelist[i*ser_length + 1] = s[i];
630                         }
631                 }
632
633                 if (version >= 10) {
634                         // Uncompress and set param2 data
635                         std::ostringstream os(std::ios_base::binary);
636                         decompress(is, os, version);
637                         std::string s = os.str();
638                         if (s.size() != nodecount)
639                                 throw SerializationError(std::string(FUNCTION_NAME)
640                                         + ": not enough input data");
641                         for (u32 i = 0; i < s.size(); i++) {
642                                 databuf_nodelist[i*ser_length + 2] = s[i];
643                         }
644                 }
645         } else { // All other versions (10 to 21)
646                 u8 flags;
647                 is.read((char*)&flags, 1);
648                 is_underground = (flags & 0x01) != 0;
649                 m_day_night_differs = (flags & 0x02) != 0;
650                 if(version >= 18)
651                         m_generated = (flags & 0x08) == 0;
652
653                 // Uncompress data
654                 std::ostringstream os(std::ios_base::binary);
655                 decompress(is, os, version);
656                 std::string s = os.str();
657                 if (s.size() != nodecount * 3)
658                         throw SerializationError(std::string(FUNCTION_NAME)
659                                 + ": decompress resulted in size other than nodecount*3");
660
661                 // deserialize nodes from buffer
662                 for (u32 i = 0; i < nodecount; i++) {
663                         databuf_nodelist[i*ser_length] = s[i];
664                         databuf_nodelist[i*ser_length + 1] = s[i+nodecount];
665                         databuf_nodelist[i*ser_length + 2] = s[i+nodecount*2];
666                 }
667
668                 /*
669                         NodeMetadata
670                 */
671                 if (version >= 14) {
672                         // Ignore errors
673                         try {
674                                 if (version <= 15) {
675                                         std::string data = deSerializeString(is);
676                                         std::istringstream iss(data, std::ios_base::binary);
677                                         content_nodemeta_deserialize_legacy(iss,
678                                                 &m_node_metadata, &m_node_timers,
679                                                 m_gamedef->idef());
680                                 } else {
681                                         //std::string data = deSerializeLongString(is);
682                                         std::ostringstream oss(std::ios_base::binary);
683                                         decompressZlib(is, oss);
684                                         std::istringstream iss(oss.str(), std::ios_base::binary);
685                                         content_nodemeta_deserialize_legacy(iss,
686                                                 &m_node_metadata, &m_node_timers,
687                                                 m_gamedef->idef());
688                                 }
689                         } catch(SerializationError &e) {
690                                 warningstream<<"MapBlock::deSerialize(): Ignoring an error"
691                                                 <<" while deserializing node metadata"<<std::endl;
692                         }
693                 }
694         }
695
696         // Deserialize node data
697         for (u32 i = 0; i < nodecount; i++) {
698                 data[i].deSerialize(&databuf_nodelist[i * ser_length], version);
699         }
700
701         if (disk) {
702                 /*
703                         Versions up from 9 have block objects. (DEPRECATED)
704                 */
705                 if (version >= 9) {
706                         u16 count = readU16(is);
707                         // Not supported and length not known if count is not 0
708                         if(count != 0){
709                                 warningstream<<"MapBlock::deSerialize_pre22(): "
710                                                 <<"Ignoring stuff coming at and after MBOs"<<std::endl;
711                                 return;
712                         }
713                 }
714
715                 /*
716                         Versions up from 15 have static objects.
717                 */
718                 if (version >= 15)
719                         m_static_objects.deSerialize(is);
720
721                 // Timestamp
722                 if (version >= 17) {
723                         setTimestamp(readU32(is));
724                         m_disk_timestamp = m_timestamp;
725                 } else {
726                         setTimestamp(BLOCK_TIMESTAMP_UNDEFINED);
727                 }
728
729                 // Dynamically re-set ids based on node names
730                 NameIdMapping nimap;
731                 // If supported, read node definition id mapping
732                 if (version >= 21) {
733                         nimap.deSerialize(is);
734                 // Else set the legacy mapping
735                 } else {
736                         content_mapnode_get_name_id_mapping(&nimap);
737                 }
738                 correctBlockNodeIds(&nimap, data, m_gamedef);
739         }
740
741
742         // Legacy data changes
743         // This code has to convert from pre-22 to post-22 format.
744         INodeDefManager *nodedef = m_gamedef->ndef();
745         for(u32 i=0; i<nodecount; i++)
746         {
747                 const ContentFeatures &f = nodedef->get(data[i].getContent());
748                 // Mineral
749                 if(nodedef->getId("default:stone") == data[i].getContent()
750                                 && data[i].getParam1() == 1)
751                 {
752                         data[i].setContent(nodedef->getId("default:stone_with_coal"));
753                         data[i].setParam1(0);
754                 }
755                 else if(nodedef->getId("default:stone") == data[i].getContent()
756                                 && data[i].getParam1() == 2)
757                 {
758                         data[i].setContent(nodedef->getId("default:stone_with_iron"));
759                         data[i].setParam1(0);
760                 }
761                 // facedir_simple
762                 if(f.legacy_facedir_simple)
763                 {
764                         data[i].setParam2(data[i].getParam1());
765                         data[i].setParam1(0);
766                 }
767                 // wall_mounted
768                 if(f.legacy_wallmounted)
769                 {
770                         u8 wallmounted_new_to_old[8] = {0x04, 0x08, 0x01, 0x02, 0x10, 0x20, 0, 0};
771                         u8 dir_old_format = data[i].getParam2();
772                         u8 dir_new_format = 0;
773                         for(u8 j=0; j<8; j++)
774                         {
775                                 if((dir_old_format & wallmounted_new_to_old[j]) != 0)
776                                 {
777                                         dir_new_format = j;
778                                         break;
779                                 }
780                         }
781                         data[i].setParam2(dir_new_format);
782                 }
783         }
784
785 }
786
787 /*
788         Get a quick string to describe what a block actually contains
789 */
790 std::string analyze_block(MapBlock *block)
791 {
792         if(block == NULL)
793                 return "NULL";
794
795         std::ostringstream desc;
796
797         v3s16 p = block->getPos();
798         char spos[25];
799         snprintf(spos, sizeof(spos), "(%2d,%2d,%2d), ", p.X, p.Y, p.Z);
800         desc<<spos;
801
802         switch(block->getModified())
803         {
804         case MOD_STATE_CLEAN:
805                 desc<<"CLEAN,           ";
806                 break;
807         case MOD_STATE_WRITE_AT_UNLOAD:
808                 desc<<"WRITE_AT_UNLOAD, ";
809                 break;
810         case MOD_STATE_WRITE_NEEDED:
811                 desc<<"WRITE_NEEDED,    ";
812                 break;
813         default:
814                 desc<<"unknown getModified()="+itos(block->getModified())+", ";
815         }
816
817         if(block->isGenerated())
818                 desc<<"is_gen [X], ";
819         else
820                 desc<<"is_gen [ ], ";
821
822         if(block->getIsUnderground())
823                 desc<<"is_ug [X], ";
824         else
825                 desc<<"is_ug [ ], ";
826
827         desc<<"lighting_complete: "<<block->getLightingComplete()<<", ";
828
829         if(block->isDummy())
830         {
831                 desc<<"Dummy, ";
832         }
833         else
834         {
835                 bool full_ignore = true;
836                 bool some_ignore = false;
837                 bool full_air = true;
838                 bool some_air = false;
839                 for(s16 z0=0; z0<MAP_BLOCKSIZE; z0++)
840                 for(s16 y0=0; y0<MAP_BLOCKSIZE; y0++)
841                 for(s16 x0=0; x0<MAP_BLOCKSIZE; x0++)
842                 {
843                         v3s16 p(x0,y0,z0);
844                         MapNode n = block->getNodeNoEx(p);
845                         content_t c = n.getContent();
846                         if(c == CONTENT_IGNORE)
847                                 some_ignore = true;
848                         else
849                                 full_ignore = false;
850                         if(c == CONTENT_AIR)
851                                 some_air = true;
852                         else
853                                 full_air = false;
854                 }
855
856                 desc<<"content {";
857
858                 std::ostringstream ss;
859
860                 if(full_ignore)
861                         ss<<"IGNORE (full), ";
862                 else if(some_ignore)
863                         ss<<"IGNORE, ";
864
865                 if(full_air)
866                         ss<<"AIR (full), ";
867                 else if(some_air)
868                         ss<<"AIR, ";
869
870                 if(ss.str().size()>=2)
871                         desc<<ss.str().substr(0, ss.str().size()-2);
872
873                 desc<<"}, ";
874         }
875
876         return desc.str().substr(0, desc.str().size()-2);
877 }
878
879
880 //END