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