3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
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.
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.
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.
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"
29 #include "scripting_server.h"
30 #include "environment.h"
33 #include "daynightratio.h"
34 #include "util/pointedthing.h"
35 #include "content_sao.h"
38 #include "pathfinder.h"
39 #include "face_position_cache.h"
41 struct EnumString ModApiEnvMod::es_ClearObjectsMode[] =
43 {CLEAR_OBJECTS_MODE_FULL, "full"},
44 {CLEAR_OBJECTS_MODE_QUICK, "quick"},
48 ///////////////////////////////////////////////////////////////////////////////
51 void LuaABM::trigger(ServerEnvironment *env, v3s16 p, MapNode n,
52 u32 active_object_count, u32 active_object_count_wider)
54 ServerScripting *scriptIface = env->getScriptIface();
55 scriptIface->realityCheck();
57 lua_State *L = scriptIface->getStack();
58 sanity_check(lua_checkstack(L, 20));
59 StackUnroller stack_unroller(L);
61 int error_handler = PUSH_ERROR_HANDLER(L);
63 // Get registered_abms
64 lua_getglobal(L, "core");
65 lua_getfield(L, -1, "registered_abms");
66 luaL_checktype(L, -1, LUA_TTABLE);
67 lua_remove(L, -2); // Remove core
69 // Get registered_abms[m_id]
70 lua_pushnumber(L, m_id);
74 lua_remove(L, -2); // Remove registered_abms
76 scriptIface->setOriginFromTable(-1);
79 luaL_checktype(L, -1, LUA_TTABLE);
80 lua_getfield(L, -1, "action");
81 luaL_checktype(L, -1, LUA_TFUNCTION);
82 lua_remove(L, -2); // Remove registered_abms[m_id]
84 pushnode(L, n, env->getGameDef()->ndef());
85 lua_pushnumber(L, active_object_count);
86 lua_pushnumber(L, active_object_count_wider);
88 int result = lua_pcall(L, 4, 0, error_handler);
90 scriptIface->scriptError(result, "LuaABM::trigger");
92 lua_pop(L, 1); // Pop error handler
95 void LuaLBM::trigger(ServerEnvironment *env, v3s16 p, MapNode n)
97 ServerScripting *scriptIface = env->getScriptIface();
98 scriptIface->realityCheck();
100 lua_State *L = scriptIface->getStack();
101 sanity_check(lua_checkstack(L, 20));
102 StackUnroller stack_unroller(L);
104 int error_handler = PUSH_ERROR_HANDLER(L);
106 // Get registered_lbms
107 lua_getglobal(L, "core");
108 lua_getfield(L, -1, "registered_lbms");
109 luaL_checktype(L, -1, LUA_TTABLE);
110 lua_remove(L, -2); // Remove core
112 // Get registered_lbms[m_id]
113 lua_pushnumber(L, m_id);
115 FATAL_ERROR_IF(lua_isnil(L, -1), "Entry with given id not found in registered_lbms table");
116 lua_remove(L, -2); // Remove registered_lbms
118 scriptIface->setOriginFromTable(-1);
121 luaL_checktype(L, -1, LUA_TTABLE);
122 lua_getfield(L, -1, "action");
123 luaL_checktype(L, -1, LUA_TFUNCTION);
124 lua_remove(L, -2); // Remove registered_lbms[m_id]
126 pushnode(L, n, env->getGameDef()->ndef());
128 int result = lua_pcall(L, 2, 0, error_handler);
130 scriptIface->scriptError(result, "LuaLBM::trigger");
132 lua_pop(L, 1); // Pop error handler
135 int LuaRaycast::l_next(lua_State *L)
139 ScriptApiItem *script = getScriptApi<ScriptApiItem>(L);
142 LuaRaycast *o = checkobject(L, 1);
143 PointedThing pointed;
144 env->continueRaycast(&o->state, &pointed);
145 if (pointed.type == POINTEDTHING_NOTHING)
148 script->pushPointedThing(pointed);
153 int LuaRaycast::create_object(lua_State *L)
155 NO_MAP_LOCK_REQUIRED;
158 bool liquids = false;
160 v3f pos1 = checkFloatPos(L, 1);
161 v3f pos2 = checkFloatPos(L, 2);
162 if (lua_isboolean(L, 3)) {
163 objects = lua_toboolean(L, 3);
165 if (lua_isboolean(L, 4)) {
166 liquids = lua_toboolean(L, 4);
169 LuaRaycast *o = new LuaRaycast(core::line3d<f32>(pos1, pos2),
172 *(void **) (lua_newuserdata(L, sizeof(void *))) = o;
173 luaL_getmetatable(L, className);
174 lua_setmetatable(L, -2);
178 LuaRaycast *LuaRaycast::checkobject(lua_State *L, int narg)
180 NO_MAP_LOCK_REQUIRED;
182 luaL_checktype(L, narg, LUA_TUSERDATA);
183 void *ud = luaL_checkudata(L, narg, className);
185 luaL_typerror(L, narg, className);
186 return *(LuaRaycast **) ud;
189 int LuaRaycast::gc_object(lua_State *L)
191 LuaRaycast *o = *(LuaRaycast **) (lua_touserdata(L, 1));
196 void LuaRaycast::Register(lua_State *L)
199 int methodtable = lua_gettop(L);
200 luaL_newmetatable(L, className);
201 int metatable = lua_gettop(L);
203 lua_pushliteral(L, "__metatable");
204 lua_pushvalue(L, methodtable);
205 lua_settable(L, metatable);
207 lua_pushliteral(L, "__index");
208 lua_pushvalue(L, methodtable);
209 lua_settable(L, metatable);
211 lua_pushliteral(L, "__gc");
212 lua_pushcfunction(L, gc_object);
213 lua_settable(L, metatable);
215 lua_pushliteral(L, "__call");
216 lua_pushcfunction(L, l_next);
217 lua_settable(L, metatable);
221 luaL_openlib(L, 0, methods, 0);
224 lua_register(L, className, create_object);
227 const char LuaRaycast::className[] = "Raycast";
228 const luaL_Reg LuaRaycast::methods[] =
230 luamethod(LuaRaycast, next),
234 void LuaEmergeAreaCallback(v3s16 blockpos, EmergeAction action, void *param)
236 ScriptCallbackState *state = (ScriptCallbackState *)param;
237 assert(state != NULL);
238 assert(state->script != NULL);
239 assert(state->refcount > 0);
241 // state must be protected by envlock
242 Server *server = state->script->getServer();
243 MutexAutoLock envlock(server->m_env_mutex);
247 state->script->on_emerge_area_completion(blockpos, action, state);
249 if (state->refcount == 0)
253 // Exported functions
255 // set_node(pos, node)
256 // pos = {x=num, y=num, z=num}
257 int ModApiEnvMod::l_set_node(lua_State *L)
261 INodeDefManager *ndef = env->getGameDef()->ndef();
263 v3s16 pos = read_v3s16(L, 1);
264 MapNode n = readnode(L, 2, ndef);
266 bool succeeded = env->setNode(pos, n);
267 lua_pushboolean(L, succeeded);
271 int ModApiEnvMod::l_add_node(lua_State *L)
273 return l_set_node(L);
277 // pos = {x=num, y=num, z=num}
278 int ModApiEnvMod::l_remove_node(lua_State *L)
283 v3s16 pos = read_v3s16(L, 1);
285 bool succeeded = env->removeNode(pos);
286 lua_pushboolean(L, succeeded);
290 // swap_node(pos, node)
291 // pos = {x=num, y=num, z=num}
292 int ModApiEnvMod::l_swap_node(lua_State *L)
296 INodeDefManager *ndef = env->getGameDef()->ndef();
298 v3s16 pos = read_v3s16(L, 1);
299 MapNode n = readnode(L, 2, ndef);
301 bool succeeded = env->swapNode(pos, n);
302 lua_pushboolean(L, succeeded);
307 // pos = {x=num, y=num, z=num}
308 int ModApiEnvMod::l_get_node(lua_State *L)
313 v3s16 pos = read_v3s16(L, 1);
315 MapNode n = env->getMap().getNodeNoEx(pos);
317 pushnode(L, n, env->getGameDef()->ndef());
321 // get_node_or_nil(pos)
322 // pos = {x=num, y=num, z=num}
323 int ModApiEnvMod::l_get_node_or_nil(lua_State *L)
328 v3s16 pos = read_v3s16(L, 1);
331 MapNode n = env->getMap().getNodeNoEx(pos, &pos_ok);
334 pushnode(L, n, env->getGameDef()->ndef());
341 // get_node_light(pos, timeofday)
342 // pos = {x=num, y=num, z=num}
343 // timeofday: nil = current time, 0 = night, 0.5 = day
344 int ModApiEnvMod::l_get_node_light(lua_State *L)
349 v3s16 pos = read_v3s16(L, 1);
350 u32 time_of_day = env->getTimeOfDay();
351 if(lua_isnumber(L, 2))
352 time_of_day = 24000.0 * lua_tonumber(L, 2);
353 time_of_day %= 24000;
354 u32 dnr = time_to_daynight_ratio(time_of_day, true);
357 MapNode n = env->getMap().getNodeNoEx(pos, &is_position_ok);
358 if (is_position_ok) {
359 INodeDefManager *ndef = env->getGameDef()->ndef();
360 lua_pushinteger(L, n.getLightBlend(dnr, ndef));
367 // place_node(pos, node)
368 // pos = {x=num, y=num, z=num}
369 int ModApiEnvMod::l_place_node(lua_State *L)
373 ScriptApiItem *scriptIfaceItem = getScriptApi<ScriptApiItem>(L);
374 Server *server = getServer(L);
375 INodeDefManager *ndef = server->ndef();
376 IItemDefManager *idef = server->idef();
378 v3s16 pos = read_v3s16(L, 1);
379 MapNode n = readnode(L, 2, ndef);
381 // Don't attempt to load non-loaded area as of now
382 MapNode n_old = env->getMap().getNodeNoEx(pos);
383 if(n_old.getContent() == CONTENT_IGNORE){
384 lua_pushboolean(L, false);
387 // Create item to place
388 ItemStack item(ndef->get(n).name, 1, 0, idef);
389 // Make pointed position
390 PointedThing pointed;
391 pointed.type = POINTEDTHING_NODE;
392 pointed.node_abovesurface = pos;
393 pointed.node_undersurface = pos + v3s16(0,-1,0);
394 // Place it with a NULL placer (appears in Lua as a non-functional
396 bool success = scriptIfaceItem->item_OnPlace(item, NULL, pointed);
397 lua_pushboolean(L, success);
402 // pos = {x=num, y=num, z=num}
403 int ModApiEnvMod::l_dig_node(lua_State *L)
407 ScriptApiNode *scriptIfaceNode = getScriptApi<ScriptApiNode>(L);
409 v3s16 pos = read_v3s16(L, 1);
411 // Don't attempt to load non-loaded area as of now
412 MapNode n = env->getMap().getNodeNoEx(pos);
413 if(n.getContent() == CONTENT_IGNORE){
414 lua_pushboolean(L, false);
417 // Dig it out with a NULL digger (appears in Lua as a
418 // non-functional ObjectRef)
419 bool success = scriptIfaceNode->node_on_dig(pos, n, NULL);
420 lua_pushboolean(L, success);
425 // pos = {x=num, y=num, z=num}
426 int ModApiEnvMod::l_punch_node(lua_State *L)
430 ScriptApiNode *scriptIfaceNode = getScriptApi<ScriptApiNode>(L);
432 v3s16 pos = read_v3s16(L, 1);
434 // Don't attempt to load non-loaded area as of now
435 MapNode n = env->getMap().getNodeNoEx(pos);
436 if(n.getContent() == CONTENT_IGNORE){
437 lua_pushboolean(L, false);
440 // Punch it with a NULL puncher (appears in Lua as a non-functional
442 bool success = scriptIfaceNode->node_on_punch(pos, n, NULL, PointedThing());
443 lua_pushboolean(L, success);
447 // get_node_max_level(pos)
448 // pos = {x=num, y=num, z=num}
449 int ModApiEnvMod::l_get_node_max_level(lua_State *L)
451 Environment *env = getEnv(L);
456 v3s16 pos = read_v3s16(L, 1);
457 MapNode n = env->getMap().getNodeNoEx(pos);
458 lua_pushnumber(L, n.getMaxLevel(env->getGameDef()->ndef()));
462 // get_node_level(pos)
463 // pos = {x=num, y=num, z=num}
464 int ModApiEnvMod::l_get_node_level(lua_State *L)
466 Environment *env = getEnv(L);
471 v3s16 pos = read_v3s16(L, 1);
472 MapNode n = env->getMap().getNodeNoEx(pos);
473 lua_pushnumber(L, n.getLevel(env->getGameDef()->ndef()));
477 // set_node_level(pos, level)
478 // pos = {x=num, y=num, z=num}
480 int ModApiEnvMod::l_set_node_level(lua_State *L)
484 v3s16 pos = read_v3s16(L, 1);
486 if(lua_isnumber(L, 2))
487 level = lua_tonumber(L, 2);
488 MapNode n = env->getMap().getNodeNoEx(pos);
489 lua_pushnumber(L, n.setLevel(env->getGameDef()->ndef(), level));
490 env->setNode(pos, n);
494 // add_node_level(pos, level)
495 // pos = {x=num, y=num, z=num}
497 int ModApiEnvMod::l_add_node_level(lua_State *L)
501 v3s16 pos = read_v3s16(L, 1);
503 if(lua_isnumber(L, 2))
504 level = lua_tonumber(L, 2);
505 MapNode n = env->getMap().getNodeNoEx(pos);
506 lua_pushnumber(L, n.addLevel(env->getGameDef()->ndef(), level));
507 env->setNode(pos, n);
511 // find_nodes_with_meta(pos1, pos2)
512 int ModApiEnvMod::l_find_nodes_with_meta(lua_State *L)
516 std::vector<v3s16> positions = env->getMap().findNodesWithMetadata(
517 check_v3s16(L, 1), check_v3s16(L, 2));
520 for (size_t i = 0; i != positions.size(); i++) {
521 push_v3s16(L, positions[i]);
522 lua_rawseti(L, -2, i + 1);
529 int ModApiEnvMod::l_get_meta(lua_State *L)
534 v3s16 p = read_v3s16(L, 1);
535 NodeMetaRef::create(L, p, env);
539 // get_node_timer(pos)
540 int ModApiEnvMod::l_get_node_timer(lua_State *L)
545 v3s16 p = read_v3s16(L, 1);
546 NodeTimerRef::create(L, p, env);
550 // add_entity(pos, entityname, [staticdata]) -> ObjectRef or nil
551 // pos = {x=num, y=num, z=num}
552 int ModApiEnvMod::l_add_entity(lua_State *L)
557 v3f pos = checkFloatPos(L, 1);
559 const char *name = luaL_checkstring(L, 2);
561 const char *staticdata = luaL_optstring(L, 3, "");
563 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, staticdata);
564 int objectid = env->addActiveObject(obj);
565 // If failed to add, return nothing (reads as nil)
569 getScriptApiBase(L)->objectrefGetOrCreate(L, obj);
573 // add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
574 // pos = {x=num, y=num, z=num}
575 int ModApiEnvMod::l_add_item(lua_State *L)
580 //v3f pos = checkFloatPos(L, 1);
582 ItemStack item = read_item(L, 2,getServer(L)->idef());
583 if(item.empty() || !item.isKnown(getServer(L)->idef()))
586 int error_handler = PUSH_ERROR_HANDLER(L);
588 // Use spawn_item to spawn a __builtin:item
589 lua_getglobal(L, "core");
590 lua_getfield(L, -1, "spawn_item");
591 lua_remove(L, -2); // Remove core
595 lua_pushstring(L, item.getItemString().c_str());
597 PCALL_RESL(L, lua_pcall(L, 2, 1, error_handler));
599 lua_remove(L, error_handler);
603 // get_player_by_name(name)
604 int ModApiEnvMod::l_get_player_by_name(lua_State *L)
609 const char *name = luaL_checkstring(L, 1);
610 RemotePlayer *player = dynamic_cast<RemotePlayer *>(env->getPlayer(name));
615 PlayerSAO *sao = player->getPlayerSAO();
620 // Put player on stack
621 getScriptApiBase(L)->objectrefGetOrCreate(L, sao);
625 // get_objects_inside_radius(pos, radius)
626 int ModApiEnvMod::l_get_objects_inside_radius(lua_State *L)
631 v3f pos = checkFloatPos(L, 1);
632 float radius = luaL_checknumber(L, 2) * BS;
633 std::vector<u16> ids;
634 env->getObjectsInsideRadius(ids, pos, radius);
635 ScriptApiBase *script = getScriptApiBase(L);
636 lua_createtable(L, ids.size(), 0);
637 std::vector<u16>::const_iterator iter = ids.begin();
638 for(u32 i = 0; iter != ids.end(); ++iter) {
639 ServerActiveObject *obj = env->getActiveObject(*iter);
640 // Insert object reference into table
641 script->objectrefGetOrCreate(L, obj);
642 lua_rawseti(L, -2, ++i);
647 // set_timeofday(val)
649 int ModApiEnvMod::l_set_timeofday(lua_State *L)
654 float timeofday_f = luaL_checknumber(L, 1);
655 sanity_check(timeofday_f >= 0.0 && timeofday_f <= 1.0);
656 int timeofday_mh = (int)(timeofday_f * 24000.0);
657 // This should be set directly in the environment but currently
658 // such changes aren't immediately sent to the clients, so call
659 // the server instead.
660 //env->setTimeOfDay(timeofday_mh);
661 getServer(L)->setTimeOfDay(timeofday_mh);
665 // get_timeofday() -> 0...1
666 int ModApiEnvMod::l_get_timeofday(lua_State *L)
668 Environment *env = getEnv(L);
674 int timeofday_mh = env->getTimeOfDay();
675 float timeofday_f = (float)timeofday_mh / 24000.0f;
676 lua_pushnumber(L, timeofday_f);
680 // get_day_count() -> int
681 int ModApiEnvMod::l_get_day_count(lua_State *L)
683 Environment *env = getEnv(L);
688 lua_pushnumber(L, env->getDayCount());
693 int ModApiEnvMod::l_get_gametime(lua_State *L)
697 int game_time = env->getGameTime();
698 lua_pushnumber(L, game_time);
703 // find_node_near(pos, radius, nodenames, search_center) -> pos or nil
704 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
705 int ModApiEnvMod::l_find_node_near(lua_State *L)
707 Environment *env = getEnv(L);
712 INodeDefManager *ndef = getGameDef(L)->ndef();
713 v3s16 pos = read_v3s16(L, 1);
714 int radius = luaL_checkinteger(L, 2);
715 std::set<content_t> filter;
716 if (lua_istable(L, 3)) {
718 while (lua_next(L, 3) != 0) {
719 // key at index -2 and value at index -1
720 luaL_checktype(L, -1, LUA_TSTRING);
721 ndef->getIds(lua_tostring(L, -1), filter);
722 // removes value, keeps key for next iteration
725 } else if (lua_isstring(L, 3)) {
726 ndef->getIds(lua_tostring(L, 3), filter);
729 int start_radius = (lua_toboolean(L, 4)) ? 0 : 1;
732 // Client API limitations
734 getClient(L)->checkCSMFlavourLimit(CSMFlavourLimit::CSM_FL_LOOKUP_NODES)) {
735 radius = std::max<int>(radius, getClient(L)->getCSMNodeRangeLimit());
739 for (int d = start_radius; d <= radius; d++) {
740 std::vector<v3s16> list = FacePositionCache::getFacePositions(d);
741 for (std::vector<v3s16>::iterator i = list.begin();
742 i != list.end(); ++i) {
743 v3s16 p = pos + (*i);
744 content_t c = env->getMap().getNodeNoEx(p).getContent();
745 if (filter.count(c) != 0) {
754 // find_nodes_in_area(minp, maxp, nodenames) -> list of positions
755 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
756 int ModApiEnvMod::l_find_nodes_in_area(lua_State *L)
760 INodeDefManager *ndef = getServer(L)->ndef();
761 v3s16 minp = read_v3s16(L, 1);
762 v3s16 maxp = read_v3s16(L, 2);
763 sortBoxVerticies(minp, maxp);
765 v3s16 cube = maxp - minp + 1;
767 /* Limit for too large areas, assume default values
768 * and give tolerances of 1 node on each side
769 * (chunksize * MAP_BLOCKSIZE + 2)^3 = 551368
771 if ((u64)cube.X * (u64)cube.Y * (u64)cube.Z > 551368) {
772 luaL_error(L, "find_nodes_in_area(): area volume"
773 " exceeds allowed value of 551368");
777 std::set<content_t> filter;
778 if (lua_istable(L, 3)) {
780 while (lua_next(L, 3) != 0) {
781 // key at index -2 and value at index -1
782 luaL_checktype(L, -1, LUA_TSTRING);
783 ndef->getIds(lua_tostring(L, -1), filter);
784 // removes value, keeps key for next iteration
787 } else if (lua_isstring(L, 3)) {
788 ndef->getIds(lua_tostring(L, 3), filter);
791 std::unordered_map<content_t, u32> individual_count;
795 for (s16 x = minp.X; x <= maxp.X; x++)
796 for (s16 y = minp.Y; y <= maxp.Y; y++)
797 for (s16 z = minp.Z; z <= maxp.Z; z++) {
799 content_t c = env->getMap().getNodeNoEx(p).getContent();
800 if (filter.count(c) != 0) {
802 lua_rawseti(L, -2, ++i);
803 individual_count[c]++;
807 for (std::set<content_t>::const_iterator it = filter.begin();
808 it != filter.end(); ++it) {
809 lua_pushnumber(L, individual_count[*it]);
810 lua_setfield(L, -2, ndef->get(*it).name.c_str());
815 // find_nodes_in_area_under_air(minp, maxp, nodenames) -> list of positions
816 // nodenames: e.g. {"ignore", "group:tree"} or "default:dirt"
817 int ModApiEnvMod::l_find_nodes_in_area_under_air(lua_State *L)
819 /* Note: A similar but generalized (and therefore slower) version of this
820 * function could be created -- e.g. find_nodes_in_area_under -- which
821 * would accept a node name (or ID?) or list of names that the "above node"
828 INodeDefManager *ndef = getServer(L)->ndef();
829 v3s16 minp = read_v3s16(L, 1);
830 v3s16 maxp = read_v3s16(L, 2);
831 sortBoxVerticies(minp, maxp);
833 v3s16 cube = maxp - minp + 1;
835 /* Limit for too large areas, assume default values
836 * and give tolerances of 1 node on each side
837 * (chunksize * MAP_BLOCKSIZE + 2)^3 = 551368
839 if ((u64)cube.X * (u64)cube.Y * (u64)cube.Z > 551368) {
840 luaL_error(L, "find_nodes_in_area_under_air(): area volume"
841 " exceeds allowed value of 551368");
845 std::set<content_t> filter;
847 if (lua_istable(L, 3)) {
849 while (lua_next(L, 3) != 0) {
850 // key at index -2 and value at index -1
851 luaL_checktype(L, -1, LUA_TSTRING);
852 ndef->getIds(lua_tostring(L, -1), filter);
853 // removes value, keeps key for next iteration
856 } else if (lua_isstring(L, 3)) {
857 ndef->getIds(lua_tostring(L, 3), filter);
862 for (s16 x = minp.X; x <= maxp.X; x++)
863 for (s16 z = minp.Z; z <= maxp.Z; z++) {
866 content_t c = env->getMap().getNodeNoEx(p).getContent();
867 for (; y <= maxp.Y; y++) {
868 v3s16 psurf(x, y + 1, z);
869 content_t csurf = env->getMap().getNodeNoEx(psurf).getContent();
870 if (c != CONTENT_AIR && csurf == CONTENT_AIR &&
871 filter.count(c) != 0) {
872 push_v3s16(L, v3s16(x, y, z));
873 lua_rawseti(L, -2, ++i);
881 // get_perlin(seeddiff, octaves, persistence, scale)
882 // returns world-specific PerlinNoise
883 int ModApiEnvMod::l_get_perlin(lua_State *L)
885 GET_ENV_PTR_NO_MAP_LOCK;
889 if (lua_istable(L, 1)) {
890 read_noiseparams(L, 1, ¶ms);
892 params.seed = luaL_checkint(L, 1);
893 params.octaves = luaL_checkint(L, 2);
894 params.persist = luaL_checknumber(L, 3);
895 params.spread = v3f(1, 1, 1) * luaL_checknumber(L, 4);
898 params.seed += (int)env->getServerMap().getSeed();
900 LuaPerlinNoise *n = new LuaPerlinNoise(¶ms);
901 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
902 luaL_getmetatable(L, "PerlinNoise");
903 lua_setmetatable(L, -2);
907 // get_perlin_map(noiseparams, size)
908 // returns world-specific PerlinNoiseMap
909 int ModApiEnvMod::l_get_perlin_map(lua_State *L)
911 GET_ENV_PTR_NO_MAP_LOCK;
914 if (!read_noiseparams(L, 1, &np))
916 v3s16 size = read_v3s16(L, 2);
918 s32 seed = (s32)(env->getServerMap().getSeed());
919 LuaPerlinNoiseMap *n = new LuaPerlinNoiseMap(&np, seed, size);
920 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
921 luaL_getmetatable(L, "PerlinNoiseMap");
922 lua_setmetatable(L, -2);
927 // returns voxel manipulator
928 int ModApiEnvMod::l_get_voxel_manip(lua_State *L)
932 Map *map = &(env->getMap());
933 LuaVoxelManip *o = (lua_istable(L, 1) && lua_istable(L, 2)) ?
934 new LuaVoxelManip(map, read_v3s16(L, 1), read_v3s16(L, 2)) :
935 new LuaVoxelManip(map);
937 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
938 luaL_getmetatable(L, "VoxelManip");
939 lua_setmetatable(L, -2);
943 // clear_objects([options])
944 // clear all objects in the environment
945 // where options = {mode = "full" or "quick"}
946 int ModApiEnvMod::l_clear_objects(lua_State *L)
950 ClearObjectsMode mode = CLEAR_OBJECTS_MODE_FULL;
951 if (lua_istable(L, 1)) {
952 mode = (ClearObjectsMode)getenumfield(L, 1, "mode",
953 ModApiEnvMod::es_ClearObjectsMode, mode);
956 env->clearObjects(mode);
960 // line_of_sight(pos1, pos2, stepsize) -> true/false, pos
961 int ModApiEnvMod::l_line_of_sight(lua_State *L)
963 float stepsize = 1.0;
967 // read position 1 from lua
968 v3f pos1 = checkFloatPos(L, 1);
969 // read position 2 from lua
970 v3f pos2 = checkFloatPos(L, 2);
971 //read step size from lua
972 if (lua_isnumber(L, 3)) {
973 stepsize = lua_tonumber(L, 3);
977 bool success = env->line_of_sight(pos1, pos2, stepsize, &p);
978 lua_pushboolean(L, success);
987 int ModApiEnvMod::l_fix_light(lua_State *L)
991 v3s16 blockpos1 = getContainerPos(read_v3s16(L, 1), MAP_BLOCKSIZE);
992 v3s16 blockpos2 = getContainerPos(read_v3s16(L, 2), MAP_BLOCKSIZE);
993 ServerMap &map = env->getServerMap();
994 std::map<v3s16, MapBlock *> modified_blocks;
997 for (blockpos.X = blockpos1.X; blockpos.X <= blockpos2.X; blockpos.X++)
998 for (blockpos.Y = blockpos1.Y; blockpos.Y <= blockpos2.Y; blockpos.Y++)
999 for (blockpos.Z = blockpos1.Z; blockpos.Z <= blockpos2.Z; blockpos.Z++) {
1000 success = success & map.repairBlockLight(blockpos, &modified_blocks);
1002 if (modified_blocks.size() > 0) {
1004 event.type = MEET_OTHER;
1005 for (std::map<v3s16, MapBlock *>::iterator it = modified_blocks.begin();
1006 it != modified_blocks.end(); ++it)
1007 event.modified_blocks.insert(it->first);
1009 map.dispatchEvent(&event);
1011 lua_pushboolean(L, success);
1016 int ModApiEnvMod::l_raycast(lua_State *L)
1018 return LuaRaycast::create_object(L);
1021 // emerge_area(p1, p2, [callback, context])
1022 // emerge mapblocks in area p1..p2, calls callback with context upon completion
1023 int ModApiEnvMod::l_emerge_area(lua_State *L)
1027 EmergeCompletionCallback callback = NULL;
1028 ScriptCallbackState *state = NULL;
1030 EmergeManager *emerge = getServer(L)->getEmergeManager();
1032 v3s16 bpmin = getNodeBlockPos(read_v3s16(L, 1));
1033 v3s16 bpmax = getNodeBlockPos(read_v3s16(L, 2));
1034 sortBoxVerticies(bpmin, bpmax);
1036 size_t num_blocks = VoxelArea(bpmin, bpmax).getVolume();
1037 assert(num_blocks != 0);
1039 if (lua_isfunction(L, 3)) {
1040 callback = LuaEmergeAreaCallback;
1042 lua_pushvalue(L, 3);
1043 int callback_ref = luaL_ref(L, LUA_REGISTRYINDEX);
1045 lua_pushvalue(L, 4);
1046 int args_ref = luaL_ref(L, LUA_REGISTRYINDEX);
1048 state = new ScriptCallbackState;
1049 state->script = getServer(L)->getScriptIface();
1050 state->callback_ref = callback_ref;
1051 state->args_ref = args_ref;
1052 state->refcount = num_blocks;
1053 state->origin = getScriptApiBase(L)->getOrigin();
1056 for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
1057 for (s16 y = bpmin.Y; y <= bpmax.Y; y++)
1058 for (s16 x = bpmin.X; x <= bpmax.X; x++) {
1059 emerge->enqueueBlockEmergeEx(v3s16(x, y, z), PEER_ID_INEXISTENT,
1060 BLOCK_EMERGE_ALLOW_GEN | BLOCK_EMERGE_FORCE_QUEUE, callback, state);
1066 // delete_area(p1, p2)
1067 // delete mapblocks in area p1..p2
1068 int ModApiEnvMod::l_delete_area(lua_State *L)
1072 v3s16 bpmin = getNodeBlockPos(read_v3s16(L, 1));
1073 v3s16 bpmax = getNodeBlockPos(read_v3s16(L, 2));
1074 sortBoxVerticies(bpmin, bpmax);
1076 ServerMap &map = env->getServerMap();
1079 event.type = MEET_OTHER;
1081 bool success = true;
1082 for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
1083 for (s16 y = bpmin.Y; y <= bpmax.Y; y++)
1084 for (s16 x = bpmin.X; x <= bpmax.X; x++) {
1086 if (map.deleteBlock(bp)) {
1087 env->setStaticForActiveObjectsInBlock(bp, false);
1088 event.modified_blocks.insert(bp);
1094 map.dispatchEvent(&event);
1095 lua_pushboolean(L, success);
1099 // find_path(pos1, pos2, searchdistance,
1100 // max_jump, max_drop, algorithm) -> table containing path
1101 int ModApiEnvMod::l_find_path(lua_State *L)
1105 v3s16 pos1 = read_v3s16(L, 1);
1106 v3s16 pos2 = read_v3s16(L, 2);
1107 unsigned int searchdistance = luaL_checkint(L, 3);
1108 unsigned int max_jump = luaL_checkint(L, 4);
1109 unsigned int max_drop = luaL_checkint(L, 5);
1110 PathAlgorithm algo = PA_PLAIN_NP;
1111 if (!lua_isnil(L, 6)) {
1112 std::string algorithm = luaL_checkstring(L,6);
1114 if (algorithm == "A*")
1117 if (algorithm == "Dijkstra")
1121 std::vector<v3s16> path = get_path(env, pos1, pos2,
1122 searchdistance, max_jump, max_drop, algo);
1124 if (path.size() > 0)
1127 int top = lua_gettop(L);
1128 unsigned int index = 1;
1129 for (std::vector<v3s16>::iterator i = path.begin(); i != path.end(); ++i) {
1130 lua_pushnumber(L,index);
1132 lua_settable(L, top);
1141 // spawn_tree(pos, treedef)
1142 int ModApiEnvMod::l_spawn_tree(lua_State *L)
1146 v3s16 p0 = read_v3s16(L, 1);
1148 treegen::TreeDef tree_def;
1149 std::string trunk,leaves,fruit;
1150 INodeDefManager *ndef = env->getGameDef()->ndef();
1152 if(lua_istable(L, 2))
1154 getstringfield(L, 2, "axiom", tree_def.initial_axiom);
1155 getstringfield(L, 2, "rules_a", tree_def.rules_a);
1156 getstringfield(L, 2, "rules_b", tree_def.rules_b);
1157 getstringfield(L, 2, "rules_c", tree_def.rules_c);
1158 getstringfield(L, 2, "rules_d", tree_def.rules_d);
1159 getstringfield(L, 2, "trunk", trunk);
1160 tree_def.trunknode=ndef->getId(trunk);
1161 getstringfield(L, 2, "leaves", leaves);
1162 tree_def.leavesnode=ndef->getId(leaves);
1163 tree_def.leaves2_chance=0;
1164 getstringfield(L, 2, "leaves2", leaves);
1167 tree_def.leaves2node=ndef->getId(leaves);
1168 getintfield(L, 2, "leaves2_chance", tree_def.leaves2_chance);
1170 getintfield(L, 2, "angle", tree_def.angle);
1171 getintfield(L, 2, "iterations", tree_def.iterations);
1172 if (!getintfield(L, 2, "random_level", tree_def.iterations_random_level))
1173 tree_def.iterations_random_level = 0;
1174 getstringfield(L, 2, "trunk_type", tree_def.trunk_type);
1175 getboolfield(L, 2, "thin_branches", tree_def.thin_branches);
1176 tree_def.fruit_chance=0;
1177 getstringfield(L, 2, "fruit", fruit);
1180 tree_def.fruitnode=ndef->getId(fruit);
1181 getintfield(L, 2, "fruit_chance",tree_def.fruit_chance);
1183 tree_def.explicit_seed = getintfield(L, 2, "seed", tree_def.seed);
1189 if ((e = treegen::spawn_ltree (env, p0, ndef, tree_def)) != treegen::SUCCESS) {
1190 if (e == treegen::UNBALANCED_BRACKETS) {
1191 luaL_error(L, "spawn_tree(): closing ']' has no matching opening bracket");
1193 luaL_error(L, "spawn_tree(): unknown error");
1200 // transforming_liquid_add(pos)
1201 int ModApiEnvMod::l_transforming_liquid_add(lua_State *L)
1205 v3s16 p0 = read_v3s16(L, 1);
1206 env->getMap().transforming_liquid_add(p0);
1210 // forceload_block(blockpos)
1211 // blockpos = {x=num, y=num, z=num}
1212 int ModApiEnvMod::l_forceload_block(lua_State *L)
1216 v3s16 blockpos = read_v3s16(L, 1);
1217 env->getForceloadedBlocks()->insert(blockpos);
1221 // forceload_free_block(blockpos)
1222 // blockpos = {x=num, y=num, z=num}
1223 int ModApiEnvMod::l_forceload_free_block(lua_State *L)
1227 v3s16 blockpos = read_v3s16(L, 1);
1228 env->getForceloadedBlocks()->erase(blockpos);
1232 void ModApiEnvMod::Initialize(lua_State *L, int top)
1238 API_FCT(remove_node);
1240 API_FCT(get_node_or_nil);
1241 API_FCT(get_node_light);
1242 API_FCT(place_node);
1244 API_FCT(punch_node);
1245 API_FCT(get_node_max_level);
1246 API_FCT(get_node_level);
1247 API_FCT(set_node_level);
1248 API_FCT(add_node_level);
1249 API_FCT(add_entity);
1250 API_FCT(find_nodes_with_meta);
1252 API_FCT(get_node_timer);
1253 API_FCT(get_player_by_name);
1254 API_FCT(get_objects_inside_radius);
1255 API_FCT(set_timeofday);
1256 API_FCT(get_timeofday);
1257 API_FCT(get_gametime);
1258 API_FCT(get_day_count);
1259 API_FCT(find_node_near);
1260 API_FCT(find_nodes_in_area);
1261 API_FCT(find_nodes_in_area_under_air);
1263 API_FCT(emerge_area);
1264 API_FCT(delete_area);
1265 API_FCT(get_perlin);
1266 API_FCT(get_perlin_map);
1267 API_FCT(get_voxel_manip);
1268 API_FCT(clear_objects);
1269 API_FCT(spawn_tree);
1271 API_FCT(line_of_sight);
1273 API_FCT(transforming_liquid_add);
1274 API_FCT(forceload_block);
1275 API_FCT(forceload_free_block);
1278 void ModApiEnvMod::InitializeClient(lua_State *L, int top)
1280 API_FCT(get_timeofday);
1281 API_FCT(get_day_count);
1282 API_FCT(get_node_max_level);
1283 API_FCT(get_node_level);
1284 API_FCT(find_node_near);