3 Copyright (C) 2014-2018 kwolekr, Ryan Kwolek <kwolekr@minetest.net>
4 Copyright (C) 2015-2018 paramat
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public License along
17 with this program; if not, write to the Free Software Foundation, Inc.,
18 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 #include "mg_schematic.h"
30 #include "util/numeric.h"
31 #include "util/serialize.h"
32 #include "serialization.h"
34 #include "voxelalgorithms.h"
36 ///////////////////////////////////////////////////////////////////////////////
39 SchematicManager::SchematicManager(Server *server) :
40 ObjDefManager(server, OBJDEF_SCHEMATIC),
46 SchematicManager *SchematicManager::clone() const
48 auto mgr = new SchematicManager();
50 ObjDefManager::cloneTo(mgr);
55 void SchematicManager::clear()
57 EmergeManager *emerge = m_server->getEmergeManager();
59 // Remove all dangling references in Decorations
60 DecorationManager *decomgr = emerge->getWritableDecorationManager();
61 for (size_t i = 0; i != decomgr->getNumObjects(); i++) {
62 Decoration *deco = (Decoration *)decomgr->getRaw(i);
65 DecoSchematic *dschem = dynamic_cast<DecoSchematic *>(deco);
67 dschem->schematic = NULL;
68 } catch (const std::bad_cast &) {
72 ObjDefManager::clear();
76 ///////////////////////////////////////////////////////////////////////////////
79 Schematic::~Schematic()
85 ObjDef *Schematic::clone() const
87 auto def = new Schematic();
89 NodeResolver::cloneTo(def);
91 def->c_nodes = c_nodes;
94 FATAL_ERROR_IF(!schemdata, "Schematic can only be cloned after loading");
95 u32 nodecount = size.X * size.Y * size.Z;
96 def->schemdata = new MapNode[nodecount];
97 memcpy(def->schemdata, schemdata, sizeof(MapNode) * nodecount);
98 def->slice_probs = new u8[size.Y];
99 memcpy(def->slice_probs, slice_probs, sizeof(u8) * size.Y);
105 void Schematic::resolveNodeNames()
108 getIdsFromNrBacklog(&c_nodes, true, CONTENT_AIR);
110 size_t bufsize = size.X * size.Y * size.Z;
111 for (size_t i = 0; i != bufsize; i++) {
112 content_t c_original = schemdata[i].getContent();
113 if (c_original >= c_nodes.size()) {
114 errorstream << "Corrupt schematic. name=\"" << name
115 << "\" at index " << i << std::endl;
118 // Unfold condensed ID layout to content_t
119 schemdata[i].setContent(c_nodes[c_original]);
124 void Schematic::blitToVManip(MMVManip *vm, v3s16 p, Rotation rot, bool force_place)
126 assert(schemdata && slice_probs);
127 sanity_check(m_ndef != NULL);
130 int ystride = size.X;
131 int zstride = size.X * size.Y;
137 int i_start, i_step_x, i_step_z;
146 i_start = zstride * (sz - 1) + sx - 1;
151 i_start = zstride * (sz - 1);
163 for (s16 y = 0; y != sy; y++) {
164 if ((slice_probs[y] != MTSCHEM_PROB_ALWAYS) &&
165 (slice_probs[y] <= myrand_range(1, MTSCHEM_PROB_ALWAYS)))
168 for (s16 z = 0; z != sz; z++) {
169 u32 i = z * i_step_z + y * ystride + i_start;
170 for (s16 x = 0; x != sx; x++, i += i_step_x) {
171 v3s16 pos(p.X + x, y_map, p.Z + z);
172 if (!vm->m_area.contains(pos))
175 if (schemdata[i].getContent() == CONTENT_IGNORE)
178 u8 placement_prob = schemdata[i].param1 & MTSCHEM_PROB_MASK;
179 bool force_place_node = schemdata[i].param1 & MTSCHEM_FORCE_PLACE;
181 if (placement_prob == MTSCHEM_PROB_NEVER)
184 u32 vi = vm->m_area.index(pos);
185 if (!force_place && !force_place_node) {
186 content_t c = vm->m_data[vi].getContent();
187 if (c != CONTENT_AIR && c != CONTENT_IGNORE)
191 if ((placement_prob != MTSCHEM_PROB_ALWAYS) &&
192 (placement_prob <= myrand_range(1, MTSCHEM_PROB_ALWAYS)))
195 vm->m_data[vi] = schemdata[i];
196 vm->m_data[vi].param1 = 0;
199 vm->m_data[vi].rotateAlongYAxis(m_ndef, rot);
207 bool Schematic::placeOnVManip(MMVManip *vm, v3s16 p, u32 flags,
208 Rotation rot, bool force_place)
211 assert(schemdata && slice_probs);
212 sanity_check(m_ndef != NULL);
214 //// Determine effective rotation and effective schematic dimensions
215 if (rot == ROTATE_RAND)
216 rot = (Rotation)myrand_range(ROTATE_0, ROTATE_270);
218 v3s16 s = (rot == ROTATE_90 || rot == ROTATE_270) ?
219 v3s16(size.Z, size.Y, size.X) : size;
221 //// Adjust placement position if necessary
222 if (flags & DECO_PLACE_CENTER_X)
223 p.X -= (s.X - 1) / 2;
224 if (flags & DECO_PLACE_CENTER_Y)
225 p.Y -= (s.Y - 1) / 2;
226 if (flags & DECO_PLACE_CENTER_Z)
227 p.Z -= (s.Z - 1) / 2;
229 blitToVManip(vm, p, rot, force_place);
231 return vm->m_area.contains(VoxelArea(p, p + s - v3s16(1, 1, 1)));
234 void Schematic::placeOnMap(ServerMap *map, v3s16 p, u32 flags,
235 Rotation rot, bool force_place)
237 std::map<v3s16, MapBlock *> lighting_modified_blocks;
238 std::map<v3s16, MapBlock *> modified_blocks;
239 std::map<v3s16, MapBlock *>::iterator it;
242 assert(schemdata != NULL);
243 sanity_check(m_ndef != NULL);
245 //// Determine effective rotation and effective schematic dimensions
246 if (rot == ROTATE_RAND)
247 rot = (Rotation)myrand_range(ROTATE_0, ROTATE_270);
249 v3s16 s = (rot == ROTATE_90 || rot == ROTATE_270) ?
250 v3s16(size.Z, size.Y, size.X) : size;
252 //// Adjust placement position if necessary
253 if (flags & DECO_PLACE_CENTER_X)
254 p.X -= (s.X - 1) / 2;
255 if (flags & DECO_PLACE_CENTER_Y)
256 p.Y -= (s.Y - 1) / 2;
257 if (flags & DECO_PLACE_CENTER_Z)
258 p.Z -= (s.Z - 1) / 2;
260 //// Create VManip for effected area, emerge our area, modify area
261 //// inside VManip, then blit back.
262 v3s16 bp1 = getNodeBlockPos(p);
263 v3s16 bp2 = getNodeBlockPos(p + s - v3s16(1, 1, 1));
266 vm.initialEmerge(bp1, bp2);
268 blitToVManip(&vm, p, rot, force_place);
270 voxalgo::blit_back_with_light(map, &vm, &modified_blocks);
272 //// Carry out post-map-modification actions
274 //// Create & dispatch map modification events to observers
276 event.type = MEET_OTHER;
277 for (it = modified_blocks.begin(); it != modified_blocks.end(); ++it)
278 event.modified_blocks.insert(it->first);
280 map->dispatchEvent(event);
284 bool Schematic::deserializeFromMts(std::istream *is)
286 std::istream &ss = *is;
287 content_t cignore = CONTENT_IGNORE;
288 bool have_cignore = false;
291 u32 signature = readU32(ss);
292 if (signature != MTSCHEM_FILE_SIGNATURE) {
293 errorstream << __FUNCTION__ << ": invalid schematic "
299 u16 version = readU16(ss);
300 if (version > MTSCHEM_FILE_VER_HIGHEST_READ) {
301 errorstream << __FUNCTION__ << ": unsupported schematic "
302 "file version" << std::endl;
307 size = readV3S16(ss);
309 //// Read Y-slice probability values
310 delete []slice_probs;
311 slice_probs = new u8[size.Y];
312 for (int y = 0; y != size.Y; y++)
313 slice_probs[y] = (version >= 3) ? readU8(ss) : MTSCHEM_PROB_ALWAYS_OLD;
316 NodeResolver::reset();
318 u16 nidmapcount = readU16(ss);
319 for (int i = 0; i != nidmapcount; i++) {
320 std::string name = deSerializeString16(ss);
322 // Instances of "ignore" from v1 are converted to air (and instances
323 // are fixed to have MTSCHEM_PROB_NEVER later on).
324 if (name == "ignore") {
330 m_nodenames.push_back(name);
333 // Prepare for node resolver
334 m_nnlistsizes.push_back(m_nodenames.size());
337 size_t nodecount = size.X * size.Y * size.Z;
340 schemdata = new MapNode[nodecount];
342 std::stringstream d_ss(std::ios_base::binary | std::ios_base::in | std::ios_base::out);
343 decompress(ss, d_ss, MTSCHEM_MAPNODE_SER_FMT_VER);
344 MapNode::deSerializeBulk(d_ss, MTSCHEM_MAPNODE_SER_FMT_VER, schemdata,
347 // Fix probability values for nodes that were ignore; removed in v2
349 for (size_t i = 0; i != nodecount; i++) {
350 if (schemdata[i].param1 == 0)
351 schemdata[i].param1 = MTSCHEM_PROB_ALWAYS_OLD;
352 if (have_cignore && schemdata[i].getContent() == cignore)
353 schemdata[i].param1 = MTSCHEM_PROB_NEVER;
357 // Fix probability values for probability range truncation introduced in v4
359 for (s16 y = 0; y != size.Y; y++)
360 slice_probs[y] >>= 1;
361 for (size_t i = 0; i != nodecount; i++)
362 schemdata[i].param1 >>= 1;
369 bool Schematic::serializeToMts(std::ostream *os) const
371 // Nodes must not be resolved (-> condensed)
372 // checking here is not possible because "schemdata" might be temporary.
374 std::ostream &ss = *os;
376 writeU32(ss, MTSCHEM_FILE_SIGNATURE); // signature
377 writeU16(ss, MTSCHEM_FILE_VER_HIGHEST_WRITE); // version
378 writeV3S16(ss, size); // schematic size
380 for (int y = 0; y != size.Y; y++) // Y slice probabilities
381 writeU8(ss, slice_probs[y]);
383 writeU16(ss, m_nodenames.size()); // name count
384 for (size_t i = 0; i != m_nodenames.size(); i++) {
385 ss << serializeString16(m_nodenames[i]); // node names
388 // compressed bulk node data
389 SharedBuffer<u8> buf = MapNode::serializeBulk(MTSCHEM_MAPNODE_SER_FMT_VER,
390 schemdata, size.X * size.Y * size.Z, 2, 2);
391 compress(buf, ss, MTSCHEM_MAPNODE_SER_FMT_VER);
397 bool Schematic::serializeToLua(std::ostream *os, bool use_comments,
398 u32 indent_spaces) const
400 std::ostream &ss = *os;
402 std::string indent("\t");
403 if (indent_spaces > 0)
404 indent.assign(indent_spaces, ' ');
406 bool resolve_done = isResolveDone();
407 FATAL_ERROR_IF(resolve_done && !m_ndef, "serializeToLua: NodeDefManager is required");
411 ss << "schematic = {" << std::endl;
412 ss << indent << "size = "
416 << "}," << std::endl;
419 //// Write y-slice probabilities
421 ss << indent << "yslice_prob = {" << std::endl;
423 for (u16 y = 0; y != size.Y; y++) {
424 u8 probability = slice_probs[y] & MTSCHEM_PROB_MASK;
426 ss << indent << indent << "{"
428 << ", prob=" << (u16)probability * 2
429 << "}," << std::endl;
432 ss << indent << "}," << std::endl;
437 ss << indent << "data = {" << std::endl;
440 for (u16 z = 0; z != size.Z; z++)
441 for (u16 y = 0; y != size.Y; y++) {
446 << ", y=" << y << std::endl;
449 for (u16 x = 0; x != size.X; x++, i++) {
450 u8 probability = schemdata[i].param1 & MTSCHEM_PROB_MASK;
451 bool force_place = schemdata[i].param1 & MTSCHEM_FORCE_PLACE;
453 // After node resolving: real content_t, lookup using NodeDefManager
454 // Prior node resolving: condensed ID, lookup using m_nodenames
455 content_t c = schemdata[i].getContent();
457 ss << indent << indent << "{" << "name=\"";
460 // Prior node resolving (eg. direct schematic load)
461 FATAL_ERROR_IF(c >= m_nodenames.size(), "Invalid node list");
462 ss << m_nodenames[c];
464 // After node resolving (eg. biome decoration)
465 ss << m_ndef->get(c).name;
468 ss << "\", prob=" << (u16)probability * 2
469 << ", param2=" << (u16)schemdata[i].param2;
472 ss << ", force_place=true";
474 ss << "}," << std::endl;
478 ss << indent << "}," << std::endl;
481 ss << "}" << std::endl;
487 bool Schematic::loadSchematicFromFile(const std::string &filename,
488 const NodeDefManager *ndef, StringMap *replace_names)
490 std::ifstream is(filename.c_str(), std::ios_base::binary);
492 errorstream << __FUNCTION__ << ": unable to open file '"
493 << filename << "'" << std::endl;
500 if (!deserializeFromMts(&is))
506 for (std::string &node_name : m_nodenames) {
507 StringMap::iterator it = replace_names->find(node_name);
508 if (it != replace_names->end())
509 node_name = it->second;
514 m_ndef->pendNodeResolve(this);
520 bool Schematic::saveSchematicToFile(const std::string &filename,
521 const NodeDefManager *ndef)
523 Schematic *schem = this;
525 bool needs_condense = isResolveDone();
530 if (needs_condense) {
534 schem = (Schematic *)this->clone();
535 schem->condenseContentIds();
538 std::ostringstream os(std::ios_base::binary);
539 bool status = schem->serializeToMts(&os);
547 return fs::safeWriteToFile(filename, os.str());
551 bool Schematic::getSchematicFromMap(Map *map, v3s16 p1, v3s16 p2)
553 MMVManip *vm = new MMVManip(map);
555 v3s16 bp1 = getNodeBlockPos(p1);
556 v3s16 bp2 = getNodeBlockPos(p2);
557 vm->initialEmerge(bp1, bp2);
561 slice_probs = new u8[size.Y];
562 for (s16 y = 0; y != size.Y; y++)
563 slice_probs[y] = MTSCHEM_PROB_ALWAYS;
565 schemdata = new MapNode[size.X * size.Y * size.Z];
568 for (s16 z = p1.Z; z <= p2.Z; z++)
569 for (s16 y = p1.Y; y <= p2.Y; y++) {
570 u32 vi = vm->m_area.index(p1.X, y, z);
571 for (s16 x = p1.X; x <= p2.X; x++, i++, vi++) {
572 schemdata[i] = vm->m_data[vi];
573 schemdata[i].param1 = MTSCHEM_PROB_ALWAYS;
579 // Reset and mark as complete
580 NodeResolver::reset(true);
586 void Schematic::applyProbabilities(v3s16 p0,
587 std::vector<std::pair<v3s16, u8> > *plist,
588 std::vector<std::pair<s16, u8> > *splist)
590 for (size_t i = 0; i != plist->size(); i++) {
591 v3s16 p = (*plist)[i].first - p0;
592 int index = p.Z * (size.Y * size.X) + p.Y * size.X + p.X;
593 if (index < size.Z * size.Y * size.X) {
594 u8 prob = (*plist)[i].second;
595 schemdata[index].param1 = prob;
597 // trim unnecessary node names from schematic
598 if (prob == MTSCHEM_PROB_NEVER)
599 schemdata[index].setContent(CONTENT_AIR);
603 for (size_t i = 0; i != splist->size(); i++) {
604 s16 slice = (*splist)[i].first;
606 slice_probs[slice] = (*splist)[i].second;
611 void Schematic::condenseContentIds()
613 std::unordered_map<content_t, content_t> nodeidmap;
614 content_t numids = 0;
616 // Reset node resolve fields
617 NodeResolver::reset();
619 size_t nodecount = size.X * size.Y * size.Z;
620 for (size_t i = 0; i != nodecount; i++) {
622 content_t c = schemdata[i].getContent();
624 auto it = nodeidmap.find(c);
625 if (it == nodeidmap.end()) {
629 m_nodenames.push_back(m_ndef->get(c).name);
630 nodeidmap.emplace(std::make_pair(c, id));
634 schemdata[i].setContent(id);