Add NodeResolver and clean up node name -> content ID resolution system
[oweals/minetest.git] / src / mapgen.cpp
1 /*
2 Minetest
3 Copyright (C) 2010-2013 celeron55, Perttu Ahola <celeron55@gmail.com>
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 "mapgen.h"
21 #include "voxel.h"
22 #include "noise.h"
23 #include "biome.h"
24 #include "mapblock.h"
25 #include "mapnode.h"
26 #include "map.h"
27 #include "content_sao.h"
28 #include "nodedef.h"
29 #include "content_mapnode.h" // For content_mapnode_get_new_name
30 #include "voxelalgorithms.h"
31 #include "profiler.h"
32 #include "settings.h" // For g_settings
33 #include "main.h" // For g_profiler
34 #include "treegen.h"
35 #include "mapgen_v6.h"
36 #include "mapgen_v7.h"
37 #include "serialization.h"
38 #include "util/serialize.h"
39 #include "filesys.h"
40 #include "log.h"
41
42
43 FlagDesc flagdesc_mapgen[] = {
44         {"trees",    MG_TREES},
45         {"caves",    MG_CAVES},
46         {"dungeons", MG_DUNGEONS},
47         {"flat",     MG_FLAT},
48         {"light",    MG_LIGHT},
49         {NULL,       0}
50 };
51
52 FlagDesc flagdesc_ore[] = {
53         {"absheight",            OREFLAG_ABSHEIGHT},
54         {"scatter_noisedensity", OREFLAG_DENSITY},
55         {"claylike_nodeisnt",    OREFLAG_NODEISNT},
56         {NULL,                   0}
57 };
58
59 FlagDesc flagdesc_deco_schematic[] = {
60         {"place_center_x", DECO_PLACE_CENTER_X},
61         {"place_center_y", DECO_PLACE_CENTER_Y},
62         {"place_center_z", DECO_PLACE_CENTER_Z},
63         {NULL,             0}
64 };
65
66 FlagDesc flagdesc_gennotify[] = {
67         {"dungeon",          1 << GENNOTIFY_DUNGEON},
68         {"temple",           1 << GENNOTIFY_TEMPLE},
69         {"cave_begin",       1 << GENNOTIFY_CAVE_BEGIN},
70         {"cave_end",         1 << GENNOTIFY_CAVE_END},
71         {"large_cave_begin", 1 << GENNOTIFY_LARGECAVE_BEGIN},
72         {"large_cave_end",   1 << GENNOTIFY_LARGECAVE_END},
73         {NULL,               0}
74 };
75
76 ///////////////////////////////////////////////////////////////////////////////
77
78
79 Ore *createOre(OreType type) {
80         switch (type) {
81                 case ORE_SCATTER:
82                         return new OreScatter;
83                 case ORE_SHEET:
84                         return new OreSheet;
85                 //case ORE_CLAYLIKE: //TODO: implement this!
86                 //      return new OreClaylike;
87                 default:
88                         return NULL;
89         }
90 }
91
92
93 Ore::~Ore() {
94         delete np;
95         delete noise;
96 }
97
98
99 void Ore::placeOre(Mapgen *mg, u32 blockseed, v3s16 nmin, v3s16 nmax) {
100         int in_range = 0;
101
102         in_range |= (nmin.Y <= height_max && nmax.Y >= height_min);
103         if (flags & OREFLAG_ABSHEIGHT)
104                 in_range |= (nmin.Y >= -height_max && nmax.Y <= -height_min) << 1;
105         if (!in_range)
106                 return;
107
108         int ymin, ymax;
109         if (in_range & ORE_RANGE_MIRROR) {
110                 ymin = MYMAX(nmin.Y, -height_max);
111                 ymax = MYMIN(nmax.Y, -height_min);
112         } else {
113                 ymin = MYMAX(nmin.Y, height_min);
114                 ymax = MYMIN(nmax.Y, height_max);
115         }
116         if (clust_size >= ymax - ymin + 1)
117                 return;
118
119         nmin.Y = ymin;
120         nmax.Y = ymax;
121         generate(mg->vm, mg->seed, blockseed, nmin, nmax);
122 }
123
124
125 void OreScatter::generate(ManualMapVoxelManipulator *vm, int seed,
126                                                   u32 blockseed, v3s16 nmin, v3s16 nmax) {
127         PseudoRandom pr(blockseed);
128         MapNode n_ore(c_ore, 0, ore_param2);
129
130         int volume = (nmax.X - nmin.X + 1) *
131                                  (nmax.Y - nmin.Y + 1) *
132                                  (nmax.Z - nmin.Z + 1);
133         int csize     = clust_size;
134         int orechance = (csize * csize * csize) / clust_num_ores;
135         int nclusters = volume / clust_scarcity;
136
137         for (int i = 0; i != nclusters; i++) {
138                 int x0 = pr.range(nmin.X, nmax.X - csize + 1);
139                 int y0 = pr.range(nmin.Y, nmax.Y - csize + 1);
140                 int z0 = pr.range(nmin.Z, nmax.Z - csize + 1);
141
142                 if (np && (NoisePerlin3D(np, x0, y0, z0, seed) < nthresh))
143                         continue;
144
145                 for (int z1 = 0; z1 != csize; z1++)
146                 for (int y1 = 0; y1 != csize; y1++)
147                 for (int x1 = 0; x1 != csize; x1++) {
148                         if (pr.range(1, orechance) != 1)
149                                 continue;
150
151                         u32 i = vm->m_area.index(x0 + x1, y0 + y1, z0 + z1);
152                         for (size_t ii = 0; ii < c_wherein.size(); ii++)
153                                 if (vm->m_data[i].getContent() == c_wherein[ii])
154                                         vm->m_data[i] = n_ore;
155                 }
156         }
157 }
158
159
160 void OreSheet::generate(ManualMapVoxelManipulator *vm, int seed,
161                                                 u32 blockseed, v3s16 nmin, v3s16 nmax) {
162         PseudoRandom pr(blockseed + 4234);
163         MapNode n_ore(c_ore, 0, ore_param2);
164
165         int max_height = clust_size;
166         int y_start = pr.range(nmin.Y, nmax.Y - max_height);
167
168         if (!noise) {
169                 int sx = nmax.X - nmin.X + 1;
170                 int sz = nmax.Z - nmin.Z + 1;
171                 noise = new Noise(np, 0, sx, sz);
172         }
173         noise->seed = seed + y_start;
174         noise->perlinMap2D(nmin.X, nmin.Z);
175
176         int index = 0;
177         for (int z = nmin.Z; z <= nmax.Z; z++)
178         for (int x = nmin.X; x <= nmax.X; x++) {
179                 float noiseval = noise->result[index++];
180                 if (noiseval < nthresh)
181                         continue;
182
183                 int height = max_height * (1. / pr.range(1, 3));
184                 int y0 = y_start + np->scale * noiseval; //pr.range(1, 3) - 1;
185                 int y1 = y0 + height;
186                 for (int y = y0; y != y1; y++) {
187                         u32 i = vm->m_area.index(x, y, z);
188                         if (!vm->m_area.contains(i))
189                                 continue;
190
191                         for (size_t ii = 0; ii < c_wherein.size(); ii++) {
192                                 if (vm->m_data[i].getContent() == c_wherein[ii]) {
193                                         vm->m_data[i] = n_ore;
194                                         break;
195                                 }
196                         }
197                 }
198         }
199 }
200
201
202 ///////////////////////////////////////////////////////////////////////////////
203
204
205 Decoration *createDecoration(DecorationType type) {
206         switch (type) {
207                 case DECO_SIMPLE:
208                         return new DecoSimple;
209                 case DECO_SCHEMATIC:
210                         return new DecoSchematic;
211                 //case DECO_LSYSTEM:
212                 //      return new DecoLSystem;
213                 default:
214                         return NULL;
215         }
216 }
217
218
219 Decoration::Decoration() {
220         mapseed    = 0;
221         np         = NULL;
222         fill_ratio = 0;
223         sidelen    = 1;
224 }
225
226
227 Decoration::~Decoration() {
228         delete np;
229 }
230
231
232 void Decoration::placeDeco(Mapgen *mg, u32 blockseed, v3s16 nmin, v3s16 nmax) {
233         PseudoRandom ps(blockseed + 53);
234         int carea_size = nmax.X - nmin.X + 1;
235
236         // Divide area into parts
237         if (carea_size % sidelen) {
238                 errorstream << "Decoration::placeDeco: chunk size is not divisible by "
239                         "sidelen; setting sidelen to " << carea_size << std::endl;
240                 sidelen = carea_size;
241         }
242
243         s16 divlen = carea_size / sidelen;
244         int area = sidelen * sidelen;
245
246         for (s16 z0 = 0; z0 < divlen; z0++)
247         for (s16 x0 = 0; x0 < divlen; x0++) {
248                 v2s16 p2d_center( // Center position of part of division
249                         nmin.X + sidelen / 2 + sidelen * x0,
250                         nmin.Z + sidelen / 2 + sidelen * z0
251                 );
252                 v2s16 p2d_min( // Minimum edge of part of division
253                         nmin.X + sidelen * x0,
254                         nmin.Z + sidelen * z0
255                 );
256                 v2s16 p2d_max( // Maximum edge of part of division
257                         nmin.X + sidelen + sidelen * x0 - 1,
258                         nmin.Z + sidelen + sidelen * z0 - 1
259                 );
260
261                 // Amount of decorations
262                 float nval = np ?
263                         NoisePerlin2D(np, p2d_center.X, p2d_center.Y, mapseed) :
264                         fill_ratio;
265                 u32 deco_count = area * MYMAX(nval, 0.f);
266
267                 for (u32 i = 0; i < deco_count; i++) {
268                         s16 x = ps.range(p2d_min.X, p2d_max.X);
269                         s16 z = ps.range(p2d_min.Y, p2d_max.Y);
270
271                         int mapindex = carea_size * (z - nmin.Z) + (x - nmin.X);
272
273                         s16 y = mg->heightmap ?
274                                         mg->heightmap[mapindex] :
275                                         mg->findGroundLevel(v2s16(x, z), nmin.Y, nmax.Y);
276
277                         if (y < nmin.Y || y > nmax.Y)
278                                 continue;
279
280                         int height = getHeight();
281                         int max_y = nmax.Y;// + MAP_BLOCKSIZE - 1;
282                         if (y + 1 + height > max_y) {
283                                 continue;
284 #if 0
285                                 printf("Decoration at (%d %d %d) cut off\n", x, y, z);
286                                 //add to queue
287                                 JMutexAutoLock cutofflock(cutoff_mutex);
288                                 cutoffs.push_back(CutoffData(x, y, z, height));
289 #endif
290                         }
291
292                         if (mg->biomemap) {
293                                 std::set<u8>::iterator iter;
294
295                                 if (biomes.size()) {
296                                         iter = biomes.find(mg->biomemap[mapindex]);
297                                         if (iter == biomes.end())
298                                                 continue;
299                                 }
300                         }
301
302                         generate(mg, &ps, max_y, v3s16(x, y, z));
303                 }
304         }
305 }
306
307
308 #if 0
309 void Decoration::placeCutoffs(Mapgen *mg, u32 blockseed, v3s16 nmin, v3s16 nmax) {
310         PseudoRandom pr(blockseed + 53);
311         std::vector<CutoffData> handled_cutoffs;
312
313         // Copy over the cutoffs we're interested in so we don't needlessly hold a lock
314         {
315                 JMutexAutoLock cutofflock(cutoff_mutex);
316                 for (std::list<CutoffData>::iterator i = cutoffs.begin();
317                         i != cutoffs.end(); ++i) {
318                         CutoffData cutoff = *i;
319                         v3s16 p    = cutoff.p;
320                         s16 height = cutoff.height;
321                         if (p.X < nmin.X || p.X > nmax.X ||
322                                 p.Z < nmin.Z || p.Z > nmax.Z)
323                                 continue;
324                         if (p.Y + height < nmin.Y || p.Y > nmax.Y)
325                                 continue;
326
327                         handled_cutoffs.push_back(cutoff);
328                 }
329         }
330
331         // Generate the cutoffs
332         for (size_t i = 0; i != handled_cutoffs.size(); i++) {
333                 v3s16 p    = handled_cutoffs[i].p;
334                 s16 height = handled_cutoffs[i].height;
335
336                 if (p.Y + height > nmax.Y) {
337                         //printf("Decoration at (%d %d %d) cut off again!\n", p.X, p.Y, p.Z);
338                         cuttoffs.push_back(v3s16(p.X, p.Y, p.Z));
339                 }
340
341                 generate(mg, &pr, nmax.Y, nmin.Y - p.Y, v3s16(p.X, nmin.Y, p.Z));
342         }
343
344         // Remove cutoffs that were handled from the cutoff list
345         {
346                 JMutexAutoLock cutofflock(cutoff_mutex);
347                 for (std::list<CutoffData>::iterator i = cutoffs.begin();
348                         i != cutoffs.end(); ++i) {
349
350                         for (size_t j = 0; j != handled_cutoffs.size(); j++) {
351                                 CutoffData coff = *i;
352                                 if (coff.p == handled_cutoffs[j].p)
353                                         i = cutoffs.erase(i);
354                         }
355                 }
356         }
357 }
358 #endif
359
360
361 ///////////////////////////////////////////////////////////////////////////////
362
363
364 void DecoSimple::generate(Mapgen *mg, PseudoRandom *pr, s16 max_y, v3s16 p) {
365         ManualMapVoxelManipulator *vm = mg->vm;
366
367         u32 vi = vm->m_area.index(p);
368         content_t c = vm->m_data[vi].getContent();
369         size_t idx;
370         for (idx = 0; idx != c_place_on.size(); idx++) {
371                 if (c == c_place_on[idx])
372                         break;
373         }
374         if ((idx != 0) && (idx == c_place_on.size()))
375                 return;
376
377         if (nspawnby != -1) {
378                 int nneighs = 0;
379                 v3s16 dirs[8] = { // a Moore neighborhood
380                         v3s16( 0, 0,  1),
381                         v3s16( 0, 0, -1),
382                         v3s16( 1, 0,  0),
383                         v3s16(-1, 0,  0),
384                         v3s16( 1, 0,  1),
385                         v3s16(-1, 0,  1),
386                         v3s16(-1, 0, -1),
387                         v3s16( 1, 0, -1)
388                 };
389
390                 for (int i = 0; i != 8; i++) {
391                         u32 index = vm->m_area.index(p + dirs[i]);
392                         if (!vm->m_area.contains(index))
393                                 continue;
394
395                         content_t c = vm->m_data[index].getContent();
396                         for (size_t j = 0; j != c_spawnby.size(); j++) {
397                                 if (c == c_spawnby[j]) {
398                                         nneighs++;
399                                         break;
400                                 }
401                         }
402                 }
403
404                 if (nneighs < nspawnby)
405                         return;
406         }
407
408         if (c_decos.size() == 0)
409                 return;
410         content_t c_place = c_decos[pr->range(0, c_decos.size() - 1)];
411
412         s16 height = (deco_height_max > 0) ?
413                 pr->range(deco_height, deco_height_max) : deco_height;
414
415         height = MYMIN(height, max_y - p.Y);
416
417         v3s16 em = vm->m_area.getExtent();
418         for (int i = 0; i < height; i++) {
419                 vm->m_area.add_y(em, vi, 1);
420
421                 content_t c = vm->m_data[vi].getContent();
422                 if (c != CONTENT_AIR && c != CONTENT_IGNORE)
423                         break;
424
425                 vm->m_data[vi] = MapNode(c_place);
426         }
427 }
428
429
430 int DecoSimple::getHeight() {
431         return (deco_height_max > 0) ? deco_height_max : deco_height;
432 }
433
434
435 std::string DecoSimple::getName() {
436         return "";
437 }
438
439
440 ///////////////////////////////////////////////////////////////////////////////
441
442
443 DecoSchematic::DecoSchematic() {
444         schematic   = NULL;
445         slice_probs = NULL;
446         flags       = 0;
447         size        = v3s16(0, 0, 0);
448 }
449
450
451 DecoSchematic::~DecoSchematic() {
452         delete []schematic;
453         delete []slice_probs;
454 }
455
456
457 void DecoSchematic::updateContentIds() {
458         if (flags & DECO_SCHEM_CIDS_UPDATED)
459                 return;
460
461         flags |= DECO_SCHEM_CIDS_UPDATED;
462
463         for (int i = 0; i != size.X * size.Y * size.Z; i++)
464                 schematic[i].setContent(c_nodes[schematic[i].getContent()]);
465 }
466
467
468 void DecoSchematic::generate(Mapgen *mg, PseudoRandom *pr, s16 max_y, v3s16 p) {
469         ManualMapVoxelManipulator *vm = mg->vm;
470
471         if (flags & DECO_PLACE_CENTER_X)
472                 p.X -= (size.X + 1) / 2;
473         if (flags & DECO_PLACE_CENTER_Y)
474                 p.Y -= (size.Y + 1) / 2;
475         if (flags & DECO_PLACE_CENTER_Z)
476                 p.Z -= (size.Z + 1) / 2;
477
478         u32 vi = vm->m_area.index(p);
479         content_t c = vm->m_data[vi].getContent();
480         size_t idx;
481         for (idx = 0; idx != c_place_on.size(); idx++) {
482                 if (c == c_place_on[idx])
483                         break;
484         }
485         if ((idx != 0) && (idx == c_place_on.size()))
486                 return;
487
488         Rotation rot = (rotation == ROTATE_RAND) ?
489                 (Rotation)pr->range(ROTATE_0, ROTATE_270) : rotation;
490
491         blitToVManip(p, vm, rot, false);
492 }
493
494
495 int DecoSchematic::getHeight() {
496         return size.Y;
497 }
498
499
500 std::string DecoSchematic::getName() {
501         return filename;
502 }
503
504
505 void DecoSchematic::blitToVManip(v3s16 p, ManualMapVoxelManipulator *vm,
506                                                                 Rotation rot, bool force_placement) {
507         int xstride = 1;
508         int ystride = size.X;
509         int zstride = size.X * size.Y;
510
511         updateContentIds();
512
513         s16 sx = size.X;
514         s16 sy = size.Y;
515         s16 sz = size.Z;
516
517         int i_start, i_step_x, i_step_z;
518         switch (rot) {
519                 case ROTATE_90:
520                         i_start  = sx - 1;
521                         i_step_x = zstride;
522                         i_step_z = -xstride;
523                         SWAP(s16, sx, sz);
524                         break;
525                 case ROTATE_180:
526                         i_start  = zstride * (sz - 1) + sx - 1;
527                         i_step_x = -xstride;
528                         i_step_z = -zstride;
529                         break;
530                 case ROTATE_270:
531                         i_start  = zstride * (sz - 1);
532                         i_step_x = -zstride;
533                         i_step_z = xstride;
534                         SWAP(s16, sx, sz);
535                         break;
536                 default:
537                         i_start  = 0;
538                         i_step_x = xstride;
539                         i_step_z = zstride;
540         }
541
542         s16 y_map = p.Y;
543         for (s16 y = 0; y != sy; y++) {
544                 if (slice_probs[y] != MTSCHEM_PROB_ALWAYS &&
545                         myrand_range(1, 255) > slice_probs[y])
546                         continue;
547
548                 for (s16 z = 0; z != sz; z++) {
549                         u32 i = z * i_step_z + y * ystride + i_start;
550                         for (s16 x = 0; x != sx; x++, i += i_step_x) {
551                                 u32 vi = vm->m_area.index(p.X + x, y_map, p.Z + z);
552                                 if (!vm->m_area.contains(vi))
553                                         continue;
554
555                                 if (schematic[i].getContent() == CONTENT_IGNORE)
556                                         continue;
557
558                                 if (schematic[i].param1 == MTSCHEM_PROB_NEVER)
559                                         continue;
560
561                                 if (!force_placement) {
562                                         content_t c = vm->m_data[vi].getContent();
563                                         if (c != CONTENT_AIR && c != CONTENT_IGNORE)
564                                                 continue;
565                                 }
566
567                                 if (schematic[i].param1 != MTSCHEM_PROB_ALWAYS &&
568                                         myrand_range(1, 255) > schematic[i].param1)
569                                         continue;
570
571                                 vm->m_data[vi] = schematic[i];
572                                 vm->m_data[vi].param1 = 0;
573
574                                 if (rot)
575                                         vm->m_data[vi].rotateAlongYAxis(ndef, rot);
576                         }
577                 }
578                 y_map++;
579         }
580 }
581
582
583 void DecoSchematic::placeStructure(Map *map, v3s16 p, bool force_placement) {
584         assert(schematic != NULL);
585         ManualMapVoxelManipulator *vm = new ManualMapVoxelManipulator(map);
586
587         Rotation rot = (rotation == ROTATE_RAND) ?
588                 (Rotation)myrand_range(ROTATE_0, ROTATE_270) : rotation;
589
590         v3s16 s = (rot == ROTATE_90 || rot == ROTATE_270) ?
591                                 v3s16(size.Z, size.Y, size.X) : size;
592
593         if (flags & DECO_PLACE_CENTER_X)
594                 p.X -= (s.X + 1) / 2;
595         if (flags & DECO_PLACE_CENTER_Y)
596                 p.Y -= (s.Y + 1) / 2;
597         if (flags & DECO_PLACE_CENTER_Z)
598                 p.Z -= (s.Z + 1) / 2;
599
600         v3s16 bp1 = getNodeBlockPos(p);
601         v3s16 bp2 = getNodeBlockPos(p + s - v3s16(1,1,1));
602         vm->initialEmerge(bp1, bp2);
603
604         blitToVManip(p, vm, rot, force_placement);
605
606         std::map<v3s16, MapBlock *> lighting_modified_blocks;
607         std::map<v3s16, MapBlock *> modified_blocks;
608         vm->blitBackAll(&modified_blocks);
609
610         // TODO: Optimize this by using Mapgen::calcLighting() instead
611         lighting_modified_blocks.insert(modified_blocks.begin(), modified_blocks.end());
612         map->updateLighting(lighting_modified_blocks, modified_blocks);
613
614         MapEditEvent event;
615         event.type = MEET_OTHER;
616         for (std::map<v3s16, MapBlock *>::iterator
617                 it = modified_blocks.begin();
618                 it != modified_blocks.end(); ++it)
619                 event.modified_blocks.insert(it->first);
620
621         map->dispatchEvent(&event);
622 }
623
624
625 bool DecoSchematic::loadSchematicFile(NodeResolver *resolver,
626         std::map<std::string, std::string> &replace_names)
627 {
628         content_t cignore = CONTENT_IGNORE;
629         bool have_cignore = false;
630
631         std::ifstream is(filename.c_str(), std::ios_base::binary);
632
633         u32 signature = readU32(is);
634         if (signature != MTSCHEM_FILE_SIGNATURE) {
635                 errorstream << "loadSchematicFile: invalid schematic "
636                         "file" << std::endl;
637                 return false;
638         }
639
640         u16 version = readU16(is);
641         if (version > MTSCHEM_FILE_VER_HIGHEST_READ) {
642                 errorstream << "loadSchematicFile: unsupported schematic "
643                         "file version" << std::endl;
644                 return false;
645         }
646
647         size = readV3S16(is);
648
649         delete []slice_probs;
650         slice_probs = new u8[size.Y];
651         if (version >= 3) {
652                 for (int y = 0; y != size.Y; y++)
653                         slice_probs[y] = readU8(is);
654         } else {
655                 for (int y = 0; y != size.Y; y++)
656                         slice_probs[y] = MTSCHEM_PROB_ALWAYS;
657         }
658
659         int nodecount = size.X * size.Y * size.Z;
660
661         u16 nidmapcount = readU16(is);
662
663         for (int i = 0; i != nidmapcount; i++) {
664                 std::string name = deSerializeString(is);
665                 if (name == "ignore") {
666                         name = "air";
667                         cignore = i;
668                         have_cignore = true;
669                 }
670
671                 std::map<std::string, std::string>::iterator it;
672
673                 it = replace_names.find(name);
674                 if (it != replace_names.end())
675                         name = it->second;
676
677                 resolver->addNodeList(name.c_str(), &c_nodes);
678         }
679
680         delete []schematic;
681         schematic = new MapNode[nodecount];
682         MapNode::deSerializeBulk(is, SER_FMT_VER_HIGHEST_READ, schematic,
683                                 nodecount, 2, 2, true);
684
685         if (version == 1) { // fix up the probability values
686                 for (int i = 0; i != nodecount; i++) {
687                         if (schematic[i].param1 == 0)
688                                 schematic[i].param1 = MTSCHEM_PROB_ALWAYS;
689                         if (have_cignore && schematic[i].getContent() == cignore)
690                                 schematic[i].param1 = MTSCHEM_PROB_NEVER;
691                 }
692         }
693
694         return true;
695 }
696
697
698 /*
699         Minetest Schematic File Format
700
701         All values are stored in big-endian byte order.
702         [u32] signature: 'MTSM'
703         [u16] version: 3
704         [u16] size X
705         [u16] size Y
706         [u16] size Z
707         For each Y:
708                 [u8] slice probability value
709         [Name-ID table] Name ID Mapping Table
710                 [u16] name-id count
711                 For each name-id mapping:
712                         [u16] name length
713                         [u8[]] name
714         ZLib deflated {
715         For each node in schematic:  (for z, y, x)
716                 [u16] content
717         For each node in schematic:
718                 [u8] probability of occurance (param1)
719         For each node in schematic:
720                 [u8] param2
721         }
722
723         Version changes:
724         1 - Initial version
725         2 - Fixed messy never/always place; 0 probability is now never, 0xFF is always
726         3 - Added y-slice probabilities; this allows for variable height structures
727 */
728 void DecoSchematic::saveSchematicFile(INodeDefManager *ndef) {
729         std::ostringstream ss(std::ios_base::binary);
730
731         writeU32(ss, MTSCHEM_FILE_SIGNATURE);         // signature
732         writeU16(ss, MTSCHEM_FILE_VER_HIGHEST_WRITE); // version
733         writeV3S16(ss, size);                         // schematic size
734
735         for (int y = 0; y != size.Y; y++)             // Y slice probabilities
736                 writeU8(ss, slice_probs[y]);
737
738         std::vector<content_t> usednodes;
739         int nodecount = size.X * size.Y * size.Z;
740         build_nnlist_and_update_ids(schematic, nodecount, &usednodes);
741
742         u16 numids = usednodes.size();
743         writeU16(ss, numids); // name count
744         for (int i = 0; i != numids; i++)
745                 ss << serializeString(ndef->get(usednodes[i]).name); // node names
746
747         // compressed bulk node data
748         MapNode::serializeBulk(ss, SER_FMT_VER_HIGHEST_WRITE, schematic,
749                                 nodecount, 2, 2, true);
750
751         fs::safeWriteToFile(filename, ss.str());
752 }
753
754
755 void build_nnlist_and_update_ids(MapNode *nodes, u32 nodecount,
756                                                 std::vector<content_t> *usednodes) {
757         std::map<content_t, content_t> nodeidmap;
758         content_t numids = 0;
759
760         for (u32 i = 0; i != nodecount; i++) {
761                 content_t id;
762                 content_t c = nodes[i].getContent();
763
764                 std::map<content_t, content_t>::const_iterator it = nodeidmap.find(c);
765                 if (it == nodeidmap.end()) {
766                         id = numids;
767                         numids++;
768
769                         usednodes->push_back(c);
770                         nodeidmap.insert(std::make_pair(c, id));
771                 } else {
772                         id = it->second;
773                 }
774                 nodes[i].setContent(id);
775         }
776 }
777
778
779 bool DecoSchematic::getSchematicFromMap(Map *map, v3s16 p1, v3s16 p2) {
780         ManualMapVoxelManipulator *vm = new ManualMapVoxelManipulator(map);
781
782         v3s16 bp1 = getNodeBlockPos(p1);
783         v3s16 bp2 = getNodeBlockPos(p2);
784         vm->initialEmerge(bp1, bp2);
785
786         size = p2 - p1 + 1;
787
788         slice_probs = new u8[size.Y];
789         for (s16 y = 0; y != size.Y; y++)
790                 slice_probs[y] = MTSCHEM_PROB_ALWAYS;
791
792         schematic = new MapNode[size.X * size.Y * size.Z];
793
794         u32 i = 0;
795         for (s16 z = p1.Z; z <= p2.Z; z++)
796         for (s16 y = p1.Y; y <= p2.Y; y++) {
797                 u32 vi = vm->m_area.index(p1.X, y, z);
798                 for (s16 x = p1.X; x <= p2.X; x++, i++, vi++) {
799                         schematic[i] = vm->m_data[vi];
800                         schematic[i].param1 = MTSCHEM_PROB_ALWAYS;
801                 }
802         }
803
804         delete vm;
805         return true;
806 }
807
808
809 void DecoSchematic::applyProbabilities(v3s16 p0,
810         std::vector<std::pair<v3s16, u8> > *plist,
811         std::vector<std::pair<s16, u8> > *splist) {
812
813         for (size_t i = 0; i != plist->size(); i++) {
814                 v3s16 p = (*plist)[i].first - p0;
815                 int index = p.Z * (size.Y * size.X) + p.Y * size.X + p.X;
816                 if (index < size.Z * size.Y * size.X) {
817                         u8 prob = (*plist)[i].second;
818                         schematic[index].param1 = prob;
819
820                         // trim unnecessary node names from schematic
821                         if (prob == MTSCHEM_PROB_NEVER)
822                                 schematic[index].setContent(CONTENT_AIR);
823                 }
824         }
825
826         for (size_t i = 0; i != splist->size(); i++) {
827                 s16 y = (*splist)[i].first - p0.Y;
828                 slice_probs[y] = (*splist)[i].second;
829         }
830 }
831
832
833 ///////////////////////////////////////////////////////////////////////////////
834
835
836 Mapgen::Mapgen() {
837         seed        = 0;
838         water_level = 0;
839         generating  = false;
840         id          = -1;
841         vm          = NULL;
842         ndef        = NULL;
843         heightmap   = NULL;
844         biomemap    = NULL;
845
846         for (unsigned int i = 0; i != NUM_GEN_NOTIFY; i++)
847                 gen_notifications[i] = new std::vector<v3s16>;
848 }
849
850
851 Mapgen::~Mapgen() {
852         for (unsigned int i = 0; i != NUM_GEN_NOTIFY; i++)
853                 delete gen_notifications[i];
854 }
855
856
857 // Returns Y one under area minimum if not found
858 s16 Mapgen::findGroundLevelFull(v2s16 p2d) {
859         v3s16 em = vm->m_area.getExtent();
860         s16 y_nodes_max = vm->m_area.MaxEdge.Y;
861         s16 y_nodes_min = vm->m_area.MinEdge.Y;
862         u32 i = vm->m_area.index(p2d.X, y_nodes_max, p2d.Y);
863         s16 y;
864
865         for (y = y_nodes_max; y >= y_nodes_min; y--) {
866                 MapNode &n = vm->m_data[i];
867                 if (ndef->get(n).walkable)
868                         break;
869
870                 vm->m_area.add_y(em, i, -1);
871         }
872         return (y >= y_nodes_min) ? y : y_nodes_min - 1;
873 }
874
875
876 s16 Mapgen::findGroundLevel(v2s16 p2d, s16 ymin, s16 ymax) {
877         v3s16 em = vm->m_area.getExtent();
878         u32 i = vm->m_area.index(p2d.X, ymax, p2d.Y);
879         s16 y;
880
881         for (y = ymax; y >= ymin; y--) {
882                 MapNode &n = vm->m_data[i];
883                 if (ndef->get(n).walkable)
884                         break;
885
886                 vm->m_area.add_y(em, i, -1);
887         }
888         return y;
889 }
890
891
892 void Mapgen::updateHeightmap(v3s16 nmin, v3s16 nmax) {
893         if (!heightmap)
894                 return;
895
896         //TimeTaker t("Mapgen::updateHeightmap", NULL, PRECISION_MICRO);
897         int index = 0;
898         for (s16 z = nmin.Z; z <= nmax.Z; z++) {
899                 for (s16 x = nmin.X; x <= nmax.X; x++, index++) {
900                         s16 y = findGroundLevel(v2s16(x, z), nmin.Y, nmax.Y);
901
902                         // if the values found are out of range, trust the old heightmap
903                         if (y == nmax.Y && heightmap[index] > nmax.Y)
904                                 continue;
905                         if (y == nmin.Y - 1 && heightmap[index] < nmin.Y)
906                                 continue;
907
908                         heightmap[index] = y;
909                 }
910         }
911         //printf("updateHeightmap: %dus\n", t.stop());
912 }
913
914
915 void Mapgen::updateLiquid(UniqueQueue<v3s16> *trans_liquid, v3s16 nmin, v3s16 nmax) {
916         bool isliquid, wasliquid;
917         v3s16 em  = vm->m_area.getExtent();
918
919         for (s16 z = nmin.Z; z <= nmax.Z; z++) {
920                 for (s16 x = nmin.X; x <= nmax.X; x++) {
921                         wasliquid = true;
922
923                         u32 i = vm->m_area.index(x, nmax.Y, z);
924                         for (s16 y = nmax.Y; y >= nmin.Y; y--) {
925                                 isliquid = ndef->get(vm->m_data[i]).isLiquid();
926
927                                 // there was a change between liquid and nonliquid, add to queue.
928                                 if (isliquid != wasliquid)
929                                         trans_liquid->push_back(v3s16(x, y, z));
930
931                                 wasliquid = isliquid;
932                                 vm->m_area.add_y(em, i, -1);
933                         }
934                 }
935         }
936 }
937
938
939 void Mapgen::setLighting(v3s16 nmin, v3s16 nmax, u8 light) {
940         ScopeProfiler sp(g_profiler, "EmergeThread: mapgen lighting update", SPT_AVG);
941         VoxelArea a(nmin, nmax);
942
943         for (int z = a.MinEdge.Z; z <= a.MaxEdge.Z; z++) {
944                 for (int y = a.MinEdge.Y; y <= a.MaxEdge.Y; y++) {
945                         u32 i = vm->m_area.index(a.MinEdge.X, y, z);
946                         for (int x = a.MinEdge.X; x <= a.MaxEdge.X; x++, i++)
947                                 vm->m_data[i].param1 = light;
948                 }
949         }
950 }
951
952
953 void Mapgen::lightSpread(VoxelArea &a, v3s16 p, u8 light) {
954         if (light <= 1 || !a.contains(p))
955                 return;
956
957         u32 vi = vm->m_area.index(p);
958         MapNode &nn = vm->m_data[vi];
959
960         light--;
961         // should probably compare masked, but doesn't seem to make a difference
962         if (light <= nn.param1 || !ndef->get(nn).light_propagates)
963                 return;
964
965         nn.param1 = light;
966
967         lightSpread(a, p + v3s16(0, 0, 1), light);
968         lightSpread(a, p + v3s16(0, 1, 0), light);
969         lightSpread(a, p + v3s16(1, 0, 0), light);
970         lightSpread(a, p - v3s16(0, 0, 1), light);
971         lightSpread(a, p - v3s16(0, 1, 0), light);
972         lightSpread(a, p - v3s16(1, 0, 0), light);
973 }
974
975
976 void Mapgen::calcLighting(v3s16 nmin, v3s16 nmax) {
977         VoxelArea a(nmin, nmax);
978         bool block_is_underground = (water_level >= nmax.Y);
979
980         ScopeProfiler sp(g_profiler, "EmergeThread: mapgen lighting update", SPT_AVG);
981         //TimeTaker t("updateLighting");
982
983         // first, send vertical rays of sunshine downward
984         v3s16 em = vm->m_area.getExtent();
985         for (int z = a.MinEdge.Z; z <= a.MaxEdge.Z; z++) {
986                 for (int x = a.MinEdge.X; x <= a.MaxEdge.X; x++) {
987                         // see if we can get a light value from the overtop
988                         u32 i = vm->m_area.index(x, a.MaxEdge.Y + 1, z);
989                         if (vm->m_data[i].getContent() == CONTENT_IGNORE) {
990                                 if (block_is_underground)
991                                         continue;
992                         } else if ((vm->m_data[i].param1 & 0x0F) != LIGHT_SUN) {
993                                 continue;
994                         }
995                         vm->m_area.add_y(em, i, -1);
996
997                         for (int y = a.MaxEdge.Y; y >= a.MinEdge.Y; y--) {
998                                 MapNode &n = vm->m_data[i];
999                                 if (!ndef->get(n).sunlight_propagates)
1000                                         break;
1001                                 n.param1 = LIGHT_SUN;
1002                                 vm->m_area.add_y(em, i, -1);
1003                         }
1004                 }
1005         }
1006
1007         // now spread the sunlight and light up any sources
1008         for (int z = a.MinEdge.Z; z <= a.MaxEdge.Z; z++) {
1009                 for (int y = a.MinEdge.Y; y <= a.MaxEdge.Y; y++) {
1010                         u32 i = vm->m_area.index(a.MinEdge.X, y, z);
1011                         for (int x = a.MinEdge.X; x <= a.MaxEdge.X; x++, i++) {
1012                                 MapNode &n = vm->m_data[i];
1013                                 if (n.getContent() == CONTENT_IGNORE ||
1014                                         !ndef->get(n).light_propagates)
1015                                         continue;
1016
1017                                 u8 light_produced = ndef->get(n).light_source & 0x0F;
1018                                 if (light_produced)
1019                                         n.param1 = light_produced;
1020
1021                                 u8 light = n.param1 & 0x0F;
1022                                 if (light) {
1023                                         lightSpread(a, v3s16(x,     y,     z + 1), light - 1);
1024                                         lightSpread(a, v3s16(x,     y + 1, z    ), light - 1);
1025                                         lightSpread(a, v3s16(x + 1, y,     z    ), light - 1);
1026                                         lightSpread(a, v3s16(x,     y,     z - 1), light - 1);
1027                                         lightSpread(a, v3s16(x,     y - 1, z    ), light - 1);
1028                                         lightSpread(a, v3s16(x - 1, y,     z    ), light - 1);
1029                                 }
1030                         }
1031                 }
1032         }
1033
1034         //printf("updateLighting: %dms\n", t.stop());
1035 }
1036
1037
1038 void Mapgen::calcLightingOld(v3s16 nmin, v3s16 nmax) {
1039         enum LightBank banks[2] = {LIGHTBANK_DAY, LIGHTBANK_NIGHT};
1040         VoxelArea a(nmin, nmax);
1041         bool block_is_underground = (water_level > nmax.Y);
1042         bool sunlight = !block_is_underground;
1043
1044         ScopeProfiler sp(g_profiler, "EmergeThread: mapgen lighting update", SPT_AVG);
1045
1046         for (int i = 0; i < 2; i++) {
1047                 enum LightBank bank = banks[i];
1048                 std::set<v3s16> light_sources;
1049                 std::map<v3s16, u8> unlight_from;
1050
1051                 voxalgo::clearLightAndCollectSources(*vm, a, bank, ndef,
1052                                                                                          light_sources, unlight_from);
1053                 voxalgo::propagateSunlight(*vm, a, sunlight, light_sources, ndef);
1054
1055                 vm->unspreadLight(bank, unlight_from, light_sources, ndef);
1056                 vm->spreadLight(bank, light_sources, ndef);
1057         }
1058 }