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