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