]> git.lizzy.rs Git - dragonfireclient.git/blob - src/script/lua_api/l_env.cpp
DevTest: Fix broken PNG textures
[dragonfireclient.git] / src / script / lua_api / l_env.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 <algorithm>
21 #include "lua_api/l_env.h"
22 #include "lua_api/l_internal.h"
23 #include "lua_api/l_nodemeta.h"
24 #include "lua_api/l_nodetimer.h"
25 #include "lua_api/l_noise.h"
26 #include "lua_api/l_vmanip.h"
27 #include "common/c_converter.h"
28 #include "common/c_content.h"
29 #include "scripting_server.h"
30 #include "environment.h"
31 #include "mapblock.h"
32 #include "server.h"
33 #include "nodedef.h"
34 #include "daynightratio.h"
35 #include "util/pointedthing.h"
36 #include "mapgen/treegen.h"
37 #include "emerge.h"
38 #include "pathfinder.h"
39 #include "face_position_cache.h"
40 #include "remoteplayer.h"
41 #include "server/luaentity_sao.h"
42 #include "server/player_sao.h"
43 #include "util/string.h"
44 #include "translation.h"
45 #ifndef SERVER
46 #include "client/client.h"
47 #endif
48
49 const EnumString ModApiEnvMod::es_ClearObjectsMode[] =
50 {
51         {CLEAR_OBJECTS_MODE_FULL,  "full"},
52         {CLEAR_OBJECTS_MODE_QUICK, "quick"},
53         {0, NULL},
54 };
55
56 const EnumString ModApiEnvMod::es_BlockStatusType[] =
57 {
58         {ServerEnvironment::BS_UNKNOWN, "unknown"},
59         {ServerEnvironment::BS_EMERGING, "emerging"},
60         {ServerEnvironment::BS_LOADED,  "loaded"},
61         {ServerEnvironment::BS_ACTIVE,  "active"},
62         {0, NULL},
63 };
64
65 ///////////////////////////////////////////////////////////////////////////////
66
67
68 void LuaABM::trigger(ServerEnvironment *env, v3s16 p, MapNode n,
69                 u32 active_object_count, u32 active_object_count_wider)
70 {
71         ServerScripting *scriptIface = env->getScriptIface();
72         scriptIface->realityCheck();
73
74         lua_State *L = scriptIface->getStack();
75         sanity_check(lua_checkstack(L, 20));
76         StackUnroller stack_unroller(L);
77
78         int error_handler = PUSH_ERROR_HANDLER(L);
79
80         // Get registered_abms
81         lua_getglobal(L, "core");
82         lua_getfield(L, -1, "registered_abms");
83         luaL_checktype(L, -1, LUA_TTABLE);
84         lua_remove(L, -2); // Remove core
85
86         // Get registered_abms[m_id]
87         lua_pushinteger(L, m_id);
88         lua_gettable(L, -2);
89         if(lua_isnil(L, -1))
90                 FATAL_ERROR("");
91         lua_remove(L, -2); // Remove registered_abms
92
93         scriptIface->setOriginFromTable(-1);
94
95         // Call action
96         luaL_checktype(L, -1, LUA_TTABLE);
97         lua_getfield(L, -1, "action");
98         luaL_checktype(L, -1, LUA_TFUNCTION);
99         lua_remove(L, -2); // Remove registered_abms[m_id]
100         push_v3s16(L, p);
101         pushnode(L, n, env->getGameDef()->ndef());
102         lua_pushnumber(L, active_object_count);
103         lua_pushnumber(L, active_object_count_wider);
104
105         int result = lua_pcall(L, 4, 0, error_handler);
106         if (result)
107                 scriptIface->scriptError(result, "LuaABM::trigger");
108
109         lua_pop(L, 1); // Pop error handler
110 }
111
112 void LuaLBM::trigger(ServerEnvironment *env, v3s16 p, MapNode n)
113 {
114         ServerScripting *scriptIface = env->getScriptIface();
115         scriptIface->realityCheck();
116
117         lua_State *L = scriptIface->getStack();
118         sanity_check(lua_checkstack(L, 20));
119         StackUnroller stack_unroller(L);
120
121         int error_handler = PUSH_ERROR_HANDLER(L);
122
123         // Get registered_lbms
124         lua_getglobal(L, "core");
125         lua_getfield(L, -1, "registered_lbms");
126         luaL_checktype(L, -1, LUA_TTABLE);
127         lua_remove(L, -2); // Remove core
128
129         // Get registered_lbms[m_id]
130         lua_pushinteger(L, m_id);
131         lua_gettable(L, -2);
132         FATAL_ERROR_IF(lua_isnil(L, -1), "Entry with given id not found in registered_lbms table");
133         lua_remove(L, -2); // Remove registered_lbms
134
135         scriptIface->setOriginFromTable(-1);
136
137         // Call action
138         luaL_checktype(L, -1, LUA_TTABLE);
139         lua_getfield(L, -1, "action");
140         luaL_checktype(L, -1, LUA_TFUNCTION);
141         lua_remove(L, -2); // Remove registered_lbms[m_id]
142         push_v3s16(L, p);
143         pushnode(L, n, env->getGameDef()->ndef());
144
145         int result = lua_pcall(L, 2, 0, error_handler);
146         if (result)
147                 scriptIface->scriptError(result, "LuaLBM::trigger");
148
149         lua_pop(L, 1); // Pop error handler
150 }
151
152 int LuaRaycast::l_next(lua_State *L)
153 {
154         GET_PLAIN_ENV_PTR;
155
156         bool csm = false;
157 #ifndef SERVER
158         csm = getClient(L) != nullptr;
159 #endif
160
161         LuaRaycast *o = checkobject(L, 1);
162         PointedThing pointed;
163         env->continueRaycast(&o->state, &pointed);
164         if (pointed.type == POINTEDTHING_NOTHING)
165                 lua_pushnil(L);
166         else
167                 push_pointed_thing(L, pointed, csm, true);
168
169         return 1;
170 }
171
172 int LuaRaycast::create_object(lua_State *L)
173 {
174         NO_MAP_LOCK_REQUIRED;
175
176         bool objects = true;
177         bool liquids = false;
178
179         v3f pos1 = checkFloatPos(L, 1);
180         v3f pos2 = checkFloatPos(L, 2);
181         if (lua_isboolean(L, 3)) {
182                 objects = readParam<bool>(L, 3);
183         }
184         if (lua_isboolean(L, 4)) {
185                 liquids = readParam<bool>(L, 4);
186         }
187
188         LuaRaycast *o = new LuaRaycast(core::line3d<f32>(pos1, pos2),
189                 objects, liquids);
190
191         *(void **) (lua_newuserdata(L, sizeof(void *))) = o;
192         luaL_getmetatable(L, className);
193         lua_setmetatable(L, -2);
194         return 1;
195 }
196
197 LuaRaycast *LuaRaycast::checkobject(lua_State *L, int narg)
198 {
199         NO_MAP_LOCK_REQUIRED;
200
201         luaL_checktype(L, narg, LUA_TUSERDATA);
202         void *ud = luaL_checkudata(L, narg, className);
203         if (!ud)
204                 luaL_typerror(L, narg, className);
205         return *(LuaRaycast **) ud;
206 }
207
208 int LuaRaycast::gc_object(lua_State *L)
209 {
210         LuaRaycast *o = *(LuaRaycast **) (lua_touserdata(L, 1));
211         delete o;
212         return 0;
213 }
214
215 void LuaRaycast::Register(lua_State *L)
216 {
217         lua_newtable(L);
218         int methodtable = lua_gettop(L);
219         luaL_newmetatable(L, className);
220         int metatable = lua_gettop(L);
221
222         lua_pushliteral(L, "__metatable");
223         lua_pushvalue(L, methodtable);
224         lua_settable(L, metatable);
225
226         lua_pushliteral(L, "__index");
227         lua_pushvalue(L, methodtable);
228         lua_settable(L, metatable);
229
230         lua_pushliteral(L, "__gc");
231         lua_pushcfunction(L, gc_object);
232         lua_settable(L, metatable);
233
234         lua_pushliteral(L, "__call");
235         lua_pushcfunction(L, l_next);
236         lua_settable(L, metatable);
237
238         lua_pop(L, 1);
239
240         luaL_register(L, nullptr, methods);
241         lua_pop(L, 1);
242
243         lua_register(L, className, create_object);
244 }
245
246 const char LuaRaycast::className[] = "Raycast";
247 const luaL_Reg LuaRaycast::methods[] =
248 {
249         luamethod(LuaRaycast, next),
250         { 0, 0 }
251 };
252
253 void LuaEmergeAreaCallback(v3s16 blockpos, EmergeAction action, void *param)
254 {
255         ScriptCallbackState *state = (ScriptCallbackState *)param;
256         assert(state != NULL);
257         assert(state->script != NULL);
258         assert(state->refcount > 0);
259
260         // state must be protected by envlock
261         Server *server = state->script->getServer();
262         MutexAutoLock envlock(server->m_env_mutex);
263
264         state->refcount--;
265
266         state->script->on_emerge_area_completion(blockpos, action, state);
267
268         if (state->refcount == 0)
269                 delete state;
270 }
271
272 // Exported functions
273
274 // set_node(pos, node)
275 // pos = {x=num, y=num, z=num}
276 int ModApiEnvMod::l_set_node(lua_State *L)
277 {
278         GET_ENV_PTR;
279
280         const NodeDefManager *ndef = env->getGameDef()->ndef();
281         // parameters
282         v3s16 pos = read_v3s16(L, 1);
283         MapNode n = readnode(L, 2, ndef);
284         // Do it
285         bool succeeded = env->setNode(pos, n);
286         lua_pushboolean(L, succeeded);
287         return 1;
288 }
289
290 // bulk_set_node([pos1, pos2, ...], node)
291 // pos = {x=num, y=num, z=num}
292 int ModApiEnvMod::l_bulk_set_node(lua_State *L)
293 {
294         GET_ENV_PTR;
295
296         const NodeDefManager *ndef = env->getGameDef()->ndef();
297         // parameters
298         if (!lua_istable(L, 1)) {
299                 return 0;
300         }
301
302         s32 len = lua_objlen(L, 1);
303         if (len == 0) {
304                 lua_pushboolean(L, true);
305                 return 1;
306         }
307
308         MapNode n = readnode(L, 2, ndef);
309
310         // Do it
311         bool succeeded = true;
312         for (s32 i = 1; i <= len; i++) {
313                 lua_rawgeti(L, 1, i);
314                 if (!env->setNode(read_v3s16(L, -1), n))
315                         succeeded = false;
316                 lua_pop(L, 1);
317         }
318
319         lua_pushboolean(L, succeeded);
320         return 1;
321 }
322
323 int ModApiEnvMod::l_add_node(lua_State *L)
324 {
325         return l_set_node(L);
326 }
327
328 // remove_node(pos)
329 // pos = {x=num, y=num, z=num}
330 int ModApiEnvMod::l_remove_node(lua_State *L)
331 {
332         GET_ENV_PTR;
333
334         // parameters
335         v3s16 pos = read_v3s16(L, 1);
336         // Do it
337         bool succeeded = env->removeNode(pos);
338         lua_pushboolean(L, succeeded);
339         return 1;
340 }
341
342 // swap_node(pos, node)
343 // pos = {x=num, y=num, z=num}
344 int ModApiEnvMod::l_swap_node(lua_State *L)
345 {
346         GET_ENV_PTR;
347
348         const NodeDefManager *ndef = env->getGameDef()->ndef();
349         // parameters
350         v3s16 pos = read_v3s16(L, 1);
351         MapNode n = readnode(L, 2, ndef);
352         // Do it
353         bool succeeded = env->swapNode(pos, n);
354         lua_pushboolean(L, succeeded);
355         return 1;
356 }
357
358 // get_node(pos)
359 // pos = {x=num, y=num, z=num}
360 int ModApiEnvMod::l_get_node(lua_State *L)
361 {
362         GET_ENV_PTR;
363
364         // pos
365         v3s16 pos = read_v3s16(L, 1);
366         // Do it
367         MapNode n = env->getMap().getNode(pos);
368         // Return node
369         pushnode(L, n, env->getGameDef()->ndef());
370         return 1;
371 }
372
373 // get_node_or_nil(pos)
374 // pos = {x=num, y=num, z=num}
375 int ModApiEnvMod::l_get_node_or_nil(lua_State *L)
376 {
377         GET_ENV_PTR;
378
379         // pos
380         v3s16 pos = read_v3s16(L, 1);
381         // Do it
382         bool pos_ok;
383         MapNode n = env->getMap().getNode(pos, &pos_ok);
384         if (pos_ok) {
385                 // Return node
386                 pushnode(L, n, env->getGameDef()->ndef());
387         } else {
388                 lua_pushnil(L);
389         }
390         return 1;
391 }
392
393 // get_node_light(pos, timeofday)
394 // pos = {x=num, y=num, z=num}
395 // timeofday: nil = current time, 0 = night, 0.5 = day
396 int ModApiEnvMod::l_get_node_light(lua_State *L)
397 {
398         GET_PLAIN_ENV_PTR;
399
400         // Do it
401         v3s16 pos = read_v3s16(L, 1);
402         u32 time_of_day = env->getTimeOfDay();
403         if(lua_isnumber(L, 2))
404                 time_of_day = 24000.0 * lua_tonumber(L, 2);
405         time_of_day %= 24000;
406         u32 dnr = time_to_daynight_ratio(time_of_day, true);
407
408         bool is_position_ok;
409         MapNode n = env->getMap().getNode(pos, &is_position_ok);
410         if (is_position_ok) {
411                 const NodeDefManager *ndef = env->getGameDef()->ndef();
412                 lua_pushinteger(L, n.getLightBlend(dnr, ndef));
413         } else {
414                 lua_pushnil(L);
415         }
416         return 1;
417 }
418
419
420 // get_natural_light(pos, timeofday)
421 // pos = {x=num, y=num, z=num}
422 // timeofday: nil = current time, 0 = night, 0.5 = day
423 int ModApiEnvMod::l_get_natural_light(lua_State *L)
424 {
425         GET_ENV_PTR;
426
427         v3s16 pos = read_v3s16(L, 1);
428
429         bool is_position_ok;
430         MapNode n = env->getMap().getNode(pos, &is_position_ok);
431         if (!is_position_ok)
432                 return 0;
433
434         // If the daylight is 0, nothing needs to be calculated
435         u8 daylight = n.param1 & 0x0f;
436         if (daylight == 0) {
437                 lua_pushinteger(L, 0);
438                 return 1;
439         }
440
441         u32 time_of_day;
442         if (lua_isnumber(L, 2)) {
443                 time_of_day = 24000.0 * lua_tonumber(L, 2);
444                 time_of_day %= 24000;
445         } else {
446                 time_of_day = env->getTimeOfDay();
447         }
448         u32 dnr = time_to_daynight_ratio(time_of_day, true);
449
450         // If it's the same as the artificial light, the sunlight needs to be
451         // searched for because the value may not emanate from the sun
452         if (daylight == n.param1 >> 4)
453                 daylight = env->findSunlight(pos);
454
455         lua_pushinteger(L, dnr * daylight / 1000);
456         return 1;
457 }
458
459 // place_node(pos, node)
460 // pos = {x=num, y=num, z=num}
461 int ModApiEnvMod::l_place_node(lua_State *L)
462 {
463         GET_ENV_PTR;
464
465         ScriptApiItem *scriptIfaceItem = getScriptApi<ScriptApiItem>(L);
466         Server *server = getServer(L);
467         const NodeDefManager *ndef = server->ndef();
468         IItemDefManager *idef = server->idef();
469
470         v3s16 pos = read_v3s16(L, 1);
471         MapNode n = readnode(L, 2, ndef);
472
473         // Don't attempt to load non-loaded area as of now
474         MapNode n_old = env->getMap().getNode(pos);
475         if(n_old.getContent() == CONTENT_IGNORE){
476                 lua_pushboolean(L, false);
477                 return 1;
478         }
479         // Create item to place
480         Optional<ItemStack> item = ItemStack(ndef->get(n).name, 1, 0, idef);
481         // Make pointed position
482         PointedThing pointed;
483         pointed.type = POINTEDTHING_NODE;
484         pointed.node_abovesurface = pos;
485         pointed.node_undersurface = pos + v3s16(0,-1,0);
486         // Place it with a NULL placer (appears in Lua as nil)
487         bool success = scriptIfaceItem->item_OnPlace(item, nullptr, pointed);
488         lua_pushboolean(L, success);
489         return 1;
490 }
491
492 // dig_node(pos)
493 // pos = {x=num, y=num, z=num}
494 int ModApiEnvMod::l_dig_node(lua_State *L)
495 {
496         GET_ENV_PTR;
497
498         ScriptApiNode *scriptIfaceNode = getScriptApi<ScriptApiNode>(L);
499
500         v3s16 pos = read_v3s16(L, 1);
501
502         // Don't attempt to load non-loaded area as of now
503         MapNode n = env->getMap().getNode(pos);
504         if(n.getContent() == CONTENT_IGNORE){
505                 lua_pushboolean(L, false);
506                 return 1;
507         }
508         // Dig it out with a NULL digger (appears in Lua as a
509         // non-functional ObjectRef)
510         bool success = scriptIfaceNode->node_on_dig(pos, n, NULL);
511         lua_pushboolean(L, success);
512         return 1;
513 }
514
515 // punch_node(pos)
516 // pos = {x=num, y=num, z=num}
517 int ModApiEnvMod::l_punch_node(lua_State *L)
518 {
519         GET_ENV_PTR;
520
521         ScriptApiNode *scriptIfaceNode = getScriptApi<ScriptApiNode>(L);
522
523         v3s16 pos = read_v3s16(L, 1);
524
525         // Don't attempt to load non-loaded area as of now
526         MapNode n = env->getMap().getNode(pos);
527         if(n.getContent() == CONTENT_IGNORE){
528                 lua_pushboolean(L, false);
529                 return 1;
530         }
531         // Punch it with a NULL puncher (appears in Lua as a non-functional
532         // ObjectRef)
533         bool success = scriptIfaceNode->node_on_punch(pos, n, NULL, PointedThing());
534         lua_pushboolean(L, success);
535         return 1;
536 }
537
538 // get_node_max_level(pos)
539 // pos = {x=num, y=num, z=num}
540 int ModApiEnvMod::l_get_node_max_level(lua_State *L)
541 {
542         GET_PLAIN_ENV_PTR;
543
544         v3s16 pos = read_v3s16(L, 1);
545         MapNode n = env->getMap().getNode(pos);
546         lua_pushnumber(L, n.getMaxLevel(env->getGameDef()->ndef()));
547         return 1;
548 }
549
550 // get_node_level(pos)
551 // pos = {x=num, y=num, z=num}
552 int ModApiEnvMod::l_get_node_level(lua_State *L)
553 {
554         GET_PLAIN_ENV_PTR;
555
556         v3s16 pos = read_v3s16(L, 1);
557         MapNode n = env->getMap().getNode(pos);
558         lua_pushnumber(L, n.getLevel(env->getGameDef()->ndef()));
559         return 1;
560 }
561
562 // set_node_level(pos, level)
563 // pos = {x=num, y=num, z=num}
564 // level: 0..63
565 int ModApiEnvMod::l_set_node_level(lua_State *L)
566 {
567         GET_ENV_PTR;
568
569         v3s16 pos = read_v3s16(L, 1);
570         u8 level = 1;
571         if(lua_isnumber(L, 2))
572                 level = lua_tonumber(L, 2);
573         MapNode n = env->getMap().getNode(pos);
574         lua_pushnumber(L, n.setLevel(env->getGameDef()->ndef(), level));
575         env->setNode(pos, n);
576         return 1;
577 }
578
579 // add_node_level(pos, level)
580 // pos = {x=num, y=num, z=num}
581 // level: -127..127
582 int ModApiEnvMod::l_add_node_level(lua_State *L)
583 {
584         GET_ENV_PTR;
585
586         v3s16 pos = read_v3s16(L, 1);
587         s16 level = 1;
588         if(lua_isnumber(L, 2))
589                 level = lua_tonumber(L, 2);
590         MapNode n = env->getMap().getNode(pos);
591         lua_pushnumber(L, n.addLevel(env->getGameDef()->ndef(), level));
592         env->setNode(pos, n);
593         return 1;
594 }
595
596 // find_nodes_with_meta(pos1, pos2)
597 int ModApiEnvMod::l_find_nodes_with_meta(lua_State *L)
598 {
599         GET_PLAIN_ENV_PTR;
600
601         std::vector<v3s16> positions = env->getMap().findNodesWithMetadata(
602                 check_v3s16(L, 1), check_v3s16(L, 2));
603
604         lua_createtable(L, positions.size(), 0);
605         for (size_t i = 0; i != positions.size(); i++) {
606                 push_v3s16(L, positions[i]);
607                 lua_rawseti(L, -2, i + 1);
608         }
609
610         return 1;
611 }
612
613 // get_meta(pos)
614 int ModApiEnvMod::l_get_meta(lua_State *L)
615 {
616         GET_ENV_PTR;
617
618         // Do it
619         v3s16 p = read_v3s16(L, 1);
620         NodeMetaRef::create(L, p, env);
621         return 1;
622 }
623
624 // get_node_timer(pos)
625 int ModApiEnvMod::l_get_node_timer(lua_State *L)
626 {
627         GET_ENV_PTR;
628
629         // Do it
630         v3s16 p = read_v3s16(L, 1);
631         NodeTimerRef::create(L, p, &env->getServerMap());
632         return 1;
633 }
634
635 // add_entity(pos, entityname, [staticdata]) -> ObjectRef or nil
636 // pos = {x=num, y=num, z=num}
637 int ModApiEnvMod::l_add_entity(lua_State *L)
638 {
639         GET_ENV_PTR;
640
641         v3f pos = checkFloatPos(L, 1);
642         const char *name = luaL_checkstring(L, 2);
643         const char *staticdata = luaL_optstring(L, 3, "");
644
645         ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, staticdata);
646         int objectid = env->addActiveObject(obj);
647         // If failed to add, return nothing (reads as nil)
648         if(objectid == 0)
649                 return 0;
650
651         // If already deleted (can happen in on_activate), return nil
652         if (obj->isGone())
653                 return 0;
654         getScriptApiBase(L)->objectrefGetOrCreate(L, obj);
655         return 1;
656 }
657
658 // add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
659 // pos = {x=num, y=num, z=num}
660 int ModApiEnvMod::l_add_item(lua_State *L)
661 {
662         GET_ENV_PTR;
663
664         // pos
665         //v3f pos = checkFloatPos(L, 1);
666         // item
667         ItemStack item = read_item(L, 2,getServer(L)->idef());
668         if(item.empty() || !item.isKnown(getServer(L)->idef()))
669                 return 0;
670
671         int error_handler = PUSH_ERROR_HANDLER(L);
672
673         // Use spawn_item to spawn a __builtin:item
674         lua_getglobal(L, "core");
675         lua_getfield(L, -1, "spawn_item");
676         lua_remove(L, -2); // Remove core
677         if(lua_isnil(L, -1))
678                 return 0;
679         lua_pushvalue(L, 1);
680         lua_pushstring(L, item.getItemString().c_str());
681
682         PCALL_RESL(L, lua_pcall(L, 2, 1, error_handler));
683
684         lua_remove(L, error_handler);
685         return 1;
686 }
687
688 // get_connected_players()
689 int ModApiEnvMod::l_get_connected_players(lua_State *L)
690 {
691         ServerEnvironment *env = (ServerEnvironment *) getEnv(L);
692         if (!env) {
693                 log_deprecated(L, "Calling get_connected_players() at mod load time"
694                                 " is deprecated");
695                 lua_createtable(L, 0, 0);
696                 return 1;
697         }
698
699         lua_createtable(L, env->getPlayerCount(), 0);
700         u32 i = 0;
701         for (RemotePlayer *player : env->getPlayers()) {
702                 if (player->getPeerId() == PEER_ID_INEXISTENT)
703                         continue;
704                 PlayerSAO *sao = player->getPlayerSAO();
705                 if (sao && !sao->isGone()) {
706                         getScriptApiBase(L)->objectrefGetOrCreate(L, sao);
707                         lua_rawseti(L, -2, ++i);
708                 }
709         }
710         return 1;
711 }
712
713 // get_player_by_name(name)
714 int ModApiEnvMod::l_get_player_by_name(lua_State *L)
715 {
716         GET_ENV_PTR;
717
718         // Do it
719         const char *name = luaL_checkstring(L, 1);
720         RemotePlayer *player = env->getPlayer(name);
721         if (!player || player->getPeerId() == PEER_ID_INEXISTENT)
722                 return 0;
723         PlayerSAO *sao = player->getPlayerSAO();
724         if (!sao || sao->isGone())
725                 return 0;
726         // Put player on stack
727         getScriptApiBase(L)->objectrefGetOrCreate(L, sao);
728         return 1;
729 }
730
731 // get_objects_inside_radius(pos, radius)
732 int ModApiEnvMod::l_get_objects_inside_radius(lua_State *L)
733 {
734         GET_ENV_PTR;
735         ScriptApiBase *script = getScriptApiBase(L);
736
737         // Do it
738         v3f pos = checkFloatPos(L, 1);
739         float radius = readParam<float>(L, 2) * BS;
740         std::vector<ServerActiveObject *> objs;
741
742         auto include_obj_cb = [](ServerActiveObject *obj){ return !obj->isGone(); };
743         env->getObjectsInsideRadius(objs, pos, radius, include_obj_cb);
744
745         int i = 0;
746         lua_createtable(L, objs.size(), 0);
747         for (const auto obj : objs) {
748                 // Insert object reference into table
749                 script->objectrefGetOrCreate(L, obj);
750                 lua_rawseti(L, -2, ++i);
751         }
752         return 1;
753 }
754
755 // get_objects_in_area(pos, minp, maxp)
756 int ModApiEnvMod::l_get_objects_in_area(lua_State *L)
757 {
758         GET_ENV_PTR;
759         ScriptApiBase *script = getScriptApiBase(L);
760
761         v3f minp = read_v3f(L, 1) * BS;
762         v3f maxp = read_v3f(L, 2) * BS;
763         aabb3f box(minp, maxp);
764         box.repair();
765         std::vector<ServerActiveObject *> objs;
766
767         auto include_obj_cb = [](ServerActiveObject *obj){ return !obj->isGone(); };
768         env->getObjectsInArea(objs, box, include_obj_cb);
769
770         int i = 0;
771         lua_createtable(L, objs.size(), 0);
772         for (const auto obj : objs) {
773                 // Insert object reference into table
774                 script->objectrefGetOrCreate(L, obj);
775                 lua_rawseti(L, -2, ++i);
776         }
777         return 1;
778 }
779
780 // set_timeofday(val)
781 // val = 0...1
782 int ModApiEnvMod::l_set_timeofday(lua_State *L)
783 {
784         GET_ENV_PTR;
785
786         // Do it
787         float timeofday_f = readParam<float>(L, 1);
788         luaL_argcheck(L, timeofday_f >= 0.0f && timeofday_f <= 1.0f, 1,
789                 "value must be between 0 and 1");
790         int timeofday_mh = (int)(timeofday_f * 24000.0f);
791         // This should be set directly in the environment but currently
792         // such changes aren't immediately sent to the clients, so call
793         // the server instead.
794         //env->setTimeOfDay(timeofday_mh);
795         getServer(L)->setTimeOfDay(timeofday_mh);
796         return 0;
797 }
798
799 // get_timeofday() -> 0...1
800 int ModApiEnvMod::l_get_timeofday(lua_State *L)
801 {
802         GET_PLAIN_ENV_PTR;
803
804         // Do it
805         int timeofday_mh = env->getTimeOfDay();
806         float timeofday_f = (float)timeofday_mh / 24000.0f;
807         lua_pushnumber(L, timeofday_f);
808         return 1;
809 }
810
811 // get_day_count() -> int
812 int ModApiEnvMod::l_get_day_count(lua_State *L)
813 {
814         GET_PLAIN_ENV_PTR;
815
816         lua_pushnumber(L, env->getDayCount());
817         return 1;
818 }
819
820 // get_gametime()
821 int ModApiEnvMod::l_get_gametime(lua_State *L)
822 {
823         GET_ENV_PTR;
824
825         int game_time = env->getGameTime();
826         lua_pushnumber(L, game_time);
827         return 1;
828 }
829
830 void ModApiEnvMod::collectNodeIds(lua_State *L, int idx, const NodeDefManager *ndef,
831         std::vector<content_t> &filter)
832 {
833         if (lua_istable(L, idx)) {
834                 lua_pushnil(L);
835                 while (lua_next(L, idx) != 0) {
836                         // key at index -2 and value at index -1
837                         luaL_checktype(L, -1, LUA_TSTRING);
838                         ndef->getIds(readParam<std::string>(L, -1), filter);
839                         // removes value, keeps key for next iteration
840                         lua_pop(L, 1);
841                 }
842         } else if (lua_isstring(L, idx)) {
843                 ndef->getIds(readParam<std::string>(L, 3), filter);
844         }
845 }
846
847 // find_node_near(pos, radius, nodenames, [search_center]) -> pos or nil
848 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
849 int ModApiEnvMod::l_find_node_near(lua_State *L)
850 {
851         GET_PLAIN_ENV_PTR;
852
853         const NodeDefManager *ndef = env->getGameDef()->ndef();
854         Map &map = env->getMap();
855
856         v3s16 pos = read_v3s16(L, 1);
857         int radius = luaL_checkinteger(L, 2);
858         std::vector<content_t> filter;
859         collectNodeIds(L, 3, ndef, filter);
860
861         int start_radius = (lua_isboolean(L, 4) && readParam<bool>(L, 4)) ? 0 : 1;
862
863 #ifndef SERVER
864         // Client API limitations
865         if (Client *client = getClient(L))
866                 radius = client->CSMClampRadius(pos, radius);
867 #endif
868
869         for (int d = start_radius; d <= radius; d++) {
870                 const std::vector<v3s16> &list = FacePositionCache::getFacePositions(d);
871                 for (const v3s16 &i : list) {
872                         v3s16 p = pos + i;
873                         content_t c = map.getNode(p).getContent();
874                         if (CONTAINS(filter, c)) {
875                                 push_v3s16(L, p);
876                                 return 1;
877                         }
878                 }
879         }
880         return 0;
881 }
882
883 static void checkArea(v3s16 &minp, v3s16 &maxp)
884 {
885         auto volume = VoxelArea(minp, maxp).getVolume();
886         // Volume limit equal to 8 default mapchunks, (80 * 2) ^ 3 = 4,096,000
887         if (volume > 4096000) {
888                 throw LuaError("Area volume exceeds allowed value of 4096000");
889         }
890
891         // Clamp to map range to avoid problems
892 #define CLAMP(arg) core::clamp(arg, (s16)-MAX_MAP_GENERATION_LIMIT, (s16)MAX_MAP_GENERATION_LIMIT)
893         minp = v3s16(CLAMP(minp.X), CLAMP(minp.Y), CLAMP(minp.Z));
894         maxp = v3s16(CLAMP(maxp.X), CLAMP(maxp.Y), CLAMP(maxp.Z));
895 #undef CLAMP
896 }
897
898 // find_nodes_in_area(minp, maxp, nodenames, [grouped])
899 int ModApiEnvMod::l_find_nodes_in_area(lua_State *L)
900 {
901         GET_PLAIN_ENV_PTR;
902
903         v3s16 minp = read_v3s16(L, 1);
904         v3s16 maxp = read_v3s16(L, 2);
905         sortBoxVerticies(minp, maxp);
906
907         const NodeDefManager *ndef = env->getGameDef()->ndef();
908         Map &map = env->getMap();
909
910 #ifndef SERVER
911         if (Client *client = getClient(L)) {
912                 minp = client->CSMClampPos(minp);
913                 maxp = client->CSMClampPos(maxp);
914         }
915 #endif
916
917         checkArea(minp, maxp);
918
919         std::vector<content_t> filter;
920         collectNodeIds(L, 3, ndef, filter);
921
922         bool grouped = lua_isboolean(L, 4) && readParam<bool>(L, 4);
923
924         if (grouped) {
925                 // create the table we will be returning
926                 lua_createtable(L, 0, filter.size());
927                 int base = lua_gettop(L);
928
929                 // create one table for each filter
930                 std::vector<u32> idx;
931                 idx.resize(filter.size());
932                 for (u32 i = 0; i < filter.size(); i++)
933                         lua_newtable(L);
934
935                 v3s16 p;
936                 for (p.X = minp.X; p.X <= maxp.X; p.X++)
937                 for (p.Y = minp.Y; p.Y <= maxp.Y; p.Y++)
938                 for (p.Z = minp.Z; p.Z <= maxp.Z; p.Z++) {
939                         content_t c = map.getNode(p).getContent();
940
941                         auto it = std::find(filter.begin(), filter.end(), c);
942                         if (it != filter.end()) {
943                                 // Calculate index of the table and append the position
944                                 u32 filt_index = it - filter.begin();
945                                 push_v3s16(L, p);
946                                 lua_rawseti(L, base + 1 + filt_index, ++idx[filt_index]);
947                         }
948                 }
949
950                 // last filter table is at top of stack
951                 u32 i = filter.size() - 1;
952                 do {
953                         if (idx[i] == 0) {
954                                 // No such node found -> drop the empty table
955                                 lua_pop(L, 1);
956                         } else {
957                                 // This node was found -> put table into the return table
958                                 lua_setfield(L, base, ndef->get(filter[i]).name.c_str());
959                         }
960                 } while (i-- != 0);
961
962                 assert(lua_gettop(L) == base);
963                 return 1;
964         } else {
965                 std::vector<u32> individual_count;
966                 individual_count.resize(filter.size());
967
968                 lua_newtable(L);
969                 u32 i = 0;
970                 v3s16 p;
971                 for (p.X = minp.X; p.X <= maxp.X; p.X++)
972                 for (p.Y = minp.Y; p.Y <= maxp.Y; p.Y++)
973                 for (p.Z = minp.Z; p.Z <= maxp.Z; p.Z++) {
974                         content_t c = env->getMap().getNode(p).getContent();
975
976                         auto it = std::find(filter.begin(), filter.end(), c);
977                         if (it != filter.end()) {
978                                 push_v3s16(L, p);
979                                 lua_rawseti(L, -2, ++i);
980
981                                 u32 filt_index = it - filter.begin();
982                                 individual_count[filt_index]++;
983                         }
984                 }
985
986                 lua_createtable(L, 0, filter.size());
987                 for (u32 i = 0; i < filter.size(); i++) {
988                         lua_pushinteger(L, individual_count[i]);
989                         lua_setfield(L, -2, ndef->get(filter[i]).name.c_str());
990                 }
991                 return 2;
992         }
993 }
994
995 // find_nodes_in_area_under_air(minp, maxp, nodenames) -> list of positions
996 // nodenames: e.g. {"ignore", "group:tree"} or "default:dirt"
997 int ModApiEnvMod::l_find_nodes_in_area_under_air(lua_State *L)
998 {
999         /* Note: A similar but generalized (and therefore slower) version of this
1000          * function could be created -- e.g. find_nodes_in_area_under -- which
1001          * would accept a node name (or ID?) or list of names that the "above node"
1002          * should be.
1003          * TODO
1004          */
1005
1006         GET_PLAIN_ENV_PTR;
1007
1008         v3s16 minp = read_v3s16(L, 1);
1009         v3s16 maxp = read_v3s16(L, 2);
1010         sortBoxVerticies(minp, maxp);
1011
1012         const NodeDefManager *ndef = env->getGameDef()->ndef();
1013         Map &map = env->getMap();
1014
1015 #ifndef SERVER
1016         if (Client *client = getClient(L)) {
1017                 minp = client->CSMClampPos(minp);
1018                 maxp = client->CSMClampPos(maxp);
1019         }
1020 #endif
1021
1022         checkArea(minp, maxp);
1023
1024         std::vector<content_t> filter;
1025         collectNodeIds(L, 3, ndef, filter);
1026
1027         lua_newtable(L);
1028         u32 i = 0;
1029         v3s16 p;
1030         for (p.X = minp.X; p.X <= maxp.X; p.X++)
1031         for (p.Z = minp.Z; p.Z <= maxp.Z; p.Z++) {
1032                 p.Y = minp.Y;
1033                 content_t c = map.getNode(p).getContent();
1034                 for (; p.Y <= maxp.Y; p.Y++) {
1035                         v3s16 psurf(p.X, p.Y + 1, p.Z);
1036                         content_t csurf = map.getNode(psurf).getContent();
1037                         if (c != CONTENT_AIR && csurf == CONTENT_AIR &&
1038                                         CONTAINS(filter, c)) {
1039                                 push_v3s16(L, p);
1040                                 lua_rawseti(L, -2, ++i);
1041                         }
1042                         c = csurf;
1043                 }
1044         }
1045         return 1;
1046 }
1047
1048 // get_perlin(seeddiff, octaves, persistence, scale)
1049 // returns world-specific PerlinNoise
1050 int ModApiEnvMod::l_get_perlin(lua_State *L)
1051 {
1052         GET_ENV_PTR_NO_MAP_LOCK;
1053
1054         NoiseParams params;
1055
1056         if (lua_istable(L, 1)) {
1057                 read_noiseparams(L, 1, &params);
1058         } else {
1059                 params.seed    = luaL_checkint(L, 1);
1060                 params.octaves = luaL_checkint(L, 2);
1061                 params.persist = readParam<float>(L, 3);
1062                 params.spread  = v3f(1, 1, 1) * readParam<float>(L, 4);
1063         }
1064
1065         params.seed += (int)env->getServerMap().getSeed();
1066
1067         LuaPerlinNoise *n = new LuaPerlinNoise(&params);
1068         *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
1069         luaL_getmetatable(L, "PerlinNoise");
1070         lua_setmetatable(L, -2);
1071         return 1;
1072 }
1073
1074 // get_perlin_map(noiseparams, size)
1075 // returns world-specific PerlinNoiseMap
1076 int ModApiEnvMod::l_get_perlin_map(lua_State *L)
1077 {
1078         GET_ENV_PTR_NO_MAP_LOCK;
1079
1080         NoiseParams np;
1081         if (!read_noiseparams(L, 1, &np))
1082                 return 0;
1083         v3s16 size = read_v3s16(L, 2);
1084
1085         s32 seed = (s32)(env->getServerMap().getSeed());
1086         LuaPerlinNoiseMap *n = new LuaPerlinNoiseMap(&np, seed, size);
1087         *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
1088         luaL_getmetatable(L, "PerlinNoiseMap");
1089         lua_setmetatable(L, -2);
1090         return 1;
1091 }
1092
1093 // get_voxel_manip()
1094 // returns voxel manipulator
1095 int ModApiEnvMod::l_get_voxel_manip(lua_State *L)
1096 {
1097         GET_ENV_PTR;
1098
1099         Map *map = &(env->getMap());
1100         LuaVoxelManip *o = (lua_istable(L, 1) && lua_istable(L, 2)) ?
1101                 new LuaVoxelManip(map, read_v3s16(L, 1), read_v3s16(L, 2)) :
1102                 new LuaVoxelManip(map);
1103
1104         *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1105         luaL_getmetatable(L, "VoxelManip");
1106         lua_setmetatable(L, -2);
1107         return 1;
1108 }
1109
1110 // clear_objects([options])
1111 // clear all objects in the environment
1112 // where options = {mode = "full" or "quick"}
1113 int ModApiEnvMod::l_clear_objects(lua_State *L)
1114 {
1115         GET_ENV_PTR;
1116
1117         ClearObjectsMode mode = CLEAR_OBJECTS_MODE_QUICK;
1118         if (lua_istable(L, 1)) {
1119                 mode = (ClearObjectsMode)getenumfield(L, 1, "mode",
1120                         ModApiEnvMod::es_ClearObjectsMode, mode);
1121         }
1122
1123         env->clearObjects(mode);
1124         return 0;
1125 }
1126
1127 // line_of_sight(pos1, pos2) -> true/false, pos
1128 int ModApiEnvMod::l_line_of_sight(lua_State *L)
1129 {
1130         GET_PLAIN_ENV_PTR;
1131
1132         // read position 1 from lua
1133         v3f pos1 = checkFloatPos(L, 1);
1134         // read position 2 from lua
1135         v3f pos2 = checkFloatPos(L, 2);
1136
1137         v3s16 p;
1138
1139         bool success = env->line_of_sight(pos1, pos2, &p);
1140         lua_pushboolean(L, success);
1141         if (!success) {
1142                 push_v3s16(L, p);
1143                 return 2;
1144         }
1145         return 1;
1146 }
1147
1148 // fix_light(p1, p2)
1149 int ModApiEnvMod::l_fix_light(lua_State *L)
1150 {
1151         GET_ENV_PTR;
1152
1153         v3s16 blockpos1 = getContainerPos(read_v3s16(L, 1), MAP_BLOCKSIZE);
1154         v3s16 blockpos2 = getContainerPos(read_v3s16(L, 2), MAP_BLOCKSIZE);
1155         ServerMap &map = env->getServerMap();
1156         std::map<v3s16, MapBlock *> modified_blocks;
1157         bool success = true;
1158         v3s16 blockpos;
1159         for (blockpos.X = blockpos1.X; blockpos.X <= blockpos2.X; blockpos.X++)
1160         for (blockpos.Y = blockpos1.Y; blockpos.Y <= blockpos2.Y; blockpos.Y++)
1161         for (blockpos.Z = blockpos1.Z; blockpos.Z <= blockpos2.Z; blockpos.Z++) {
1162                 success = success & map.repairBlockLight(blockpos, &modified_blocks);
1163         }
1164         if (!modified_blocks.empty()) {
1165                 MapEditEvent event;
1166                 event.type = MEET_OTHER;
1167                 for (auto &modified_block : modified_blocks)
1168                         event.modified_blocks.insert(modified_block.first);
1169
1170                 map.dispatchEvent(event);
1171         }
1172         lua_pushboolean(L, success);
1173
1174         return 1;
1175 }
1176
1177 int ModApiEnvMod::l_raycast(lua_State *L)
1178 {
1179         return LuaRaycast::create_object(L);
1180 }
1181
1182 // load_area(p1, [p2])
1183 // load mapblocks in area p1..p2, but do not generate map
1184 int ModApiEnvMod::l_load_area(lua_State *L)
1185 {
1186         GET_ENV_PTR;
1187         MAP_LOCK_REQUIRED;
1188
1189         Map *map = &(env->getMap());
1190         v3s16 bp1 = getNodeBlockPos(check_v3s16(L, 1));
1191         if (!lua_istable(L, 2)) {
1192                 map->emergeBlock(bp1);
1193         } else {
1194                 v3s16 bp2 = getNodeBlockPos(check_v3s16(L, 2));
1195                 sortBoxVerticies(bp1, bp2);
1196                 for (s16 z = bp1.Z; z <= bp2.Z; z++)
1197                 for (s16 y = bp1.Y; y <= bp2.Y; y++)
1198                 for (s16 x = bp1.X; x <= bp2.X; x++) {
1199                         map->emergeBlock(v3s16(x, y, z));
1200                 }
1201         }
1202
1203         return 0;
1204 }
1205
1206 // emerge_area(p1, p2, [callback, context])
1207 // emerge mapblocks in area p1..p2, calls callback with context upon completion
1208 int ModApiEnvMod::l_emerge_area(lua_State *L)
1209 {
1210         GET_ENV_PTR;
1211
1212         EmergeCompletionCallback callback = NULL;
1213         ScriptCallbackState *state = NULL;
1214
1215         EmergeManager *emerge = getServer(L)->getEmergeManager();
1216
1217         v3s16 bpmin = getNodeBlockPos(read_v3s16(L, 1));
1218         v3s16 bpmax = getNodeBlockPos(read_v3s16(L, 2));
1219         sortBoxVerticies(bpmin, bpmax);
1220
1221         size_t num_blocks = VoxelArea(bpmin, bpmax).getVolume();
1222         assert(num_blocks != 0);
1223
1224         if (lua_isfunction(L, 3)) {
1225                 callback = LuaEmergeAreaCallback;
1226
1227                 lua_pushvalue(L, 3);
1228                 int callback_ref = luaL_ref(L, LUA_REGISTRYINDEX);
1229
1230                 lua_pushvalue(L, 4);
1231                 int args_ref = luaL_ref(L, LUA_REGISTRYINDEX);
1232
1233                 state = new ScriptCallbackState;
1234                 state->script       = getServer(L)->getScriptIface();
1235                 state->callback_ref = callback_ref;
1236                 state->args_ref     = args_ref;
1237                 state->refcount     = num_blocks;
1238                 state->origin       = getScriptApiBase(L)->getOrigin();
1239         }
1240
1241         for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
1242         for (s16 y = bpmin.Y; y <= bpmax.Y; y++)
1243         for (s16 x = bpmin.X; x <= bpmax.X; x++) {
1244                 emerge->enqueueBlockEmergeEx(v3s16(x, y, z), PEER_ID_INEXISTENT,
1245                         BLOCK_EMERGE_ALLOW_GEN | BLOCK_EMERGE_FORCE_QUEUE, callback, state);
1246         }
1247
1248         return 0;
1249 }
1250
1251 // delete_area(p1, p2)
1252 // delete mapblocks in area p1..p2
1253 int ModApiEnvMod::l_delete_area(lua_State *L)
1254 {
1255         GET_ENV_PTR;
1256
1257         v3s16 bpmin = getNodeBlockPos(read_v3s16(L, 1));
1258         v3s16 bpmax = getNodeBlockPos(read_v3s16(L, 2));
1259         sortBoxVerticies(bpmin, bpmax);
1260
1261         ServerMap &map = env->getServerMap();
1262
1263         MapEditEvent event;
1264         event.type = MEET_OTHER;
1265
1266         bool success = true;
1267         for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
1268         for (s16 y = bpmin.Y; y <= bpmax.Y; y++)
1269         for (s16 x = bpmin.X; x <= bpmax.X; x++) {
1270                 v3s16 bp(x, y, z);
1271                 if (map.deleteBlock(bp)) {
1272                         env->setStaticForActiveObjectsInBlock(bp, false);
1273                         event.modified_blocks.insert(bp);
1274                 } else {
1275                         success = false;
1276                 }
1277         }
1278
1279         map.dispatchEvent(event);
1280         lua_pushboolean(L, success);
1281         return 1;
1282 }
1283
1284 // find_path(pos1, pos2, searchdistance,
1285 //     max_jump, max_drop, algorithm) -> table containing path
1286 int ModApiEnvMod::l_find_path(lua_State *L)
1287 {
1288         GET_ENV_PTR;
1289
1290         v3s16 pos1                  = read_v3s16(L, 1);
1291         v3s16 pos2                  = read_v3s16(L, 2);
1292         unsigned int searchdistance = luaL_checkint(L, 3);
1293         unsigned int max_jump       = luaL_checkint(L, 4);
1294         unsigned int max_drop       = luaL_checkint(L, 5);
1295         PathAlgorithm algo          = PA_PLAIN_NP;
1296         if (!lua_isnoneornil(L, 6)) {
1297                 std::string algorithm = luaL_checkstring(L,6);
1298
1299                 if (algorithm == "A*")
1300                         algo = PA_PLAIN;
1301
1302                 if (algorithm == "Dijkstra")
1303                         algo = PA_DIJKSTRA;
1304         }
1305
1306         std::vector<v3s16> path = get_path(&env->getServerMap(), env->getGameDef()->ndef(), pos1, pos2,
1307                 searchdistance, max_jump, max_drop, algo);
1308
1309         if (!path.empty()) {
1310                 lua_createtable(L, path.size(), 0);
1311                 int top = lua_gettop(L);
1312                 unsigned int index = 1;
1313                 for (const v3s16 &i : path) {
1314                         lua_pushnumber(L,index);
1315                         push_v3s16(L, i);
1316                         lua_settable(L, top);
1317                         index++;
1318                 }
1319                 return 1;
1320         }
1321
1322         return 0;
1323 }
1324
1325 // spawn_tree(pos, treedef)
1326 int ModApiEnvMod::l_spawn_tree(lua_State *L)
1327 {
1328         GET_ENV_PTR;
1329
1330         v3s16 p0 = read_v3s16(L, 1);
1331
1332         treegen::TreeDef tree_def;
1333         std::string trunk,leaves,fruit;
1334         const NodeDefManager *ndef = env->getGameDef()->ndef();
1335
1336         if(lua_istable(L, 2))
1337         {
1338                 getstringfield(L, 2, "axiom", tree_def.initial_axiom);
1339                 getstringfield(L, 2, "rules_a", tree_def.rules_a);
1340                 getstringfield(L, 2, "rules_b", tree_def.rules_b);
1341                 getstringfield(L, 2, "rules_c", tree_def.rules_c);
1342                 getstringfield(L, 2, "rules_d", tree_def.rules_d);
1343                 getstringfield(L, 2, "trunk", trunk);
1344                 tree_def.trunknode=ndef->getId(trunk);
1345                 getstringfield(L, 2, "leaves", leaves);
1346                 tree_def.leavesnode=ndef->getId(leaves);
1347                 tree_def.leaves2_chance=0;
1348                 getstringfield(L, 2, "leaves2", leaves);
1349                 if (!leaves.empty()) {
1350                         tree_def.leaves2node=ndef->getId(leaves);
1351                         getintfield(L, 2, "leaves2_chance", tree_def.leaves2_chance);
1352                 }
1353                 getintfield(L, 2, "angle", tree_def.angle);
1354                 getintfield(L, 2, "iterations", tree_def.iterations);
1355                 if (!getintfield(L, 2, "random_level", tree_def.iterations_random_level))
1356                         tree_def.iterations_random_level = 0;
1357                 getstringfield(L, 2, "trunk_type", tree_def.trunk_type);
1358                 getboolfield(L, 2, "thin_branches", tree_def.thin_branches);
1359                 tree_def.fruit_chance=0;
1360                 getstringfield(L, 2, "fruit", fruit);
1361                 if (!fruit.empty()) {
1362                         tree_def.fruitnode=ndef->getId(fruit);
1363                         getintfield(L, 2, "fruit_chance",tree_def.fruit_chance);
1364                 }
1365                 tree_def.explicit_seed = getintfield(L, 2, "seed", tree_def.seed);
1366         }
1367         else
1368                 return 0;
1369
1370         ServerMap *map = &env->getServerMap();
1371         treegen::error e;
1372         if ((e = treegen::spawn_ltree (map, p0, ndef, tree_def)) != treegen::SUCCESS) {
1373                 if (e == treegen::UNBALANCED_BRACKETS) {
1374                         luaL_error(L, "spawn_tree(): closing ']' has no matching opening bracket");
1375                 } else {
1376                         luaL_error(L, "spawn_tree(): unknown error");
1377                 }
1378         }
1379
1380         return 1;
1381 }
1382
1383 // transforming_liquid_add(pos)
1384 int ModApiEnvMod::l_transforming_liquid_add(lua_State *L)
1385 {
1386         GET_ENV_PTR;
1387
1388         v3s16 p0 = read_v3s16(L, 1);
1389         env->getServerMap().transforming_liquid_add(p0);
1390         return 1;
1391 }
1392
1393 // forceload_block(blockpos)
1394 // blockpos = {x=num, y=num, z=num}
1395 int ModApiEnvMod::l_forceload_block(lua_State *L)
1396 {
1397         GET_ENV_PTR;
1398
1399         v3s16 blockpos = read_v3s16(L, 1);
1400         env->getForceloadedBlocks()->insert(blockpos);
1401         return 0;
1402 }
1403
1404 // compare_block_status(nodepos)
1405 int ModApiEnvMod::l_compare_block_status(lua_State *L)
1406 {
1407         GET_ENV_PTR;
1408
1409         v3s16 nodepos = check_v3s16(L, 1);
1410         std::string condition_s = luaL_checkstring(L, 2);
1411         auto status = env->getBlockStatus(getNodeBlockPos(nodepos));
1412
1413         int condition_i = -1;
1414         if (!string_to_enum(es_BlockStatusType, condition_i, condition_s))
1415                 return 0; // Unsupported
1416
1417         lua_pushboolean(L, status >= condition_i);
1418         return 1;
1419 }
1420
1421
1422 // forceload_free_block(blockpos)
1423 // blockpos = {x=num, y=num, z=num}
1424 int ModApiEnvMod::l_forceload_free_block(lua_State *L)
1425 {
1426         GET_ENV_PTR;
1427
1428         v3s16 blockpos = read_v3s16(L, 1);
1429         env->getForceloadedBlocks()->erase(blockpos);
1430         return 0;
1431 }
1432
1433 // get_translated_string(lang_code, string)
1434 int ModApiEnvMod::l_get_translated_string(lua_State * L)
1435 {
1436         GET_ENV_PTR;
1437         std::string lang_code = luaL_checkstring(L, 1);
1438         std::string string = luaL_checkstring(L, 2);
1439
1440         auto *translations = getServer(L)->getTranslationLanguage(lang_code);
1441         string = wide_to_utf8(translate_string(utf8_to_wide(string), translations));
1442         lua_pushstring(L, string.c_str());
1443         return 1;
1444 }
1445
1446 void ModApiEnvMod::Initialize(lua_State *L, int top)
1447 {
1448         API_FCT(set_node);
1449         API_FCT(bulk_set_node);
1450         API_FCT(add_node);
1451         API_FCT(swap_node);
1452         API_FCT(add_item);
1453         API_FCT(remove_node);
1454         API_FCT(get_node);
1455         API_FCT(get_node_or_nil);
1456         API_FCT(get_node_light);
1457         API_FCT(get_natural_light);
1458         API_FCT(place_node);
1459         API_FCT(dig_node);
1460         API_FCT(punch_node);
1461         API_FCT(get_node_max_level);
1462         API_FCT(get_node_level);
1463         API_FCT(set_node_level);
1464         API_FCT(add_node_level);
1465         API_FCT(add_entity);
1466         API_FCT(find_nodes_with_meta);
1467         API_FCT(get_meta);
1468         API_FCT(get_node_timer);
1469         API_FCT(get_connected_players);
1470         API_FCT(get_player_by_name);
1471         API_FCT(get_objects_in_area);
1472         API_FCT(get_objects_inside_radius);
1473         API_FCT(set_timeofday);
1474         API_FCT(get_timeofday);
1475         API_FCT(get_gametime);
1476         API_FCT(get_day_count);
1477         API_FCT(find_node_near);
1478         API_FCT(find_nodes_in_area);
1479         API_FCT(find_nodes_in_area_under_air);
1480         API_FCT(fix_light);
1481         API_FCT(load_area);
1482         API_FCT(emerge_area);
1483         API_FCT(delete_area);
1484         API_FCT(get_perlin);
1485         API_FCT(get_perlin_map);
1486         API_FCT(get_voxel_manip);
1487         API_FCT(clear_objects);
1488         API_FCT(spawn_tree);
1489         API_FCT(find_path);
1490         API_FCT(line_of_sight);
1491         API_FCT(raycast);
1492         API_FCT(transforming_liquid_add);
1493         API_FCT(forceload_block);
1494         API_FCT(forceload_free_block);
1495         API_FCT(compare_block_status);
1496         API_FCT(get_translated_string);
1497 }
1498
1499 void ModApiEnvMod::InitializeClient(lua_State *L, int top)
1500 {
1501         API_FCT(get_node_light);
1502         API_FCT(get_timeofday);
1503         API_FCT(get_node_max_level);
1504         API_FCT(get_node_level);
1505         API_FCT(find_nodes_with_meta);
1506         API_FCT(find_node_near);
1507         API_FCT(find_nodes_in_area);
1508         API_FCT(find_nodes_in_area_under_air);
1509         API_FCT(line_of_sight);
1510         API_FCT(raycast);
1511 }