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