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