]> git.lizzy.rs Git - dragonfireclient.git/blob - src/script/lua_api/l_env.cpp
442c4b99a1b45c29a7a16185f6aaa4213f403ce2
[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 "serverscripting.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         ServerScripting *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         ServerScripting *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, [staticdata]) -> 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         // staticdata
454         const char *staticdata = luaL_optstring(L, 3, "");
455         // Do it
456         ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, staticdata);
457         int objectid = env->addActiveObject(obj);
458         // If failed to add, return nothing (reads as nil)
459         if(objectid == 0)
460                 return 0;
461         // Return ObjectRef
462         getScriptApiBase(L)->objectrefGetOrCreate(L, obj);
463         return 1;
464 }
465
466 // add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
467 // pos = {x=num, y=num, z=num}
468 int ModApiEnvMod::l_add_item(lua_State *L)
469 {
470         GET_ENV_PTR;
471
472         // pos
473         //v3f pos = checkFloatPos(L, 1);
474         // item
475         ItemStack item = read_item(L, 2,getServer(L));
476         if(item.empty() || !item.isKnown(getServer(L)->idef()))
477                 return 0;
478
479         int error_handler = PUSH_ERROR_HANDLER(L);
480
481         // Use spawn_item to spawn a __builtin:item
482         lua_getglobal(L, "core");
483         lua_getfield(L, -1, "spawn_item");
484         lua_remove(L, -2); // Remove core
485         if(lua_isnil(L, -1))
486                 return 0;
487         lua_pushvalue(L, 1);
488         lua_pushstring(L, item.getItemString().c_str());
489
490         PCALL_RESL(L, lua_pcall(L, 2, 1, error_handler));
491
492         lua_remove(L, error_handler);
493         return 1;
494 }
495
496 // get_player_by_name(name)
497 int ModApiEnvMod::l_get_player_by_name(lua_State *L)
498 {
499         GET_ENV_PTR;
500
501         // Do it
502         const char *name = luaL_checkstring(L, 1);
503         RemotePlayer *player = dynamic_cast<RemotePlayer *>(env->getPlayer(name));
504         if (player == NULL){
505                 lua_pushnil(L);
506                 return 1;
507         }
508         PlayerSAO *sao = player->getPlayerSAO();
509         if(sao == NULL){
510                 lua_pushnil(L);
511                 return 1;
512         }
513         // Put player on stack
514         getScriptApiBase(L)->objectrefGetOrCreate(L, sao);
515         return 1;
516 }
517
518 // get_objects_inside_radius(pos, radius)
519 int ModApiEnvMod::l_get_objects_inside_radius(lua_State *L)
520 {
521         GET_ENV_PTR;
522
523         // Do it
524         v3f pos = checkFloatPos(L, 1);
525         float radius = luaL_checknumber(L, 2) * BS;
526         std::vector<u16> ids;
527         env->getObjectsInsideRadius(ids, pos, radius);
528         ScriptApiBase *script = getScriptApiBase(L);
529         lua_createtable(L, ids.size(), 0);
530         std::vector<u16>::const_iterator iter = ids.begin();
531         for(u32 i = 0; iter != ids.end(); iter++) {
532                 ServerActiveObject *obj = env->getActiveObject(*iter);
533                 // Insert object reference into table
534                 script->objectrefGetOrCreate(L, obj);
535                 lua_rawseti(L, -2, ++i);
536         }
537         return 1;
538 }
539
540 // set_timeofday(val)
541 // val = 0...1
542 int ModApiEnvMod::l_set_timeofday(lua_State *L)
543 {
544         GET_ENV_PTR;
545
546         // Do it
547         float timeofday_f = luaL_checknumber(L, 1);
548         sanity_check(timeofday_f >= 0.0 && timeofday_f <= 1.0);
549         int timeofday_mh = (int)(timeofday_f * 24000.0);
550         // This should be set directly in the environment but currently
551         // such changes aren't immediately sent to the clients, so call
552         // the server instead.
553         //env->setTimeOfDay(timeofday_mh);
554         getServer(L)->setTimeOfDay(timeofday_mh);
555         return 0;
556 }
557
558 // get_timeofday() -> 0...1
559 int ModApiEnvMod::l_get_timeofday(lua_State *L)
560 {
561         GET_ENV_PTR;
562
563         // Do it
564         int timeofday_mh = env->getTimeOfDay();
565         float timeofday_f = (float)timeofday_mh / 24000.0;
566         lua_pushnumber(L, timeofday_f);
567         return 1;
568 }
569
570 // get_day_count() -> int
571 int ModApiEnvMod::l_get_day_count(lua_State *L)
572 {
573         GET_ENV_PTR;
574
575         lua_pushnumber(L, env->getDayCount());
576         return 1;
577 }
578
579 // get_gametime()
580 int ModApiEnvMod::l_get_gametime(lua_State *L)
581 {
582         GET_ENV_PTR;
583
584         int game_time = env->getGameTime();
585         lua_pushnumber(L, game_time);
586         return 1;
587 }
588
589
590 // find_node_near(pos, radius, nodenames) -> pos or nil
591 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
592 int ModApiEnvMod::l_find_node_near(lua_State *L)
593 {
594         GET_ENV_PTR;
595
596         INodeDefManager *ndef = getServer(L)->ndef();
597         v3s16 pos = read_v3s16(L, 1);
598         int radius = luaL_checkinteger(L, 2);
599         std::set<content_t> filter;
600         if(lua_istable(L, 3)){
601                 int table = 3;
602                 lua_pushnil(L);
603                 while(lua_next(L, table) != 0){
604                         // key at index -2 and value at index -1
605                         luaL_checktype(L, -1, LUA_TSTRING);
606                         ndef->getIds(lua_tostring(L, -1), filter);
607                         // removes value, keeps key for next iteration
608                         lua_pop(L, 1);
609                 }
610         } else if(lua_isstring(L, 3)){
611                 ndef->getIds(lua_tostring(L, 3), filter);
612         }
613
614         for(int d=1; d<=radius; d++){
615                 std::vector<v3s16> list = FacePositionCache::getFacePositions(d);
616                 for(std::vector<v3s16>::iterator i = list.begin();
617                                 i != list.end(); ++i){
618                         v3s16 p = pos + (*i);
619                         content_t c = env->getMap().getNodeNoEx(p).getContent();
620                         if(filter.count(c) != 0){
621                                 push_v3s16(L, p);
622                                 return 1;
623                         }
624                 }
625         }
626         return 0;
627 }
628
629 // find_nodes_in_area(minp, maxp, nodenames) -> list of positions
630 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
631 int ModApiEnvMod::l_find_nodes_in_area(lua_State *L)
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         if(lua_istable(L, 3)) {
640                 int table = 3;
641                 lua_pushnil(L);
642                 while(lua_next(L, table) != 0) {
643                         // key at index -2 and value at index -1
644                         luaL_checktype(L, -1, LUA_TSTRING);
645                         ndef->getIds(lua_tostring(L, -1), filter);
646                         // removes value, keeps key for next iteration
647                         lua_pop(L, 1);
648                 }
649         } else if(lua_isstring(L, 3)) {
650                 ndef->getIds(lua_tostring(L, 3), filter);
651         }
652
653         std::map<content_t, u16> individual_count;
654
655         lua_newtable(L);
656         u64 i = 0;
657         for (s16 x = minp.X; x <= maxp.X; x++)
658                 for (s16 y = minp.Y; y <= maxp.Y; y++)
659                         for (s16 z = minp.Z; z <= maxp.Z; z++) {
660                                 v3s16 p(x, y, z);
661                                 content_t c = env->getMap().getNodeNoEx(p).getContent();
662                                 if (filter.count(c) != 0) {
663                                         push_v3s16(L, p);
664                                         lua_rawseti(L, -2, ++i);
665                                         individual_count[c]++;
666                                 }
667         }
668         lua_newtable(L);
669         for (std::set<content_t>::iterator it = filter.begin();
670                         it != filter.end(); ++it) {
671                 lua_pushnumber(L, individual_count[*it]);
672                 lua_setfield(L, -2, ndef->get(*it).name.c_str());
673         }
674         return 2;
675 }
676
677 // find_nodes_in_area_under_air(minp, maxp, nodenames) -> list of positions
678 // nodenames: e.g. {"ignore", "group:tree"} or "default:dirt"
679 int ModApiEnvMod::l_find_nodes_in_area_under_air(lua_State *L)
680 {
681         /* Note: A similar but generalized (and therefore slower) version of this
682          * function could be created -- e.g. find_nodes_in_area_under -- which
683          * would accept a node name (or ID?) or list of names that the "above node"
684          * should be.
685          * TODO
686          */
687
688         GET_ENV_PTR;
689
690         INodeDefManager *ndef = getServer(L)->ndef();
691         v3s16 minp = read_v3s16(L, 1);
692         v3s16 maxp = read_v3s16(L, 2);
693         std::set<content_t> filter;
694
695         if (lua_istable(L, 3)) {
696                 int table = 3;
697                 lua_pushnil(L);
698                 while(lua_next(L, table) != 0) {
699                         // key at index -2 and value at index -1
700                         luaL_checktype(L, -1, LUA_TSTRING);
701                         ndef->getIds(lua_tostring(L, -1), filter);
702                         // removes value, keeps key for next iteration
703                         lua_pop(L, 1);
704                 }
705         } else if (lua_isstring(L, 3)) {
706                 ndef->getIds(lua_tostring(L, 3), filter);
707         }
708
709         lua_newtable(L);
710         u64 i = 0;
711         for (s16 x = minp.X; x <= maxp.X; x++)
712         for (s16 z = minp.Z; z <= maxp.Z; z++) {
713                 s16 y = minp.Y;
714                 v3s16 p(x, y, z);
715                 content_t c = env->getMap().getNodeNoEx(p).getContent();
716                 for (; y <= maxp.Y; y++) {
717                         v3s16 psurf(x, y + 1, z);
718                         content_t csurf = env->getMap().getNodeNoEx(psurf).getContent();
719                         if(c != CONTENT_AIR && csurf == CONTENT_AIR &&
720                                         filter.count(c) != 0) {
721                                 push_v3s16(L, v3s16(x, y, z));
722                                 lua_rawseti(L, -2, ++i);
723                         }
724                         c = csurf;
725                 }
726         }
727         return 1;
728 }
729
730 // get_perlin(seeddiff, octaves, persistence, scale)
731 // returns world-specific PerlinNoise
732 int ModApiEnvMod::l_get_perlin(lua_State *L)
733 {
734         GET_ENV_PTR_NO_MAP_LOCK;
735
736         NoiseParams params;
737
738         if (lua_istable(L, 1)) {
739                 read_noiseparams(L, 1, &params);
740         } else {
741                 params.seed    = luaL_checkint(L, 1);
742                 params.octaves = luaL_checkint(L, 2);
743                 params.persist = luaL_checknumber(L, 3);
744                 params.spread  = v3f(1, 1, 1) * luaL_checknumber(L, 4);
745         }
746
747         params.seed += (int)env->getServerMap().getSeed();
748
749         LuaPerlinNoise *n = new LuaPerlinNoise(&params);
750         *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
751         luaL_getmetatable(L, "PerlinNoise");
752         lua_setmetatable(L, -2);
753         return 1;
754 }
755
756 // get_perlin_map(noiseparams, size)
757 // returns world-specific PerlinNoiseMap
758 int ModApiEnvMod::l_get_perlin_map(lua_State *L)
759 {
760         GET_ENV_PTR_NO_MAP_LOCK;
761
762         NoiseParams np;
763         if (!read_noiseparams(L, 1, &np))
764                 return 0;
765         v3s16 size = read_v3s16(L, 2);
766
767         s32 seed = (s32)(env->getServerMap().getSeed());
768         LuaPerlinNoiseMap *n = new LuaPerlinNoiseMap(&np, seed, size);
769         *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
770         luaL_getmetatable(L, "PerlinNoiseMap");
771         lua_setmetatable(L, -2);
772         return 1;
773 }
774
775 // get_voxel_manip()
776 // returns voxel manipulator
777 int ModApiEnvMod::l_get_voxel_manip(lua_State *L)
778 {
779         GET_ENV_PTR;
780
781         Map *map = &(env->getMap());
782         LuaVoxelManip *o = (lua_istable(L, 1) && lua_istable(L, 2)) ?
783                 new LuaVoxelManip(map, read_v3s16(L, 1), read_v3s16(L, 2)) :
784                 new LuaVoxelManip(map);
785
786         *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
787         luaL_getmetatable(L, "VoxelManip");
788         lua_setmetatable(L, -2);
789         return 1;
790 }
791
792 // clear_objects([options])
793 // clear all objects in the environment
794 // where options = {mode = "full" or "quick"}
795 int ModApiEnvMod::l_clear_objects(lua_State *L)
796 {
797         GET_ENV_PTR;
798
799         ClearObjectsMode mode = CLEAR_OBJECTS_MODE_FULL;
800         if (lua_istable(L, 1)) {
801                 mode = (ClearObjectsMode)getenumfield(L, 1, "mode",
802                         ModApiEnvMod::es_ClearObjectsMode, mode);
803         }
804
805         env->clearObjects(mode);
806         return 0;
807 }
808
809 // line_of_sight(pos1, pos2, stepsize) -> true/false, pos
810 int ModApiEnvMod::l_line_of_sight(lua_State *L)
811 {
812         float stepsize = 1.0;
813
814         GET_ENV_PTR;
815
816         // read position 1 from lua
817         v3f pos1 = checkFloatPos(L, 1);
818         // read position 2 from lua
819         v3f pos2 = checkFloatPos(L, 2);
820         //read step size from lua
821         if (lua_isnumber(L, 3)) {
822                 stepsize = lua_tonumber(L, 3);
823         }
824
825         v3s16 p;
826         bool success = env->line_of_sight(pos1, pos2, stepsize, &p);
827         lua_pushboolean(L, success);
828         if (!success) {
829                 push_v3s16(L, p);
830                 return 2;
831         }
832         return 1;
833 }
834
835 // emerge_area(p1, p2, [callback, context])
836 // emerge mapblocks in area p1..p2, calls callback with context upon completion
837 int ModApiEnvMod::l_emerge_area(lua_State *L)
838 {
839         GET_ENV_PTR;
840
841         EmergeCompletionCallback callback = NULL;
842         ScriptCallbackState *state = NULL;
843
844         EmergeManager *emerge = getServer(L)->getEmergeManager();
845
846         v3s16 bpmin = getNodeBlockPos(read_v3s16(L, 1));
847         v3s16 bpmax = getNodeBlockPos(read_v3s16(L, 2));
848         sortBoxVerticies(bpmin, bpmax);
849
850         size_t num_blocks = VoxelArea(bpmin, bpmax).getVolume();
851         assert(num_blocks != 0);
852
853         if (lua_isfunction(L, 3)) {
854                 callback = LuaEmergeAreaCallback;
855
856                 lua_pushvalue(L, 3);
857                 int callback_ref = luaL_ref(L, LUA_REGISTRYINDEX);
858
859                 lua_pushvalue(L, 4);
860                 int args_ref = luaL_ref(L, LUA_REGISTRYINDEX);
861
862                 state = new ScriptCallbackState;
863                 state->script       = getServer(L)->getScriptIface();
864                 state->callback_ref = callback_ref;
865                 state->args_ref     = args_ref;
866                 state->refcount     = num_blocks;
867                 state->origin       = getScriptApiBase(L)->getOrigin();
868         }
869
870         for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
871         for (s16 y = bpmin.Y; y <= bpmax.Y; y++)
872         for (s16 x = bpmin.X; x <= bpmax.X; x++) {
873                 emerge->enqueueBlockEmergeEx(v3s16(x, y, z), PEER_ID_INEXISTENT,
874                         BLOCK_EMERGE_ALLOW_GEN | BLOCK_EMERGE_FORCE_QUEUE, callback, state);
875         }
876
877         return 0;
878 }
879
880 // delete_area(p1, p2)
881 // delete mapblocks in area p1..p2
882 int ModApiEnvMod::l_delete_area(lua_State *L)
883 {
884         GET_ENV_PTR;
885
886         v3s16 bpmin = getNodeBlockPos(read_v3s16(L, 1));
887         v3s16 bpmax = getNodeBlockPos(read_v3s16(L, 2));
888         sortBoxVerticies(bpmin, bpmax);
889
890         ServerMap &map = env->getServerMap();
891
892         MapEditEvent event;
893         event.type = MEET_OTHER;
894
895         bool success = true;
896         for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
897         for (s16 y = bpmin.Y; y <= bpmax.Y; y++)
898         for (s16 x = bpmin.X; x <= bpmax.X; x++) {
899                 v3s16 bp(x, y, z);
900                 if (map.deleteBlock(bp)) {
901                         env->setStaticForActiveObjectsInBlock(bp, false);
902                         event.modified_blocks.insert(bp);
903                 } else {
904                         success = false;
905                 }
906         }
907
908         map.dispatchEvent(&event);
909         lua_pushboolean(L, success);
910         return 1;
911 }
912
913 // find_path(pos1, pos2, searchdistance,
914 //     max_jump, max_drop, algorithm) -> table containing path
915 int ModApiEnvMod::l_find_path(lua_State *L)
916 {
917         GET_ENV_PTR;
918
919         v3s16 pos1                  = read_v3s16(L, 1);
920         v3s16 pos2                  = read_v3s16(L, 2);
921         unsigned int searchdistance = luaL_checkint(L, 3);
922         unsigned int max_jump       = luaL_checkint(L, 4);
923         unsigned int max_drop       = luaL_checkint(L, 5);
924         PathAlgorithm algo          = PA_PLAIN_NP;
925         if (!lua_isnil(L, 6)) {
926                 std::string algorithm = luaL_checkstring(L,6);
927
928                 if (algorithm == "A*")
929                         algo = PA_PLAIN;
930
931                 if (algorithm == "Dijkstra")
932                         algo = PA_DIJKSTRA;
933         }
934
935         std::vector<v3s16> path = get_path(env, pos1, pos2,
936                 searchdistance, max_jump, max_drop, algo);
937
938         if (path.size() > 0)
939         {
940                 lua_newtable(L);
941                 int top = lua_gettop(L);
942                 unsigned int index = 1;
943                 for (std::vector<v3s16>::iterator i = path.begin(); i != path.end();i++)
944                 {
945                         lua_pushnumber(L,index);
946                         push_v3s16(L, *i);
947                         lua_settable(L, top);
948                         index++;
949                 }
950                 return 1;
951         }
952
953         return 0;
954 }
955
956 // spawn_tree(pos, treedef)
957 int ModApiEnvMod::l_spawn_tree(lua_State *L)
958 {
959         GET_ENV_PTR;
960
961         v3s16 p0 = read_v3s16(L, 1);
962
963         treegen::TreeDef tree_def;
964         std::string trunk,leaves,fruit;
965         INodeDefManager *ndef = env->getGameDef()->ndef();
966
967         if(lua_istable(L, 2))
968         {
969                 getstringfield(L, 2, "axiom", tree_def.initial_axiom);
970                 getstringfield(L, 2, "rules_a", tree_def.rules_a);
971                 getstringfield(L, 2, "rules_b", tree_def.rules_b);
972                 getstringfield(L, 2, "rules_c", tree_def.rules_c);
973                 getstringfield(L, 2, "rules_d", tree_def.rules_d);
974                 getstringfield(L, 2, "trunk", trunk);
975                 tree_def.trunknode=ndef->getId(trunk);
976                 getstringfield(L, 2, "leaves", leaves);
977                 tree_def.leavesnode=ndef->getId(leaves);
978                 tree_def.leaves2_chance=0;
979                 getstringfield(L, 2, "leaves2", leaves);
980                 if (leaves !="")
981                 {
982                         tree_def.leaves2node=ndef->getId(leaves);
983                         getintfield(L, 2, "leaves2_chance", tree_def.leaves2_chance);
984                 }
985                 getintfield(L, 2, "angle", tree_def.angle);
986                 getintfield(L, 2, "iterations", tree_def.iterations);
987                 if (!getintfield(L, 2, "random_level", tree_def.iterations_random_level))
988                         tree_def.iterations_random_level = 0;
989                 getstringfield(L, 2, "trunk_type", tree_def.trunk_type);
990                 getboolfield(L, 2, "thin_branches", tree_def.thin_branches);
991                 tree_def.fruit_chance=0;
992                 getstringfield(L, 2, "fruit", fruit);
993                 if (fruit != "")
994                 {
995                         tree_def.fruitnode=ndef->getId(fruit);
996                         getintfield(L, 2, "fruit_chance",tree_def.fruit_chance);
997                 }
998                 tree_def.explicit_seed = getintfield(L, 2, "seed", tree_def.seed);
999         }
1000         else
1001                 return 0;
1002
1003         treegen::error e;
1004         if ((e = treegen::spawn_ltree (env, p0, ndef, tree_def)) != treegen::SUCCESS) {
1005                 if (e == treegen::UNBALANCED_BRACKETS) {
1006                         luaL_error(L, "spawn_tree(): closing ']' has no matching opening bracket");
1007                 } else {
1008                         luaL_error(L, "spawn_tree(): unknown error");
1009                 }
1010         }
1011
1012         return 1;
1013 }
1014
1015 // transforming_liquid_add(pos)
1016 int ModApiEnvMod::l_transforming_liquid_add(lua_State *L)
1017 {
1018         GET_ENV_PTR;
1019
1020         v3s16 p0 = read_v3s16(L, 1);
1021         env->getMap().transforming_liquid_add(p0);
1022         return 1;
1023 }
1024
1025 // forceload_block(blockpos)
1026 // blockpos = {x=num, y=num, z=num}
1027 int ModApiEnvMod::l_forceload_block(lua_State *L)
1028 {
1029         GET_ENV_PTR;
1030
1031         v3s16 blockpos = read_v3s16(L, 1);
1032         env->getForceloadedBlocks()->insert(blockpos);
1033         return 0;
1034 }
1035
1036 // forceload_free_block(blockpos)
1037 // blockpos = {x=num, y=num, z=num}
1038 int ModApiEnvMod::l_forceload_free_block(lua_State *L)
1039 {
1040         GET_ENV_PTR;
1041
1042         v3s16 blockpos = read_v3s16(L, 1);
1043         env->getForceloadedBlocks()->erase(blockpos);
1044         return 0;
1045 }
1046
1047 void ModApiEnvMod::Initialize(lua_State *L, int top)
1048 {
1049         API_FCT(set_node);
1050         API_FCT(add_node);
1051         API_FCT(swap_node);
1052         API_FCT(add_item);
1053         API_FCT(remove_node);
1054         API_FCT(get_node);
1055         API_FCT(get_node_or_nil);
1056         API_FCT(get_node_light);
1057         API_FCT(place_node);
1058         API_FCT(dig_node);
1059         API_FCT(punch_node);
1060         API_FCT(get_node_max_level);
1061         API_FCT(get_node_level);
1062         API_FCT(set_node_level);
1063         API_FCT(add_node_level);
1064         API_FCT(add_entity);
1065         API_FCT(find_nodes_with_meta);
1066         API_FCT(get_meta);
1067         API_FCT(get_node_timer);
1068         API_FCT(get_player_by_name);
1069         API_FCT(get_objects_inside_radius);
1070         API_FCT(set_timeofday);
1071         API_FCT(get_timeofday);
1072         API_FCT(get_gametime);
1073         API_FCT(get_day_count);
1074         API_FCT(find_node_near);
1075         API_FCT(find_nodes_in_area);
1076         API_FCT(find_nodes_in_area_under_air);
1077         API_FCT(emerge_area);
1078         API_FCT(delete_area);
1079         API_FCT(get_perlin);
1080         API_FCT(get_perlin_map);
1081         API_FCT(get_voxel_manip);
1082         API_FCT(clear_objects);
1083         API_FCT(spawn_tree);
1084         API_FCT(find_path);
1085         API_FCT(line_of_sight);
1086         API_FCT(transforming_liquid_add);
1087         API_FCT(forceload_block);
1088         API_FCT(forceload_free_block);
1089 }