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