]> git.lizzy.rs Git - minetest.git/blob - src/mg_schematic.cpp
bb60cf5fd2f7a713d316c71cb5cbd576b9c8e1de
[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 "mg_schematic.h"
22 #include "mapgen.h"
23 #include "map.h"
24 #include "mapblock.h"
25 #include "log.h"
26 #include "util/numeric.h"
27 #include "util/serialize.h"
28 #include "serialization.h"
29 #include "filesys.h"
30
31 const char *SchematicManager::ELEMENT_TITLE = "schematic";
32
33
34 ///////////////////////////////////////////////////////////////////////////////
35
36
37 Schematic::Schematic()
38 {
39         schemdata   = NULL;
40         slice_probs = NULL;
41         flags       = 0;
42         size        = v3s16(0, 0, 0);
43 }
44
45
46 Schematic::~Schematic()
47 {
48         delete []schemdata;
49         delete []slice_probs;
50 }
51
52
53 void Schematic::updateContentIds()
54 {
55         if (flags & SCHEM_CIDS_UPDATED)
56                 return;
57
58         flags |= SCHEM_CIDS_UPDATED;
59
60         size_t bufsize = size.X * size.Y * size.Z;
61         for (size_t i = 0; i != bufsize; i++)
62                 schemdata[i].setContent(c_nodes[schemdata[i].getContent()]);
63 }
64
65
66 void Schematic::blitToVManip(v3s16 p, ManualMapVoxelManipulator *vm,
67         Rotation rot, bool force_placement, INodeDefManager *ndef)
68 {
69         int xstride = 1;
70         int ystride = size.X;
71         int zstride = size.X * size.Y;
72
73         updateContentIds();
74
75         s16 sx = size.X;
76         s16 sy = size.Y;
77         s16 sz = size.Z;
78
79         int i_start, i_step_x, i_step_z;
80         switch (rot) {
81                 case ROTATE_90:
82                         i_start  = sx - 1;
83                         i_step_x = zstride;
84                         i_step_z = -xstride;
85                         SWAP(s16, sx, sz);
86                         break;
87                 case ROTATE_180:
88                         i_start  = zstride * (sz - 1) + sx - 1;
89                         i_step_x = -xstride;
90                         i_step_z = -zstride;
91                         break;
92                 case ROTATE_270:
93                         i_start  = zstride * (sz - 1);
94                         i_step_x = -zstride;
95                         i_step_z = xstride;
96                         SWAP(s16, sx, sz);
97                         break;
98                 default:
99                         i_start  = 0;
100                         i_step_x = xstride;
101                         i_step_z = zstride;
102         }
103
104         s16 y_map = p.Y;
105         for (s16 y = 0; y != sy; y++) {
106                 if (slice_probs[y] != MTSCHEM_PROB_ALWAYS &&
107                         myrand_range(1, 255) > slice_probs[y])
108                         continue;
109
110                 for (s16 z = 0; z != sz; z++) {
111                         u32 i = z * i_step_z + y * ystride + i_start;
112                         for (s16 x = 0; x != sx; x++, i += i_step_x) {
113                                 u32 vi = vm->m_area.index(p.X + x, y_map, p.Z + z);
114                                 if (!vm->m_area.contains(vi))
115                                         continue;
116
117                                 if (schemdata[i].getContent() == CONTENT_IGNORE)
118                                         continue;
119
120                                 if (schemdata[i].param1 == MTSCHEM_PROB_NEVER)
121                                         continue;
122
123                                 if (!force_placement) {
124                                         content_t c = vm->m_data[vi].getContent();
125                                         if (c != CONTENT_AIR && c != CONTENT_IGNORE)
126                                                 continue;
127                                 }
128
129                                 if (schemdata[i].param1 != MTSCHEM_PROB_ALWAYS &&
130                                         myrand_range(1, 255) > schemdata[i].param1)
131                                         continue;
132
133                                 vm->m_data[vi] = schemdata[i];
134                                 vm->m_data[vi].param1 = 0;
135
136                                 if (rot)
137                                         vm->m_data[vi].rotateAlongYAxis(ndef, rot);
138                         }
139                 }
140                 y_map++;
141         }
142 }
143
144
145 void Schematic::placeStructure(Map *map, v3s16 p, u32 flags,
146         Rotation rot, bool force_placement, INodeDefManager *ndef)
147 {
148         assert(schemdata != NULL);
149         ManualMapVoxelManipulator *vm = new ManualMapVoxelManipulator(map);
150
151         if (rot == ROTATE_RAND)
152                 rot = (Rotation)myrand_range(ROTATE_0, ROTATE_270);
153
154         v3s16 s = (rot == ROTATE_90 || rot == ROTATE_270) ?
155                                 v3s16(size.Z, size.Y, size.X) : size;
156
157         if (flags & DECO_PLACE_CENTER_X)
158                 p.X -= (s.X + 1) / 2;
159         if (flags & DECO_PLACE_CENTER_Y)
160                 p.Y -= (s.Y + 1) / 2;
161         if (flags & DECO_PLACE_CENTER_Z)
162                 p.Z -= (s.Z + 1) / 2;
163
164         v3s16 bp1 = getNodeBlockPos(p);
165         v3s16 bp2 = getNodeBlockPos(p + s - v3s16(1,1,1));
166         vm->initialEmerge(bp1, bp2);
167
168         blitToVManip(p, vm, rot, force_placement, ndef);
169
170         std::map<v3s16, MapBlock *> lighting_modified_blocks;
171         std::map<v3s16, MapBlock *> modified_blocks;
172         vm->blitBackAll(&modified_blocks);
173
174         // TODO: Optimize this by using Mapgen::calcLighting() instead
175         lighting_modified_blocks.insert(modified_blocks.begin(), modified_blocks.end());
176         map->updateLighting(lighting_modified_blocks, modified_blocks);
177
178         MapEditEvent event;
179         event.type = MEET_OTHER;
180         for (std::map<v3s16, MapBlock *>::iterator
181                 it = modified_blocks.begin();
182                 it != modified_blocks.end(); ++it)
183                 event.modified_blocks.insert(it->first);
184
185         map->dispatchEvent(&event);
186 }
187
188
189 bool Schematic::loadSchematicFromFile(const char *filename,
190         NodeResolver *resolver,
191         std::map<std::string, std::string> &replace_names)
192 {
193         content_t cignore = CONTENT_IGNORE;
194         bool have_cignore = false;
195
196         std::ifstream is(filename, std::ios_base::binary);
197
198         u32 signature = readU32(is);
199         if (signature != MTSCHEM_FILE_SIGNATURE) {
200                 errorstream << "loadSchematicFile: invalid schematic "
201                         "file" << std::endl;
202                 return false;
203         }
204
205         u16 version = readU16(is);
206         if (version > MTSCHEM_FILE_VER_HIGHEST_READ) {
207                 errorstream << "loadSchematicFile: unsupported schematic "
208                         "file version" << std::endl;
209                 return false;
210         }
211
212         size = readV3S16(is);
213
214         delete []slice_probs;
215         slice_probs = new u8[size.Y];
216         for (int y = 0; y != size.Y; y++)
217                 slice_probs[y] = (version >= 3) ? readU8(is) : MTSCHEM_PROB_ALWAYS;
218
219         int nodecount = size.X * size.Y * size.Z;
220
221         u16 nidmapcount = readU16(is);
222
223         for (int i = 0; i != nidmapcount; i++) {
224                 std::string name = deSerializeString(is);
225                 if (name == "ignore") {
226                         name = "air";
227                         cignore = i;
228                         have_cignore = true;
229                 }
230
231                 std::map<std::string, std::string>::iterator it;
232                 it = replace_names.find(name);
233                 if (it != replace_names.end())
234                         name = it->second;
235
236                 resolver->addNodeList(name.c_str(), &c_nodes);
237         }
238
239         delete []schemdata;
240         schemdata = new MapNode[nodecount];
241         MapNode::deSerializeBulk(is, SER_FMT_VER_HIGHEST_READ, schemdata,
242                                 nodecount, 2, 2, true);
243
244         if (version == 1) { // fix up the probability values
245                 for (int i = 0; i != nodecount; i++) {
246                         if (schemdata[i].param1 == 0)
247                                 schemdata[i].param1 = MTSCHEM_PROB_ALWAYS;
248                         if (have_cignore && schemdata[i].getContent() == cignore)
249                                 schemdata[i].param1 = MTSCHEM_PROB_NEVER;
250                 }
251         }
252
253         return true;
254 }
255
256
257 /*
258         Minetest Schematic File Format
259
260         All values are stored in big-endian byte order.
261         [u32] signature: 'MTSM'
262         [u16] version: 3
263         [u16] size X
264         [u16] size Y
265         [u16] size Z
266         For each Y:
267                 [u8] slice probability value
268         [Name-ID table] Name ID Mapping Table
269                 [u16] name-id count
270                 For each name-id mapping:
271                         [u16] name length
272                         [u8[]] name
273         ZLib deflated {
274         For each node in schematic:  (for z, y, x)
275                 [u16] content
276         For each node in schematic:
277                 [u8] probability of occurance (param1)
278         For each node in schematic:
279                 [u8] param2
280         }
281
282         Version changes:
283         1 - Initial version
284         2 - Fixed messy never/always place; 0 probability is now never, 0xFF is always
285         3 - Added y-slice probabilities; this allows for variable height structures
286 */
287 void Schematic::saveSchematicToFile(const char *filename, INodeDefManager *ndef)
288 {
289         std::ostringstream ss(std::ios_base::binary);
290
291         writeU32(ss, MTSCHEM_FILE_SIGNATURE);         // signature
292         writeU16(ss, MTSCHEM_FILE_VER_HIGHEST_WRITE); // version
293         writeV3S16(ss, size);                         // schematic size
294
295         for (int y = 0; y != size.Y; y++)             // Y slice probabilities
296                 writeU8(ss, slice_probs[y]);
297
298         std::vector<content_t> usednodes;
299         int nodecount = size.X * size.Y * size.Z;
300         build_nnlist_and_update_ids(schemdata, nodecount, &usednodes);
301
302         u16 numids = usednodes.size();
303         writeU16(ss, numids); // name count
304         for (int i = 0; i != numids; i++)
305                 ss << serializeString(ndef->get(usednodes[i]).name); // node names
306
307         // compressed bulk node data
308         MapNode::serializeBulk(ss, SER_FMT_VER_HIGHEST_WRITE, schemdata,
309                                 nodecount, 2, 2, true);
310
311         fs::safeWriteToFile(filename, ss.str());
312 }
313
314
315 void build_nnlist_and_update_ids(MapNode *nodes, u32 nodecount,
316         std::vector<content_t> *usednodes)
317 {
318         std::map<content_t, content_t> nodeidmap;
319         content_t numids = 0;
320
321         for (u32 i = 0; i != nodecount; i++) {
322                 content_t id;
323                 content_t c = nodes[i].getContent();
324
325                 std::map<content_t, content_t>::const_iterator it = nodeidmap.find(c);
326                 if (it == nodeidmap.end()) {
327                         id = numids;
328                         numids++;
329
330                         usednodes->push_back(c);
331                         nodeidmap.insert(std::make_pair(c, id));
332                 } else {
333                         id = it->second;
334                 }
335                 nodes[i].setContent(id);
336         }
337 }
338
339
340 bool Schematic::getSchematicFromMap(Map *map, v3s16 p1, v3s16 p2)
341 {
342         ManualMapVoxelManipulator *vm = new ManualMapVoxelManipulator(map);
343
344         v3s16 bp1 = getNodeBlockPos(p1);
345         v3s16 bp2 = getNodeBlockPos(p2);
346         vm->initialEmerge(bp1, bp2);
347
348         size = p2 - p1 + 1;
349
350         slice_probs = new u8[size.Y];
351         for (s16 y = 0; y != size.Y; y++)
352                 slice_probs[y] = MTSCHEM_PROB_ALWAYS;
353
354         schemdata = new MapNode[size.X * size.Y * size.Z];
355
356         u32 i = 0;
357         for (s16 z = p1.Z; z <= p2.Z; z++)
358         for (s16 y = p1.Y; y <= p2.Y; y++) {
359                 u32 vi = vm->m_area.index(p1.X, y, z);
360                 for (s16 x = p1.X; x <= p2.X; x++, i++, vi++) {
361                         schemdata[i] = vm->m_data[vi];
362                         schemdata[i].param1 = MTSCHEM_PROB_ALWAYS;
363                 }
364         }
365
366         delete vm;
367         return true;
368 }
369
370
371 void Schematic::applyProbabilities(v3s16 p0,
372         std::vector<std::pair<v3s16, u8> > *plist,
373         std::vector<std::pair<s16, u8> > *splist)
374 {
375         for (size_t i = 0; i != plist->size(); i++) {
376                 v3s16 p = (*plist)[i].first - p0;
377                 int index = p.Z * (size.Y * size.X) + p.Y * size.X + p.X;
378                 if (index < size.Z * size.Y * size.X) {
379                         u8 prob = (*plist)[i].second;
380                         schemdata[index].param1 = prob;
381
382                         // trim unnecessary node names from schematic
383                         if (prob == MTSCHEM_PROB_NEVER)
384                                 schemdata[index].setContent(CONTENT_AIR);
385                 }
386         }
387
388         for (size_t i = 0; i != splist->size(); i++) {
389                 s16 y = (*splist)[i].first - p0.Y;
390                 slice_probs[y] = (*splist)[i].second;
391         }
392 }