]> git.lizzy.rs Git - dragonfireclient.git/blob - src/script/lua_api/l_env.cpp
Add spider
[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         ItemStack item(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         int start_radius = (lua_isboolean(L, 4) && readParam<bool>(L, 4)) ? 0 : 1;
861
862 #ifndef SERVER
863         // Client API limitations
864         if (Client *client = getClient(L))
865                 radius = client->CSMClampRadius(pos, radius);
866 #endif
867
868         for (int d = start_radius; d <= radius; d++) {
869                 const std::vector<v3s16> &list = FacePositionCache::getFacePositions(d);
870                 for (const v3s16 &i : list) {
871                         v3s16 p = pos + i;
872                         content_t c = map.getNode(p).getContent();
873                         if (CONTAINS(filter, c)) {
874                                 push_v3s16(L, p);
875                                 return 1;
876                         }
877                 }
878         }
879         return 0;
880 }
881
882 // find_nodes_near(pos, radius, nodenames, [search_center])
883 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
884 int ModApiEnvMod::l_find_nodes_near(lua_State *L)
885 {
886         GET_PLAIN_ENV_PTR;
887
888         const NodeDefManager *ndef = env->getGameDef()->ndef();
889         Map &map = env->getMap();
890
891         v3s16 pos = read_v3s16(L, 1);
892         int radius = luaL_checkinteger(L, 2);
893         std::vector<content_t> filter;
894         collectNodeIds(L, 3, ndef, filter);
895
896         int start_radius = (lua_isboolean(L, 4) && readParam<bool>(L, 4)) ? 0 : 1;
897
898 #ifndef SERVER
899         // Client API limitations
900         if (Client *client = getClient(L))
901                 radius = client->CSMClampRadius(pos, radius);
902 #endif
903
904         std::vector<u32> individual_count;
905         individual_count.resize(filter.size());
906
907         lua_newtable(L);
908         u32 i = 0;
909
910         for (int d = start_radius; d <= radius; d++) {
911                 const std::vector<v3s16> &list = FacePositionCache::getFacePositions(d);
912                 for (const v3s16 &posi : list) {
913                         v3s16 p = pos + posi;
914                         content_t c = map.getNode(p).getContent();
915                         auto it = std::find(filter.begin(), filter.end(), c);
916                         if (it != filter.end()) {
917                                 push_v3s16(L, p);
918                                 lua_rawseti(L, -2, ++i);
919
920                                 u32 filt_index = it - filter.begin();
921                                 individual_count[filt_index]++;
922                         }
923                 }
924         }
925         lua_createtable(L, 0, filter.size());
926         for (u32 i = 0; i < filter.size(); i++) {
927                 lua_pushinteger(L, individual_count[i]);
928                 lua_setfield(L, -2, ndef->get(filter[i]).name.c_str());
929         }
930         return 2;
931 }
932
933 // find_nodes_near_under_air(pos, radius, nodenames, [search_center])
934 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
935 int ModApiEnvMod::l_find_nodes_near_under_air(lua_State *L)
936 {
937         GET_PLAIN_ENV_PTR;
938
939         const NodeDefManager *ndef = env->getGameDef()->ndef();
940         Map &map = env->getMap();
941
942         v3s16 pos = read_v3s16(L, 1);
943         int radius = luaL_checkinteger(L, 2);
944         std::vector<content_t> filter;
945         collectNodeIds(L, 3, ndef, filter);
946         int start_radius = (lua_isboolean(L, 4) && readParam<bool>(L, 4)) ? 0 : 1;
947
948 #ifndef SERVER
949         // Client API limitations
950         if (Client *client = getClient(L))
951                 radius = client->CSMClampRadius(pos, radius);
952 #endif
953
954         std::vector<u32> individual_count;
955         individual_count.resize(filter.size());
956
957         lua_newtable(L);
958         u32 i = 0;
959
960         for (int d = start_radius; d <= radius; d++) {
961                 const std::vector<v3s16> &list = FacePositionCache::getFacePositions(d);
962                 for (const v3s16 &posi : list) {
963                         v3s16 p = pos + posi;
964                         content_t c = map.getNode(p).getContent();
965                         v3s16 psurf(p.X, p.Y + 1, p.Z);
966                         content_t csurf = map.getNode(psurf).getContent();
967                         if (c == CONTENT_AIR || csurf != CONTENT_AIR)
968                                 continue;
969                         auto it = std::find(filter.begin(), filter.end(), c);
970                         if (it != filter.end()) {
971                                 push_v3s16(L, p);
972                                 lua_rawseti(L, -2, ++i);
973
974                                 u32 filt_index = it - filter.begin();
975                                 individual_count[filt_index]++;
976                         }
977                 }
978         }
979         lua_createtable(L, 0, filter.size());
980         for (u32 i = 0; i < filter.size(); i++) {
981                 lua_pushinteger(L, individual_count[i]);
982                 lua_setfield(L, -2, ndef->get(filter[i]).name.c_str());
983         }
984         return 2;
985 }
986
987 // find_nodes_near_under_air_except(pos, radius, nodenames, [search_center])
988 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
989 int ModApiEnvMod::l_find_nodes_near_under_air_except(lua_State *L)
990 {
991         GET_PLAIN_ENV_PTR;
992
993         const NodeDefManager *ndef = env->getGameDef()->ndef();
994         Map &map = env->getMap();
995
996         v3s16 pos = read_v3s16(L, 1);
997         int radius = luaL_checkinteger(L, 2);
998         std::vector<content_t> filter;
999         collectNodeIds(L, 3, ndef, filter);
1000         int start_radius = (lua_isboolean(L, 4) && readParam<bool>(L, 4)) ? 0 : 1;
1001
1002 #ifndef SERVER
1003         // Client API limitations
1004         if (Client *client = getClient(L))
1005                 radius = client->CSMClampRadius(pos, radius);
1006 #endif
1007
1008         std::vector<u32> individual_count;
1009         individual_count.resize(filter.size());
1010
1011         lua_newtable(L);
1012         u32 i = 0;
1013
1014         for (int d = start_radius; d <= radius; d++) {
1015                 const std::vector<v3s16> &list = FacePositionCache::getFacePositions(d);
1016                 for (const v3s16 &posi : list) {
1017                         v3s16 p = pos + posi;
1018                         content_t c = map.getNode(p).getContent();
1019                         v3s16 psurf(p.X, p.Y + 1, p.Z);
1020                         content_t csurf = map.getNode(psurf).getContent();
1021                         if (c == CONTENT_AIR || csurf != CONTENT_AIR)
1022                                 continue;
1023                         auto it = std::find(filter.begin(), filter.end(), c);
1024                         if (it == filter.end()) {
1025                                 push_v3s16(L, p);
1026                                 lua_rawseti(L, -2, ++i);
1027
1028                                 u32 filt_index = it - filter.begin();
1029                                 individual_count[filt_index]++;
1030                         }
1031                 }
1032         }
1033         lua_createtable(L, 0, filter.size());
1034         for (u32 i = 0; i < filter.size(); i++) {
1035                 lua_pushinteger(L, individual_count[i]);
1036                 lua_setfield(L, -2, ndef->get(filter[i]).name.c_str());
1037         }
1038         return 2;
1039 }
1040
1041 // find_nodes_in_area(minp, maxp, nodenames, [grouped])
1042 int ModApiEnvMod::l_find_nodes_in_area(lua_State *L)
1043 {
1044         GET_PLAIN_ENV_PTR;
1045
1046         v3s16 minp = read_v3s16(L, 1);
1047         v3s16 maxp = read_v3s16(L, 2);
1048         sortBoxVerticies(minp, maxp);
1049
1050         const NodeDefManager *ndef = env->getGameDef()->ndef();
1051         Map &map = env->getMap();
1052
1053 #ifndef SERVER
1054         if (Client *client = getClient(L)) {
1055                 minp = client->CSMClampPos(minp);
1056                 maxp = client->CSMClampPos(maxp);
1057         }
1058 #endif
1059
1060         v3s16 cube = maxp - minp + 1;
1061         // Volume limit equal to 8 default mapchunks, (80 * 2) ^ 3 = 4,096,000
1062         if ((u64)cube.X * (u64)cube.Y * (u64)cube.Z > 4096000) {
1063                 luaL_error(L, "find_nodes_in_area(): area volume"
1064                                 " exceeds allowed value of 4096000");
1065                 return 0;
1066         }
1067
1068         std::vector<content_t> filter;
1069         collectNodeIds(L, 3, ndef, filter);
1070
1071         bool grouped = lua_isboolean(L, 4) && readParam<bool>(L, 4);
1072
1073         if (grouped) {
1074                 // create the table we will be returning
1075                 lua_createtable(L, 0, filter.size());
1076                 int base = lua_gettop(L);
1077
1078                 // create one table for each filter
1079                 std::vector<u32> idx;
1080                 idx.resize(filter.size());
1081                 for (u32 i = 0; i < filter.size(); i++)
1082                         lua_newtable(L);
1083
1084                 v3s16 p;
1085                 for (p.X = minp.X; p.X <= maxp.X; p.X++)
1086                 for (p.Y = minp.Y; p.Y <= maxp.Y; p.Y++)
1087                 for (p.Z = minp.Z; p.Z <= maxp.Z; p.Z++) {
1088                         content_t c = map.getNode(p).getContent();
1089
1090                         auto it = std::find(filter.begin(), filter.end(), c);
1091                         if (it != filter.end()) {
1092                                 // Calculate index of the table and append the position
1093                                 u32 filt_index = it - filter.begin();
1094                                 push_v3s16(L, p);
1095                                 lua_rawseti(L, base + 1 + filt_index, ++idx[filt_index]);
1096                         }
1097                 }
1098
1099                 // last filter table is at top of stack
1100                 u32 i = filter.size() - 1;
1101                 do {
1102                         if (idx[i] == 0) {
1103                                 // No such node found -> drop the empty table
1104                                 lua_pop(L, 1);
1105                         } else {
1106                                 // This node was found -> put table into the return table
1107                                 lua_setfield(L, base, ndef->get(filter[i]).name.c_str());
1108                         }
1109                 } while (i-- != 0);
1110
1111                 assert(lua_gettop(L) == base);
1112                 return 1;
1113         } else {
1114                 std::vector<u32> individual_count;
1115                 individual_count.resize(filter.size());
1116
1117                 lua_newtable(L);
1118                 u32 i = 0;
1119                 v3s16 p;
1120                 for (p.X = minp.X; p.X <= maxp.X; p.X++)
1121                 for (p.Y = minp.Y; p.Y <= maxp.Y; p.Y++)
1122                 for (p.Z = minp.Z; p.Z <= maxp.Z; p.Z++) {
1123                         content_t c = env->getMap().getNode(p).getContent();
1124
1125                         auto it = std::find(filter.begin(), filter.end(), c);
1126                         if (it != filter.end()) {
1127                                 push_v3s16(L, p);
1128                                 lua_rawseti(L, -2, ++i);
1129
1130                                 u32 filt_index = it - filter.begin();
1131                                 individual_count[filt_index]++;
1132                         }
1133                 }
1134
1135                 lua_createtable(L, 0, filter.size());
1136                 for (u32 i = 0; i < filter.size(); i++) {
1137                         lua_pushinteger(L, individual_count[i]);
1138                         lua_setfield(L, -2, ndef->get(filter[i]).name.c_str());
1139                 }
1140                 return 2;
1141         }
1142 }
1143
1144 // find_nodes_in_area_under_air(minp, maxp, nodenames) -> list of positions
1145 // nodenames: e.g. {"ignore", "group:tree"} or "default:dirt"
1146 int ModApiEnvMod::l_find_nodes_in_area_under_air(lua_State *L)
1147 {
1148         /* Note: A similar but generalized (and therefore slower) version of this
1149          * function could be created -- e.g. find_nodes_in_area_under -- which
1150          * would accept a node name (or ID?) or list of names that the "above node"
1151          * should be.
1152          * TODO
1153          */
1154
1155         GET_PLAIN_ENV_PTR;
1156
1157         v3s16 minp = read_v3s16(L, 1);
1158         v3s16 maxp = read_v3s16(L, 2);
1159         sortBoxVerticies(minp, maxp);
1160
1161         const NodeDefManager *ndef = env->getGameDef()->ndef();
1162         Map &map = env->getMap();
1163
1164 #ifndef SERVER
1165         if (Client *client = getClient(L)) {
1166                 minp = client->CSMClampPos(minp);
1167                 maxp = client->CSMClampPos(maxp);
1168         }
1169 #endif
1170
1171         v3s16 cube = maxp - minp + 1;
1172         // Volume limit equal to 8 default mapchunks, (80 * 2) ^ 3 = 4,096,000
1173         if ((u64)cube.X * (u64)cube.Y * (u64)cube.Z > 4096000) {
1174                 luaL_error(L, "find_nodes_in_area_under_air(): area volume"
1175                                 " exceeds allowed value of 4096000");
1176                 return 0;
1177         }
1178
1179         std::vector<content_t> filter;
1180         collectNodeIds(L, 3, ndef, filter);
1181
1182         lua_newtable(L);
1183         u32 i = 0;
1184         v3s16 p;
1185         for (p.X = minp.X; p.X <= maxp.X; p.X++)
1186         for (p.Z = minp.Z; p.Z <= maxp.Z; p.Z++) {
1187                 p.Y = minp.Y;
1188                 content_t c = map.getNode(p).getContent();
1189                 for (; p.Y <= maxp.Y; p.Y++) {
1190                         v3s16 psurf(p.X, p.Y + 1, p.Z);
1191                         content_t csurf = map.getNode(psurf).getContent();
1192                         if (c != CONTENT_AIR && csurf == CONTENT_AIR &&
1193                                         CONTAINS(filter, c)) {
1194                                 push_v3s16(L, p);
1195                                 lua_rawseti(L, -2, ++i);
1196                         }
1197                         c = csurf;
1198                 }
1199         }
1200         return 1;
1201 }
1202
1203 // get_perlin(seeddiff, octaves, persistence, scale)
1204 // returns world-specific PerlinNoise
1205 int ModApiEnvMod::l_get_perlin(lua_State *L)
1206 {
1207         GET_ENV_PTR_NO_MAP_LOCK;
1208
1209         NoiseParams params;
1210
1211         if (lua_istable(L, 1)) {
1212                 read_noiseparams(L, 1, &params);
1213         } else {
1214                 params.seed    = luaL_checkint(L, 1);
1215                 params.octaves = luaL_checkint(L, 2);
1216                 params.persist = readParam<float>(L, 3);
1217                 params.spread  = v3f(1, 1, 1) * readParam<float>(L, 4);
1218         }
1219
1220         params.seed += (int)env->getServerMap().getSeed();
1221
1222         LuaPerlinNoise *n = new LuaPerlinNoise(&params);
1223         *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
1224         luaL_getmetatable(L, "PerlinNoise");
1225         lua_setmetatable(L, -2);
1226         return 1;
1227 }
1228
1229 // get_perlin_map(noiseparams, size)
1230 // returns world-specific PerlinNoiseMap
1231 int ModApiEnvMod::l_get_perlin_map(lua_State *L)
1232 {
1233         GET_ENV_PTR_NO_MAP_LOCK;
1234
1235         NoiseParams np;
1236         if (!read_noiseparams(L, 1, &np))
1237                 return 0;
1238         v3s16 size = read_v3s16(L, 2);
1239
1240         s32 seed = (s32)(env->getServerMap().getSeed());
1241         LuaPerlinNoiseMap *n = new LuaPerlinNoiseMap(&np, seed, size);
1242         *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
1243         luaL_getmetatable(L, "PerlinNoiseMap");
1244         lua_setmetatable(L, -2);
1245         return 1;
1246 }
1247
1248 // get_voxel_manip()
1249 // returns voxel manipulator
1250 int ModApiEnvMod::l_get_voxel_manip(lua_State *L)
1251 {
1252         GET_ENV_PTR;
1253
1254         Map *map = &(env->getMap());
1255         LuaVoxelManip *o = (lua_istable(L, 1) && lua_istable(L, 2)) ?
1256                 new LuaVoxelManip(map, read_v3s16(L, 1), read_v3s16(L, 2)) :
1257                 new LuaVoxelManip(map);
1258
1259         *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1260         luaL_getmetatable(L, "VoxelManip");
1261         lua_setmetatable(L, -2);
1262         return 1;
1263 }
1264
1265 // clear_objects([options])
1266 // clear all objects in the environment
1267 // where options = {mode = "full" or "quick"}
1268 int ModApiEnvMod::l_clear_objects(lua_State *L)
1269 {
1270         GET_ENV_PTR;
1271
1272         ClearObjectsMode mode = CLEAR_OBJECTS_MODE_QUICK;
1273         if (lua_istable(L, 1)) {
1274                 mode = (ClearObjectsMode)getenumfield(L, 1, "mode",
1275                         ModApiEnvMod::es_ClearObjectsMode, mode);
1276         }
1277
1278         env->clearObjects(mode);
1279         return 0;
1280 }
1281
1282 // line_of_sight(pos1, pos2) -> true/false, pos
1283 int ModApiEnvMod::l_line_of_sight(lua_State *L)
1284 {
1285         GET_PLAIN_ENV_PTR;
1286
1287         // read position 1 from lua
1288         v3f pos1 = checkFloatPos(L, 1);
1289         // read position 2 from lua
1290         v3f pos2 = checkFloatPos(L, 2);
1291
1292         v3s16 p;
1293
1294         bool success = env->line_of_sight(pos1, pos2, &p);
1295         lua_pushboolean(L, success);
1296         if (!success) {
1297                 push_v3s16(L, p);
1298                 return 2;
1299         }
1300         return 1;
1301 }
1302
1303 // fix_light(p1, p2)
1304 int ModApiEnvMod::l_fix_light(lua_State *L)
1305 {
1306         GET_ENV_PTR;
1307
1308         v3s16 blockpos1 = getContainerPos(read_v3s16(L, 1), MAP_BLOCKSIZE);
1309         v3s16 blockpos2 = getContainerPos(read_v3s16(L, 2), MAP_BLOCKSIZE);
1310         ServerMap &map = env->getServerMap();
1311         std::map<v3s16, MapBlock *> modified_blocks;
1312         bool success = true;
1313         v3s16 blockpos;
1314         for (blockpos.X = blockpos1.X; blockpos.X <= blockpos2.X; blockpos.X++)
1315         for (blockpos.Y = blockpos1.Y; blockpos.Y <= blockpos2.Y; blockpos.Y++)
1316         for (blockpos.Z = blockpos1.Z; blockpos.Z <= blockpos2.Z; blockpos.Z++) {
1317                 success = success & map.repairBlockLight(blockpos, &modified_blocks);
1318         }
1319         if (!modified_blocks.empty()) {
1320                 MapEditEvent event;
1321                 event.type = MEET_OTHER;
1322                 for (auto &modified_block : modified_blocks)
1323                         event.modified_blocks.insert(modified_block.first);
1324
1325                 map.dispatchEvent(event);
1326         }
1327         lua_pushboolean(L, success);
1328
1329         return 1;
1330 }
1331
1332 int ModApiEnvMod::l_raycast(lua_State *L)
1333 {
1334         return LuaRaycast::create_object(L);
1335 }
1336
1337 // load_area(p1, [p2])
1338 // load mapblocks in area p1..p2, but do not generate map
1339 int ModApiEnvMod::l_load_area(lua_State *L)
1340 {
1341         GET_ENV_PTR;
1342         MAP_LOCK_REQUIRED;
1343
1344         Map *map = &(env->getMap());
1345         v3s16 bp1 = getNodeBlockPos(check_v3s16(L, 1));
1346         if (!lua_istable(L, 2)) {
1347                 map->emergeBlock(bp1);
1348         } else {
1349                 v3s16 bp2 = getNodeBlockPos(check_v3s16(L, 2));
1350                 sortBoxVerticies(bp1, bp2);
1351                 for (s16 z = bp1.Z; z <= bp2.Z; z++)
1352                 for (s16 y = bp1.Y; y <= bp2.Y; y++)
1353                 for (s16 x = bp1.X; x <= bp2.X; x++) {
1354                         map->emergeBlock(v3s16(x, y, z));
1355                 }
1356         }
1357
1358         return 0;
1359 }
1360
1361 // emerge_area(p1, p2, [callback, context])
1362 // emerge mapblocks in area p1..p2, calls callback with context upon completion
1363 int ModApiEnvMod::l_emerge_area(lua_State *L)
1364 {
1365         GET_ENV_PTR;
1366
1367         EmergeCompletionCallback callback = NULL;
1368         ScriptCallbackState *state = NULL;
1369
1370         EmergeManager *emerge = getServer(L)->getEmergeManager();
1371
1372         v3s16 bpmin = getNodeBlockPos(read_v3s16(L, 1));
1373         v3s16 bpmax = getNodeBlockPos(read_v3s16(L, 2));
1374         sortBoxVerticies(bpmin, bpmax);
1375
1376         size_t num_blocks = VoxelArea(bpmin, bpmax).getVolume();
1377         assert(num_blocks != 0);
1378
1379         if (lua_isfunction(L, 3)) {
1380                 callback = LuaEmergeAreaCallback;
1381
1382                 lua_pushvalue(L, 3);
1383                 int callback_ref = luaL_ref(L, LUA_REGISTRYINDEX);
1384
1385                 lua_pushvalue(L, 4);
1386                 int args_ref = luaL_ref(L, LUA_REGISTRYINDEX);
1387
1388                 state = new ScriptCallbackState;
1389                 state->script       = getServer(L)->getScriptIface();
1390                 state->callback_ref = callback_ref;
1391                 state->args_ref     = args_ref;
1392                 state->refcount     = num_blocks;
1393                 state->origin       = getScriptApiBase(L)->getOrigin();
1394         }
1395
1396         for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
1397         for (s16 y = bpmin.Y; y <= bpmax.Y; y++)
1398         for (s16 x = bpmin.X; x <= bpmax.X; x++) {
1399                 emerge->enqueueBlockEmergeEx(v3s16(x, y, z), PEER_ID_INEXISTENT,
1400                         BLOCK_EMERGE_ALLOW_GEN | BLOCK_EMERGE_FORCE_QUEUE, callback, state);
1401         }
1402
1403         return 0;
1404 }
1405
1406 // delete_area(p1, p2)
1407 // delete mapblocks in area p1..p2
1408 int ModApiEnvMod::l_delete_area(lua_State *L)
1409 {
1410         GET_ENV_PTR;
1411
1412         v3s16 bpmin = getNodeBlockPos(read_v3s16(L, 1));
1413         v3s16 bpmax = getNodeBlockPos(read_v3s16(L, 2));
1414         sortBoxVerticies(bpmin, bpmax);
1415
1416         ServerMap &map = env->getServerMap();
1417
1418         MapEditEvent event;
1419         event.type = MEET_OTHER;
1420
1421         bool success = true;
1422         for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
1423         for (s16 y = bpmin.Y; y <= bpmax.Y; y++)
1424         for (s16 x = bpmin.X; x <= bpmax.X; x++) {
1425                 v3s16 bp(x, y, z);
1426                 if (map.deleteBlock(bp)) {
1427                         env->setStaticForActiveObjectsInBlock(bp, false);
1428                         event.modified_blocks.insert(bp);
1429                 } else {
1430                         success = false;
1431                 }
1432         }
1433
1434         map.dispatchEvent(event);
1435         lua_pushboolean(L, success);
1436         return 1;
1437 }
1438
1439 // find_path(pos1, pos2, searchdistance,
1440 //     max_jump, max_drop, algorithm) -> table containing path
1441 int ModApiEnvMod::l_find_path(lua_State *L)
1442 {
1443         Environment *env = getEnv(L);
1444
1445         v3s16 pos1                  = read_v3s16(L, 1);
1446         v3s16 pos2                  = read_v3s16(L, 2);
1447         unsigned int searchdistance = luaL_checkint(L, 3);
1448         unsigned int max_jump       = luaL_checkint(L, 4);
1449         unsigned int max_drop       = luaL_checkint(L, 5);
1450         PathAlgorithm algo          = PA_PLAIN_NP;
1451         if (!lua_isnoneornil(L, 6)) {
1452                 std::string algorithm = luaL_checkstring(L,6);
1453
1454                 if (algorithm == "A*")
1455                         algo = PA_PLAIN;
1456
1457                 if (algorithm == "Dijkstra")
1458                         algo = PA_DIJKSTRA;
1459         }
1460
1461         std::vector<v3s16> path = get_path(&env->getMap(), env->getGameDef()->ndef(), pos1, pos2,
1462                 searchdistance, max_jump, max_drop, algo);
1463
1464         if (!path.empty()) {
1465                 lua_createtable(L, path.size(), 0);
1466                 int top = lua_gettop(L);
1467                 unsigned int index = 1;
1468                 for (const v3s16 &i : path) {
1469                         lua_pushnumber(L,index);
1470                         push_v3s16(L, i);
1471                         lua_settable(L, top);
1472                         index++;
1473                 }
1474                 return 1;
1475         }
1476
1477         return 0;
1478 }
1479
1480 // spawn_tree(pos, treedef)
1481 int ModApiEnvMod::l_spawn_tree(lua_State *L)
1482 {
1483         GET_ENV_PTR;
1484
1485         v3s16 p0 = read_v3s16(L, 1);
1486
1487         treegen::TreeDef tree_def;
1488         std::string trunk,leaves,fruit;
1489         const NodeDefManager *ndef = env->getGameDef()->ndef();
1490
1491         if(lua_istable(L, 2))
1492         {
1493                 getstringfield(L, 2, "axiom", tree_def.initial_axiom);
1494                 getstringfield(L, 2, "rules_a", tree_def.rules_a);
1495                 getstringfield(L, 2, "rules_b", tree_def.rules_b);
1496                 getstringfield(L, 2, "rules_c", tree_def.rules_c);
1497                 getstringfield(L, 2, "rules_d", tree_def.rules_d);
1498                 getstringfield(L, 2, "trunk", trunk);
1499                 tree_def.trunknode=ndef->getId(trunk);
1500                 getstringfield(L, 2, "leaves", leaves);
1501                 tree_def.leavesnode=ndef->getId(leaves);
1502                 tree_def.leaves2_chance=0;
1503                 getstringfield(L, 2, "leaves2", leaves);
1504                 if (!leaves.empty()) {
1505                         tree_def.leaves2node=ndef->getId(leaves);
1506                         getintfield(L, 2, "leaves2_chance", tree_def.leaves2_chance);
1507                 }
1508                 getintfield(L, 2, "angle", tree_def.angle);
1509                 getintfield(L, 2, "iterations", tree_def.iterations);
1510                 if (!getintfield(L, 2, "random_level", tree_def.iterations_random_level))
1511                         tree_def.iterations_random_level = 0;
1512                 getstringfield(L, 2, "trunk_type", tree_def.trunk_type);
1513                 getboolfield(L, 2, "thin_branches", tree_def.thin_branches);
1514                 tree_def.fruit_chance=0;
1515                 getstringfield(L, 2, "fruit", fruit);
1516                 if (!fruit.empty()) {
1517                         tree_def.fruitnode=ndef->getId(fruit);
1518                         getintfield(L, 2, "fruit_chance",tree_def.fruit_chance);
1519                 }
1520                 tree_def.explicit_seed = getintfield(L, 2, "seed", tree_def.seed);
1521         }
1522         else
1523                 return 0;
1524
1525         ServerMap *map = &env->getServerMap();
1526         treegen::error e;
1527         if ((e = treegen::spawn_ltree (map, p0, ndef, tree_def)) != treegen::SUCCESS) {
1528                 if (e == treegen::UNBALANCED_BRACKETS) {
1529                         luaL_error(L, "spawn_tree(): closing ']' has no matching opening bracket");
1530                 } else {
1531                         luaL_error(L, "spawn_tree(): unknown error");
1532                 }
1533         }
1534
1535         return 1;
1536 }
1537
1538 // transforming_liquid_add(pos)
1539 int ModApiEnvMod::l_transforming_liquid_add(lua_State *L)
1540 {
1541         GET_ENV_PTR;
1542
1543         v3s16 p0 = read_v3s16(L, 1);
1544         env->getMap().transforming_liquid_add(p0);
1545         return 1;
1546 }
1547
1548 // forceload_block(blockpos)
1549 // blockpos = {x=num, y=num, z=num}
1550 int ModApiEnvMod::l_forceload_block(lua_State *L)
1551 {
1552         GET_ENV_PTR;
1553
1554         v3s16 blockpos = read_v3s16(L, 1);
1555         env->getForceloadedBlocks()->insert(blockpos);
1556         return 0;
1557 }
1558
1559 // compare_block_status(nodepos)
1560 int ModApiEnvMod::l_compare_block_status(lua_State *L)
1561 {
1562         GET_ENV_PTR;
1563
1564         v3s16 nodepos = check_v3s16(L, 1);
1565         std::string condition_s = luaL_checkstring(L, 2);
1566         auto status = env->getBlockStatus(getNodeBlockPos(nodepos));
1567
1568         int condition_i = -1;
1569         if (!string_to_enum(es_BlockStatusType, condition_i, condition_s))
1570                 return 0; // Unsupported
1571
1572         lua_pushboolean(L, status >= condition_i);
1573         return 1;
1574 }
1575
1576
1577 // forceload_free_block(blockpos)
1578 // blockpos = {x=num, y=num, z=num}
1579 int ModApiEnvMod::l_forceload_free_block(lua_State *L)
1580 {
1581         GET_ENV_PTR;
1582
1583         v3s16 blockpos = read_v3s16(L, 1);
1584         env->getForceloadedBlocks()->erase(blockpos);
1585         return 0;
1586 }
1587
1588 // get_translated_string(lang_code, string)
1589 int ModApiEnvMod::l_get_translated_string(lua_State * L)
1590 {
1591         GET_ENV_PTR;
1592         std::string lang_code = luaL_checkstring(L, 1);
1593         std::string string = luaL_checkstring(L, 2);
1594
1595         auto *translations = getServer(L)->getTranslationLanguage(lang_code);
1596         string = wide_to_utf8(translate_string(utf8_to_wide(string), translations));
1597         lua_pushstring(L, string.c_str());
1598         return 1;
1599 }
1600
1601 void ModApiEnvMod::Initialize(lua_State *L, int top)
1602 {
1603         API_FCT(set_node);
1604         API_FCT(bulk_set_node);
1605         API_FCT(add_node);
1606         API_FCT(swap_node);
1607         API_FCT(add_item);
1608         API_FCT(remove_node);
1609         API_FCT(get_node);
1610         API_FCT(get_node_or_nil);
1611         API_FCT(get_node_light);
1612         API_FCT(get_natural_light);
1613         API_FCT(place_node);
1614         API_FCT(dig_node);
1615         API_FCT(punch_node);
1616         API_FCT(get_node_max_level);
1617         API_FCT(get_node_level);
1618         API_FCT(set_node_level);
1619         API_FCT(add_node_level);
1620         API_FCT(add_entity);
1621         API_FCT(find_nodes_with_meta);
1622         API_FCT(get_meta);
1623         API_FCT(get_node_timer);
1624         API_FCT(get_connected_players);
1625         API_FCT(get_player_by_name);
1626         API_FCT(get_objects_in_area);
1627         API_FCT(get_objects_inside_radius);
1628         API_FCT(set_timeofday);
1629         API_FCT(get_timeofday);
1630         API_FCT(get_gametime);
1631         API_FCT(get_day_count);
1632         API_FCT(find_node_near);
1633         API_FCT(find_nodes_in_area);
1634         API_FCT(find_nodes_in_area_under_air);
1635         API_FCT(fix_light);
1636         API_FCT(load_area);
1637         API_FCT(emerge_area);
1638         API_FCT(delete_area);
1639         API_FCT(get_perlin);
1640         API_FCT(get_perlin_map);
1641         API_FCT(get_voxel_manip);
1642         API_FCT(clear_objects);
1643         API_FCT(spawn_tree);
1644         API_FCT(find_path);
1645         API_FCT(line_of_sight);
1646         API_FCT(raycast);
1647         API_FCT(transforming_liquid_add);
1648         API_FCT(forceload_block);
1649         API_FCT(forceload_free_block);
1650         API_FCT(compare_block_status);
1651         API_FCT(get_translated_string);
1652 }
1653
1654 void ModApiEnvMod::InitializeClient(lua_State *L, int top)
1655 {
1656         API_FCT(get_node_light);
1657         API_FCT(get_timeofday);
1658         API_FCT(get_node_max_level);
1659         API_FCT(get_node_level);
1660         API_FCT(find_nodes_with_meta);
1661         API_FCT(find_node_near);
1662         API_FCT(find_nodes_near);
1663         API_FCT(find_nodes_near_under_air);
1664         API_FCT(find_nodes_near_under_air_except);
1665         API_FCT(find_nodes_in_area);
1666         API_FCT(find_nodes_in_area_under_air);
1667         API_FCT(get_voxel_manip);
1668         API_FCT(find_path);
1669         API_FCT(line_of_sight);
1670         API_FCT(raycast);
1671 }