]> git.lizzy.rs Git - minetest.git/blob - src/script/lua_api/l_mapgen.cpp
92ed4377ea5dac20ff496afe31ab017909ef630c
[minetest.git] / src / script / lua_api / l_mapgen.cpp
1 /*
2 Minetest
3 Copyright (C) 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 "lua_api/l_mapgen.h"
21 #include "lua_api/l_internal.h"
22 #include "lua_api/l_vmanip.h"
23 #include "common/c_converter.h"
24 #include "common/c_content.h"
25 #include "cpp_api/s_security.h"
26 #include "util/serialize.h"
27 #include "server.h"
28 #include "environment.h"
29 #include "emerge.h"
30 #include "mapgen/mg_biome.h"
31 #include "mapgen/mg_ore.h"
32 #include "mapgen/mg_decoration.h"
33 #include "mapgen/mg_schematic.h"
34 #include "mapgen/mapgen_v5.h"
35 #include "mapgen/mapgen_v7.h"
36 #include "filesys.h"
37 #include "settings.h"
38 #include "log.h"
39
40 struct EnumString ModApiMapgen::es_BiomeTerrainType[] =
41 {
42         {BIOMETYPE_NORMAL, "normal"},
43         {0, NULL},
44 };
45
46 struct EnumString ModApiMapgen::es_DecorationType[] =
47 {
48         {DECO_SIMPLE,    "simple"},
49         {DECO_SCHEMATIC, "schematic"},
50         {DECO_LSYSTEM,   "lsystem"},
51         {0, NULL},
52 };
53
54 struct EnumString ModApiMapgen::es_MapgenObject[] =
55 {
56         {MGOBJ_VMANIP,    "voxelmanip"},
57         {MGOBJ_HEIGHTMAP, "heightmap"},
58         {MGOBJ_BIOMEMAP,  "biomemap"},
59         {MGOBJ_HEATMAP,   "heatmap"},
60         {MGOBJ_HUMIDMAP,  "humiditymap"},
61         {MGOBJ_GENNOTIFY, "gennotify"},
62         {0, NULL},
63 };
64
65 struct EnumString ModApiMapgen::es_OreType[] =
66 {
67         {ORE_SCATTER, "scatter"},
68         {ORE_SHEET,   "sheet"},
69         {ORE_PUFF,    "puff"},
70         {ORE_BLOB,    "blob"},
71         {ORE_VEIN,    "vein"},
72         {ORE_STRATUM, "stratum"},
73         {0, NULL},
74 };
75
76 struct EnumString ModApiMapgen::es_Rotation[] =
77 {
78         {ROTATE_0,    "0"},
79         {ROTATE_90,   "90"},
80         {ROTATE_180,  "180"},
81         {ROTATE_270,  "270"},
82         {ROTATE_RAND, "random"},
83         {0, NULL},
84 };
85
86 struct EnumString ModApiMapgen::es_SchematicFormatType[] =
87 {
88         {SCHEM_FMT_HANDLE, "handle"},
89         {SCHEM_FMT_MTS,    "mts"},
90         {SCHEM_FMT_LUA,    "lua"},
91         {0, NULL},
92 };
93
94 ObjDef *get_objdef(lua_State *L, int index, ObjDefManager *objmgr);
95
96 Biome *get_or_load_biome(lua_State *L, int index,
97         BiomeManager *biomemgr);
98 Biome *read_biome_def(lua_State *L, int index, const NodeDefManager *ndef);
99 size_t get_biome_list(lua_State *L, int index,
100         BiomeManager *biomemgr, std::unordered_set<u8> *biome_id_list);
101
102 Schematic *get_or_load_schematic(lua_State *L, int index,
103         SchematicManager *schemmgr, StringMap *replace_names);
104 Schematic *load_schematic(lua_State *L, int index, const NodeDefManager *ndef,
105         StringMap *replace_names);
106 Schematic *load_schematic_from_def(lua_State *L, int index,
107         const NodeDefManager *ndef, StringMap *replace_names);
108 bool read_schematic_def(lua_State *L, int index,
109         Schematic *schem, std::vector<std::string> *names);
110
111 bool read_deco_simple(lua_State *L, DecoSimple *deco);
112 bool read_deco_schematic(lua_State *L, SchematicManager *schemmgr, DecoSchematic *deco);
113
114
115 ///////////////////////////////////////////////////////////////////////////////
116
117 ObjDef *get_objdef(lua_State *L, int index, ObjDefManager *objmgr)
118 {
119         if (index < 0)
120                 index = lua_gettop(L) + 1 + index;
121
122         // If a number, assume this is a handle to an object def
123         if (lua_isnumber(L, index))
124                 return objmgr->get(lua_tointeger(L, index));
125
126         // If a string, assume a name is given instead
127         if (lua_isstring(L, index))
128                 return objmgr->getByName(lua_tostring(L, index));
129
130         return NULL;
131 }
132
133 ///////////////////////////////////////////////////////////////////////////////
134
135 Schematic *get_or_load_schematic(lua_State *L, int index,
136         SchematicManager *schemmgr, StringMap *replace_names)
137 {
138         if (index < 0)
139                 index = lua_gettop(L) + 1 + index;
140
141         Schematic *schem = (Schematic *)get_objdef(L, index, schemmgr);
142         if (schem)
143                 return schem;
144
145         schem = load_schematic(L, index, schemmgr->getNodeDef(),
146                 replace_names);
147         if (!schem)
148                 return NULL;
149
150         if (schemmgr->add(schem) == OBJDEF_INVALID_HANDLE) {
151                 delete schem;
152                 return NULL;
153         }
154
155         return schem;
156 }
157
158
159 Schematic *load_schematic(lua_State *L, int index, const NodeDefManager *ndef,
160         StringMap *replace_names)
161 {
162         if (index < 0)
163                 index = lua_gettop(L) + 1 + index;
164
165         Schematic *schem = NULL;
166
167         if (lua_istable(L, index)) {
168                 schem = load_schematic_from_def(L, index, ndef,
169                         replace_names);
170                 if (!schem) {
171                         delete schem;
172                         return NULL;
173                 }
174         } else if (lua_isnumber(L, index)) {
175                 return NULL;
176         } else if (lua_isstring(L, index)) {
177                 schem = SchematicManager::create(SCHEMATIC_NORMAL);
178
179                 std::string filepath = lua_tostring(L, index);
180                 if (!fs::IsPathAbsolute(filepath))
181                         filepath = ModApiBase::getCurrentModPath(L) + DIR_DELIM + filepath;
182
183                 if (!schem->loadSchematicFromFile(filepath, ndef,
184                                 replace_names)) {
185                         delete schem;
186                         return NULL;
187                 }
188         }
189
190         return schem;
191 }
192
193
194 Schematic *load_schematic_from_def(lua_State *L, int index,
195         const NodeDefManager *ndef, StringMap *replace_names)
196 {
197         Schematic *schem = SchematicManager::create(SCHEMATIC_NORMAL);
198
199         if (!read_schematic_def(L, index, schem, &schem->m_nodenames)) {
200                 delete schem;
201                 return NULL;
202         }
203
204         size_t num_nodes = schem->m_nodenames.size();
205
206         schem->m_nnlistsizes.push_back(num_nodes);
207
208         if (replace_names) {
209                 for (size_t i = 0; i != num_nodes; i++) {
210                         StringMap::iterator it = replace_names->find(schem->m_nodenames[i]);
211                         if (it != replace_names->end())
212                                 schem->m_nodenames[i] = it->second;
213                 }
214         }
215
216         if (ndef)
217                 ndef->pendNodeResolve(schem);
218
219         return schem;
220 }
221
222
223 bool read_schematic_def(lua_State *L, int index,
224         Schematic *schem, std::vector<std::string> *names)
225 {
226         if (!lua_istable(L, index))
227                 return false;
228
229         //// Get schematic size
230         lua_getfield(L, index, "size");
231         v3s16 size = check_v3s16(L, -1);
232         lua_pop(L, 1);
233
234         schem->size = size;
235
236         //// Get schematic data
237         lua_getfield(L, index, "data");
238         luaL_checktype(L, -1, LUA_TTABLE);
239
240         u32 numnodes = size.X * size.Y * size.Z;
241         schem->schemdata = new MapNode[numnodes];
242
243         size_t names_base = names->size();
244         std::unordered_map<std::string, content_t> name_id_map;
245
246         u32 i = 0;
247         for (lua_pushnil(L); lua_next(L, -2); i++, lua_pop(L, 1)) {
248                 if (i >= numnodes)
249                         continue;
250
251                 //// Read name
252                 std::string name;
253                 if (!getstringfield(L, -1, "name", name))
254                         throw LuaError("Schematic data definition with missing name field");
255
256                 //// Read param1/prob
257                 u8 param1;
258                 if (!getintfield(L, -1, "param1", param1) &&
259                         !getintfield(L, -1, "prob", param1))
260                         param1 = MTSCHEM_PROB_ALWAYS_OLD;
261
262                 //// Read param2
263                 u8 param2 = getintfield_default(L, -1, "param2", 0);
264
265                 //// Find or add new nodename-to-ID mapping
266                 std::unordered_map<std::string, content_t>::iterator it = name_id_map.find(name);
267                 content_t name_index;
268                 if (it != name_id_map.end()) {
269                         name_index = it->second;
270                 } else {
271                         name_index = names->size() - names_base;
272                         name_id_map[name] = name_index;
273                         names->push_back(name);
274                 }
275
276                 //// Perform probability/force_place fixup on param1
277                 param1 >>= 1;
278                 if (getboolfield_default(L, -1, "force_place", false))
279                         param1 |= MTSCHEM_FORCE_PLACE;
280
281                 //// Actually set the node in the schematic
282                 schem->schemdata[i] = MapNode(name_index, param1, param2);
283         }
284
285         if (i != numnodes) {
286                 errorstream << "read_schematic_def: incorrect number of "
287                         "nodes provided in raw schematic data (got " << i <<
288                         ", expected " << numnodes << ")." << std::endl;
289                 return false;
290         }
291
292         //// Get Y-slice probability values (if present)
293         schem->slice_probs = new u8[size.Y];
294         for (i = 0; i != (u32) size.Y; i++)
295                 schem->slice_probs[i] = MTSCHEM_PROB_ALWAYS;
296
297         lua_getfield(L, index, "yslice_prob");
298         if (lua_istable(L, -1)) {
299                 for (lua_pushnil(L); lua_next(L, -2); lua_pop(L, 1)) {
300                         u16 ypos;
301                         if (!getintfield(L, -1, "ypos", ypos) || (ypos >= size.Y) ||
302                                 !getintfield(L, -1, "prob", schem->slice_probs[ypos]))
303                                 continue;
304
305                         schem->slice_probs[ypos] >>= 1;
306                 }
307         }
308
309         return true;
310 }
311
312
313 void read_schematic_replacements(lua_State *L, int index, StringMap *replace_names)
314 {
315         if (index < 0)
316                 index = lua_gettop(L) + 1 + index;
317
318         lua_pushnil(L);
319         while (lua_next(L, index)) {
320                 std::string replace_from;
321                 std::string replace_to;
322
323                 if (lua_istable(L, -1)) { // Old {{"x", "y"}, ...} format
324                         lua_rawgeti(L, -1, 1);
325                         if (!lua_isstring(L, -1))
326                                 throw LuaError("schematics: replace_from field is not a string");
327                         replace_from = lua_tostring(L, -1);
328                         lua_pop(L, 1);
329
330                         lua_rawgeti(L, -1, 2);
331                         if (!lua_isstring(L, -1))
332                                 throw LuaError("schematics: replace_to field is not a string");
333                         replace_to = lua_tostring(L, -1);
334                         lua_pop(L, 1);
335                 } else { // New {x = "y", ...} format
336                         if (!lua_isstring(L, -2))
337                                 throw LuaError("schematics: replace_from field is not a string");
338                         replace_from = lua_tostring(L, -2);
339                         if (!lua_isstring(L, -1))
340                                 throw LuaError("schematics: replace_to field is not a string");
341                         replace_to = lua_tostring(L, -1);
342                 }
343
344                 replace_names->insert(std::make_pair(replace_from, replace_to));
345                 lua_pop(L, 1);
346         }
347 }
348
349 ///////////////////////////////////////////////////////////////////////////////
350
351 Biome *get_or_load_biome(lua_State *L, int index, BiomeManager *biomemgr)
352 {
353         if (index < 0)
354                 index = lua_gettop(L) + 1 + index;
355
356         Biome *biome = (Biome *)get_objdef(L, index, biomemgr);
357         if (biome)
358                 return biome;
359
360         biome = read_biome_def(L, index, biomemgr->getNodeDef());
361         if (!biome)
362                 return NULL;
363
364         if (biomemgr->add(biome) == OBJDEF_INVALID_HANDLE) {
365                 delete biome;
366                 return NULL;
367         }
368
369         return biome;
370 }
371
372
373 Biome *read_biome_def(lua_State *L, int index, const NodeDefManager *ndef)
374 {
375         if (!lua_istable(L, index))
376                 return NULL;
377
378         BiomeType biometype = (BiomeType)getenumfield(L, index, "type",
379                 ModApiMapgen::es_BiomeTerrainType, BIOMETYPE_NORMAL);
380         Biome *b = BiomeManager::create(biometype);
381
382         b->name            = getstringfield_default(L, index, "name", "");
383         b->depth_top       = getintfield_default(L,    index, "depth_top",       0);
384         b->depth_filler    = getintfield_default(L,    index, "depth_filler",    -31000);
385         b->depth_water_top = getintfield_default(L,    index, "depth_water_top", 0);
386         b->depth_riverbed  = getintfield_default(L,    index, "depth_riverbed",  0);
387         b->heat_point      = getfloatfield_default(L,  index, "heat_point",      0.f);
388         b->humidity_point  = getfloatfield_default(L,  index, "humidity_point",  0.f);
389         b->vertical_blend  = getintfield_default(L,    index, "vertical_blend",  0);
390         b->flags           = 0; // reserved
391
392         b->min_pos = getv3s16field_default(
393                 L, index, "min_pos", v3s16(-31000, -31000, -31000));
394         getintfield(L, index, "y_min", b->min_pos.Y);
395         b->max_pos = getv3s16field_default(
396                 L, index, "max_pos", v3s16(31000, 31000, 31000));
397         getintfield(L, index, "y_max", b->max_pos.Y);
398
399         std::vector<std::string> &nn = b->m_nodenames;
400         nn.push_back(getstringfield_default(L, index, "node_top",           ""));
401         nn.push_back(getstringfield_default(L, index, "node_filler",        ""));
402         nn.push_back(getstringfield_default(L, index, "node_stone",         ""));
403         nn.push_back(getstringfield_default(L, index, "node_water_top",     ""));
404         nn.push_back(getstringfield_default(L, index, "node_water",         ""));
405         nn.push_back(getstringfield_default(L, index, "node_river_water",   ""));
406         nn.push_back(getstringfield_default(L, index, "node_riverbed",      ""));
407         nn.push_back(getstringfield_default(L, index, "node_dust",          ""));
408         nn.push_back(getstringfield_default(L, index, "node_cave_liquid",   ""));
409         nn.push_back(getstringfield_default(L, index, "node_dungeon",       ""));
410         nn.push_back(getstringfield_default(L, index, "node_dungeon_alt",   ""));
411         nn.push_back(getstringfield_default(L, index, "node_dungeon_stair", ""));
412         ndef->pendNodeResolve(b);
413
414         return b;
415 }
416
417
418 size_t get_biome_list(lua_State *L, int index,
419         BiomeManager *biomemgr, std::unordered_set<u8> *biome_id_list)
420 {
421         if (index < 0)
422                 index = lua_gettop(L) + 1 + index;
423
424         if (lua_isnil(L, index))
425                 return 0;
426
427         bool is_single = true;
428         if (lua_istable(L, index)) {
429                 lua_getfield(L, index, "name");
430                 is_single = !lua_isnil(L, -1);
431                 lua_pop(L, 1);
432         }
433
434         if (is_single) {
435                 Biome *biome = get_or_load_biome(L, index, biomemgr);
436                 if (!biome) {
437                         infostream << "get_biome_list: failed to get biome '"
438                                 << (lua_isstring(L, index) ? lua_tostring(L, index) : "")
439                                 << "'." << std::endl;
440                         return 1;
441                 }
442
443                 biome_id_list->insert(biome->index);
444                 return 0;
445         }
446
447         // returns number of failed resolutions
448         size_t fail_count = 0;
449         size_t count = 0;
450
451         for (lua_pushnil(L); lua_next(L, index); lua_pop(L, 1)) {
452                 count++;
453                 Biome *biome = get_or_load_biome(L, -1, biomemgr);
454                 if (!biome) {
455                         fail_count++;
456                         infostream << "get_biome_list: failed to get biome '"
457                                 << (lua_isstring(L, -1) ? lua_tostring(L, -1) : "")
458                                 << "'" << std::endl;
459                         continue;
460                 }
461
462                 biome_id_list->insert(biome->index);
463         }
464
465         return fail_count;
466 }
467
468 ///////////////////////////////////////////////////////////////////////////////
469
470 // get_biome_id(biomename)
471 // returns the biome id as used in biomemap and returned by 'get_biome_data()'
472 int ModApiMapgen::l_get_biome_id(lua_State *L)
473 {
474         NO_MAP_LOCK_REQUIRED;
475
476         const char *biome_str = lua_tostring(L, 1);
477         if (!biome_str)
478                 return 0;
479
480         BiomeManager *bmgr = getServer(L)->getEmergeManager()->biomemgr;
481         if (!bmgr)
482                 return 0;
483
484         Biome *biome = (Biome *)bmgr->getByName(biome_str);
485         if (!biome || biome->index == OBJDEF_INVALID_INDEX)
486                 return 0;
487
488         lua_pushinteger(L, biome->index);
489
490         return 1;
491 }
492
493
494 // get_biome_name(biome_id)
495 // returns the biome name string
496 int ModApiMapgen::l_get_biome_name(lua_State *L)
497 {
498         NO_MAP_LOCK_REQUIRED;
499
500         int biome_id = luaL_checkinteger(L, 1);
501
502         BiomeManager *bmgr = getServer(L)->getEmergeManager()->biomemgr;
503         if (!bmgr)
504                 return 0;
505
506         Biome *b = (Biome *)bmgr->getRaw(biome_id);
507         lua_pushstring(L, b->name.c_str());
508
509         return 1;
510 }
511
512
513 // get_heat(pos)
514 // returns the heat at the position
515 int ModApiMapgen::l_get_heat(lua_State *L)
516 {
517         NO_MAP_LOCK_REQUIRED;
518
519         v3s16 pos = read_v3s16(L, 1);
520
521         NoiseParams np_heat;
522         NoiseParams np_heat_blend;
523
524         MapSettingsManager *settingsmgr =
525                 getServer(L)->getEmergeManager()->map_settings_mgr;
526
527         if (!settingsmgr->getMapSettingNoiseParams("mg_biome_np_heat",
528                         &np_heat) ||
529                         !settingsmgr->getMapSettingNoiseParams("mg_biome_np_heat_blend",
530                         &np_heat_blend))
531                 return 0;
532
533         std::string value;
534         if (!settingsmgr->getMapSetting("seed", &value))
535                 return 0;
536         std::istringstream ss(value);
537         u64 seed;
538         ss >> seed;
539
540         BiomeManager *bmgr = getServer(L)->getEmergeManager()->biomemgr;
541         if (!bmgr)
542                 return 0;
543
544         float heat = bmgr->getHeatAtPosOriginal(pos, np_heat, np_heat_blend, seed);
545         if (!heat)
546                 return 0;
547
548         lua_pushnumber(L, heat);
549
550         return 1;
551 }
552
553
554 // get_humidity(pos)
555 // returns the humidity at the position
556 int ModApiMapgen::l_get_humidity(lua_State *L)
557 {
558         NO_MAP_LOCK_REQUIRED;
559
560         v3s16 pos = read_v3s16(L, 1);
561
562         NoiseParams np_humidity;
563         NoiseParams np_humidity_blend;
564
565         MapSettingsManager *settingsmgr =
566                 getServer(L)->getEmergeManager()->map_settings_mgr;
567
568         if (!settingsmgr->getMapSettingNoiseParams("mg_biome_np_humidity",
569                         &np_humidity) ||
570                         !settingsmgr->getMapSettingNoiseParams("mg_biome_np_humidity_blend",
571                         &np_humidity_blend))
572                 return 0;
573
574         std::string value;
575         if (!settingsmgr->getMapSetting("seed", &value))
576                 return 0;
577         std::istringstream ss(value);
578         u64 seed;
579         ss >> seed;
580
581         BiomeManager *bmgr = getServer(L)->getEmergeManager()->biomemgr;
582         if (!bmgr)
583                 return 0;
584
585         float humidity = bmgr->getHumidityAtPosOriginal(pos, np_humidity,
586                 np_humidity_blend, seed);
587         if (!humidity)
588                 return 0;
589
590         lua_pushnumber(L, humidity);
591
592         return 1;
593 }
594
595
596 // get_biome_data(pos)
597 // returns a table containing the biome id, heat and humidity at the position
598 int ModApiMapgen::l_get_biome_data(lua_State *L)
599 {
600         NO_MAP_LOCK_REQUIRED;
601
602         v3s16 pos = read_v3s16(L, 1);
603
604         NoiseParams np_heat;
605         NoiseParams np_heat_blend;
606         NoiseParams np_humidity;
607         NoiseParams np_humidity_blend;
608
609         MapSettingsManager *settingsmgr =
610                 getServer(L)->getEmergeManager()->map_settings_mgr;
611
612         if (!settingsmgr->getMapSettingNoiseParams("mg_biome_np_heat",
613                         &np_heat) ||
614                         !settingsmgr->getMapSettingNoiseParams("mg_biome_np_heat_blend",
615                         &np_heat_blend) ||
616                         !settingsmgr->getMapSettingNoiseParams("mg_biome_np_humidity",
617                         &np_humidity) ||
618                         !settingsmgr->getMapSettingNoiseParams("mg_biome_np_humidity_blend",
619                         &np_humidity_blend))
620                 return 0;
621
622         std::string value;
623         if (!settingsmgr->getMapSetting("seed", &value))
624                 return 0;
625         std::istringstream ss(value);
626         u64 seed;
627         ss >> seed;
628
629         BiomeManager *bmgr = getServer(L)->getEmergeManager()->biomemgr;
630         if (!bmgr)
631                 return 0;
632
633         float heat = bmgr->getHeatAtPosOriginal(pos, np_heat, np_heat_blend, seed);
634         if (!heat)
635                 return 0;
636
637         float humidity = bmgr->getHumidityAtPosOriginal(pos, np_humidity,
638                 np_humidity_blend, seed);
639         if (!humidity)
640                 return 0;
641
642         Biome *biome = (Biome *)bmgr->getBiomeFromNoiseOriginal(heat, humidity, pos);
643         if (!biome || biome->index == OBJDEF_INVALID_INDEX)
644                 return 0;
645
646         lua_newtable(L);
647
648         lua_pushinteger(L, biome->index);
649         lua_setfield(L, -2, "biome");
650
651         lua_pushnumber(L, heat);
652         lua_setfield(L, -2, "heat");
653
654         lua_pushnumber(L, humidity);
655         lua_setfield(L, -2, "humidity");
656
657         return 1;
658 }
659
660
661 // get_mapgen_object(objectname)
662 // returns the requested object used during map generation
663 int ModApiMapgen::l_get_mapgen_object(lua_State *L)
664 {
665         NO_MAP_LOCK_REQUIRED;
666
667         const char *mgobjstr = lua_tostring(L, 1);
668
669         int mgobjint;
670         if (!string_to_enum(es_MapgenObject, mgobjint, mgobjstr ? mgobjstr : ""))
671                 return 0;
672
673         enum MapgenObject mgobj = (MapgenObject)mgobjint;
674
675         EmergeManager *emerge = getServer(L)->getEmergeManager();
676         Mapgen *mg = emerge->getCurrentMapgen();
677         if (!mg)
678                 throw LuaError("Must only be called in a mapgen thread!");
679
680         size_t maplen = mg->csize.X * mg->csize.Z;
681
682         switch (mgobj) {
683         case MGOBJ_VMANIP: {
684                 MMVManip *vm = mg->vm;
685
686                 // VoxelManip object
687                 LuaVoxelManip *o = new LuaVoxelManip(vm, true);
688                 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
689                 luaL_getmetatable(L, "VoxelManip");
690                 lua_setmetatable(L, -2);
691
692                 // emerged min pos
693                 push_v3s16(L, vm->m_area.MinEdge);
694
695                 // emerged max pos
696                 push_v3s16(L, vm->m_area.MaxEdge);
697
698                 return 3;
699         }
700         case MGOBJ_HEIGHTMAP: {
701                 if (!mg->heightmap)
702                         return 0;
703
704                 lua_newtable(L);
705                 for (size_t i = 0; i != maplen; i++) {
706                         lua_pushinteger(L, mg->heightmap[i]);
707                         lua_rawseti(L, -2, i + 1);
708                 }
709
710                 return 1;
711         }
712         case MGOBJ_BIOMEMAP: {
713                 if (!mg->biomegen)
714                         return 0;
715
716                 lua_newtable(L);
717                 for (size_t i = 0; i != maplen; i++) {
718                         lua_pushinteger(L, mg->biomegen->biomemap[i]);
719                         lua_rawseti(L, -2, i + 1);
720                 }
721
722                 return 1;
723         }
724         case MGOBJ_HEATMAP: {
725                 if (!mg->biomegen || mg->biomegen->getType() != BIOMEGEN_ORIGINAL)
726                         return 0;
727
728                 BiomeGenOriginal *bg = (BiomeGenOriginal *)mg->biomegen;
729
730                 lua_newtable(L);
731                 for (size_t i = 0; i != maplen; i++) {
732                         lua_pushnumber(L, bg->heatmap[i]);
733                         lua_rawseti(L, -2, i + 1);
734                 }
735
736                 return 1;
737         }
738
739         case MGOBJ_HUMIDMAP: {
740                 if (!mg->biomegen || mg->biomegen->getType() != BIOMEGEN_ORIGINAL)
741                         return 0;
742
743                 BiomeGenOriginal *bg = (BiomeGenOriginal *)mg->biomegen;
744
745                 lua_newtable(L);
746                 for (size_t i = 0; i != maplen; i++) {
747                         lua_pushnumber(L, bg->humidmap[i]);
748                         lua_rawseti(L, -2, i + 1);
749                 }
750
751                 return 1;
752         }
753         case MGOBJ_GENNOTIFY: {
754                 std::map<std::string, std::vector<v3s16> >event_map;
755                 std::map<std::string, std::vector<v3s16> >::iterator it;
756
757                 mg->gennotify.getEvents(event_map);
758
759                 lua_newtable(L);
760                 for (it = event_map.begin(); it != event_map.end(); ++it) {
761                         lua_newtable(L);
762
763                         for (size_t j = 0; j != it->second.size(); j++) {
764                                 push_v3s16(L, it->second[j]);
765                                 lua_rawseti(L, -2, j + 1);
766                         }
767
768                         lua_setfield(L, -2, it->first.c_str());
769                 }
770
771                 return 1;
772         }
773         }
774
775         return 0;
776 }
777
778
779 // get_spawn_level(x = num, z = num)
780 int ModApiMapgen::l_get_spawn_level(lua_State *L)
781 {
782         NO_MAP_LOCK_REQUIRED;
783
784         s16 x = luaL_checkinteger(L, 1);
785         s16 z = luaL_checkinteger(L, 2);
786
787         EmergeManager *emerge = getServer(L)->getEmergeManager();
788         int spawn_level = emerge->getSpawnLevelAtPoint(v2s16(x, z));
789         // Unsuitable spawn point
790         if (spawn_level == MAX_MAP_GENERATION_LIMIT)
791                 return 0;
792
793         // 'findSpawnPos()' in server.cpp adds at least 1
794         lua_pushinteger(L, spawn_level + 1);
795
796         return 1;
797 }
798
799
800 int ModApiMapgen::l_get_mapgen_params(lua_State *L)
801 {
802         NO_MAP_LOCK_REQUIRED;
803
804         log_deprecated(L, "get_mapgen_params is deprecated; "
805                 "use get_mapgen_setting instead");
806
807         std::string value;
808
809         MapSettingsManager *settingsmgr =
810                 getServer(L)->getEmergeManager()->map_settings_mgr;
811
812         lua_newtable(L);
813
814         settingsmgr->getMapSetting("mg_name", &value);
815         lua_pushstring(L, value.c_str());
816         lua_setfield(L, -2, "mgname");
817
818         settingsmgr->getMapSetting("seed", &value);
819         std::istringstream ss(value);
820         u64 seed;
821         ss >> seed;
822         lua_pushinteger(L, seed);
823         lua_setfield(L, -2, "seed");
824
825         settingsmgr->getMapSetting("water_level", &value);
826         lua_pushinteger(L, stoi(value, -32768, 32767));
827         lua_setfield(L, -2, "water_level");
828
829         settingsmgr->getMapSetting("chunksize", &value);
830         lua_pushinteger(L, stoi(value, -32768, 32767));
831         lua_setfield(L, -2, "chunksize");
832
833         settingsmgr->getMapSetting("mg_flags", &value);
834         lua_pushstring(L, value.c_str());
835         lua_setfield(L, -2, "flags");
836
837         return 1;
838 }
839
840
841 // set_mapgen_params(params)
842 // set mapgen parameters
843 int ModApiMapgen::l_set_mapgen_params(lua_State *L)
844 {
845         NO_MAP_LOCK_REQUIRED;
846
847         log_deprecated(L, "set_mapgen_params is deprecated; "
848                 "use set_mapgen_setting instead");
849
850         if (!lua_istable(L, 1))
851                 return 0;
852
853         MapSettingsManager *settingsmgr =
854                 getServer(L)->getEmergeManager()->map_settings_mgr;
855
856         lua_getfield(L, 1, "mgname");
857         if (lua_isstring(L, -1))
858                 settingsmgr->setMapSetting("mg_name", readParam<std::string>(L, -1), true);
859
860         lua_getfield(L, 1, "seed");
861         if (lua_isnumber(L, -1))
862                 settingsmgr->setMapSetting("seed", readParam<std::string>(L, -1), true);
863
864         lua_getfield(L, 1, "water_level");
865         if (lua_isnumber(L, -1))
866                 settingsmgr->setMapSetting("water_level", readParam<std::string>(L, -1), true);
867
868         lua_getfield(L, 1, "chunksize");
869         if (lua_isnumber(L, -1))
870                 settingsmgr->setMapSetting("chunksize", readParam<std::string>(L, -1), true);
871
872         warn_if_field_exists(L, 1, "flagmask",
873                 "Deprecated: flags field now includes unset flags.");
874
875         lua_getfield(L, 1, "flags");
876         if (lua_isstring(L, -1))
877                 settingsmgr->setMapSetting("mg_flags", readParam<std::string>(L, -1), true);
878
879         return 0;
880 }
881
882 // get_mapgen_setting(name)
883 int ModApiMapgen::l_get_mapgen_setting(lua_State *L)
884 {
885         NO_MAP_LOCK_REQUIRED;
886
887         std::string value;
888         MapSettingsManager *settingsmgr =
889                 getServer(L)->getEmergeManager()->map_settings_mgr;
890
891         const char *name = luaL_checkstring(L, 1);
892         if (!settingsmgr->getMapSetting(name, &value))
893                 return 0;
894
895         lua_pushstring(L, value.c_str());
896         return 1;
897 }
898
899 // get_mapgen_setting_noiseparams(name)
900 int ModApiMapgen::l_get_mapgen_setting_noiseparams(lua_State *L)
901 {
902         NO_MAP_LOCK_REQUIRED;
903
904         NoiseParams np;
905         MapSettingsManager *settingsmgr =
906                 getServer(L)->getEmergeManager()->map_settings_mgr;
907
908         const char *name = luaL_checkstring(L, 1);
909         if (!settingsmgr->getMapSettingNoiseParams(name, &np))
910                 return 0;
911
912         push_noiseparams(L, &np);
913         return 1;
914 }
915
916 // set_mapgen_setting(name, value, override_meta)
917 // set mapgen config values
918 int ModApiMapgen::l_set_mapgen_setting(lua_State *L)
919 {
920         NO_MAP_LOCK_REQUIRED;
921
922         MapSettingsManager *settingsmgr =
923                 getServer(L)->getEmergeManager()->map_settings_mgr;
924
925         const char *name   = luaL_checkstring(L, 1);
926         const char *value  = luaL_checkstring(L, 2);
927         bool override_meta = readParam<bool>(L, 3, false);
928
929         if (!settingsmgr->setMapSetting(name, value, override_meta)) {
930                 errorstream << "set_mapgen_setting: cannot set '"
931                         << name << "' after initialization" << std::endl;
932         }
933
934         return 0;
935 }
936
937
938 // set_mapgen_setting_noiseparams(name, noiseparams, set_default)
939 // set mapgen config values for noise parameters
940 int ModApiMapgen::l_set_mapgen_setting_noiseparams(lua_State *L)
941 {
942         NO_MAP_LOCK_REQUIRED;
943
944         MapSettingsManager *settingsmgr =
945                 getServer(L)->getEmergeManager()->map_settings_mgr;
946
947         const char *name = luaL_checkstring(L, 1);
948
949         NoiseParams np;
950         if (!read_noiseparams(L, 2, &np)) {
951                 errorstream << "set_mapgen_setting_noiseparams: cannot set '" << name
952                         << "'; invalid noiseparams table" << std::endl;
953                 return 0;
954         }
955
956         bool override_meta = readParam<bool>(L, 3, false);
957
958         if (!settingsmgr->setMapSettingNoiseParams(name, &np, override_meta)) {
959                 errorstream << "set_mapgen_setting_noiseparams: cannot set '"
960                         << name << "' after initialization" << std::endl;
961         }
962
963         return 0;
964 }
965
966
967 // set_noiseparams(name, noiseparams, set_default)
968 // set global config values for noise parameters
969 int ModApiMapgen::l_set_noiseparams(lua_State *L)
970 {
971         NO_MAP_LOCK_REQUIRED;
972
973         const char *name = luaL_checkstring(L, 1);
974
975         NoiseParams np;
976         if (!read_noiseparams(L, 2, &np)) {
977                 errorstream << "set_noiseparams: cannot set '" << name
978                         << "'; invalid noiseparams table" << std::endl;
979                 return 0;
980         }
981
982         bool set_default = !lua_isboolean(L, 3) || readParam<bool>(L, 3);
983
984         g_settings->setNoiseParams(name, np, set_default);
985
986         return 0;
987 }
988
989
990 // get_noiseparams(name)
991 int ModApiMapgen::l_get_noiseparams(lua_State *L)
992 {
993         NO_MAP_LOCK_REQUIRED;
994
995         std::string name = luaL_checkstring(L, 1);
996
997         NoiseParams np;
998         if (!g_settings->getNoiseParams(name, np))
999                 return 0;
1000
1001         push_noiseparams(L, &np);
1002         return 1;
1003 }
1004
1005
1006 // set_gen_notify(flags, {deco_id_table})
1007 int ModApiMapgen::l_set_gen_notify(lua_State *L)
1008 {
1009         NO_MAP_LOCK_REQUIRED;
1010
1011         u32 flags = 0, flagmask = 0;
1012         EmergeManager *emerge = getServer(L)->getEmergeManager();
1013
1014         if (read_flags(L, 1, flagdesc_gennotify, &flags, &flagmask)) {
1015                 emerge->gen_notify_on &= ~flagmask;
1016                 emerge->gen_notify_on |= flags;
1017         }
1018
1019         if (lua_istable(L, 2)) {
1020                 lua_pushnil(L);
1021                 while (lua_next(L, 2)) {
1022                         if (lua_isnumber(L, -1))
1023                                 emerge->gen_notify_on_deco_ids.insert((u32)lua_tonumber(L, -1));
1024                         lua_pop(L, 1);
1025                 }
1026         }
1027
1028         return 0;
1029 }
1030
1031
1032 // get_gen_notify()
1033 int ModApiMapgen::l_get_gen_notify(lua_State *L)
1034 {
1035         NO_MAP_LOCK_REQUIRED;
1036
1037         EmergeManager *emerge = getServer(L)->getEmergeManager();
1038         push_flags_string(L, flagdesc_gennotify, emerge->gen_notify_on,
1039                 emerge->gen_notify_on);
1040
1041         lua_newtable(L);
1042         int i = 1;
1043         for (u32 gen_notify_on_deco_id : emerge->gen_notify_on_deco_ids) {
1044                 lua_pushnumber(L, gen_notify_on_deco_id);
1045                 lua_rawseti(L, -2, i++);
1046         }
1047         return 2;
1048 }
1049
1050
1051 // get_decoration_id(decoration_name)
1052 // returns the decoration ID as used in gennotify
1053 int ModApiMapgen::l_get_decoration_id(lua_State *L)
1054 {
1055         NO_MAP_LOCK_REQUIRED;
1056
1057         const char *deco_str = luaL_checkstring(L, 1);
1058         if (!deco_str)
1059                 return 0;
1060
1061         DecorationManager *dmgr = getServer(L)->getEmergeManager()->decomgr;
1062
1063         if (!dmgr)
1064                 return 0;
1065
1066         Decoration *deco = (Decoration *)dmgr->getByName(deco_str);
1067
1068         if (!deco)
1069                 return 0;
1070
1071         lua_pushinteger(L, deco->index);
1072
1073         return 1;
1074 }
1075
1076
1077 // register_biome({lots of stuff})
1078 int ModApiMapgen::l_register_biome(lua_State *L)
1079 {
1080         NO_MAP_LOCK_REQUIRED;
1081
1082         int index = 1;
1083         luaL_checktype(L, index, LUA_TTABLE);
1084
1085         const NodeDefManager *ndef = getServer(L)->getNodeDefManager();
1086         BiomeManager *bmgr = getServer(L)->getEmergeManager()->biomemgr;
1087
1088         Biome *biome = read_biome_def(L, index, ndef);
1089         if (!biome)
1090                 return 0;
1091
1092         ObjDefHandle handle = bmgr->add(biome);
1093         if (handle == OBJDEF_INVALID_HANDLE) {
1094                 delete biome;
1095                 return 0;
1096         }
1097
1098         lua_pushinteger(L, handle);
1099         return 1;
1100 }
1101
1102
1103 // register_decoration({lots of stuff})
1104 int ModApiMapgen::l_register_decoration(lua_State *L)
1105 {
1106         NO_MAP_LOCK_REQUIRED;
1107
1108         int index = 1;
1109         luaL_checktype(L, index, LUA_TTABLE);
1110
1111         const NodeDefManager *ndef      = getServer(L)->getNodeDefManager();
1112         DecorationManager *decomgr = getServer(L)->getEmergeManager()->decomgr;
1113         BiomeManager *biomemgr     = getServer(L)->getEmergeManager()->biomemgr;
1114         SchematicManager *schemmgr = getServer(L)->getEmergeManager()->schemmgr;
1115
1116         enum DecorationType decotype = (DecorationType)getenumfield(L, index,
1117                                 "deco_type", es_DecorationType, -1);
1118
1119         Decoration *deco = decomgr->create(decotype);
1120         if (!deco) {
1121                 errorstream << "register_decoration: decoration placement type "
1122                         << decotype << " not implemented" << std::endl;
1123                 return 0;
1124         }
1125
1126         deco->name           = getstringfield_default(L, index, "name", "");
1127         deco->fill_ratio     = getfloatfield_default(L, index, "fill_ratio", 0.02);
1128         deco->y_min          = getintfield_default(L, index, "y_min", -31000);
1129         deco->y_max          = getintfield_default(L, index, "y_max", 31000);
1130         deco->nspawnby       = getintfield_default(L, index, "num_spawn_by", -1);
1131         deco->place_offset_y = getintfield_default(L, index, "place_offset_y", 0);
1132         deco->sidelen        = getintfield_default(L, index, "sidelen", 8);
1133         if (deco->sidelen <= 0) {
1134                 errorstream << "register_decoration: sidelen must be "
1135                         "greater than 0" << std::endl;
1136                 delete deco;
1137                 return 0;
1138         }
1139
1140         //// Get node name(s) to place decoration on
1141         size_t nread = getstringlistfield(L, index, "place_on", &deco->m_nodenames);
1142         deco->m_nnlistsizes.push_back(nread);
1143
1144         //// Get decoration flags
1145         getflagsfield(L, index, "flags", flagdesc_deco, &deco->flags, NULL);
1146
1147         //// Get NoiseParams to define how decoration is placed
1148         lua_getfield(L, index, "noise_params");
1149         if (read_noiseparams(L, -1, &deco->np))
1150                 deco->flags |= DECO_USE_NOISE;
1151         lua_pop(L, 1);
1152
1153         //// Get biomes associated with this decoration (if any)
1154         lua_getfield(L, index, "biomes");
1155         if (get_biome_list(L, -1, biomemgr, &deco->biomes))
1156                 infostream << "register_decoration: couldn't get all biomes " << std::endl;
1157         lua_pop(L, 1);
1158
1159         //// Get node name(s) to 'spawn by'
1160         size_t nnames = getstringlistfield(L, index, "spawn_by", &deco->m_nodenames);
1161         deco->m_nnlistsizes.push_back(nnames);
1162         if (nnames == 0 && deco->nspawnby != -1) {
1163                 errorstream << "register_decoration: no spawn_by nodes defined,"
1164                         " but num_spawn_by specified" << std::endl;
1165         }
1166
1167         //// Handle decoration type-specific parameters
1168         bool success = false;
1169         switch (decotype) {
1170         case DECO_SIMPLE:
1171                 success = read_deco_simple(L, (DecoSimple *)deco);
1172                 break;
1173         case DECO_SCHEMATIC:
1174                 success = read_deco_schematic(L, schemmgr, (DecoSchematic *)deco);
1175                 break;
1176         case DECO_LSYSTEM:
1177                 break;
1178         }
1179
1180         if (!success) {
1181                 delete deco;
1182                 return 0;
1183         }
1184
1185         ndef->pendNodeResolve(deco);
1186
1187         ObjDefHandle handle = decomgr->add(deco);
1188         if (handle == OBJDEF_INVALID_HANDLE) {
1189                 delete deco;
1190                 return 0;
1191         }
1192
1193         lua_pushinteger(L, handle);
1194         return 1;
1195 }
1196
1197
1198 bool read_deco_simple(lua_State *L, DecoSimple *deco)
1199 {
1200         int index = 1;
1201         int param2;
1202         int param2_max;
1203
1204         deco->deco_height     = getintfield_default(L, index, "height", 1);
1205         deco->deco_height_max = getintfield_default(L, index, "height_max", 0);
1206
1207         if (deco->deco_height <= 0) {
1208                 errorstream << "register_decoration: simple decoration height"
1209                         " must be greater than 0" << std::endl;
1210                 return false;
1211         }
1212
1213         size_t nnames = getstringlistfield(L, index, "decoration", &deco->m_nodenames);
1214         deco->m_nnlistsizes.push_back(nnames);
1215
1216         if (nnames == 0) {
1217                 errorstream << "register_decoration: no decoration nodes "
1218                         "defined" << std::endl;
1219                 return false;
1220         }
1221
1222         param2 = getintfield_default(L, index, "param2", 0);
1223         param2_max = getintfield_default(L, index, "param2_max", 0);
1224
1225         if (param2 < 0 || param2 > 255 || param2_max < 0 || param2_max > 255) {
1226                 errorstream << "register_decoration: param2 or param2_max out of bounds (0-255)"
1227                         << std::endl;
1228                 return false;
1229         }
1230
1231         deco->deco_param2 = (u8)param2;
1232         deco->deco_param2_max = (u8)param2_max;
1233
1234         return true;
1235 }
1236
1237
1238 bool read_deco_schematic(lua_State *L, SchematicManager *schemmgr, DecoSchematic *deco)
1239 {
1240         int index = 1;
1241
1242         deco->rotation = (Rotation)getenumfield(L, index, "rotation",
1243                 ModApiMapgen::es_Rotation, ROTATE_0);
1244
1245         StringMap replace_names;
1246         lua_getfield(L, index, "replacements");
1247         if (lua_istable(L, -1))
1248                 read_schematic_replacements(L, -1, &replace_names);
1249         lua_pop(L, 1);
1250
1251         lua_getfield(L, index, "schematic");
1252         Schematic *schem = get_or_load_schematic(L, -1, schemmgr, &replace_names);
1253         lua_pop(L, 1);
1254
1255         deco->schematic = schem;
1256         return schem != NULL;
1257 }
1258
1259
1260 // register_ore({lots of stuff})
1261 int ModApiMapgen::l_register_ore(lua_State *L)
1262 {
1263         NO_MAP_LOCK_REQUIRED;
1264
1265         int index = 1;
1266         luaL_checktype(L, index, LUA_TTABLE);
1267
1268         const NodeDefManager *ndef = getServer(L)->getNodeDefManager();
1269         BiomeManager *bmgr    = getServer(L)->getEmergeManager()->biomemgr;
1270         OreManager *oremgr    = getServer(L)->getEmergeManager()->oremgr;
1271
1272         enum OreType oretype = (OreType)getenumfield(L, index,
1273                                 "ore_type", es_OreType, ORE_SCATTER);
1274         Ore *ore = oremgr->create(oretype);
1275         if (!ore) {
1276                 errorstream << "register_ore: ore_type " << oretype << " not implemented\n";
1277                 return 0;
1278         }
1279
1280         ore->name           = getstringfield_default(L, index, "name", "");
1281         ore->ore_param2     = (u8)getintfield_default(L, index, "ore_param2", 0);
1282         ore->clust_scarcity = getintfield_default(L, index, "clust_scarcity", 1);
1283         ore->clust_num_ores = getintfield_default(L, index, "clust_num_ores", 1);
1284         ore->clust_size     = getintfield_default(L, index, "clust_size", 0);
1285         ore->noise          = NULL;
1286         ore->flags          = 0;
1287
1288         //// Get noise_threshold
1289         warn_if_field_exists(L, index, "noise_threshhold",
1290                 "Deprecated: new name is \"noise_threshold\".");
1291
1292         float nthresh;
1293         if (!getfloatfield(L, index, "noise_threshold", nthresh) &&
1294                         !getfloatfield(L, index, "noise_threshhold", nthresh))
1295                 nthresh = 0;
1296         ore->nthresh = nthresh;
1297
1298         //// Get y_min/y_max
1299         warn_if_field_exists(L, index, "height_min",
1300                 "Deprecated: new name is \"y_min\".");
1301         warn_if_field_exists(L, index, "height_max",
1302                 "Deprecated: new name is \"y_max\".");
1303
1304         int ymin, ymax;
1305         if (!getintfield(L, index, "y_min", ymin) &&
1306                 !getintfield(L, index, "height_min", ymin))
1307                 ymin = -31000;
1308         if (!getintfield(L, index, "y_max", ymax) &&
1309                 !getintfield(L, index, "height_max", ymax))
1310                 ymax = 31000;
1311         ore->y_min = ymin;
1312         ore->y_max = ymax;
1313
1314         if (ore->clust_scarcity <= 0 || ore->clust_num_ores <= 0) {
1315                 errorstream << "register_ore: clust_scarcity and clust_num_ores"
1316                         "must be greater than 0" << std::endl;
1317                 delete ore;
1318                 return 0;
1319         }
1320
1321         //// Get flags
1322         getflagsfield(L, index, "flags", flagdesc_ore, &ore->flags, NULL);
1323
1324         //// Get biomes associated with this decoration (if any)
1325         lua_getfield(L, index, "biomes");
1326         if (get_biome_list(L, -1, bmgr, &ore->biomes))
1327                 infostream << "register_ore: couldn't get all biomes " << std::endl;
1328         lua_pop(L, 1);
1329
1330         //// Get noise parameters if needed
1331         lua_getfield(L, index, "noise_params");
1332         if (read_noiseparams(L, -1, &ore->np)) {
1333                 ore->flags |= OREFLAG_USE_NOISE;
1334         } else if (ore->NEEDS_NOISE) {
1335                 errorstream << "register_ore: specified ore type requires valid "
1336                         "'noise_params' parameter" << std::endl;
1337                 delete ore;
1338                 return 0;
1339         }
1340         lua_pop(L, 1);
1341
1342         //// Get type-specific parameters
1343         switch (oretype) {
1344                 case ORE_SHEET: {
1345                         OreSheet *oresheet = (OreSheet *)ore;
1346
1347                         oresheet->column_height_min = getintfield_default(L, index,
1348                                 "column_height_min", 1);
1349                         oresheet->column_height_max = getintfield_default(L, index,
1350                                 "column_height_max", ore->clust_size);
1351                         oresheet->column_midpoint_factor = getfloatfield_default(L, index,
1352                                 "column_midpoint_factor", 0.5f);
1353
1354                         break;
1355                 }
1356                 case ORE_PUFF: {
1357                         OrePuff *orepuff = (OrePuff *)ore;
1358
1359                         lua_getfield(L, index, "np_puff_top");
1360                         read_noiseparams(L, -1, &orepuff->np_puff_top);
1361                         lua_pop(L, 1);
1362
1363                         lua_getfield(L, index, "np_puff_bottom");
1364                         read_noiseparams(L, -1, &orepuff->np_puff_bottom);
1365                         lua_pop(L, 1);
1366
1367                         break;
1368                 }
1369                 case ORE_VEIN: {
1370                         OreVein *orevein = (OreVein *)ore;
1371
1372                         orevein->random_factor = getfloatfield_default(L, index,
1373                                 "random_factor", 1.f);
1374
1375                         break;
1376                 }
1377                 case ORE_STRATUM: {
1378                         OreStratum *orestratum = (OreStratum *)ore;
1379
1380                         lua_getfield(L, index, "np_stratum_thickness");
1381                         if (read_noiseparams(L, -1, &orestratum->np_stratum_thickness))
1382                                 ore->flags |= OREFLAG_USE_NOISE2;
1383                         lua_pop(L, 1);
1384
1385                         orestratum->stratum_thickness = getintfield_default(L, index,
1386                                 "stratum_thickness", 8);
1387
1388                         break;
1389                 }
1390                 default:
1391                         break;
1392         }
1393
1394         ObjDefHandle handle = oremgr->add(ore);
1395         if (handle == OBJDEF_INVALID_HANDLE) {
1396                 delete ore;
1397                 return 0;
1398         }
1399
1400         ore->m_nodenames.push_back(getstringfield_default(L, index, "ore", ""));
1401
1402         size_t nnames = getstringlistfield(L, index, "wherein", &ore->m_nodenames);
1403         ore->m_nnlistsizes.push_back(nnames);
1404
1405         ndef->pendNodeResolve(ore);
1406
1407         lua_pushinteger(L, handle);
1408         return 1;
1409 }
1410
1411
1412 // register_schematic({schematic}, replacements={})
1413 int ModApiMapgen::l_register_schematic(lua_State *L)
1414 {
1415         NO_MAP_LOCK_REQUIRED;
1416
1417         SchematicManager *schemmgr = getServer(L)->getEmergeManager()->schemmgr;
1418
1419         StringMap replace_names;
1420         if (lua_istable(L, 2))
1421                 read_schematic_replacements(L, 2, &replace_names);
1422
1423         Schematic *schem = load_schematic(L, 1, schemmgr->getNodeDef(),
1424                 &replace_names);
1425         if (!schem)
1426                 return 0;
1427
1428         ObjDefHandle handle = schemmgr->add(schem);
1429         if (handle == OBJDEF_INVALID_HANDLE) {
1430                 delete schem;
1431                 return 0;
1432         }
1433
1434         lua_pushinteger(L, handle);
1435         return 1;
1436 }
1437
1438
1439 // clear_registered_biomes()
1440 int ModApiMapgen::l_clear_registered_biomes(lua_State *L)
1441 {
1442         NO_MAP_LOCK_REQUIRED;
1443
1444         BiomeManager *bmgr = getServer(L)->getEmergeManager()->biomemgr;
1445         bmgr->clear();
1446         return 0;
1447 }
1448
1449
1450 // clear_registered_decorations()
1451 int ModApiMapgen::l_clear_registered_decorations(lua_State *L)
1452 {
1453         NO_MAP_LOCK_REQUIRED;
1454
1455         DecorationManager *dmgr = getServer(L)->getEmergeManager()->decomgr;
1456         dmgr->clear();
1457         return 0;
1458 }
1459
1460
1461 // clear_registered_ores()
1462 int ModApiMapgen::l_clear_registered_ores(lua_State *L)
1463 {
1464         NO_MAP_LOCK_REQUIRED;
1465
1466         OreManager *omgr = getServer(L)->getEmergeManager()->oremgr;
1467         omgr->clear();
1468         return 0;
1469 }
1470
1471
1472 // clear_registered_schematics()
1473 int ModApiMapgen::l_clear_registered_schematics(lua_State *L)
1474 {
1475         NO_MAP_LOCK_REQUIRED;
1476
1477         SchematicManager *smgr = getServer(L)->getEmergeManager()->schemmgr;
1478         smgr->clear();
1479         return 0;
1480 }
1481
1482
1483 // generate_ores(vm, p1, p2, [ore_id])
1484 int ModApiMapgen::l_generate_ores(lua_State *L)
1485 {
1486         NO_MAP_LOCK_REQUIRED;
1487
1488         EmergeManager *emerge = getServer(L)->getEmergeManager();
1489
1490         Mapgen mg;
1491         mg.seed = emerge->mgparams->seed;
1492         mg.vm   = LuaVoxelManip::checkobject(L, 1)->vm;
1493         mg.ndef = getServer(L)->getNodeDefManager();
1494
1495         v3s16 pmin = lua_istable(L, 2) ? check_v3s16(L, 2) :
1496                         mg.vm->m_area.MinEdge + v3s16(1,1,1) * MAP_BLOCKSIZE;
1497         v3s16 pmax = lua_istable(L, 3) ? check_v3s16(L, 3) :
1498                         mg.vm->m_area.MaxEdge - v3s16(1,1,1) * MAP_BLOCKSIZE;
1499         sortBoxVerticies(pmin, pmax);
1500
1501         u32 blockseed = Mapgen::getBlockSeed(pmin, mg.seed);
1502
1503         emerge->oremgr->placeAllOres(&mg, blockseed, pmin, pmax);
1504
1505         return 0;
1506 }
1507
1508
1509 // generate_decorations(vm, p1, p2, [deco_id])
1510 int ModApiMapgen::l_generate_decorations(lua_State *L)
1511 {
1512         NO_MAP_LOCK_REQUIRED;
1513
1514         EmergeManager *emerge = getServer(L)->getEmergeManager();
1515
1516         Mapgen mg;
1517         mg.seed = emerge->mgparams->seed;
1518         mg.vm   = LuaVoxelManip::checkobject(L, 1)->vm;
1519         mg.ndef = getServer(L)->getNodeDefManager();
1520
1521         v3s16 pmin = lua_istable(L, 2) ? check_v3s16(L, 2) :
1522                         mg.vm->m_area.MinEdge + v3s16(1,1,1) * MAP_BLOCKSIZE;
1523         v3s16 pmax = lua_istable(L, 3) ? check_v3s16(L, 3) :
1524                         mg.vm->m_area.MaxEdge - v3s16(1,1,1) * MAP_BLOCKSIZE;
1525         sortBoxVerticies(pmin, pmax);
1526
1527         u32 blockseed = Mapgen::getBlockSeed(pmin, mg.seed);
1528
1529         emerge->decomgr->placeAllDecos(&mg, blockseed, pmin, pmax);
1530
1531         return 0;
1532 }
1533
1534
1535 // create_schematic(p1, p2, probability_list, filename, y_slice_prob_list)
1536 int ModApiMapgen::l_create_schematic(lua_State *L)
1537 {
1538         MAP_LOCK_REQUIRED;
1539
1540         const NodeDefManager *ndef = getServer(L)->getNodeDefManager();
1541
1542         const char *filename = luaL_checkstring(L, 4);
1543         CHECK_SECURE_PATH(L, filename, true);
1544
1545         Map *map = &(getEnv(L)->getMap());
1546         Schematic schem;
1547
1548         v3s16 p1 = check_v3s16(L, 1);
1549         v3s16 p2 = check_v3s16(L, 2);
1550         sortBoxVerticies(p1, p2);
1551
1552         std::vector<std::pair<v3s16, u8> > prob_list;
1553         if (lua_istable(L, 3)) {
1554                 lua_pushnil(L);
1555                 while (lua_next(L, 3)) {
1556                         if (lua_istable(L, -1)) {
1557                                 lua_getfield(L, -1, "pos");
1558                                 v3s16 pos = check_v3s16(L, -1);
1559                                 lua_pop(L, 1);
1560
1561                                 u8 prob = getintfield_default(L, -1, "prob", MTSCHEM_PROB_ALWAYS);
1562                                 prob_list.emplace_back(pos, prob);
1563                         }
1564
1565                         lua_pop(L, 1);
1566                 }
1567         }
1568
1569         std::vector<std::pair<s16, u8> > slice_prob_list;
1570         if (lua_istable(L, 5)) {
1571                 lua_pushnil(L);
1572                 while (lua_next(L, 5)) {
1573                         if (lua_istable(L, -1)) {
1574                                 s16 ypos = getintfield_default(L, -1, "ypos", 0);
1575                                 u8 prob  = getintfield_default(L, -1, "prob", MTSCHEM_PROB_ALWAYS);
1576                                 slice_prob_list.emplace_back(ypos, prob);
1577                         }
1578
1579                         lua_pop(L, 1);
1580                 }
1581         }
1582
1583         if (!schem.getSchematicFromMap(map, p1, p2)) {
1584                 errorstream << "create_schematic: failed to get schematic "
1585                         "from map" << std::endl;
1586                 return 0;
1587         }
1588
1589         schem.applyProbabilities(p1, &prob_list, &slice_prob_list);
1590
1591         schem.saveSchematicToFile(filename, ndef);
1592         actionstream << "create_schematic: saved schematic file '"
1593                 << filename << "'." << std::endl;
1594
1595         lua_pushboolean(L, true);
1596         return 1;
1597 }
1598
1599
1600 // place_schematic(p, schematic, rotation,
1601 //     replacements, force_placement, flagstring)
1602 int ModApiMapgen::l_place_schematic(lua_State *L)
1603 {
1604         MAP_LOCK_REQUIRED;
1605
1606         GET_ENV_PTR;
1607
1608         ServerMap *map = &(env->getServerMap());
1609         SchematicManager *schemmgr = getServer(L)->getEmergeManager()->schemmgr;
1610
1611         //// Read position
1612         v3s16 p = check_v3s16(L, 1);
1613
1614         //// Read rotation
1615         int rot = ROTATE_0;
1616         std::string enumstr = readParam<std::string>(L, 3, "");
1617         if (!enumstr.empty())
1618                 string_to_enum(es_Rotation, rot, enumstr);
1619
1620         //// Read force placement
1621         bool force_placement = true;
1622         if (lua_isboolean(L, 5))
1623                 force_placement = readParam<bool>(L, 5);
1624
1625         //// Read node replacements
1626         StringMap replace_names;
1627         if (lua_istable(L, 4))
1628                 read_schematic_replacements(L, 4, &replace_names);
1629
1630         //// Read schematic
1631         Schematic *schem = get_or_load_schematic(L, 2, schemmgr, &replace_names);
1632         if (!schem) {
1633                 errorstream << "place_schematic: failed to get schematic" << std::endl;
1634                 return 0;
1635         }
1636
1637         //// Read flags
1638         u32 flags = 0;
1639         read_flags(L, 6, flagdesc_deco, &flags, NULL);
1640
1641         schem->placeOnMap(map, p, flags, (Rotation)rot, force_placement);
1642
1643         lua_pushboolean(L, true);
1644         return 1;
1645 }
1646
1647
1648 // place_schematic_on_vmanip(vm, p, schematic, rotation,
1649 //     replacements, force_placement, flagstring)
1650 int ModApiMapgen::l_place_schematic_on_vmanip(lua_State *L)
1651 {
1652         NO_MAP_LOCK_REQUIRED;
1653
1654         SchematicManager *schemmgr = getServer(L)->getEmergeManager()->schemmgr;
1655
1656         //// Read VoxelManip object
1657         MMVManip *vm = LuaVoxelManip::checkobject(L, 1)->vm;
1658
1659         //// Read position
1660         v3s16 p = check_v3s16(L, 2);
1661
1662         //// Read rotation
1663         int rot = ROTATE_0;
1664         std::string enumstr = readParam<std::string>(L, 4, "");
1665         if (!enumstr.empty())
1666                 string_to_enum(es_Rotation, rot, std::string(enumstr));
1667
1668         //// Read force placement
1669         bool force_placement = true;
1670         if (lua_isboolean(L, 6))
1671                 force_placement = readParam<bool>(L, 6);
1672
1673         //// Read node replacements
1674         StringMap replace_names;
1675         if (lua_istable(L, 5))
1676                 read_schematic_replacements(L, 5, &replace_names);
1677
1678         //// Read schematic
1679         Schematic *schem = get_or_load_schematic(L, 3, schemmgr, &replace_names);
1680         if (!schem) {
1681                 errorstream << "place_schematic: failed to get schematic" << std::endl;
1682                 return 0;
1683         }
1684
1685         //// Read flags
1686         u32 flags = 0;
1687         read_flags(L, 7, flagdesc_deco, &flags, NULL);
1688
1689         bool schematic_did_fit = schem->placeOnVManip(
1690                 vm, p, flags, (Rotation)rot, force_placement);
1691
1692         lua_pushboolean(L, schematic_did_fit);
1693         return 1;
1694 }
1695
1696
1697 // serialize_schematic(schematic, format, options={...})
1698 int ModApiMapgen::l_serialize_schematic(lua_State *L)
1699 {
1700         NO_MAP_LOCK_REQUIRED;
1701
1702         SchematicManager *schemmgr = getServer(L)->getEmergeManager()->schemmgr;
1703
1704         //// Read options
1705         bool use_comments = getboolfield_default(L, 3, "lua_use_comments", false);
1706         u32 indent_spaces = getintfield_default(L, 3, "lua_num_indent_spaces", 0);
1707
1708         //// Get schematic
1709         bool was_loaded = false;
1710         Schematic *schem = (Schematic *)get_objdef(L, 1, schemmgr);
1711         if (!schem) {
1712                 schem = load_schematic(L, 1, NULL, NULL);
1713                 was_loaded = true;
1714         }
1715         if (!schem) {
1716                 errorstream << "serialize_schematic: failed to get schematic" << std::endl;
1717                 return 0;
1718         }
1719
1720         //// Read format of definition to save as
1721         int schem_format = SCHEM_FMT_MTS;
1722         std::string enumstr = readParam<std::string>(L, 2, "");
1723         if (!enumstr.empty())
1724                 string_to_enum(es_SchematicFormatType, schem_format, enumstr);
1725
1726         //// Serialize to binary string
1727         std::ostringstream os(std::ios_base::binary);
1728         switch (schem_format) {
1729         case SCHEM_FMT_MTS:
1730                 schem->serializeToMts(&os, schem->m_nodenames);
1731                 break;
1732         case SCHEM_FMT_LUA:
1733                 schem->serializeToLua(&os, schem->m_nodenames,
1734                         use_comments, indent_spaces);
1735                 break;
1736         default:
1737                 return 0;
1738         }
1739
1740         if (was_loaded)
1741                 delete schem;
1742
1743         std::string ser = os.str();
1744         lua_pushlstring(L, ser.c_str(), ser.length());
1745         return 1;
1746 }
1747
1748
1749 void ModApiMapgen::Initialize(lua_State *L, int top)
1750 {
1751         API_FCT(get_biome_id);
1752         API_FCT(get_biome_name);
1753         API_FCT(get_heat);
1754         API_FCT(get_humidity);
1755         API_FCT(get_biome_data);
1756         API_FCT(get_mapgen_object);
1757         API_FCT(get_spawn_level);
1758
1759         API_FCT(get_mapgen_params);
1760         API_FCT(set_mapgen_params);
1761         API_FCT(get_mapgen_setting);
1762         API_FCT(set_mapgen_setting);
1763         API_FCT(get_mapgen_setting_noiseparams);
1764         API_FCT(set_mapgen_setting_noiseparams);
1765         API_FCT(set_noiseparams);
1766         API_FCT(get_noiseparams);
1767         API_FCT(set_gen_notify);
1768         API_FCT(get_gen_notify);
1769         API_FCT(get_decoration_id);
1770
1771         API_FCT(register_biome);
1772         API_FCT(register_decoration);
1773         API_FCT(register_ore);
1774         API_FCT(register_schematic);
1775
1776         API_FCT(clear_registered_biomes);
1777         API_FCT(clear_registered_decorations);
1778         API_FCT(clear_registered_ores);
1779         API_FCT(clear_registered_schematics);
1780
1781         API_FCT(generate_ores);
1782         API_FCT(generate_decorations);
1783         API_FCT(create_schematic);
1784         API_FCT(place_schematic);
1785         API_FCT(place_schematic_on_vmanip);
1786         API_FCT(serialize_schematic);
1787 }