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