]> git.lizzy.rs Git - minetest.git/blob - src/mg_schematic.cpp
019ed4dee9887c023d8bea92b70641229704c548
[minetest.git] / src / mg_schematic.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2014 kwolekr, Ryan Kwolek <kwolekr@minetest.net>
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 <fstream>
21 #include <typeinfo>
22 #include "mg_schematic.h"
23 #include "gamedef.h"
24 #include "mapgen.h"
25 #include "emerge.h"
26 #include "map.h"
27 #include "mapblock.h"
28 #include "log.h"
29 #include "util/numeric.h"
30 #include "util/serialize.h"
31 #include "serialization.h"
32 #include "filesys.h"
33
34 ///////////////////////////////////////////////////////////////////////////////
35
36
37 SchematicManager::SchematicManager(IGameDef *gamedef) :
38         ObjDefManager(gamedef, OBJDEF_SCHEMATIC)
39 {
40         m_gamedef = gamedef;
41 }
42
43
44 void SchematicManager::clear()
45 {
46         EmergeManager *emerge = m_gamedef->getEmergeManager();
47
48         // Remove all dangling references in Decorations
49         DecorationManager *decomgr = emerge->decomgr;
50         for (size_t i = 0; i != decomgr->getNumObjects(); i++) {
51                 Decoration *deco = (Decoration *)decomgr->getRaw(i);
52
53                 try {
54                         DecoSchematic *dschem = dynamic_cast<DecoSchematic *>(deco);
55                         if (dschem)
56                                 dschem->schematic = NULL;
57                 } catch (std::bad_cast) {
58                 }
59         }
60
61         ObjDefManager::clear();
62 }
63
64
65 ///////////////////////////////////////////////////////////////////////////////
66
67
68 Schematic::Schematic()
69 {
70         schemdata   = NULL;
71         slice_probs = NULL;
72         flags       = 0;
73         size        = v3s16(0, 0, 0);
74 }
75
76
77 Schematic::~Schematic()
78 {
79         delete []schemdata;
80         delete []slice_probs;
81 }
82
83
84 void Schematic::resolveNodeNames()
85 {
86         getIdsFromNrBacklog(&c_nodes, true, CONTENT_AIR);
87
88         size_t bufsize = size.X * size.Y * size.Z;
89         for (size_t i = 0; i != bufsize; i++) {
90                 content_t c_original = schemdata[i].getContent();
91                 content_t c_new = c_nodes[c_original];
92                 schemdata[i].setContent(c_new);
93         }
94 }
95
96
97 void Schematic::blitToVManip(MMVManip *vm, v3s16 p, Rotation rot, bool force_place)
98 {
99         sanity_check(m_ndef != NULL);
100
101         int xstride = 1;
102         int ystride = size.X;
103         int zstride = size.X * size.Y;
104
105         s16 sx = size.X;
106         s16 sy = size.Y;
107         s16 sz = size.Z;
108
109         int i_start, i_step_x, i_step_z;
110         switch (rot) {
111                 case ROTATE_90:
112                         i_start  = sx - 1;
113                         i_step_x = zstride;
114                         i_step_z = -xstride;
115                         SWAP(s16, sx, sz);
116                         break;
117                 case ROTATE_180:
118                         i_start  = zstride * (sz - 1) + sx - 1;
119                         i_step_x = -xstride;
120                         i_step_z = -zstride;
121                         break;
122                 case ROTATE_270:
123                         i_start  = zstride * (sz - 1);
124                         i_step_x = -zstride;
125                         i_step_z = xstride;
126                         SWAP(s16, sx, sz);
127                         break;
128                 default:
129                         i_start  = 0;
130                         i_step_x = xstride;
131                         i_step_z = zstride;
132         }
133
134         s16 y_map = p.Y;
135         for (s16 y = 0; y != sy; y++) {
136                 if ((slice_probs[y] != MTSCHEM_PROB_ALWAYS) &&
137                         (slice_probs[y] <= myrand_range(1, MTSCHEM_PROB_ALWAYS)))
138                         continue;
139
140                 for (s16 z = 0; z != sz; z++) {
141                         u32 i = z * i_step_z + y * ystride + i_start;
142                         for (s16 x = 0; x != sx; x++, i += i_step_x) {
143                                 u32 vi = vm->m_area.index(p.X + x, y_map, p.Z + z);
144                                 if (!vm->m_area.contains(vi))
145                                         continue;
146
147                                 if (schemdata[i].getContent() == CONTENT_IGNORE)
148                                         continue;
149
150                                 u8 placement_prob     = schemdata[i].param1 & MTSCHEM_PROB_MASK;
151                                 bool force_place_node = schemdata[i].param1 & MTSCHEM_FORCE_PLACE;
152
153                                 if (placement_prob == MTSCHEM_PROB_NEVER)
154                                         continue;
155
156                                 if (!force_place && !force_place_node) {
157                                         content_t c = vm->m_data[vi].getContent();
158                                         if (c != CONTENT_AIR && c != CONTENT_IGNORE)
159                                                 continue;
160                                 }
161
162                                 if ((placement_prob != MTSCHEM_PROB_ALWAYS) &&
163                                         (placement_prob <= myrand_range(1, MTSCHEM_PROB_ALWAYS)))
164                                         continue;
165
166                                 vm->m_data[vi] = schemdata[i];
167                                 vm->m_data[vi].param1 = 0;
168
169                                 if (rot)
170                                         vm->m_data[vi].rotateAlongYAxis(m_ndef, rot);
171                         }
172                 }
173                 y_map++;
174         }
175 }
176
177
178 bool Schematic::placeOnVManip(MMVManip *vm, v3s16 p, u32 flags,
179         Rotation rot, bool force_place)
180 {
181         assert(vm != NULL);
182         assert(schemdata != NULL);
183         sanity_check(m_ndef != NULL);
184
185         //// Determine effective rotation and effective schematic dimensions
186         if (rot == ROTATE_RAND)
187                 rot = (Rotation)myrand_range(ROTATE_0, ROTATE_270);
188
189         v3s16 s = (rot == ROTATE_90 || rot == ROTATE_270) ?
190                 v3s16(size.Z, size.Y, size.X) : size;
191
192         //// Adjust placement position if necessary
193         if (flags & DECO_PLACE_CENTER_X)
194                 p.X -= (s.X + 1) / 2;
195         if (flags & DECO_PLACE_CENTER_Y)
196                 p.Y -= (s.Y + 1) / 2;
197         if (flags & DECO_PLACE_CENTER_Z)
198                 p.Z -= (s.Z + 1) / 2;
199
200         blitToVManip(vm, p, rot, force_place);
201
202         return vm->m_area.contains(VoxelArea(p, p + s - v3s16(1,1,1)));
203 }
204
205 void Schematic::placeOnMap(Map *map, v3s16 p, u32 flags,
206         Rotation rot, bool force_place)
207 {
208         std::map<v3s16, MapBlock *> lighting_modified_blocks;
209         std::map<v3s16, MapBlock *> modified_blocks;
210         std::map<v3s16, MapBlock *>::iterator it;
211
212         assert(map != NULL);
213         assert(schemdata != NULL);
214         sanity_check(m_ndef != NULL);
215
216         //// Determine effective rotation and effective schematic dimensions
217         if (rot == ROTATE_RAND)
218                 rot = (Rotation)myrand_range(ROTATE_0, ROTATE_270);
219
220         v3s16 s = (rot == ROTATE_90 || rot == ROTATE_270) ?
221                         v3s16(size.Z, size.Y, size.X) : size;
222
223         //// Adjust placement position if necessary
224         if (flags & DECO_PLACE_CENTER_X)
225                 p.X -= (s.X + 1) / 2;
226         if (flags & DECO_PLACE_CENTER_Y)
227                 p.Y -= (s.Y + 1) / 2;
228         if (flags & DECO_PLACE_CENTER_Z)
229                 p.Z -= (s.Z + 1) / 2;
230
231         //// Create VManip for effected area, emerge our area, modify area
232         //// inside VManip, then blit back.
233         v3s16 bp1 = getNodeBlockPos(p);
234         v3s16 bp2 = getNodeBlockPos(p + s - v3s16(1,1,1));
235
236         MMVManip vm(map);
237         vm.initialEmerge(bp1, bp2);
238
239         blitToVManip(&vm, p, rot, force_place);
240
241         vm.blitBackAll(&modified_blocks);
242
243         //// Carry out post-map-modification actions
244
245         //// Update lighting
246         // TODO: Optimize this by using Mapgen::calcLighting() instead
247         lighting_modified_blocks.insert(modified_blocks.begin(), modified_blocks.end());
248         map->updateLighting(lighting_modified_blocks, modified_blocks);
249
250         //// Create & dispatch map modification events to observers
251         MapEditEvent event;
252         event.type = MEET_OTHER;
253         for (it = modified_blocks.begin(); it != modified_blocks.end(); ++it)
254                 event.modified_blocks.insert(it->first);
255
256         map->dispatchEvent(&event);
257 }
258
259
260 bool Schematic::deserializeFromMts(std::istream *is,
261         std::vector<std::string> *names)
262 {
263         std::istream &ss = *is;
264         content_t cignore = CONTENT_IGNORE;
265         bool have_cignore = false;
266
267         //// Read signature
268         u32 signature = readU32(ss);
269         if (signature != MTSCHEM_FILE_SIGNATURE) {
270                 errorstream << "Schematic::deserializeFromMts: invalid schematic "
271                         "file" << std::endl;
272                 return false;
273         }
274
275         //// Read version
276         u16 version = readU16(ss);
277         if (version > MTSCHEM_FILE_VER_HIGHEST_READ) {
278                 errorstream << "Schematic::deserializeFromMts: unsupported schematic "
279                         "file version" << std::endl;
280                 return false;
281         }
282
283         //// Read size
284         size = readV3S16(ss);
285
286         //// Read Y-slice probability values
287         delete []slice_probs;
288         slice_probs = new u8[size.Y];
289         for (int y = 0; y != size.Y; y++)
290                 slice_probs[y] = (version >= 3) ? readU8(ss) : MTSCHEM_PROB_ALWAYS_OLD;
291
292         //// Read node names
293         u16 nidmapcount = readU16(ss);
294         for (int i = 0; i != nidmapcount; i++) {
295                 std::string name = deSerializeString(ss);
296
297                 // Instances of "ignore" from v1 are converted to air (and instances
298                 // are fixed to have MTSCHEM_PROB_NEVER later on).
299                 if (name == "ignore") {
300                         name = "air";
301                         cignore = i;
302                         have_cignore = true;
303                 }
304
305                 names->push_back(name);
306         }
307
308         //// Read node data
309         size_t nodecount = size.X * size.Y * size.Z;
310
311         delete []schemdata;
312         schemdata = new MapNode[nodecount];
313
314         MapNode::deSerializeBulk(ss, SER_FMT_VER_HIGHEST_READ, schemdata,
315                 nodecount, 2, 2, true);
316
317         // Fix probability values for nodes that were ignore; removed in v2
318         if (version < 2) {
319                 for (size_t i = 0; i != nodecount; i++) {
320                         if (schemdata[i].param1 == 0)
321                                 schemdata[i].param1 = MTSCHEM_PROB_ALWAYS_OLD;
322                         if (have_cignore && schemdata[i].getContent() == cignore)
323                                 schemdata[i].param1 = MTSCHEM_PROB_NEVER;
324                 }
325         }
326
327         // Fix probability values for probability range truncation introduced in v4
328         if (version < 4) {
329                 for (s16 y = 0; y != size.Y; y++)
330                         slice_probs[y] >>= 1;
331                 for (size_t i = 0; i != nodecount; i++)
332                         schemdata[i].param1 >>= 1;
333         }
334
335         return true;
336 }
337
338
339 bool Schematic::serializeToMts(std::ostream *os,
340         const std::vector<std::string> &names)
341 {
342         std::ostream &ss = *os;
343
344         writeU32(ss, MTSCHEM_FILE_SIGNATURE);         // signature
345         writeU16(ss, MTSCHEM_FILE_VER_HIGHEST_WRITE); // version
346         writeV3S16(ss, size);                         // schematic size
347
348         for (int y = 0; y != size.Y; y++)             // Y slice probabilities
349                 writeU8(ss, slice_probs[y]);
350
351         writeU16(ss, names.size()); // name count
352         for (size_t i = 0; i != names.size(); i++)
353                 ss << serializeString(names[i]); // node names
354
355         // compressed bulk node data
356         MapNode::serializeBulk(ss, SER_FMT_VER_HIGHEST_WRITE,
357                 schemdata, size.X * size.Y * size.Z, 2, 2, true);
358
359         return true;
360 }
361
362
363 bool Schematic::serializeToLua(std::ostream *os,
364         const std::vector<std::string> &names, bool use_comments, u32 indent_spaces)
365 {
366         std::ostream &ss = *os;
367
368         std::string indent("\t");
369         if (indent_spaces > 0)
370                 indent.assign(indent_spaces, ' ');
371
372         //// Write header
373         {
374                 ss << "schematic = {" << std::endl;
375                 ss << indent << "size = "
376                         << "{x=" << size.X
377                         << ", y=" << size.Y
378                         << ", z=" << size.Z
379                         << "}," << std::endl;
380         }
381
382         //// Write y-slice probabilities
383         {
384                 ss << indent << "yslice_prob = {" << std::endl;
385
386                 for (u16 y = 0; y != size.Y; y++) {
387                         u8 probability = slice_probs[y] & MTSCHEM_PROB_MASK;
388
389                         ss << indent << indent << "{"
390                                 << "ypos=" << y
391                                 << ", prob=" << (u16)probability * 2
392                                 << "}," << std::endl;
393                 }
394
395                 ss << indent << "}," << std::endl;
396         }
397
398         //// Write node data
399         {
400                 ss << indent << "data = {" << std::endl;
401
402                 u32 i = 0;
403                 for (u16 z = 0; z != size.Z; z++)
404                 for (u16 y = 0; y != size.Y; y++) {
405                         if (use_comments) {
406                                 ss << std::endl
407                                         << indent << indent
408                                         << "-- z=" << z
409                                         << ", y=" << y << std::endl;
410                         }
411
412                         for (u16 x = 0; x != size.X; x++, i++) {
413                                 u8 probability   = schemdata[i].param1 & MTSCHEM_PROB_MASK;
414                                 bool force_place = schemdata[i].param1 & MTSCHEM_FORCE_PLACE;
415
416                                 ss << indent << indent << "{"
417                                         << "name=\"" << names[schemdata[i].getContent()]
418                                         << "\", prob=" << (u16)probability * 2
419                                         << ", param2=" << (u16)schemdata[i].param2;
420
421                                 if (force_place)
422                                         ss << ", force_place=true";
423
424                                 ss << "}," << std::endl;
425                         }
426                 }
427
428                 ss << indent << "}," << std::endl;
429         }
430
431         ss << "}" << std::endl;
432
433         return true;
434 }
435
436
437 bool Schematic::loadSchematicFromFile(const std::string &filename,
438         INodeDefManager *ndef, StringMap *replace_names)
439 {
440         std::ifstream is(filename.c_str(), std::ios_base::binary);
441         if (!is.good()) {
442                 errorstream << "Schematic::loadSchematicFile: unable to open file '"
443                         << filename << "'" << std::endl;
444                 return false;
445         }
446
447         size_t origsize = m_nodenames.size();
448         if (!deserializeFromMts(&is, &m_nodenames))
449                 return false;
450
451         if (replace_names) {
452                 for (size_t i = origsize; i != m_nodenames.size(); i++) {
453                         std::string &name = m_nodenames[i];
454                         StringMap::iterator it = replace_names->find(name);
455                         if (it != replace_names->end())
456                                 name = it->second;
457                 }
458         }
459
460         m_nnlistsizes.push_back(m_nodenames.size() - origsize);
461
462         if (ndef)
463                 ndef->pendNodeResolve(this);
464
465         return true;
466 }
467
468
469 bool Schematic::saveSchematicToFile(const std::string &filename,
470         INodeDefManager *ndef)
471 {
472         MapNode *orig_schemdata = schemdata;
473         std::vector<std::string> ndef_nodenames;
474         std::vector<std::string> *names;
475
476         if (m_resolve_done && ndef == NULL)
477                 ndef = m_ndef;
478
479         if (ndef) {
480                 names = &ndef_nodenames;
481
482                 u32 volume = size.X * size.Y * size.Z;
483                 schemdata = new MapNode[volume];
484                 for (u32 i = 0; i != volume; i++)
485                         schemdata[i] = orig_schemdata[i];
486
487                 generate_nodelist_and_update_ids(schemdata, volume, names, ndef);
488         } else { // otherwise, use the names we have on hand in the list
489                 names = &m_nodenames;
490         }
491
492         std::ostringstream os(std::ios_base::binary);
493         bool status = serializeToMts(&os, *names);
494
495         if (ndef) {
496                 delete []schemdata;
497                 schemdata = orig_schemdata;
498         }
499
500         if (!status)
501                 return false;
502
503         return fs::safeWriteToFile(filename, os.str());
504 }
505
506
507 bool Schematic::getSchematicFromMap(Map *map, v3s16 p1, v3s16 p2)
508 {
509         MMVManip *vm = new MMVManip(map);
510
511         v3s16 bp1 = getNodeBlockPos(p1);
512         v3s16 bp2 = getNodeBlockPos(p2);
513         vm->initialEmerge(bp1, bp2);
514
515         size = p2 - p1 + 1;
516
517         slice_probs = new u8[size.Y];
518         for (s16 y = 0; y != size.Y; y++)
519                 slice_probs[y] = MTSCHEM_PROB_ALWAYS;
520
521         schemdata = new MapNode[size.X * size.Y * size.Z];
522
523         u32 i = 0;
524         for (s16 z = p1.Z; z <= p2.Z; z++)
525         for (s16 y = p1.Y; y <= p2.Y; y++) {
526                 u32 vi = vm->m_area.index(p1.X, y, z);
527                 for (s16 x = p1.X; x <= p2.X; x++, i++, vi++) {
528                         schemdata[i] = vm->m_data[vi];
529                         schemdata[i].param1 = MTSCHEM_PROB_ALWAYS;
530                 }
531         }
532
533         delete vm;
534         return true;
535 }
536
537
538 void Schematic::applyProbabilities(v3s16 p0,
539         std::vector<std::pair<v3s16, u8> > *plist,
540         std::vector<std::pair<s16, u8> > *splist)
541 {
542         for (size_t i = 0; i != plist->size(); i++) {
543                 v3s16 p = (*plist)[i].first - p0;
544                 int index = p.Z * (size.Y * size.X) + p.Y * size.X + p.X;
545                 if (index < size.Z * size.Y * size.X) {
546                         u8 prob = (*plist)[i].second;
547                         schemdata[index].param1 = prob;
548
549                         // trim unnecessary node names from schematic
550                         if (prob == MTSCHEM_PROB_NEVER)
551                                 schemdata[index].setContent(CONTENT_AIR);
552                 }
553         }
554
555         for (size_t i = 0; i != splist->size(); i++) {
556                 s16 y = (*splist)[i].first - p0.Y;
557                 slice_probs[y] = (*splist)[i].second;
558         }
559 }
560
561
562 void generate_nodelist_and_update_ids(MapNode *nodes, size_t nodecount,
563         std::vector<std::string> *usednodes, INodeDefManager *ndef)
564 {
565         std::map<content_t, content_t> nodeidmap;
566         content_t numids = 0;
567
568         for (size_t i = 0; i != nodecount; i++) {
569                 content_t id;
570                 content_t c = nodes[i].getContent();
571
572                 std::map<content_t, content_t>::const_iterator it = nodeidmap.find(c);
573                 if (it == nodeidmap.end()) {
574                         id = numids;
575                         numids++;
576
577                         usednodes->push_back(ndef->get(c).name);
578                         nodeidmap.insert(std::make_pair(c, id));
579                 } else {
580                         id = it->second;
581                 }
582                 nodes[i].setContent(id);
583         }
584 }