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