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