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