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"
34 #include "daynightratio.h"
35 #include "util/pointedthing.h"
36 #include "content_sao.h"
37 #include "mapgen/treegen.h"
39 #include "pathfinder.h"
40 #include "face_position_cache.h"
41 #include "remoteplayer.h"
46 struct EnumString ModApiEnvMod::es_ClearObjectsMode[] =
48 {CLEAR_OBJECTS_MODE_FULL, "full"},
49 {CLEAR_OBJECTS_MODE_QUICK, "quick"},
53 ///////////////////////////////////////////////////////////////////////////////
56 void LuaABM::trigger(ServerEnvironment *env, v3s16 p, MapNode n,
57 u32 active_object_count, u32 active_object_count_wider)
59 ServerScripting *scriptIface = env->getScriptIface();
60 scriptIface->realityCheck();
62 lua_State *L = scriptIface->getStack();
63 sanity_check(lua_checkstack(L, 20));
64 StackUnroller stack_unroller(L);
66 int error_handler = PUSH_ERROR_HANDLER(L);
68 // Get registered_abms
69 lua_getglobal(L, "core");
70 lua_getfield(L, -1, "registered_abms");
71 luaL_checktype(L, -1, LUA_TTABLE);
72 lua_remove(L, -2); // Remove core
74 // Get registered_abms[m_id]
75 lua_pushnumber(L, m_id);
79 lua_remove(L, -2); // Remove registered_abms
81 scriptIface->setOriginFromTable(-1);
84 luaL_checktype(L, -1, LUA_TTABLE);
85 lua_getfield(L, -1, "action");
86 luaL_checktype(L, -1, LUA_TFUNCTION);
87 lua_remove(L, -2); // Remove registered_abms[m_id]
89 pushnode(L, n, env->getGameDef()->ndef());
90 lua_pushnumber(L, active_object_count);
91 lua_pushnumber(L, active_object_count_wider);
93 int result = lua_pcall(L, 4, 0, error_handler);
95 scriptIface->scriptError(result, "LuaABM::trigger");
97 lua_pop(L, 1); // Pop error handler
100 void LuaLBM::trigger(ServerEnvironment *env, v3s16 p, MapNode n)
102 ServerScripting *scriptIface = env->getScriptIface();
103 scriptIface->realityCheck();
105 lua_State *L = scriptIface->getStack();
106 sanity_check(lua_checkstack(L, 20));
107 StackUnroller stack_unroller(L);
109 int error_handler = PUSH_ERROR_HANDLER(L);
111 // Get registered_lbms
112 lua_getglobal(L, "core");
113 lua_getfield(L, -1, "registered_lbms");
114 luaL_checktype(L, -1, LUA_TTABLE);
115 lua_remove(L, -2); // Remove core
117 // Get registered_lbms[m_id]
118 lua_pushnumber(L, m_id);
120 FATAL_ERROR_IF(lua_isnil(L, -1), "Entry with given id not found in registered_lbms table");
121 lua_remove(L, -2); // Remove registered_lbms
123 scriptIface->setOriginFromTable(-1);
126 luaL_checktype(L, -1, LUA_TTABLE);
127 lua_getfield(L, -1, "action");
128 luaL_checktype(L, -1, LUA_TFUNCTION);
129 lua_remove(L, -2); // Remove registered_lbms[m_id]
131 pushnode(L, n, env->getGameDef()->ndef());
133 int result = lua_pcall(L, 2, 0, error_handler);
135 scriptIface->scriptError(result, "LuaLBM::trigger");
137 lua_pop(L, 1); // Pop error handler
140 int LuaRaycast::l_next(lua_State *L)
144 ScriptApiItem *script = getScriptApi<ScriptApiItem>(L);
147 LuaRaycast *o = checkobject(L, 1);
148 PointedThing pointed;
149 env->continueRaycast(&o->state, &pointed);
150 if (pointed.type == POINTEDTHING_NOTHING)
153 script->pushPointedThing(pointed);
158 int LuaRaycast::create_object(lua_State *L)
160 NO_MAP_LOCK_REQUIRED;
163 bool liquids = false;
165 v3f pos1 = checkFloatPos(L, 1);
166 v3f pos2 = checkFloatPos(L, 2);
167 if (lua_isboolean(L, 3)) {
168 objects = readParam<bool>(L, 3);
170 if (lua_isboolean(L, 4)) {
171 liquids = readParam<bool>(L, 4);
174 LuaRaycast *o = new LuaRaycast(core::line3d<f32>(pos1, pos2),
177 *(void **) (lua_newuserdata(L, sizeof(void *))) = o;
178 luaL_getmetatable(L, className);
179 lua_setmetatable(L, -2);
183 LuaRaycast *LuaRaycast::checkobject(lua_State *L, int narg)
185 NO_MAP_LOCK_REQUIRED;
187 luaL_checktype(L, narg, LUA_TUSERDATA);
188 void *ud = luaL_checkudata(L, narg, className);
190 luaL_typerror(L, narg, className);
191 return *(LuaRaycast **) ud;
194 int LuaRaycast::gc_object(lua_State *L)
196 LuaRaycast *o = *(LuaRaycast **) (lua_touserdata(L, 1));
201 void LuaRaycast::Register(lua_State *L)
204 int methodtable = lua_gettop(L);
205 luaL_newmetatable(L, className);
206 int metatable = lua_gettop(L);
208 lua_pushliteral(L, "__metatable");
209 lua_pushvalue(L, methodtable);
210 lua_settable(L, metatable);
212 lua_pushliteral(L, "__index");
213 lua_pushvalue(L, methodtable);
214 lua_settable(L, metatable);
216 lua_pushliteral(L, "__gc");
217 lua_pushcfunction(L, gc_object);
218 lua_settable(L, metatable);
220 lua_pushliteral(L, "__call");
221 lua_pushcfunction(L, l_next);
222 lua_settable(L, metatable);
226 luaL_openlib(L, 0, methods, 0);
229 lua_register(L, className, create_object);
232 const char LuaRaycast::className[] = "Raycast";
233 const luaL_Reg LuaRaycast::methods[] =
235 luamethod(LuaRaycast, next),
239 void LuaEmergeAreaCallback(v3s16 blockpos, EmergeAction action, void *param)
241 ScriptCallbackState *state = (ScriptCallbackState *)param;
242 assert(state != NULL);
243 assert(state->script != NULL);
244 assert(state->refcount > 0);
246 // state must be protected by envlock
247 Server *server = state->script->getServer();
248 MutexAutoLock envlock(server->m_env_mutex);
252 state->script->on_emerge_area_completion(blockpos, action, state);
254 if (state->refcount == 0)
258 // Exported functions
260 // set_node(pos, node)
261 // pos = {x=num, y=num, z=num}
262 int ModApiEnvMod::l_set_node(lua_State *L)
266 const NodeDefManager *ndef = env->getGameDef()->ndef();
268 v3s16 pos = read_v3s16(L, 1);
269 MapNode n = readnode(L, 2, ndef);
271 bool succeeded = env->setNode(pos, n);
272 lua_pushboolean(L, succeeded);
276 // bulk_set_node([pos1, pos2, ...], node)
277 // pos = {x=num, y=num, z=num}
278 int ModApiEnvMod::l_bulk_set_node(lua_State *L)
282 const NodeDefManager *ndef = env->getGameDef()->ndef();
284 if (!lua_istable(L, 1)) {
288 s32 len = lua_objlen(L, 1);
290 lua_pushboolean(L, true);
294 MapNode n = readnode(L, 2, ndef);
297 bool succeeded = true;
298 for (s32 i = 1; i <= len; i++) {
299 lua_rawgeti(L, 1, i);
300 if (!env->setNode(read_v3s16(L, -1), n))
305 lua_pushboolean(L, succeeded);
309 int ModApiEnvMod::l_add_node(lua_State *L)
311 return l_set_node(L);
315 // pos = {x=num, y=num, z=num}
316 int ModApiEnvMod::l_remove_node(lua_State *L)
321 v3s16 pos = read_v3s16(L, 1);
323 bool succeeded = env->removeNode(pos);
324 lua_pushboolean(L, succeeded);
328 // swap_node(pos, node)
329 // pos = {x=num, y=num, z=num}
330 int ModApiEnvMod::l_swap_node(lua_State *L)
334 const NodeDefManager *ndef = env->getGameDef()->ndef();
336 v3s16 pos = read_v3s16(L, 1);
337 MapNode n = readnode(L, 2, ndef);
339 bool succeeded = env->swapNode(pos, n);
340 lua_pushboolean(L, succeeded);
345 // pos = {x=num, y=num, z=num}
346 int ModApiEnvMod::l_get_node(lua_State *L)
351 v3s16 pos = read_v3s16(L, 1);
353 MapNode n = env->getMap().getNodeNoEx(pos);
355 pushnode(L, n, env->getGameDef()->ndef());
359 // get_node_or_nil(pos)
360 // pos = {x=num, y=num, z=num}
361 int ModApiEnvMod::l_get_node_or_nil(lua_State *L)
366 v3s16 pos = read_v3s16(L, 1);
369 MapNode n = env->getMap().getNodeNoEx(pos, &pos_ok);
372 pushnode(L, n, env->getGameDef()->ndef());
379 // get_node_light(pos, timeofday)
380 // pos = {x=num, y=num, z=num}
381 // timeofday: nil = current time, 0 = night, 0.5 = day
382 int ModApiEnvMod::l_get_node_light(lua_State *L)
387 v3s16 pos = read_v3s16(L, 1);
388 u32 time_of_day = env->getTimeOfDay();
389 if(lua_isnumber(L, 2))
390 time_of_day = 24000.0 * lua_tonumber(L, 2);
391 time_of_day %= 24000;
392 u32 dnr = time_to_daynight_ratio(time_of_day, true);
395 MapNode n = env->getMap().getNodeNoEx(pos, &is_position_ok);
396 if (is_position_ok) {
397 const NodeDefManager *ndef = env->getGameDef()->ndef();
398 lua_pushinteger(L, n.getLightBlend(dnr, ndef));
405 // place_node(pos, node)
406 // pos = {x=num, y=num, z=num}
407 int ModApiEnvMod::l_place_node(lua_State *L)
411 ScriptApiItem *scriptIfaceItem = getScriptApi<ScriptApiItem>(L);
412 Server *server = getServer(L);
413 const NodeDefManager *ndef = server->ndef();
414 IItemDefManager *idef = server->idef();
416 v3s16 pos = read_v3s16(L, 1);
417 MapNode n = readnode(L, 2, ndef);
419 // Don't attempt to load non-loaded area as of now
420 MapNode n_old = env->getMap().getNodeNoEx(pos);
421 if(n_old.getContent() == CONTENT_IGNORE){
422 lua_pushboolean(L, false);
425 // Create item to place
426 ItemStack item(ndef->get(n).name, 1, 0, idef);
427 // Make pointed position
428 PointedThing pointed;
429 pointed.type = POINTEDTHING_NODE;
430 pointed.node_abovesurface = pos;
431 pointed.node_undersurface = pos + v3s16(0,-1,0);
432 // Place it with a NULL placer (appears in Lua as nil)
433 bool success = scriptIfaceItem->item_OnPlace(item, nullptr, pointed);
434 lua_pushboolean(L, success);
439 // pos = {x=num, y=num, z=num}
440 int ModApiEnvMod::l_dig_node(lua_State *L)
444 ScriptApiNode *scriptIfaceNode = getScriptApi<ScriptApiNode>(L);
446 v3s16 pos = read_v3s16(L, 1);
448 // Don't attempt to load non-loaded area as of now
449 MapNode n = env->getMap().getNodeNoEx(pos);
450 if(n.getContent() == CONTENT_IGNORE){
451 lua_pushboolean(L, false);
454 // Dig it out with a NULL digger (appears in Lua as a
455 // non-functional ObjectRef)
456 bool success = scriptIfaceNode->node_on_dig(pos, n, NULL);
457 lua_pushboolean(L, success);
462 // pos = {x=num, y=num, z=num}
463 int ModApiEnvMod::l_punch_node(lua_State *L)
467 ScriptApiNode *scriptIfaceNode = getScriptApi<ScriptApiNode>(L);
469 v3s16 pos = read_v3s16(L, 1);
471 // Don't attempt to load non-loaded area as of now
472 MapNode n = env->getMap().getNodeNoEx(pos);
473 if(n.getContent() == CONTENT_IGNORE){
474 lua_pushboolean(L, false);
477 // Punch it with a NULL puncher (appears in Lua as a non-functional
479 bool success = scriptIfaceNode->node_on_punch(pos, n, NULL, PointedThing());
480 lua_pushboolean(L, success);
484 // get_node_max_level(pos)
485 // pos = {x=num, y=num, z=num}
486 int ModApiEnvMod::l_get_node_max_level(lua_State *L)
488 Environment *env = getEnv(L);
493 v3s16 pos = read_v3s16(L, 1);
494 MapNode n = env->getMap().getNodeNoEx(pos);
495 lua_pushnumber(L, n.getMaxLevel(env->getGameDef()->ndef()));
499 // get_node_level(pos)
500 // pos = {x=num, y=num, z=num}
501 int ModApiEnvMod::l_get_node_level(lua_State *L)
503 Environment *env = getEnv(L);
508 v3s16 pos = read_v3s16(L, 1);
509 MapNode n = env->getMap().getNodeNoEx(pos);
510 lua_pushnumber(L, n.getLevel(env->getGameDef()->ndef()));
514 // set_node_level(pos, level)
515 // pos = {x=num, y=num, z=num}
517 int ModApiEnvMod::l_set_node_level(lua_State *L)
521 v3s16 pos = read_v3s16(L, 1);
523 if(lua_isnumber(L, 2))
524 level = lua_tonumber(L, 2);
525 MapNode n = env->getMap().getNodeNoEx(pos);
526 lua_pushnumber(L, n.setLevel(env->getGameDef()->ndef(), level));
527 env->setNode(pos, n);
531 // add_node_level(pos, level)
532 // pos = {x=num, y=num, z=num}
534 int ModApiEnvMod::l_add_node_level(lua_State *L)
538 v3s16 pos = read_v3s16(L, 1);
540 if(lua_isnumber(L, 2))
541 level = lua_tonumber(L, 2);
542 MapNode n = env->getMap().getNodeNoEx(pos);
543 lua_pushnumber(L, n.addLevel(env->getGameDef()->ndef(), level));
544 env->setNode(pos, n);
548 // find_nodes_with_meta(pos1, pos2)
549 int ModApiEnvMod::l_find_nodes_with_meta(lua_State *L)
553 std::vector<v3s16> positions = env->getMap().findNodesWithMetadata(
554 check_v3s16(L, 1), check_v3s16(L, 2));
557 for (size_t i = 0; i != positions.size(); i++) {
558 push_v3s16(L, positions[i]);
559 lua_rawseti(L, -2, i + 1);
566 int ModApiEnvMod::l_get_meta(lua_State *L)
571 v3s16 p = read_v3s16(L, 1);
572 NodeMetaRef::create(L, p, env);
576 // get_node_timer(pos)
577 int ModApiEnvMod::l_get_node_timer(lua_State *L)
582 v3s16 p = read_v3s16(L, 1);
583 NodeTimerRef::create(L, p, env);
587 // add_entity(pos, entityname, [staticdata]) -> ObjectRef or nil
588 // pos = {x=num, y=num, z=num}
589 int ModApiEnvMod::l_add_entity(lua_State *L)
594 v3f pos = checkFloatPos(L, 1);
596 const char *name = luaL_checkstring(L, 2);
598 const char *staticdata = luaL_optstring(L, 3, "");
600 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, staticdata);
601 int objectid = env->addActiveObject(obj);
602 // If failed to add, return nothing (reads as nil)
606 getScriptApiBase(L)->objectrefGetOrCreate(L, obj);
610 // add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
611 // pos = {x=num, y=num, z=num}
612 int ModApiEnvMod::l_add_item(lua_State *L)
617 //v3f pos = checkFloatPos(L, 1);
619 ItemStack item = read_item(L, 2,getServer(L)->idef());
620 if(item.empty() || !item.isKnown(getServer(L)->idef()))
623 int error_handler = PUSH_ERROR_HANDLER(L);
625 // Use spawn_item to spawn a __builtin:item
626 lua_getglobal(L, "core");
627 lua_getfield(L, -1, "spawn_item");
628 lua_remove(L, -2); // Remove core
632 lua_pushstring(L, item.getItemString().c_str());
634 PCALL_RESL(L, lua_pcall(L, 2, 1, error_handler));
636 lua_remove(L, error_handler);
640 // get_player_by_name(name)
641 int ModApiEnvMod::l_get_player_by_name(lua_State *L)
646 const char *name = luaL_checkstring(L, 1);
647 RemotePlayer *player = dynamic_cast<RemotePlayer *>(env->getPlayer(name));
652 PlayerSAO *sao = player->getPlayerSAO();
657 // Put player on stack
658 getScriptApiBase(L)->objectrefGetOrCreate(L, sao);
662 // get_objects_inside_radius(pos, radius)
663 int ModApiEnvMod::l_get_objects_inside_radius(lua_State *L)
668 v3f pos = checkFloatPos(L, 1);
669 float radius = readParam<float>(L, 2) * BS;
670 std::vector<u16> ids;
671 env->getObjectsInsideRadius(ids, pos, radius);
672 ScriptApiBase *script = getScriptApiBase(L);
673 lua_createtable(L, ids.size(), 0);
674 std::vector<u16>::const_iterator iter = ids.begin();
675 for(u32 i = 0; iter != ids.end(); ++iter) {
676 ServerActiveObject *obj = env->getActiveObject(*iter);
677 if (!obj->isGone()) {
678 // Insert object reference into table
679 script->objectrefGetOrCreate(L, obj);
680 lua_rawseti(L, -2, ++i);
686 // set_timeofday(val)
688 int ModApiEnvMod::l_set_timeofday(lua_State *L)
693 float timeofday_f = readParam<float>(L, 1);
694 sanity_check(timeofday_f >= 0.0 && timeofday_f <= 1.0);
695 int timeofday_mh = (int)(timeofday_f * 24000.0);
696 // This should be set directly in the environment but currently
697 // such changes aren't immediately sent to the clients, so call
698 // the server instead.
699 //env->setTimeOfDay(timeofday_mh);
700 getServer(L)->setTimeOfDay(timeofday_mh);
704 // get_timeofday() -> 0...1
705 int ModApiEnvMod::l_get_timeofday(lua_State *L)
707 Environment *env = getEnv(L);
713 int timeofday_mh = env->getTimeOfDay();
714 float timeofday_f = (float)timeofday_mh / 24000.0f;
715 lua_pushnumber(L, timeofday_f);
719 // get_day_count() -> int
720 int ModApiEnvMod::l_get_day_count(lua_State *L)
722 Environment *env = getEnv(L);
727 lua_pushnumber(L, env->getDayCount());
732 int ModApiEnvMod::l_get_gametime(lua_State *L)
736 int game_time = env->getGameTime();
737 lua_pushnumber(L, game_time);
742 // find_node_near(pos, radius, nodenames, search_center) -> pos or nil
743 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
744 int ModApiEnvMod::l_find_node_near(lua_State *L)
746 Environment *env = getEnv(L);
751 const NodeDefManager *ndef = getGameDef(L)->ndef();
752 v3s16 pos = read_v3s16(L, 1);
753 int radius = luaL_checkinteger(L, 2);
754 std::vector<content_t> filter;
755 if (lua_istable(L, 3)) {
757 while (lua_next(L, 3) != 0) {
758 // key at index -2 and value at index -1
759 luaL_checktype(L, -1, LUA_TSTRING);
760 ndef->getIds(readParam<std::string>(L, -1), filter);
761 // removes value, keeps key for next iteration
764 } else if (lua_isstring(L, 3)) {
765 ndef->getIds(readParam<std::string>(L, 3), filter);
768 int start_radius = (lua_isboolean(L, 4) && readParam<bool>(L, 4)) ? 0 : 1;
771 // Client API limitations
773 getClient(L)->checkCSMRestrictionFlag(
774 CSMRestrictionFlags::CSM_RF_LOOKUP_NODES)) {
775 radius = std::max<int>(radius, getClient(L)->getCSMNodeRangeLimit());
779 for (int d = start_radius; d <= radius; d++) {
780 std::vector<v3s16> list = FacePositionCache::getFacePositions(d);
781 for (const v3s16 &i : list) {
783 content_t c = env->getMap().getNodeNoEx(p).getContent();
784 if (CONTAINS(filter, c)) {
793 // find_nodes_in_area(minp, maxp, nodenames) -> list of positions
794 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
795 int ModApiEnvMod::l_find_nodes_in_area(lua_State *L)
799 const NodeDefManager *ndef = getServer(L)->ndef();
800 v3s16 minp = read_v3s16(L, 1);
801 v3s16 maxp = read_v3s16(L, 2);
802 sortBoxVerticies(minp, maxp);
804 v3s16 cube = maxp - minp + 1;
805 // Volume limit equal to 8 default mapchunks, (80 * 2) ^ 3 = 4,096,000
806 if ((u64)cube.X * (u64)cube.Y * (u64)cube.Z > 4096000) {
807 luaL_error(L, "find_nodes_in_area(): area volume"
808 " exceeds allowed value of 4096000");
812 std::vector<content_t> filter;
813 if (lua_istable(L, 3)) {
815 while (lua_next(L, 3) != 0) {
816 // key at index -2 and value at index -1
817 luaL_checktype(L, -1, LUA_TSTRING);
818 ndef->getIds(readParam<std::string>(L, -1), filter);
819 // removes value, keeps key for next iteration
822 } else if (lua_isstring(L, 3)) {
823 ndef->getIds(readParam<std::string>(L, 3), filter);
826 std::vector<u32> individual_count;
827 individual_count.resize(filter.size());
831 for (s16 x = minp.X; x <= maxp.X; x++)
832 for (s16 y = minp.Y; y <= maxp.Y; y++)
833 for (s16 z = minp.Z; z <= maxp.Z; z++) {
835 content_t c = env->getMap().getNodeNoEx(p).getContent();
837 std::vector<content_t>::iterator it = std::find(filter.begin(), filter.end(), c);
838 if (it != filter.end()) {
840 lua_rawseti(L, -2, ++i);
842 u32 filt_index = it - filter.begin();
843 individual_count[filt_index]++;
847 for (u32 i = 0; i < filter.size(); i++) {
848 lua_pushnumber(L, individual_count[i]);
849 lua_setfield(L, -2, ndef->get(filter[i]).name.c_str());
854 // find_nodes_in_area_under_air(minp, maxp, nodenames) -> list of positions
855 // nodenames: e.g. {"ignore", "group:tree"} or "default:dirt"
856 int ModApiEnvMod::l_find_nodes_in_area_under_air(lua_State *L)
858 /* Note: A similar but generalized (and therefore slower) version of this
859 * function could be created -- e.g. find_nodes_in_area_under -- which
860 * would accept a node name (or ID?) or list of names that the "above node"
867 const NodeDefManager *ndef = getServer(L)->ndef();
868 v3s16 minp = read_v3s16(L, 1);
869 v3s16 maxp = read_v3s16(L, 2);
870 sortBoxVerticies(minp, maxp);
872 v3s16 cube = maxp - minp + 1;
873 // Volume limit equal to 8 default mapchunks, (80 * 2) ^ 3 = 4,096,000
874 if ((u64)cube.X * (u64)cube.Y * (u64)cube.Z > 4096000) {
875 luaL_error(L, "find_nodes_in_area_under_air(): area volume"
876 " exceeds allowed value of 4096000");
880 std::vector<content_t> filter;
882 if (lua_istable(L, 3)) {
884 while (lua_next(L, 3) != 0) {
885 // key at index -2 and value at index -1
886 luaL_checktype(L, -1, LUA_TSTRING);
887 ndef->getIds(readParam<std::string>(L, -1), filter);
888 // removes value, keeps key for next iteration
891 } else if (lua_isstring(L, 3)) {
892 ndef->getIds(readParam<std::string>(L, 3), filter);
897 for (s16 x = minp.X; x <= maxp.X; x++)
898 for (s16 z = minp.Z; z <= maxp.Z; z++) {
901 content_t c = env->getMap().getNodeNoEx(p).getContent();
902 for (; y <= maxp.Y; y++) {
903 v3s16 psurf(x, y + 1, z);
904 content_t csurf = env->getMap().getNodeNoEx(psurf).getContent();
905 if (c != CONTENT_AIR && csurf == CONTENT_AIR &&
906 CONTAINS(filter, c)) {
907 push_v3s16(L, v3s16(x, y, z));
908 lua_rawseti(L, -2, ++i);
916 // get_perlin(seeddiff, octaves, persistence, scale)
917 // returns world-specific PerlinNoise
918 int ModApiEnvMod::l_get_perlin(lua_State *L)
920 GET_ENV_PTR_NO_MAP_LOCK;
924 if (lua_istable(L, 1)) {
925 read_noiseparams(L, 1, ¶ms);
927 params.seed = luaL_checkint(L, 1);
928 params.octaves = luaL_checkint(L, 2);
929 params.persist = readParam<float>(L, 3);
930 params.spread = v3f(1, 1, 1) * readParam<float>(L, 4);
933 params.seed += (int)env->getServerMap().getSeed();
935 LuaPerlinNoise *n = new LuaPerlinNoise(¶ms);
936 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
937 luaL_getmetatable(L, "PerlinNoise");
938 lua_setmetatable(L, -2);
942 // get_perlin_map(noiseparams, size)
943 // returns world-specific PerlinNoiseMap
944 int ModApiEnvMod::l_get_perlin_map(lua_State *L)
946 GET_ENV_PTR_NO_MAP_LOCK;
949 if (!read_noiseparams(L, 1, &np))
951 v3s16 size = read_v3s16(L, 2);
953 s32 seed = (s32)(env->getServerMap().getSeed());
954 LuaPerlinNoiseMap *n = new LuaPerlinNoiseMap(&np, seed, size);
955 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
956 luaL_getmetatable(L, "PerlinNoiseMap");
957 lua_setmetatable(L, -2);
962 // returns voxel manipulator
963 int ModApiEnvMod::l_get_voxel_manip(lua_State *L)
967 Map *map = &(env->getMap());
968 LuaVoxelManip *o = (lua_istable(L, 1) && lua_istable(L, 2)) ?
969 new LuaVoxelManip(map, read_v3s16(L, 1), read_v3s16(L, 2)) :
970 new LuaVoxelManip(map);
972 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
973 luaL_getmetatable(L, "VoxelManip");
974 lua_setmetatable(L, -2);
978 // clear_objects([options])
979 // clear all objects in the environment
980 // where options = {mode = "full" or "quick"}
981 int ModApiEnvMod::l_clear_objects(lua_State *L)
985 ClearObjectsMode mode = CLEAR_OBJECTS_MODE_QUICK;
986 if (lua_istable(L, 1)) {
987 mode = (ClearObjectsMode)getenumfield(L, 1, "mode",
988 ModApiEnvMod::es_ClearObjectsMode, mode);
991 env->clearObjects(mode);
995 // line_of_sight(pos1, pos2) -> true/false, pos
996 int ModApiEnvMod::l_line_of_sight(lua_State *L)
1000 // read position 1 from lua
1001 v3f pos1 = checkFloatPos(L, 1);
1002 // read position 2 from lua
1003 v3f pos2 = checkFloatPos(L, 2);
1007 bool success = env->line_of_sight(pos1, pos2, &p);
1008 lua_pushboolean(L, success);
1016 // fix_light(p1, p2)
1017 int ModApiEnvMod::l_fix_light(lua_State *L)
1021 v3s16 blockpos1 = getContainerPos(read_v3s16(L, 1), MAP_BLOCKSIZE);
1022 v3s16 blockpos2 = getContainerPos(read_v3s16(L, 2), MAP_BLOCKSIZE);
1023 ServerMap &map = env->getServerMap();
1024 std::map<v3s16, MapBlock *> modified_blocks;
1025 bool success = true;
1027 for (blockpos.X = blockpos1.X; blockpos.X <= blockpos2.X; blockpos.X++)
1028 for (blockpos.Y = blockpos1.Y; blockpos.Y <= blockpos2.Y; blockpos.Y++)
1029 for (blockpos.Z = blockpos1.Z; blockpos.Z <= blockpos2.Z; blockpos.Z++) {
1030 success = success & map.repairBlockLight(blockpos, &modified_blocks);
1032 if (!modified_blocks.empty()) {
1034 event.type = MEET_OTHER;
1035 for (auto &modified_block : modified_blocks)
1036 event.modified_blocks.insert(modified_block.first);
1038 map.dispatchEvent(&event);
1040 lua_pushboolean(L, success);
1045 int ModApiEnvMod::l_raycast(lua_State *L)
1047 return LuaRaycast::create_object(L);
1050 // emerge_area(p1, p2, [callback, context])
1051 // emerge mapblocks in area p1..p2, calls callback with context upon completion
1052 int ModApiEnvMod::l_emerge_area(lua_State *L)
1056 EmergeCompletionCallback callback = NULL;
1057 ScriptCallbackState *state = NULL;
1059 EmergeManager *emerge = getServer(L)->getEmergeManager();
1061 v3s16 bpmin = getNodeBlockPos(read_v3s16(L, 1));
1062 v3s16 bpmax = getNodeBlockPos(read_v3s16(L, 2));
1063 sortBoxVerticies(bpmin, bpmax);
1065 size_t num_blocks = VoxelArea(bpmin, bpmax).getVolume();
1066 assert(num_blocks != 0);
1068 if (lua_isfunction(L, 3)) {
1069 callback = LuaEmergeAreaCallback;
1071 lua_pushvalue(L, 3);
1072 int callback_ref = luaL_ref(L, LUA_REGISTRYINDEX);
1074 lua_pushvalue(L, 4);
1075 int args_ref = luaL_ref(L, LUA_REGISTRYINDEX);
1077 state = new ScriptCallbackState;
1078 state->script = getServer(L)->getScriptIface();
1079 state->callback_ref = callback_ref;
1080 state->args_ref = args_ref;
1081 state->refcount = num_blocks;
1082 state->origin = getScriptApiBase(L)->getOrigin();
1085 for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
1086 for (s16 y = bpmin.Y; y <= bpmax.Y; y++)
1087 for (s16 x = bpmin.X; x <= bpmax.X; x++) {
1088 emerge->enqueueBlockEmergeEx(v3s16(x, y, z), PEER_ID_INEXISTENT,
1089 BLOCK_EMERGE_ALLOW_GEN | BLOCK_EMERGE_FORCE_QUEUE, callback, state);
1095 // delete_area(p1, p2)
1096 // delete mapblocks in area p1..p2
1097 int ModApiEnvMod::l_delete_area(lua_State *L)
1101 v3s16 bpmin = getNodeBlockPos(read_v3s16(L, 1));
1102 v3s16 bpmax = getNodeBlockPos(read_v3s16(L, 2));
1103 sortBoxVerticies(bpmin, bpmax);
1105 ServerMap &map = env->getServerMap();
1108 event.type = MEET_OTHER;
1110 bool success = true;
1111 for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
1112 for (s16 y = bpmin.Y; y <= bpmax.Y; y++)
1113 for (s16 x = bpmin.X; x <= bpmax.X; x++) {
1115 if (map.deleteBlock(bp)) {
1116 env->setStaticForActiveObjectsInBlock(bp, false);
1117 event.modified_blocks.insert(bp);
1123 map.dispatchEvent(&event);
1124 lua_pushboolean(L, success);
1128 // find_path(pos1, pos2, searchdistance,
1129 // max_jump, max_drop, algorithm) -> table containing path
1130 int ModApiEnvMod::l_find_path(lua_State *L)
1134 v3s16 pos1 = read_v3s16(L, 1);
1135 v3s16 pos2 = read_v3s16(L, 2);
1136 unsigned int searchdistance = luaL_checkint(L, 3);
1137 unsigned int max_jump = luaL_checkint(L, 4);
1138 unsigned int max_drop = luaL_checkint(L, 5);
1139 PathAlgorithm algo = PA_PLAIN_NP;
1140 if (!lua_isnil(L, 6)) {
1141 std::string algorithm = luaL_checkstring(L,6);
1143 if (algorithm == "A*")
1146 if (algorithm == "Dijkstra")
1150 std::vector<v3s16> path = get_path(env, pos1, pos2,
1151 searchdistance, max_jump, max_drop, algo);
1153 if (!path.empty()) {
1155 int top = lua_gettop(L);
1156 unsigned int index = 1;
1157 for (const v3s16 &i : path) {
1158 lua_pushnumber(L,index);
1160 lua_settable(L, top);
1169 // spawn_tree(pos, treedef)
1170 int ModApiEnvMod::l_spawn_tree(lua_State *L)
1174 v3s16 p0 = read_v3s16(L, 1);
1176 treegen::TreeDef tree_def;
1177 std::string trunk,leaves,fruit;
1178 const NodeDefManager *ndef = env->getGameDef()->ndef();
1180 if(lua_istable(L, 2))
1182 getstringfield(L, 2, "axiom", tree_def.initial_axiom);
1183 getstringfield(L, 2, "rules_a", tree_def.rules_a);
1184 getstringfield(L, 2, "rules_b", tree_def.rules_b);
1185 getstringfield(L, 2, "rules_c", tree_def.rules_c);
1186 getstringfield(L, 2, "rules_d", tree_def.rules_d);
1187 getstringfield(L, 2, "trunk", trunk);
1188 tree_def.trunknode=ndef->getId(trunk);
1189 getstringfield(L, 2, "leaves", leaves);
1190 tree_def.leavesnode=ndef->getId(leaves);
1191 tree_def.leaves2_chance=0;
1192 getstringfield(L, 2, "leaves2", leaves);
1193 if (!leaves.empty()) {
1194 tree_def.leaves2node=ndef->getId(leaves);
1195 getintfield(L, 2, "leaves2_chance", tree_def.leaves2_chance);
1197 getintfield(L, 2, "angle", tree_def.angle);
1198 getintfield(L, 2, "iterations", tree_def.iterations);
1199 if (!getintfield(L, 2, "random_level", tree_def.iterations_random_level))
1200 tree_def.iterations_random_level = 0;
1201 getstringfield(L, 2, "trunk_type", tree_def.trunk_type);
1202 getboolfield(L, 2, "thin_branches", tree_def.thin_branches);
1203 tree_def.fruit_chance=0;
1204 getstringfield(L, 2, "fruit", fruit);
1205 if (!fruit.empty()) {
1206 tree_def.fruitnode=ndef->getId(fruit);
1207 getintfield(L, 2, "fruit_chance",tree_def.fruit_chance);
1209 tree_def.explicit_seed = getintfield(L, 2, "seed", tree_def.seed);
1215 if ((e = treegen::spawn_ltree (env, p0, ndef, tree_def)) != treegen::SUCCESS) {
1216 if (e == treegen::UNBALANCED_BRACKETS) {
1217 luaL_error(L, "spawn_tree(): closing ']' has no matching opening bracket");
1219 luaL_error(L, "spawn_tree(): unknown error");
1226 // transforming_liquid_add(pos)
1227 int ModApiEnvMod::l_transforming_liquid_add(lua_State *L)
1231 v3s16 p0 = read_v3s16(L, 1);
1232 env->getMap().transforming_liquid_add(p0);
1236 // forceload_block(blockpos)
1237 // blockpos = {x=num, y=num, z=num}
1238 int ModApiEnvMod::l_forceload_block(lua_State *L)
1242 v3s16 blockpos = read_v3s16(L, 1);
1243 env->getForceloadedBlocks()->insert(blockpos);
1247 // forceload_free_block(blockpos)
1248 // blockpos = {x=num, y=num, z=num}
1249 int ModApiEnvMod::l_forceload_free_block(lua_State *L)
1253 v3s16 blockpos = read_v3s16(L, 1);
1254 env->getForceloadedBlocks()->erase(blockpos);
1258 void ModApiEnvMod::Initialize(lua_State *L, int top)
1261 API_FCT(bulk_set_node);
1265 API_FCT(remove_node);
1267 API_FCT(get_node_or_nil);
1268 API_FCT(get_node_light);
1269 API_FCT(place_node);
1271 API_FCT(punch_node);
1272 API_FCT(get_node_max_level);
1273 API_FCT(get_node_level);
1274 API_FCT(set_node_level);
1275 API_FCT(add_node_level);
1276 API_FCT(add_entity);
1277 API_FCT(find_nodes_with_meta);
1279 API_FCT(get_node_timer);
1280 API_FCT(get_player_by_name);
1281 API_FCT(get_objects_inside_radius);
1282 API_FCT(set_timeofday);
1283 API_FCT(get_timeofday);
1284 API_FCT(get_gametime);
1285 API_FCT(get_day_count);
1286 API_FCT(find_node_near);
1287 API_FCT(find_nodes_in_area);
1288 API_FCT(find_nodes_in_area_under_air);
1290 API_FCT(emerge_area);
1291 API_FCT(delete_area);
1292 API_FCT(get_perlin);
1293 API_FCT(get_perlin_map);
1294 API_FCT(get_voxel_manip);
1295 API_FCT(clear_objects);
1296 API_FCT(spawn_tree);
1298 API_FCT(line_of_sight);
1300 API_FCT(transforming_liquid_add);
1301 API_FCT(forceload_block);
1302 API_FCT(forceload_free_block);
1305 void ModApiEnvMod::InitializeClient(lua_State *L, int top)
1307 API_FCT(get_timeofday);
1308 API_FCT(get_day_count);
1309 API_FCT(get_node_max_level);
1310 API_FCT(get_node_level);
1311 API_FCT(find_node_near);