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