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