3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
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.
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.
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.
26 #include "nodemetadata.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"
34 #include "mapblock_mesh.h"
36 #include "util/string.h"
37 #include "util/serialize.h"
38 #include "util/basic_macros.h"
40 static const char *modified_reason_strings[] = {
49 "NodeMetaRef::reportMetadataChange",
51 "Timestamp expired (step)",
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",
68 MapBlock::MapBlock(Map *parent, v3s16 pos, IGameDef *gamedef, bool dummy):
71 m_pos_relative(pos * MAP_BLOCKSIZE),
90 bool MapBlock::isValidPositionParent(v3s16 p)
92 if (isValidPosition(p)) {
96 return m_parent->isValidPosition(getPosRelative() + p);
99 MapNode MapBlock::getNodeParent(v3s16 p, bool *is_valid_position)
101 if (!isValidPosition(p))
102 return m_parent->getNodeNoEx(getPosRelative() + p, is_valid_position);
105 if (is_valid_position)
106 *is_valid_position = false;
107 return {CONTENT_IGNORE};
109 if (is_valid_position)
110 *is_valid_position = true;
111 return data[p.Z * zstride + p.Y * ystride + p.X];
114 std::string MapBlock::getModifiedReasonString()
118 const u32 ubound = MYMIN(sizeof(m_modified_reason) * CHAR_BIT,
119 ARRLEN(modified_reason_strings));
121 for (u32 i = 0; i != ubound; i++) {
122 if ((m_modified_reason & (1 << i)) == 0)
125 reason += modified_reason_strings[i];
129 if (reason.length() > 2)
130 reason.resize(reason.length() - 2);
135 void MapBlock::copyTo(VoxelManipulator &dst)
137 v3s16 data_size(MAP_BLOCKSIZE, MAP_BLOCKSIZE, MAP_BLOCKSIZE);
138 VoxelArea data_area(v3s16(0,0,0), data_size - v3s16(1,1,1));
140 // Copy from data to VoxelManipulator
141 dst.copyFrom(data, data_area, v3s16(0,0,0),
142 getPosRelative(), data_size);
145 void MapBlock::copyFrom(VoxelManipulator &dst)
147 v3s16 data_size(MAP_BLOCKSIZE, MAP_BLOCKSIZE, MAP_BLOCKSIZE);
148 VoxelArea data_area(v3s16(0,0,0), data_size - v3s16(1,1,1));
150 // Copy from VoxelManipulator to data
151 dst.copyTo(data, data_area, v3s16(0,0,0),
152 getPosRelative(), data_size);
155 void MapBlock::actuallyUpdateDayNightDiff()
157 INodeDefManager *nodemgr = m_gamedef->ndef();
159 // Running this function un-expires m_day_night_differs
160 m_day_night_differs_expired = false;
163 m_day_night_differs = false;
167 bool differs = false;
170 Check if any lighting value differs
173 MapNode previous_n(CONTENT_IGNORE);
174 for (u32 i = 0; i < nodecount; i++) {
177 // If node is identical to previous node, don't verify if it differs
181 differs = !n.isLightDayNightEq(nodemgr);
188 If some lighting values differ, check if the whole thing is
189 just air. If it is just air, differs = false
192 bool only_air = true;
193 for (u32 i = 0; i < nodecount; i++) {
194 MapNode &n = data[i];
195 if (n.getContent() != CONTENT_AIR) {
204 // Set member variable
205 m_day_night_differs = differs;
208 void MapBlock::expireDayNightDiff()
211 m_day_night_differs = false;
212 m_day_night_differs_expired = false;
216 m_day_night_differs_expired = true;
219 s16 MapBlock::getGroundLevel(v2s16 p2d)
225 s16 y = MAP_BLOCKSIZE-1;
228 MapNode n = getNodeRef(p2d.X, y, p2d.Y);
229 if (m_gamedef->ndef()->get(n).walkable) {
230 if(y == MAP_BLOCKSIZE-1)
238 catch(InvalidPositionException &e)
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
253 static content_t getBlockNodeIdMapping_mapping[USHRT_MAX + 1];
254 static void getBlockNodeIdMapping(NameIdMapping *nimap, MapNode *nodes,
255 INodeDefManager *nodedef)
257 memset(getBlockNodeIdMapping_mapping, 0xFF, (USHRT_MAX + 1) * sizeof(content_t));
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;
265 // Try to find an existing mapping
266 if (getBlockNodeIdMapping_mapping[global_id] != 0xFFFF) {
267 id = getBlockNodeIdMapping_mapping[global_id];
271 // We have to assign a new mapping
273 getBlockNodeIdMapping_mapping[global_id] = id;
275 const ContentFeatures &f = nodedef->get(global_id);
276 const std::string &name = f.name;
278 unknown_contents.insert(global_id);
280 nimap->set(id, name);
283 // Update the MapNode
284 nodes[i].setContent(id);
286 for (u16 unknown_content : unknown_contents) {
287 errorstream << "getBlockNodeIdMapping(): IGNORING ERROR: "
288 << "Name for node id " << unknown_content << " not known" << std::endl;
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,
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
302 std::unordered_set<content_t> unnamed_contents;
303 std::unordered_set<std::string> unallocatable_contents;
305 bool previous_exists = false;
306 content_t previous_local_id = CONTENT_IGNORE;
307 content_t previous_global_id = CONTENT_IGNORE;
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);
321 if (!nimap->getName(local_id, name)) {
322 unnamed_contents.insert(local_id);
323 previous_exists = false;
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;
336 nodes[i].setContent(global_id);
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;
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;
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;
356 void MapBlock::serialize(std::ostream &os, u8 version, bool disk)
358 if(!ser_ver_supported(version))
359 throw VersionMismatchException("ERROR: MapBlock format not supported");
362 throw SerializationError("ERROR: Not writing dummy block.");
364 FATAL_ERROR_IF(version < SER_FMT_VER_LOWEST_WRITE, "Serialisation version error");
370 if(getDayNightDiff())
376 writeU16(os, m_lighting_complete);
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());
390 u8 content_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);
400 u8 content_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);
411 std::ostringstream oss(std::ios_base::binary);
412 m_node_metadata.serialize(oss, version, disk);
413 compressZlib(oss.str(), os);
416 Data that goes to disk, but not the network
422 m_node_timers.serialize(os, version);
426 m_static_objects.serialize(os);
429 writeU32(os, getTimestamp());
431 // Write block-specific node definition id mapping
436 m_node_timers.serialize(os, version);
441 void MapBlock::serializeNetworkSpecific(std::ostream &os)
444 throw SerializationError("ERROR: Not writing dummy block.");
447 writeU8(os, 1); // version
448 writeF1000(os, 0); // deprecated heat
449 writeF1000(os, 0); // deprecated humidity
452 void MapBlock::deSerialize(std::istream &is, u8 version, bool disk)
454 if(!ser_ver_supported(version))
455 throw VersionMismatchException("ERROR: MapBlock format not supported");
457 TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos())<<std::endl);
459 m_day_night_differs_expired = false;
463 deSerialize_pre22(is, version, disk);
467 u8 flags = readU8(is);
468 is_underground = (flags & 0x01) != 0;
469 m_day_night_differs = (flags & 0x02) != 0;
471 m_lighting_complete = 0xFFFF;
473 m_lighting_complete = readU16(is);
474 m_generated = (flags & 0x08) == 0;
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);
493 TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos())
494 <<": Node metadata"<<std::endl);
497 std::ostringstream oss(std::ios_base::binary);
498 decompressZlib(is, oss);
499 std::istringstream iss(oss.str(), std::ios_base::binary);
501 m_node_metadata.deSerialize(iss, m_gamedef->idef());
503 content_nodemeta_deserialize_legacy(iss,
504 &m_node_metadata, &m_node_timers,
506 } catch(SerializationError &e) {
507 warningstream<<"MapBlock::deSerialize(): Ignoring an error"
508 <<" while deserializing node metadata at ("
509 <<PP(getPos())<<": "<<e.what()<<std::endl;
513 Data that is only on disk
523 TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos())
524 <<": Node timers (ver==24)"<<std::endl);
525 m_node_timers.deSerialize(is, version);
529 TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos())
530 <<": Static objects"<<std::endl);
531 m_static_objects.deSerialize(is);
534 TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos())
535 <<": Timestamp"<<std::endl);
536 setTimestamp(readU32(is));
537 m_disk_timestamp = m_timestamp;
539 // Dynamically re-set ids based on node names
540 TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos())
541 <<": NameIdMapping"<<std::endl);
543 nimap.deSerialize(is);
544 correctBlockNodeIds(&nimap, data, m_gamedef);
547 TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos())
548 <<": Node timers (ver>=25)"<<std::endl);
549 m_node_timers.deSerialize(is, version);
553 TRACESTREAM(<<"MapBlock::deSerialize "<<PP(getPos())
554 <<": Done."<<std::endl);
557 void MapBlock::deSerializeNetworkSpecific(std::istream &is)
560 int version = readU8(is);
562 // throw SerializationError("unsupported MapBlock version");
564 readF1000(is); // deprecated heat
565 readF1000(is); // deprecated humidity
568 catch(SerializationError &e)
570 warningstream<<"MapBlock::deSerializeNetworkSpecific(): Ignoring an error"
571 <<": "<<e.what()<<std::endl;
579 void MapBlock::deSerialize_pre22(std::istream &is, u8 version, bool disk)
581 // Initialize default flags
582 is_underground = false;
583 m_day_night_differs = false;
584 m_lighting_complete = 0xFFFF;
587 // Make a temporary buffer
588 u32 ser_length = MapNode::serializedLength(version);
589 SharedBuffer<u8> databuf_nodelist(nodecount * ser_length);
591 // These have no compression
592 if (version <= 3 || version == 5 || version == 6) {
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) {
605 is.read((char *)&t8, 1);
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];
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];
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];
645 } else { // All other versions (10 to 21)
647 is.read((char*)&flags, 1);
648 is_underground = (flags & 0x01) != 0;
649 m_day_night_differs = (flags & 0x02) != 0;
651 m_generated = (flags & 0x08) == 0;
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");
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];
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,
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,
689 } catch(SerializationError &e) {
690 warningstream<<"MapBlock::deSerialize(): Ignoring an error"
691 <<" while deserializing node metadata"<<std::endl;
696 // Deserialize node data
697 for (u32 i = 0; i < nodecount; i++) {
698 data[i].deSerialize(&databuf_nodelist[i * ser_length], version);
703 Versions up from 9 have block objects. (DEPRECATED)
706 u16 count = readU16(is);
707 // Not supported and length not known if count is not 0
709 warningstream<<"MapBlock::deSerialize_pre22(): "
710 <<"Ignoring stuff coming at and after MBOs"<<std::endl;
716 Versions up from 15 have static objects.
719 m_static_objects.deSerialize(is);
723 setTimestamp(readU32(is));
724 m_disk_timestamp = m_timestamp;
726 setTimestamp(BLOCK_TIMESTAMP_UNDEFINED);
729 // Dynamically re-set ids based on node names
731 // If supported, read node definition id mapping
733 nimap.deSerialize(is);
734 // Else set the legacy mapping
736 content_mapnode_get_name_id_mapping(&nimap);
738 correctBlockNodeIds(&nimap, data, m_gamedef);
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++)
747 const ContentFeatures &f = nodedef->get(data[i].getContent());
749 if(nodedef->getId("default:stone") == data[i].getContent()
750 && data[i].getParam1() == 1)
752 data[i].setContent(nodedef->getId("default:stone_with_coal"));
753 data[i].setParam1(0);
755 else if(nodedef->getId("default:stone") == data[i].getContent()
756 && data[i].getParam1() == 2)
758 data[i].setContent(nodedef->getId("default:stone_with_iron"));
759 data[i].setParam1(0);
762 if(f.legacy_facedir_simple)
764 data[i].setParam2(data[i].getParam1());
765 data[i].setParam1(0);
768 if(f.legacy_wallmounted)
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++)
775 if((dir_old_format & wallmounted_new_to_old[j]) != 0)
781 data[i].setParam2(dir_new_format);
788 Get a quick string to describe what a block actually contains
790 std::string analyze_block(MapBlock *block)
795 std::ostringstream desc;
797 v3s16 p = block->getPos();
799 snprintf(spos, sizeof(spos), "(%2d,%2d,%2d), ", p.X, p.Y, p.Z);
802 switch(block->getModified())
804 case MOD_STATE_CLEAN:
807 case MOD_STATE_WRITE_AT_UNLOAD:
808 desc<<"WRITE_AT_UNLOAD, ";
810 case MOD_STATE_WRITE_NEEDED:
811 desc<<"WRITE_NEEDED, ";
814 desc<<"unknown getModified()="+itos(block->getModified())+", ";
817 if(block->isGenerated())
818 desc<<"is_gen [X], ";
820 desc<<"is_gen [ ], ";
822 if(block->getIsUnderground())
827 desc<<"lighting_complete: "<<block->getLightingComplete()<<", ";
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++)
844 MapNode n = block->getNodeNoEx(p);
845 content_t c = n.getContent();
846 if(c == CONTENT_IGNORE)
858 std::ostringstream ss;
861 ss<<"IGNORE (full), ";
870 if(ss.str().size()>=2)
871 desc<<ss.str().substr(0, ss.str().size()-2);
876 return desc.str().substr(0, desc.str().size()-2);