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.
21 #include "lua_api/l_env.h"
22 #include "lua_api/l_internal.h"
23 #include "lua_api/l_nodemeta.h"
24 #include "lua_api/l_nodetimer.h"
25 #include "lua_api/l_noise.h"
26 #include "lua_api/l_vmanip.h"
27 #include "common/c_converter.h"
28 #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 "mapgen/treegen.h"
38 #include "pathfinder.h"
39 #include "face_position_cache.h"
40 #include "remoteplayer.h"
41 #include "server/luaentity_sao.h"
42 #include "server/player_sao.h"
43 #include "util/string.h"
44 #include "translation.h"
46 #include "client/client.h"
49 const EnumString ModApiEnvMod::es_ClearObjectsMode[] =
51 {CLEAR_OBJECTS_MODE_FULL, "full"},
52 {CLEAR_OBJECTS_MODE_QUICK, "quick"},
56 const EnumString ModApiEnvMod::es_BlockStatusType[] =
58 {ServerEnvironment::BS_UNKNOWN, "unknown"},
59 {ServerEnvironment::BS_EMERGING, "emerging"},
60 {ServerEnvironment::BS_LOADED, "loaded"},
61 {ServerEnvironment::BS_ACTIVE, "active"},
65 ///////////////////////////////////////////////////////////////////////////////
68 void LuaABM::trigger(ServerEnvironment *env, v3s16 p, MapNode n,
69 u32 active_object_count, u32 active_object_count_wider)
71 ServerScripting *scriptIface = env->getScriptIface();
72 scriptIface->realityCheck();
74 lua_State *L = scriptIface->getStack();
75 sanity_check(lua_checkstack(L, 20));
76 StackUnroller stack_unroller(L);
78 int error_handler = PUSH_ERROR_HANDLER(L);
80 // Get registered_abms
81 lua_getglobal(L, "core");
82 lua_getfield(L, -1, "registered_abms");
83 luaL_checktype(L, -1, LUA_TTABLE);
84 lua_remove(L, -2); // Remove core
86 // Get registered_abms[m_id]
87 lua_pushinteger(L, m_id);
91 lua_remove(L, -2); // Remove registered_abms
93 scriptIface->setOriginFromTable(-1);
96 luaL_checktype(L, -1, LUA_TTABLE);
97 lua_getfield(L, -1, "action");
98 luaL_checktype(L, -1, LUA_TFUNCTION);
99 lua_remove(L, -2); // Remove registered_abms[m_id]
101 pushnode(L, n, env->getGameDef()->ndef());
102 lua_pushnumber(L, active_object_count);
103 lua_pushnumber(L, active_object_count_wider);
105 int result = lua_pcall(L, 4, 0, error_handler);
107 scriptIface->scriptError(result, "LuaABM::trigger");
109 lua_pop(L, 1); // Pop error handler
112 void LuaLBM::trigger(ServerEnvironment *env, v3s16 p, MapNode n)
114 ServerScripting *scriptIface = env->getScriptIface();
115 scriptIface->realityCheck();
117 lua_State *L = scriptIface->getStack();
118 sanity_check(lua_checkstack(L, 20));
119 StackUnroller stack_unroller(L);
121 int error_handler = PUSH_ERROR_HANDLER(L);
123 // Get registered_lbms
124 lua_getglobal(L, "core");
125 lua_getfield(L, -1, "registered_lbms");
126 luaL_checktype(L, -1, LUA_TTABLE);
127 lua_remove(L, -2); // Remove core
129 // Get registered_lbms[m_id]
130 lua_pushinteger(L, m_id);
132 FATAL_ERROR_IF(lua_isnil(L, -1), "Entry with given id not found in registered_lbms table");
133 lua_remove(L, -2); // Remove registered_lbms
135 scriptIface->setOriginFromTable(-1);
138 luaL_checktype(L, -1, LUA_TTABLE);
139 lua_getfield(L, -1, "action");
140 luaL_checktype(L, -1, LUA_TFUNCTION);
141 lua_remove(L, -2); // Remove registered_lbms[m_id]
143 pushnode(L, n, env->getGameDef()->ndef());
145 int result = lua_pcall(L, 2, 0, error_handler);
147 scriptIface->scriptError(result, "LuaLBM::trigger");
149 lua_pop(L, 1); // Pop error handler
152 int LuaRaycast::l_next(lua_State *L)
158 csm = getClient(L) != nullptr;
161 LuaRaycast *o = checkobject(L, 1);
162 PointedThing pointed;
163 env->continueRaycast(&o->state, &pointed);
164 if (pointed.type == POINTEDTHING_NOTHING)
167 push_pointed_thing(L, pointed, csm, true);
172 int LuaRaycast::create_object(lua_State *L)
174 NO_MAP_LOCK_REQUIRED;
177 bool liquids = false;
179 v3f pos1 = checkFloatPos(L, 1);
180 v3f pos2 = checkFloatPos(L, 2);
181 if (lua_isboolean(L, 3)) {
182 objects = readParam<bool>(L, 3);
184 if (lua_isboolean(L, 4)) {
185 liquids = readParam<bool>(L, 4);
188 LuaRaycast *o = new LuaRaycast(core::line3d<f32>(pos1, pos2),
191 *(void **) (lua_newuserdata(L, sizeof(void *))) = o;
192 luaL_getmetatable(L, className);
193 lua_setmetatable(L, -2);
197 LuaRaycast *LuaRaycast::checkobject(lua_State *L, int narg)
199 NO_MAP_LOCK_REQUIRED;
201 luaL_checktype(L, narg, LUA_TUSERDATA);
202 void *ud = luaL_checkudata(L, narg, className);
204 luaL_typerror(L, narg, className);
205 return *(LuaRaycast **) ud;
208 int LuaRaycast::gc_object(lua_State *L)
210 LuaRaycast *o = *(LuaRaycast **) (lua_touserdata(L, 1));
215 void LuaRaycast::Register(lua_State *L)
218 int methodtable = lua_gettop(L);
219 luaL_newmetatable(L, className);
220 int metatable = lua_gettop(L);
222 lua_pushliteral(L, "__metatable");
223 lua_pushvalue(L, methodtable);
224 lua_settable(L, metatable);
226 lua_pushliteral(L, "__index");
227 lua_pushvalue(L, methodtable);
228 lua_settable(L, metatable);
230 lua_pushliteral(L, "__gc");
231 lua_pushcfunction(L, gc_object);
232 lua_settable(L, metatable);
234 lua_pushliteral(L, "__call");
235 lua_pushcfunction(L, l_next);
236 lua_settable(L, metatable);
240 luaL_register(L, nullptr, methods);
243 lua_register(L, className, create_object);
246 const char LuaRaycast::className[] = "Raycast";
247 const luaL_Reg LuaRaycast::methods[] =
249 luamethod(LuaRaycast, next),
253 void LuaEmergeAreaCallback(v3s16 blockpos, EmergeAction action, void *param)
255 ScriptCallbackState *state = (ScriptCallbackState *)param;
256 assert(state != NULL);
257 assert(state->script != NULL);
258 assert(state->refcount > 0);
260 // state must be protected by envlock
261 Server *server = state->script->getServer();
262 MutexAutoLock envlock(server->m_env_mutex);
266 state->script->on_emerge_area_completion(blockpos, action, state);
268 if (state->refcount == 0)
272 // Exported functions
274 // set_node(pos, node)
275 // pos = {x=num, y=num, z=num}
276 int ModApiEnvMod::l_set_node(lua_State *L)
280 const NodeDefManager *ndef = env->getGameDef()->ndef();
282 v3s16 pos = read_v3s16(L, 1);
283 MapNode n = readnode(L, 2, ndef);
285 bool succeeded = env->setNode(pos, n);
286 lua_pushboolean(L, succeeded);
290 // bulk_set_node([pos1, pos2, ...], node)
291 // pos = {x=num, y=num, z=num}
292 int ModApiEnvMod::l_bulk_set_node(lua_State *L)
296 const NodeDefManager *ndef = env->getGameDef()->ndef();
298 if (!lua_istable(L, 1)) {
302 s32 len = lua_objlen(L, 1);
304 lua_pushboolean(L, true);
308 MapNode n = readnode(L, 2, ndef);
311 bool succeeded = true;
312 for (s32 i = 1; i <= len; i++) {
313 lua_rawgeti(L, 1, i);
314 if (!env->setNode(read_v3s16(L, -1), n))
319 lua_pushboolean(L, succeeded);
323 int ModApiEnvMod::l_add_node(lua_State *L)
325 return l_set_node(L);
329 // pos = {x=num, y=num, z=num}
330 int ModApiEnvMod::l_remove_node(lua_State *L)
335 v3s16 pos = read_v3s16(L, 1);
337 bool succeeded = env->removeNode(pos);
338 lua_pushboolean(L, succeeded);
342 // swap_node(pos, node)
343 // pos = {x=num, y=num, z=num}
344 int ModApiEnvMod::l_swap_node(lua_State *L)
348 const NodeDefManager *ndef = env->getGameDef()->ndef();
350 v3s16 pos = read_v3s16(L, 1);
351 MapNode n = readnode(L, 2, ndef);
353 bool succeeded = env->swapNode(pos, n);
354 lua_pushboolean(L, succeeded);
359 // pos = {x=num, y=num, z=num}
360 int ModApiEnvMod::l_get_node(lua_State *L)
365 v3s16 pos = read_v3s16(L, 1);
367 MapNode n = env->getMap().getNode(pos);
369 pushnode(L, n, env->getGameDef()->ndef());
373 // get_node_or_nil(pos)
374 // pos = {x=num, y=num, z=num}
375 int ModApiEnvMod::l_get_node_or_nil(lua_State *L)
380 v3s16 pos = read_v3s16(L, 1);
383 MapNode n = env->getMap().getNode(pos, &pos_ok);
386 pushnode(L, n, env->getGameDef()->ndef());
393 // get_node_light(pos, timeofday)
394 // pos = {x=num, y=num, z=num}
395 // timeofday: nil = current time, 0 = night, 0.5 = day
396 int ModApiEnvMod::l_get_node_light(lua_State *L)
401 v3s16 pos = read_v3s16(L, 1);
402 u32 time_of_day = env->getTimeOfDay();
403 if(lua_isnumber(L, 2))
404 time_of_day = 24000.0 * lua_tonumber(L, 2);
405 time_of_day %= 24000;
406 u32 dnr = time_to_daynight_ratio(time_of_day, true);
409 MapNode n = env->getMap().getNode(pos, &is_position_ok);
410 if (is_position_ok) {
411 const NodeDefManager *ndef = env->getGameDef()->ndef();
412 lua_pushinteger(L, n.getLightBlend(dnr, ndef));
420 // get_natural_light(pos, timeofday)
421 // pos = {x=num, y=num, z=num}
422 // timeofday: nil = current time, 0 = night, 0.5 = day
423 int ModApiEnvMod::l_get_natural_light(lua_State *L)
427 v3s16 pos = read_v3s16(L, 1);
430 MapNode n = env->getMap().getNode(pos, &is_position_ok);
434 // If the daylight is 0, nothing needs to be calculated
435 u8 daylight = n.param1 & 0x0f;
437 lua_pushinteger(L, 0);
442 if (lua_isnumber(L, 2)) {
443 time_of_day = 24000.0 * lua_tonumber(L, 2);
444 time_of_day %= 24000;
446 time_of_day = env->getTimeOfDay();
448 u32 dnr = time_to_daynight_ratio(time_of_day, true);
450 // If it's the same as the artificial light, the sunlight needs to be
451 // searched for because the value may not emanate from the sun
452 if (daylight == n.param1 >> 4)
453 daylight = env->findSunlight(pos);
455 lua_pushinteger(L, dnr * daylight / 1000);
459 // place_node(pos, node)
460 // pos = {x=num, y=num, z=num}
461 int ModApiEnvMod::l_place_node(lua_State *L)
465 ScriptApiItem *scriptIfaceItem = getScriptApi<ScriptApiItem>(L);
466 Server *server = getServer(L);
467 const NodeDefManager *ndef = server->ndef();
468 IItemDefManager *idef = server->idef();
470 v3s16 pos = read_v3s16(L, 1);
471 MapNode n = readnode(L, 2, ndef);
473 // Don't attempt to load non-loaded area as of now
474 MapNode n_old = env->getMap().getNode(pos);
475 if(n_old.getContent() == CONTENT_IGNORE){
476 lua_pushboolean(L, false);
479 // Create item to place
480 Optional<ItemStack> item = ItemStack(ndef->get(n).name, 1, 0, idef);
481 // Make pointed position
482 PointedThing pointed;
483 pointed.type = POINTEDTHING_NODE;
484 pointed.node_abovesurface = pos;
485 pointed.node_undersurface = pos + v3s16(0,-1,0);
486 // Place it with a NULL placer (appears in Lua as nil)
487 bool success = scriptIfaceItem->item_OnPlace(item, nullptr, pointed);
488 lua_pushboolean(L, success);
493 // pos = {x=num, y=num, z=num}
494 int ModApiEnvMod::l_dig_node(lua_State *L)
498 ScriptApiNode *scriptIfaceNode = getScriptApi<ScriptApiNode>(L);
500 v3s16 pos = read_v3s16(L, 1);
502 // Don't attempt to load non-loaded area as of now
503 MapNode n = env->getMap().getNode(pos);
504 if(n.getContent() == CONTENT_IGNORE){
505 lua_pushboolean(L, false);
508 // Dig it out with a NULL digger (appears in Lua as a
509 // non-functional ObjectRef)
510 bool success = scriptIfaceNode->node_on_dig(pos, n, NULL);
511 lua_pushboolean(L, success);
516 // pos = {x=num, y=num, z=num}
517 int ModApiEnvMod::l_punch_node(lua_State *L)
521 ScriptApiNode *scriptIfaceNode = getScriptApi<ScriptApiNode>(L);
523 v3s16 pos = read_v3s16(L, 1);
525 // Don't attempt to load non-loaded area as of now
526 MapNode n = env->getMap().getNode(pos);
527 if(n.getContent() == CONTENT_IGNORE){
528 lua_pushboolean(L, false);
531 // Punch it with a NULL puncher (appears in Lua as a non-functional
533 bool success = scriptIfaceNode->node_on_punch(pos, n, NULL, PointedThing());
534 lua_pushboolean(L, success);
538 // get_node_max_level(pos)
539 // pos = {x=num, y=num, z=num}
540 int ModApiEnvMod::l_get_node_max_level(lua_State *L)
544 v3s16 pos = read_v3s16(L, 1);
545 MapNode n = env->getMap().getNode(pos);
546 lua_pushnumber(L, n.getMaxLevel(env->getGameDef()->ndef()));
550 // get_node_level(pos)
551 // pos = {x=num, y=num, z=num}
552 int ModApiEnvMod::l_get_node_level(lua_State *L)
556 v3s16 pos = read_v3s16(L, 1);
557 MapNode n = env->getMap().getNode(pos);
558 lua_pushnumber(L, n.getLevel(env->getGameDef()->ndef()));
562 // set_node_level(pos, level)
563 // pos = {x=num, y=num, z=num}
565 int ModApiEnvMod::l_set_node_level(lua_State *L)
569 v3s16 pos = read_v3s16(L, 1);
571 if(lua_isnumber(L, 2))
572 level = lua_tonumber(L, 2);
573 MapNode n = env->getMap().getNode(pos);
574 lua_pushnumber(L, n.setLevel(env->getGameDef()->ndef(), level));
575 env->setNode(pos, n);
579 // add_node_level(pos, level)
580 // pos = {x=num, y=num, z=num}
582 int ModApiEnvMod::l_add_node_level(lua_State *L)
586 v3s16 pos = read_v3s16(L, 1);
588 if(lua_isnumber(L, 2))
589 level = lua_tonumber(L, 2);
590 MapNode n = env->getMap().getNode(pos);
591 lua_pushnumber(L, n.addLevel(env->getGameDef()->ndef(), level));
592 env->setNode(pos, n);
596 // find_nodes_with_meta(pos1, pos2)
597 int ModApiEnvMod::l_find_nodes_with_meta(lua_State *L)
601 std::vector<v3s16> positions = env->getMap().findNodesWithMetadata(
602 check_v3s16(L, 1), check_v3s16(L, 2));
604 lua_createtable(L, positions.size(), 0);
605 for (size_t i = 0; i != positions.size(); i++) {
606 push_v3s16(L, positions[i]);
607 lua_rawseti(L, -2, i + 1);
614 int ModApiEnvMod::l_get_meta(lua_State *L)
619 v3s16 p = read_v3s16(L, 1);
620 NodeMetaRef::create(L, p, env);
624 // get_node_timer(pos)
625 int ModApiEnvMod::l_get_node_timer(lua_State *L)
630 v3s16 p = read_v3s16(L, 1);
631 NodeTimerRef::create(L, p, &env->getServerMap());
635 // add_entity(pos, entityname, [staticdata]) -> ObjectRef or nil
636 // pos = {x=num, y=num, z=num}
637 int ModApiEnvMod::l_add_entity(lua_State *L)
641 v3f pos = checkFloatPos(L, 1);
642 const char *name = luaL_checkstring(L, 2);
643 const char *staticdata = luaL_optstring(L, 3, "");
645 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, staticdata);
646 int objectid = env->addActiveObject(obj);
647 // If failed to add, return nothing (reads as nil)
651 // If already deleted (can happen in on_activate), return nil
654 getScriptApiBase(L)->objectrefGetOrCreate(L, obj);
658 // add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
659 // pos = {x=num, y=num, z=num}
660 int ModApiEnvMod::l_add_item(lua_State *L)
665 //v3f pos = checkFloatPos(L, 1);
667 ItemStack item = read_item(L, 2,getServer(L)->idef());
668 if(item.empty() || !item.isKnown(getServer(L)->idef()))
671 int error_handler = PUSH_ERROR_HANDLER(L);
673 // Use spawn_item to spawn a __builtin:item
674 lua_getglobal(L, "core");
675 lua_getfield(L, -1, "spawn_item");
676 lua_remove(L, -2); // Remove core
680 lua_pushstring(L, item.getItemString().c_str());
682 PCALL_RESL(L, lua_pcall(L, 2, 1, error_handler));
684 lua_remove(L, error_handler);
688 // get_connected_players()
689 int ModApiEnvMod::l_get_connected_players(lua_State *L)
691 ServerEnvironment *env = (ServerEnvironment *) getEnv(L);
693 log_deprecated(L, "Calling get_connected_players() at mod load time"
695 lua_createtable(L, 0, 0);
699 lua_createtable(L, env->getPlayerCount(), 0);
701 for (RemotePlayer *player : env->getPlayers()) {
702 if (player->getPeerId() == PEER_ID_INEXISTENT)
704 PlayerSAO *sao = player->getPlayerSAO();
705 if (sao && !sao->isGone()) {
706 getScriptApiBase(L)->objectrefGetOrCreate(L, sao);
707 lua_rawseti(L, -2, ++i);
713 // get_player_by_name(name)
714 int ModApiEnvMod::l_get_player_by_name(lua_State *L)
719 const char *name = luaL_checkstring(L, 1);
720 RemotePlayer *player = env->getPlayer(name);
721 if (!player || player->getPeerId() == PEER_ID_INEXISTENT)
723 PlayerSAO *sao = player->getPlayerSAO();
724 if (!sao || sao->isGone())
726 // Put player on stack
727 getScriptApiBase(L)->objectrefGetOrCreate(L, sao);
731 // get_objects_inside_radius(pos, radius)
732 int ModApiEnvMod::l_get_objects_inside_radius(lua_State *L)
735 ScriptApiBase *script = getScriptApiBase(L);
738 v3f pos = checkFloatPos(L, 1);
739 float radius = readParam<float>(L, 2) * BS;
740 std::vector<ServerActiveObject *> objs;
742 auto include_obj_cb = [](ServerActiveObject *obj){ return !obj->isGone(); };
743 env->getObjectsInsideRadius(objs, pos, radius, include_obj_cb);
746 lua_createtable(L, objs.size(), 0);
747 for (const auto obj : objs) {
748 // Insert object reference into table
749 script->objectrefGetOrCreate(L, obj);
750 lua_rawseti(L, -2, ++i);
755 // get_objects_in_area(pos, minp, maxp)
756 int ModApiEnvMod::l_get_objects_in_area(lua_State *L)
759 ScriptApiBase *script = getScriptApiBase(L);
761 v3f minp = read_v3f(L, 1) * BS;
762 v3f maxp = read_v3f(L, 2) * BS;
763 aabb3f box(minp, maxp);
765 std::vector<ServerActiveObject *> objs;
767 auto include_obj_cb = [](ServerActiveObject *obj){ return !obj->isGone(); };
768 env->getObjectsInArea(objs, box, include_obj_cb);
771 lua_createtable(L, objs.size(), 0);
772 for (const auto obj : objs) {
773 // Insert object reference into table
774 script->objectrefGetOrCreate(L, obj);
775 lua_rawseti(L, -2, ++i);
780 // set_timeofday(val)
782 int ModApiEnvMod::l_set_timeofday(lua_State *L)
787 float timeofday_f = readParam<float>(L, 1);
788 luaL_argcheck(L, timeofday_f >= 0.0f && timeofday_f <= 1.0f, 1,
789 "value must be between 0 and 1");
790 int timeofday_mh = (int)(timeofday_f * 24000.0f);
791 // This should be set directly in the environment but currently
792 // such changes aren't immediately sent to the clients, so call
793 // the server instead.
794 //env->setTimeOfDay(timeofday_mh);
795 getServer(L)->setTimeOfDay(timeofday_mh);
799 // get_timeofday() -> 0...1
800 int ModApiEnvMod::l_get_timeofday(lua_State *L)
805 int timeofday_mh = env->getTimeOfDay();
806 float timeofday_f = (float)timeofday_mh / 24000.0f;
807 lua_pushnumber(L, timeofday_f);
811 // get_day_count() -> int
812 int ModApiEnvMod::l_get_day_count(lua_State *L)
816 lua_pushnumber(L, env->getDayCount());
821 int ModApiEnvMod::l_get_gametime(lua_State *L)
825 int game_time = env->getGameTime();
826 lua_pushnumber(L, game_time);
830 void ModApiEnvMod::collectNodeIds(lua_State *L, int idx, const NodeDefManager *ndef,
831 std::vector<content_t> &filter)
833 if (lua_istable(L, idx)) {
835 while (lua_next(L, idx) != 0) {
836 // key at index -2 and value at index -1
837 luaL_checktype(L, -1, LUA_TSTRING);
838 ndef->getIds(readParam<std::string>(L, -1), filter);
839 // removes value, keeps key for next iteration
842 } else if (lua_isstring(L, idx)) {
843 ndef->getIds(readParam<std::string>(L, 3), filter);
847 // find_node_near(pos, radius, nodenames, [search_center]) -> pos or nil
848 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
849 int ModApiEnvMod::l_find_node_near(lua_State *L)
853 const NodeDefManager *ndef = env->getGameDef()->ndef();
854 Map &map = env->getMap();
856 v3s16 pos = read_v3s16(L, 1);
857 int radius = luaL_checkinteger(L, 2);
858 std::vector<content_t> filter;
859 collectNodeIds(L, 3, ndef, filter);
861 int start_radius = (lua_isboolean(L, 4) && readParam<bool>(L, 4)) ? 0 : 1;
864 // Client API limitations
865 if (Client *client = getClient(L))
866 radius = client->CSMClampRadius(pos, radius);
869 for (int d = start_radius; d <= radius; d++) {
870 const std::vector<v3s16> &list = FacePositionCache::getFacePositions(d);
871 for (const v3s16 &i : list) {
873 content_t c = map.getNode(p).getContent();
874 if (CONTAINS(filter, c)) {
883 // find_nodes_in_area(minp, maxp, nodenames, [grouped])
884 int ModApiEnvMod::l_find_nodes_in_area(lua_State *L)
888 v3s16 minp = read_v3s16(L, 1);
889 v3s16 maxp = read_v3s16(L, 2);
890 sortBoxVerticies(minp, maxp);
892 const NodeDefManager *ndef = env->getGameDef()->ndef();
893 Map &map = env->getMap();
896 if (Client *client = getClient(L)) {
897 minp = client->CSMClampPos(minp);
898 maxp = client->CSMClampPos(maxp);
902 v3s16 cube = maxp - minp + 1;
903 // Volume limit equal to 8 default mapchunks, (80 * 2) ^ 3 = 4,096,000
904 if ((u64)cube.X * (u64)cube.Y * (u64)cube.Z > 4096000) {
905 luaL_error(L, "find_nodes_in_area(): area volume"
906 " exceeds allowed value of 4096000");
910 std::vector<content_t> filter;
911 collectNodeIds(L, 3, ndef, filter);
913 bool grouped = lua_isboolean(L, 4) && readParam<bool>(L, 4);
916 // create the table we will be returning
917 lua_createtable(L, 0, filter.size());
918 int base = lua_gettop(L);
920 // create one table for each filter
921 std::vector<u32> idx;
922 idx.resize(filter.size());
923 for (u32 i = 0; i < filter.size(); i++)
927 for (p.X = minp.X; p.X <= maxp.X; p.X++)
928 for (p.Y = minp.Y; p.Y <= maxp.Y; p.Y++)
929 for (p.Z = minp.Z; p.Z <= maxp.Z; p.Z++) {
930 content_t c = map.getNode(p).getContent();
932 auto it = std::find(filter.begin(), filter.end(), c);
933 if (it != filter.end()) {
934 // Calculate index of the table and append the position
935 u32 filt_index = it - filter.begin();
937 lua_rawseti(L, base + 1 + filt_index, ++idx[filt_index]);
941 // last filter table is at top of stack
942 u32 i = filter.size() - 1;
945 // No such node found -> drop the empty table
948 // This node was found -> put table into the return table
949 lua_setfield(L, base, ndef->get(filter[i]).name.c_str());
953 assert(lua_gettop(L) == base);
956 std::vector<u32> individual_count;
957 individual_count.resize(filter.size());
962 for (p.X = minp.X; p.X <= maxp.X; p.X++)
963 for (p.Y = minp.Y; p.Y <= maxp.Y; p.Y++)
964 for (p.Z = minp.Z; p.Z <= maxp.Z; p.Z++) {
965 content_t c = env->getMap().getNode(p).getContent();
967 auto it = std::find(filter.begin(), filter.end(), c);
968 if (it != filter.end()) {
970 lua_rawseti(L, -2, ++i);
972 u32 filt_index = it - filter.begin();
973 individual_count[filt_index]++;
977 lua_createtable(L, 0, filter.size());
978 for (u32 i = 0; i < filter.size(); i++) {
979 lua_pushinteger(L, individual_count[i]);
980 lua_setfield(L, -2, ndef->get(filter[i]).name.c_str());
986 // find_nodes_in_area_under_air(minp, maxp, nodenames) -> list of positions
987 // nodenames: e.g. {"ignore", "group:tree"} or "default:dirt"
988 int ModApiEnvMod::l_find_nodes_in_area_under_air(lua_State *L)
990 /* Note: A similar but generalized (and therefore slower) version of this
991 * function could be created -- e.g. find_nodes_in_area_under -- which
992 * would accept a node name (or ID?) or list of names that the "above node"
999 v3s16 minp = read_v3s16(L, 1);
1000 v3s16 maxp = read_v3s16(L, 2);
1001 sortBoxVerticies(minp, maxp);
1003 const NodeDefManager *ndef = env->getGameDef()->ndef();
1004 Map &map = env->getMap();
1007 if (Client *client = getClient(L)) {
1008 minp = client->CSMClampPos(minp);
1009 maxp = client->CSMClampPos(maxp);
1013 v3s16 cube = maxp - minp + 1;
1014 // Volume limit equal to 8 default mapchunks, (80 * 2) ^ 3 = 4,096,000
1015 if ((u64)cube.X * (u64)cube.Y * (u64)cube.Z > 4096000) {
1016 luaL_error(L, "find_nodes_in_area_under_air(): area volume"
1017 " exceeds allowed value of 4096000");
1021 std::vector<content_t> filter;
1022 collectNodeIds(L, 3, ndef, filter);
1027 for (p.X = minp.X; p.X <= maxp.X; p.X++)
1028 for (p.Z = minp.Z; p.Z <= maxp.Z; p.Z++) {
1030 content_t c = map.getNode(p).getContent();
1031 for (; p.Y <= maxp.Y; p.Y++) {
1032 v3s16 psurf(p.X, p.Y + 1, p.Z);
1033 content_t csurf = map.getNode(psurf).getContent();
1034 if (c != CONTENT_AIR && csurf == CONTENT_AIR &&
1035 CONTAINS(filter, c)) {
1037 lua_rawseti(L, -2, ++i);
1045 // get_perlin(seeddiff, octaves, persistence, scale)
1046 // returns world-specific PerlinNoise
1047 int ModApiEnvMod::l_get_perlin(lua_State *L)
1049 GET_ENV_PTR_NO_MAP_LOCK;
1053 if (lua_istable(L, 1)) {
1054 read_noiseparams(L, 1, ¶ms);
1056 params.seed = luaL_checkint(L, 1);
1057 params.octaves = luaL_checkint(L, 2);
1058 params.persist = readParam<float>(L, 3);
1059 params.spread = v3f(1, 1, 1) * readParam<float>(L, 4);
1062 params.seed += (int)env->getServerMap().getSeed();
1064 LuaPerlinNoise *n = new LuaPerlinNoise(¶ms);
1065 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
1066 luaL_getmetatable(L, "PerlinNoise");
1067 lua_setmetatable(L, -2);
1071 // get_perlin_map(noiseparams, size)
1072 // returns world-specific PerlinNoiseMap
1073 int ModApiEnvMod::l_get_perlin_map(lua_State *L)
1075 GET_ENV_PTR_NO_MAP_LOCK;
1078 if (!read_noiseparams(L, 1, &np))
1080 v3s16 size = read_v3s16(L, 2);
1082 s32 seed = (s32)(env->getServerMap().getSeed());
1083 LuaPerlinNoiseMap *n = new LuaPerlinNoiseMap(&np, seed, size);
1084 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
1085 luaL_getmetatable(L, "PerlinNoiseMap");
1086 lua_setmetatable(L, -2);
1090 // get_voxel_manip()
1091 // returns voxel manipulator
1092 int ModApiEnvMod::l_get_voxel_manip(lua_State *L)
1096 Map *map = &(env->getMap());
1097 LuaVoxelManip *o = (lua_istable(L, 1) && lua_istable(L, 2)) ?
1098 new LuaVoxelManip(map, read_v3s16(L, 1), read_v3s16(L, 2)) :
1099 new LuaVoxelManip(map);
1101 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1102 luaL_getmetatable(L, "VoxelManip");
1103 lua_setmetatable(L, -2);
1107 // clear_objects([options])
1108 // clear all objects in the environment
1109 // where options = {mode = "full" or "quick"}
1110 int ModApiEnvMod::l_clear_objects(lua_State *L)
1114 ClearObjectsMode mode = CLEAR_OBJECTS_MODE_QUICK;
1115 if (lua_istable(L, 1)) {
1116 mode = (ClearObjectsMode)getenumfield(L, 1, "mode",
1117 ModApiEnvMod::es_ClearObjectsMode, mode);
1120 env->clearObjects(mode);
1124 // line_of_sight(pos1, pos2) -> true/false, pos
1125 int ModApiEnvMod::l_line_of_sight(lua_State *L)
1129 // read position 1 from lua
1130 v3f pos1 = checkFloatPos(L, 1);
1131 // read position 2 from lua
1132 v3f pos2 = checkFloatPos(L, 2);
1136 bool success = env->line_of_sight(pos1, pos2, &p);
1137 lua_pushboolean(L, success);
1145 // fix_light(p1, p2)
1146 int ModApiEnvMod::l_fix_light(lua_State *L)
1150 v3s16 blockpos1 = getContainerPos(read_v3s16(L, 1), MAP_BLOCKSIZE);
1151 v3s16 blockpos2 = getContainerPos(read_v3s16(L, 2), MAP_BLOCKSIZE);
1152 ServerMap &map = env->getServerMap();
1153 std::map<v3s16, MapBlock *> modified_blocks;
1154 bool success = true;
1156 for (blockpos.X = blockpos1.X; blockpos.X <= blockpos2.X; blockpos.X++)
1157 for (blockpos.Y = blockpos1.Y; blockpos.Y <= blockpos2.Y; blockpos.Y++)
1158 for (blockpos.Z = blockpos1.Z; blockpos.Z <= blockpos2.Z; blockpos.Z++) {
1159 success = success & map.repairBlockLight(blockpos, &modified_blocks);
1161 if (!modified_blocks.empty()) {
1163 event.type = MEET_OTHER;
1164 for (auto &modified_block : modified_blocks)
1165 event.modified_blocks.insert(modified_block.first);
1167 map.dispatchEvent(event);
1169 lua_pushboolean(L, success);
1174 int ModApiEnvMod::l_raycast(lua_State *L)
1176 return LuaRaycast::create_object(L);
1179 // load_area(p1, [p2])
1180 // load mapblocks in area p1..p2, but do not generate map
1181 int ModApiEnvMod::l_load_area(lua_State *L)
1186 Map *map = &(env->getMap());
1187 v3s16 bp1 = getNodeBlockPos(check_v3s16(L, 1));
1188 if (!lua_istable(L, 2)) {
1189 map->emergeBlock(bp1);
1191 v3s16 bp2 = getNodeBlockPos(check_v3s16(L, 2));
1192 sortBoxVerticies(bp1, bp2);
1193 for (s16 z = bp1.Z; z <= bp2.Z; z++)
1194 for (s16 y = bp1.Y; y <= bp2.Y; y++)
1195 for (s16 x = bp1.X; x <= bp2.X; x++) {
1196 map->emergeBlock(v3s16(x, y, z));
1203 // emerge_area(p1, p2, [callback, context])
1204 // emerge mapblocks in area p1..p2, calls callback with context upon completion
1205 int ModApiEnvMod::l_emerge_area(lua_State *L)
1209 EmergeCompletionCallback callback = NULL;
1210 ScriptCallbackState *state = NULL;
1212 EmergeManager *emerge = getServer(L)->getEmergeManager();
1214 v3s16 bpmin = getNodeBlockPos(read_v3s16(L, 1));
1215 v3s16 bpmax = getNodeBlockPos(read_v3s16(L, 2));
1216 sortBoxVerticies(bpmin, bpmax);
1218 size_t num_blocks = VoxelArea(bpmin, bpmax).getVolume();
1219 assert(num_blocks != 0);
1221 if (lua_isfunction(L, 3)) {
1222 callback = LuaEmergeAreaCallback;
1224 lua_pushvalue(L, 3);
1225 int callback_ref = luaL_ref(L, LUA_REGISTRYINDEX);
1227 lua_pushvalue(L, 4);
1228 int args_ref = luaL_ref(L, LUA_REGISTRYINDEX);
1230 state = new ScriptCallbackState;
1231 state->script = getServer(L)->getScriptIface();
1232 state->callback_ref = callback_ref;
1233 state->args_ref = args_ref;
1234 state->refcount = num_blocks;
1235 state->origin = getScriptApiBase(L)->getOrigin();
1238 for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
1239 for (s16 y = bpmin.Y; y <= bpmax.Y; y++)
1240 for (s16 x = bpmin.X; x <= bpmax.X; x++) {
1241 emerge->enqueueBlockEmergeEx(v3s16(x, y, z), PEER_ID_INEXISTENT,
1242 BLOCK_EMERGE_ALLOW_GEN | BLOCK_EMERGE_FORCE_QUEUE, callback, state);
1248 // delete_area(p1, p2)
1249 // delete mapblocks in area p1..p2
1250 int ModApiEnvMod::l_delete_area(lua_State *L)
1254 v3s16 bpmin = getNodeBlockPos(read_v3s16(L, 1));
1255 v3s16 bpmax = getNodeBlockPos(read_v3s16(L, 2));
1256 sortBoxVerticies(bpmin, bpmax);
1258 ServerMap &map = env->getServerMap();
1261 event.type = MEET_OTHER;
1263 bool success = true;
1264 for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
1265 for (s16 y = bpmin.Y; y <= bpmax.Y; y++)
1266 for (s16 x = bpmin.X; x <= bpmax.X; x++) {
1268 if (map.deleteBlock(bp)) {
1269 env->setStaticForActiveObjectsInBlock(bp, false);
1270 event.modified_blocks.insert(bp);
1276 map.dispatchEvent(event);
1277 lua_pushboolean(L, success);
1281 // find_path(pos1, pos2, searchdistance,
1282 // max_jump, max_drop, algorithm) -> table containing path
1283 int ModApiEnvMod::l_find_path(lua_State *L)
1287 v3s16 pos1 = read_v3s16(L, 1);
1288 v3s16 pos2 = read_v3s16(L, 2);
1289 unsigned int searchdistance = luaL_checkint(L, 3);
1290 unsigned int max_jump = luaL_checkint(L, 4);
1291 unsigned int max_drop = luaL_checkint(L, 5);
1292 PathAlgorithm algo = PA_PLAIN_NP;
1293 if (!lua_isnoneornil(L, 6)) {
1294 std::string algorithm = luaL_checkstring(L,6);
1296 if (algorithm == "A*")
1299 if (algorithm == "Dijkstra")
1303 std::vector<v3s16> path = get_path(&env->getServerMap(), env->getGameDef()->ndef(), pos1, pos2,
1304 searchdistance, max_jump, max_drop, algo);
1306 if (!path.empty()) {
1307 lua_createtable(L, path.size(), 0);
1308 int top = lua_gettop(L);
1309 unsigned int index = 1;
1310 for (const v3s16 &i : path) {
1311 lua_pushnumber(L,index);
1313 lua_settable(L, top);
1322 // spawn_tree(pos, treedef)
1323 int ModApiEnvMod::l_spawn_tree(lua_State *L)
1327 v3s16 p0 = read_v3s16(L, 1);
1329 treegen::TreeDef tree_def;
1330 std::string trunk,leaves,fruit;
1331 const NodeDefManager *ndef = env->getGameDef()->ndef();
1333 if(lua_istable(L, 2))
1335 getstringfield(L, 2, "axiom", tree_def.initial_axiom);
1336 getstringfield(L, 2, "rules_a", tree_def.rules_a);
1337 getstringfield(L, 2, "rules_b", tree_def.rules_b);
1338 getstringfield(L, 2, "rules_c", tree_def.rules_c);
1339 getstringfield(L, 2, "rules_d", tree_def.rules_d);
1340 getstringfield(L, 2, "trunk", trunk);
1341 tree_def.trunknode=ndef->getId(trunk);
1342 getstringfield(L, 2, "leaves", leaves);
1343 tree_def.leavesnode=ndef->getId(leaves);
1344 tree_def.leaves2_chance=0;
1345 getstringfield(L, 2, "leaves2", leaves);
1346 if (!leaves.empty()) {
1347 tree_def.leaves2node=ndef->getId(leaves);
1348 getintfield(L, 2, "leaves2_chance", tree_def.leaves2_chance);
1350 getintfield(L, 2, "angle", tree_def.angle);
1351 getintfield(L, 2, "iterations", tree_def.iterations);
1352 if (!getintfield(L, 2, "random_level", tree_def.iterations_random_level))
1353 tree_def.iterations_random_level = 0;
1354 getstringfield(L, 2, "trunk_type", tree_def.trunk_type);
1355 getboolfield(L, 2, "thin_branches", tree_def.thin_branches);
1356 tree_def.fruit_chance=0;
1357 getstringfield(L, 2, "fruit", fruit);
1358 if (!fruit.empty()) {
1359 tree_def.fruitnode=ndef->getId(fruit);
1360 getintfield(L, 2, "fruit_chance",tree_def.fruit_chance);
1362 tree_def.explicit_seed = getintfield(L, 2, "seed", tree_def.seed);
1367 ServerMap *map = &env->getServerMap();
1369 if ((e = treegen::spawn_ltree (map, p0, ndef, tree_def)) != treegen::SUCCESS) {
1370 if (e == treegen::UNBALANCED_BRACKETS) {
1371 luaL_error(L, "spawn_tree(): closing ']' has no matching opening bracket");
1373 luaL_error(L, "spawn_tree(): unknown error");
1380 // transforming_liquid_add(pos)
1381 int ModApiEnvMod::l_transforming_liquid_add(lua_State *L)
1385 v3s16 p0 = read_v3s16(L, 1);
1386 env->getMap().transforming_liquid_add(p0);
1390 // forceload_block(blockpos)
1391 // blockpos = {x=num, y=num, z=num}
1392 int ModApiEnvMod::l_forceload_block(lua_State *L)
1396 v3s16 blockpos = read_v3s16(L, 1);
1397 env->getForceloadedBlocks()->insert(blockpos);
1401 // compare_block_status(nodepos)
1402 int ModApiEnvMod::l_compare_block_status(lua_State *L)
1406 v3s16 nodepos = check_v3s16(L, 1);
1407 std::string condition_s = luaL_checkstring(L, 2);
1408 auto status = env->getBlockStatus(getNodeBlockPos(nodepos));
1410 int condition_i = -1;
1411 if (!string_to_enum(es_BlockStatusType, condition_i, condition_s))
1412 return 0; // Unsupported
1414 lua_pushboolean(L, status >= condition_i);
1419 // forceload_free_block(blockpos)
1420 // blockpos = {x=num, y=num, z=num}
1421 int ModApiEnvMod::l_forceload_free_block(lua_State *L)
1425 v3s16 blockpos = read_v3s16(L, 1);
1426 env->getForceloadedBlocks()->erase(blockpos);
1430 // get_translated_string(lang_code, string)
1431 int ModApiEnvMod::l_get_translated_string(lua_State * L)
1434 std::string lang_code = luaL_checkstring(L, 1);
1435 std::string string = luaL_checkstring(L, 2);
1437 auto *translations = getServer(L)->getTranslationLanguage(lang_code);
1438 string = wide_to_utf8(translate_string(utf8_to_wide(string), translations));
1439 lua_pushstring(L, string.c_str());
1443 void ModApiEnvMod::Initialize(lua_State *L, int top)
1446 API_FCT(bulk_set_node);
1450 API_FCT(remove_node);
1452 API_FCT(get_node_or_nil);
1453 API_FCT(get_node_light);
1454 API_FCT(get_natural_light);
1455 API_FCT(place_node);
1457 API_FCT(punch_node);
1458 API_FCT(get_node_max_level);
1459 API_FCT(get_node_level);
1460 API_FCT(set_node_level);
1461 API_FCT(add_node_level);
1462 API_FCT(add_entity);
1463 API_FCT(find_nodes_with_meta);
1465 API_FCT(get_node_timer);
1466 API_FCT(get_connected_players);
1467 API_FCT(get_player_by_name);
1468 API_FCT(get_objects_in_area);
1469 API_FCT(get_objects_inside_radius);
1470 API_FCT(set_timeofday);
1471 API_FCT(get_timeofday);
1472 API_FCT(get_gametime);
1473 API_FCT(get_day_count);
1474 API_FCT(find_node_near);
1475 API_FCT(find_nodes_in_area);
1476 API_FCT(find_nodes_in_area_under_air);
1479 API_FCT(emerge_area);
1480 API_FCT(delete_area);
1481 API_FCT(get_perlin);
1482 API_FCT(get_perlin_map);
1483 API_FCT(get_voxel_manip);
1484 API_FCT(clear_objects);
1485 API_FCT(spawn_tree);
1487 API_FCT(line_of_sight);
1489 API_FCT(transforming_liquid_add);
1490 API_FCT(forceload_block);
1491 API_FCT(forceload_free_block);
1492 API_FCT(compare_block_status);
1493 API_FCT(get_translated_string);
1496 void ModApiEnvMod::InitializeClient(lua_State *L, int top)
1498 API_FCT(get_node_light);
1499 API_FCT(get_timeofday);
1500 API_FCT(get_node_max_level);
1501 API_FCT(get_node_level);
1502 API_FCT(find_nodes_with_meta);
1503 API_FCT(find_node_near);
1504 API_FCT(find_nodes_in_area);
1505 API_FCT(find_nodes_in_area_under_air);
1506 API_FCT(line_of_sight);