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 struct EnumString ModApiEnvMod::es_ClearObjectsMode[] =
51 {CLEAR_OBJECTS_MODE_FULL, "full"},
52 {CLEAR_OBJECTS_MODE_QUICK, "quick"},
56 ///////////////////////////////////////////////////////////////////////////////
59 void LuaABM::trigger(ServerEnvironment *env, v3s16 p, MapNode n,
60 u32 active_object_count, u32 active_object_count_wider)
62 ServerScripting *scriptIface = env->getScriptIface();
63 scriptIface->realityCheck();
65 lua_State *L = scriptIface->getStack();
66 sanity_check(lua_checkstack(L, 20));
67 StackUnroller stack_unroller(L);
69 int error_handler = PUSH_ERROR_HANDLER(L);
71 // Get registered_abms
72 lua_getglobal(L, "core");
73 lua_getfield(L, -1, "registered_abms");
74 luaL_checktype(L, -1, LUA_TTABLE);
75 lua_remove(L, -2); // Remove core
77 // Get registered_abms[m_id]
78 lua_pushinteger(L, m_id);
82 lua_remove(L, -2); // Remove registered_abms
84 scriptIface->setOriginFromTable(-1);
87 luaL_checktype(L, -1, LUA_TTABLE);
88 lua_getfield(L, -1, "action");
89 luaL_checktype(L, -1, LUA_TFUNCTION);
90 lua_remove(L, -2); // Remove registered_abms[m_id]
92 pushnode(L, n, env->getGameDef()->ndef());
93 lua_pushnumber(L, active_object_count);
94 lua_pushnumber(L, active_object_count_wider);
96 int result = lua_pcall(L, 4, 0, error_handler);
98 scriptIface->scriptError(result, "LuaABM::trigger");
100 lua_pop(L, 1); // Pop error handler
103 void LuaLBM::trigger(ServerEnvironment *env, v3s16 p, MapNode n)
105 ServerScripting *scriptIface = env->getScriptIface();
106 scriptIface->realityCheck();
108 lua_State *L = scriptIface->getStack();
109 sanity_check(lua_checkstack(L, 20));
110 StackUnroller stack_unroller(L);
112 int error_handler = PUSH_ERROR_HANDLER(L);
114 // Get registered_lbms
115 lua_getglobal(L, "core");
116 lua_getfield(L, -1, "registered_lbms");
117 luaL_checktype(L, -1, LUA_TTABLE);
118 lua_remove(L, -2); // Remove core
120 // Get registered_lbms[m_id]
121 lua_pushinteger(L, m_id);
123 FATAL_ERROR_IF(lua_isnil(L, -1), "Entry with given id not found in registered_lbms table");
124 lua_remove(L, -2); // Remove registered_lbms
126 scriptIface->setOriginFromTable(-1);
129 luaL_checktype(L, -1, LUA_TTABLE);
130 lua_getfield(L, -1, "action");
131 luaL_checktype(L, -1, LUA_TFUNCTION);
132 lua_remove(L, -2); // Remove registered_lbms[m_id]
134 pushnode(L, n, env->getGameDef()->ndef());
136 int result = lua_pcall(L, 2, 0, error_handler);
138 scriptIface->scriptError(result, "LuaLBM::trigger");
140 lua_pop(L, 1); // Pop error handler
143 int LuaRaycast::l_next(lua_State *L)
149 csm = getClient(L) != nullptr;
152 LuaRaycast *o = checkobject(L, 1);
153 PointedThing pointed;
154 env->continueRaycast(&o->state, &pointed);
155 if (pointed.type == POINTEDTHING_NOTHING)
158 push_pointed_thing(L, pointed, csm, true);
163 int LuaRaycast::create_object(lua_State *L)
165 NO_MAP_LOCK_REQUIRED;
168 bool liquids = false;
170 v3f pos1 = checkFloatPos(L, 1);
171 v3f pos2 = checkFloatPos(L, 2);
172 if (lua_isboolean(L, 3)) {
173 objects = readParam<bool>(L, 3);
175 if (lua_isboolean(L, 4)) {
176 liquids = readParam<bool>(L, 4);
179 LuaRaycast *o = new LuaRaycast(core::line3d<f32>(pos1, pos2),
182 *(void **) (lua_newuserdata(L, sizeof(void *))) = o;
183 luaL_getmetatable(L, className);
184 lua_setmetatable(L, -2);
188 LuaRaycast *LuaRaycast::checkobject(lua_State *L, int narg)
190 NO_MAP_LOCK_REQUIRED;
192 luaL_checktype(L, narg, LUA_TUSERDATA);
193 void *ud = luaL_checkudata(L, narg, className);
195 luaL_typerror(L, narg, className);
196 return *(LuaRaycast **) ud;
199 int LuaRaycast::gc_object(lua_State *L)
201 LuaRaycast *o = *(LuaRaycast **) (lua_touserdata(L, 1));
206 void LuaRaycast::Register(lua_State *L)
209 int methodtable = lua_gettop(L);
210 luaL_newmetatable(L, className);
211 int metatable = lua_gettop(L);
213 lua_pushliteral(L, "__metatable");
214 lua_pushvalue(L, methodtable);
215 lua_settable(L, metatable);
217 lua_pushliteral(L, "__index");
218 lua_pushvalue(L, methodtable);
219 lua_settable(L, metatable);
221 lua_pushliteral(L, "__gc");
222 lua_pushcfunction(L, gc_object);
223 lua_settable(L, metatable);
225 lua_pushliteral(L, "__call");
226 lua_pushcfunction(L, l_next);
227 lua_settable(L, metatable);
231 luaL_openlib(L, 0, methods, 0);
234 lua_register(L, className, create_object);
237 const char LuaRaycast::className[] = "Raycast";
238 const luaL_Reg LuaRaycast::methods[] =
240 luamethod(LuaRaycast, next),
244 void LuaEmergeAreaCallback(v3s16 blockpos, EmergeAction action, void *param)
246 ScriptCallbackState *state = (ScriptCallbackState *)param;
247 assert(state != NULL);
248 assert(state->script != NULL);
249 assert(state->refcount > 0);
251 // state must be protected by envlock
252 Server *server = state->script->getServer();
253 MutexAutoLock envlock(server->m_env_mutex);
257 state->script->on_emerge_area_completion(blockpos, action, state);
259 if (state->refcount == 0)
263 // Exported functions
265 // set_node(pos, node)
266 // pos = {x=num, y=num, z=num}
267 int ModApiEnvMod::l_set_node(lua_State *L)
271 const NodeDefManager *ndef = env->getGameDef()->ndef();
273 v3s16 pos = read_v3s16(L, 1);
274 MapNode n = readnode(L, 2, ndef);
276 bool succeeded = env->setNode(pos, n);
277 lua_pushboolean(L, succeeded);
281 // bulk_set_node([pos1, pos2, ...], node)
282 // pos = {x=num, y=num, z=num}
283 int ModApiEnvMod::l_bulk_set_node(lua_State *L)
287 const NodeDefManager *ndef = env->getGameDef()->ndef();
289 if (!lua_istable(L, 1)) {
293 s32 len = lua_objlen(L, 1);
295 lua_pushboolean(L, true);
299 MapNode n = readnode(L, 2, ndef);
302 bool succeeded = true;
303 for (s32 i = 1; i <= len; i++) {
304 lua_rawgeti(L, 1, i);
305 if (!env->setNode(read_v3s16(L, -1), n))
310 lua_pushboolean(L, succeeded);
314 int ModApiEnvMod::l_add_node(lua_State *L)
316 return l_set_node(L);
320 // pos = {x=num, y=num, z=num}
321 int ModApiEnvMod::l_remove_node(lua_State *L)
326 v3s16 pos = read_v3s16(L, 1);
328 bool succeeded = env->removeNode(pos);
329 lua_pushboolean(L, succeeded);
333 // swap_node(pos, node)
334 // pos = {x=num, y=num, z=num}
335 int ModApiEnvMod::l_swap_node(lua_State *L)
339 const NodeDefManager *ndef = env->getGameDef()->ndef();
341 v3s16 pos = read_v3s16(L, 1);
342 MapNode n = readnode(L, 2, ndef);
344 bool succeeded = env->swapNode(pos, n);
345 lua_pushboolean(L, succeeded);
350 // pos = {x=num, y=num, z=num}
351 int ModApiEnvMod::l_get_node(lua_State *L)
356 v3s16 pos = read_v3s16(L, 1);
358 MapNode n = env->getMap().getNode(pos);
360 pushnode(L, n, env->getGameDef()->ndef());
364 // get_node_or_nil(pos)
365 // pos = {x=num, y=num, z=num}
366 int ModApiEnvMod::l_get_node_or_nil(lua_State *L)
371 v3s16 pos = read_v3s16(L, 1);
374 MapNode n = env->getMap().getNode(pos, &pos_ok);
377 pushnode(L, n, env->getGameDef()->ndef());
384 // get_node_light(pos, timeofday)
385 // pos = {x=num, y=num, z=num}
386 // timeofday: nil = current time, 0 = night, 0.5 = day
387 int ModApiEnvMod::l_get_node_light(lua_State *L)
392 v3s16 pos = read_v3s16(L, 1);
393 u32 time_of_day = env->getTimeOfDay();
394 if(lua_isnumber(L, 2))
395 time_of_day = 24000.0 * lua_tonumber(L, 2);
396 time_of_day %= 24000;
397 u32 dnr = time_to_daynight_ratio(time_of_day, true);
400 MapNode n = env->getMap().getNode(pos, &is_position_ok);
401 if (is_position_ok) {
402 const NodeDefManager *ndef = env->getGameDef()->ndef();
403 lua_pushinteger(L, n.getLightBlend(dnr, ndef));
411 // get_natural_light(pos, timeofday)
412 // pos = {x=num, y=num, z=num}
413 // timeofday: nil = current time, 0 = night, 0.5 = day
414 int ModApiEnvMod::l_get_natural_light(lua_State *L)
418 v3s16 pos = read_v3s16(L, 1);
421 MapNode n = env->getMap().getNode(pos, &is_position_ok);
425 // If the daylight is 0, nothing needs to be calculated
426 u8 daylight = n.param1 & 0x0f;
428 lua_pushinteger(L, 0);
433 if (lua_isnumber(L, 2)) {
434 time_of_day = 24000.0 * lua_tonumber(L, 2);
435 time_of_day %= 24000;
437 time_of_day = env->getTimeOfDay();
439 u32 dnr = time_to_daynight_ratio(time_of_day, true);
441 // If it's the same as the artificial light, the sunlight needs to be
442 // searched for because the value may not emanate from the sun
443 if (daylight == n.param1 >> 4)
444 daylight = env->findSunlight(pos);
446 lua_pushinteger(L, dnr * daylight / 1000);
450 // place_node(pos, node)
451 // pos = {x=num, y=num, z=num}
452 int ModApiEnvMod::l_place_node(lua_State *L)
456 ScriptApiItem *scriptIfaceItem = getScriptApi<ScriptApiItem>(L);
457 Server *server = getServer(L);
458 const NodeDefManager *ndef = server->ndef();
459 IItemDefManager *idef = server->idef();
461 v3s16 pos = read_v3s16(L, 1);
462 MapNode n = readnode(L, 2, ndef);
464 // Don't attempt to load non-loaded area as of now
465 MapNode n_old = env->getMap().getNode(pos);
466 if(n_old.getContent() == CONTENT_IGNORE){
467 lua_pushboolean(L, false);
470 // Create item to place
471 ItemStack item(ndef->get(n).name, 1, 0, idef);
472 // Make pointed position
473 PointedThing pointed;
474 pointed.type = POINTEDTHING_NODE;
475 pointed.node_abovesurface = pos;
476 pointed.node_undersurface = pos + v3s16(0,-1,0);
477 // Place it with a NULL placer (appears in Lua as nil)
478 bool success = scriptIfaceItem->item_OnPlace(item, nullptr, pointed);
479 lua_pushboolean(L, success);
484 // pos = {x=num, y=num, z=num}
485 int ModApiEnvMod::l_dig_node(lua_State *L)
489 ScriptApiNode *scriptIfaceNode = getScriptApi<ScriptApiNode>(L);
491 v3s16 pos = read_v3s16(L, 1);
493 // Don't attempt to load non-loaded area as of now
494 MapNode n = env->getMap().getNode(pos);
495 if(n.getContent() == CONTENT_IGNORE){
496 lua_pushboolean(L, false);
499 // Dig it out with a NULL digger (appears in Lua as a
500 // non-functional ObjectRef)
501 bool success = scriptIfaceNode->node_on_dig(pos, n, NULL);
502 lua_pushboolean(L, success);
507 // pos = {x=num, y=num, z=num}
508 int ModApiEnvMod::l_punch_node(lua_State *L)
512 ScriptApiNode *scriptIfaceNode = getScriptApi<ScriptApiNode>(L);
514 v3s16 pos = read_v3s16(L, 1);
516 // Don't attempt to load non-loaded area as of now
517 MapNode n = env->getMap().getNode(pos);
518 if(n.getContent() == CONTENT_IGNORE){
519 lua_pushboolean(L, false);
522 // Punch it with a NULL puncher (appears in Lua as a non-functional
524 bool success = scriptIfaceNode->node_on_punch(pos, n, NULL, PointedThing());
525 lua_pushboolean(L, success);
529 // get_node_max_level(pos)
530 // pos = {x=num, y=num, z=num}
531 int ModApiEnvMod::l_get_node_max_level(lua_State *L)
535 v3s16 pos = read_v3s16(L, 1);
536 MapNode n = env->getMap().getNode(pos);
537 lua_pushnumber(L, n.getMaxLevel(env->getGameDef()->ndef()));
541 // get_node_level(pos)
542 // pos = {x=num, y=num, z=num}
543 int ModApiEnvMod::l_get_node_level(lua_State *L)
547 v3s16 pos = read_v3s16(L, 1);
548 MapNode n = env->getMap().getNode(pos);
549 lua_pushnumber(L, n.getLevel(env->getGameDef()->ndef()));
553 // set_node_level(pos, level)
554 // pos = {x=num, y=num, z=num}
556 int ModApiEnvMod::l_set_node_level(lua_State *L)
560 v3s16 pos = read_v3s16(L, 1);
562 if(lua_isnumber(L, 2))
563 level = lua_tonumber(L, 2);
564 MapNode n = env->getMap().getNode(pos);
565 lua_pushnumber(L, n.setLevel(env->getGameDef()->ndef(), level));
566 env->setNode(pos, n);
570 // add_node_level(pos, level)
571 // pos = {x=num, y=num, z=num}
573 int ModApiEnvMod::l_add_node_level(lua_State *L)
577 v3s16 pos = read_v3s16(L, 1);
579 if(lua_isnumber(L, 2))
580 level = lua_tonumber(L, 2);
581 MapNode n = env->getMap().getNode(pos);
582 lua_pushnumber(L, n.addLevel(env->getGameDef()->ndef(), level));
583 env->setNode(pos, n);
587 // find_nodes_with_meta(pos1, pos2)
588 int ModApiEnvMod::l_find_nodes_with_meta(lua_State *L)
592 std::vector<v3s16> positions = env->getMap().findNodesWithMetadata(
593 check_v3s16(L, 1), check_v3s16(L, 2));
595 lua_createtable(L, positions.size(), 0);
596 for (size_t i = 0; i != positions.size(); i++) {
597 push_v3s16(L, positions[i]);
598 lua_rawseti(L, -2, i + 1);
605 int ModApiEnvMod::l_get_meta(lua_State *L)
610 v3s16 p = read_v3s16(L, 1);
611 NodeMetaRef::create(L, p, env);
615 // get_node_timer(pos)
616 int ModApiEnvMod::l_get_node_timer(lua_State *L)
621 v3s16 p = read_v3s16(L, 1);
622 NodeTimerRef::create(L, p, &env->getServerMap());
626 // add_entity(pos, entityname, [staticdata]) -> ObjectRef or nil
627 // pos = {x=num, y=num, z=num}
628 int ModApiEnvMod::l_add_entity(lua_State *L)
632 v3f pos = checkFloatPos(L, 1);
633 const char *name = luaL_checkstring(L, 2);
634 const char *staticdata = luaL_optstring(L, 3, "");
636 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, staticdata);
637 int objectid = env->addActiveObject(obj);
638 // If failed to add, return nothing (reads as nil)
642 // If already deleted (can happen in on_activate), return nil
645 getScriptApiBase(L)->objectrefGetOrCreate(L, obj);
649 // add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
650 // pos = {x=num, y=num, z=num}
651 int ModApiEnvMod::l_add_item(lua_State *L)
656 //v3f pos = checkFloatPos(L, 1);
658 ItemStack item = read_item(L, 2,getServer(L)->idef());
659 if(item.empty() || !item.isKnown(getServer(L)->idef()))
662 int error_handler = PUSH_ERROR_HANDLER(L);
664 // Use spawn_item to spawn a __builtin:item
665 lua_getglobal(L, "core");
666 lua_getfield(L, -1, "spawn_item");
667 lua_remove(L, -2); // Remove core
671 lua_pushstring(L, item.getItemString().c_str());
673 PCALL_RESL(L, lua_pcall(L, 2, 1, error_handler));
675 lua_remove(L, error_handler);
679 // get_connected_players()
680 int ModApiEnvMod::l_get_connected_players(lua_State *L)
682 ServerEnvironment *env = (ServerEnvironment *) getEnv(L);
684 log_deprecated(L, "Calling get_connected_players() at mod load time"
686 lua_createtable(L, 0, 0);
690 lua_createtable(L, env->getPlayerCount(), 0);
692 for (RemotePlayer *player : env->getPlayers()) {
693 if (player->getPeerId() == PEER_ID_INEXISTENT)
695 PlayerSAO *sao = player->getPlayerSAO();
696 if (sao && !sao->isGone()) {
697 getScriptApiBase(L)->objectrefGetOrCreate(L, sao);
698 lua_rawseti(L, -2, ++i);
704 // get_player_by_name(name)
705 int ModApiEnvMod::l_get_player_by_name(lua_State *L)
710 const char *name = luaL_checkstring(L, 1);
711 RemotePlayer *player = env->getPlayer(name);
712 if (!player || player->getPeerId() == PEER_ID_INEXISTENT)
714 PlayerSAO *sao = player->getPlayerSAO();
715 if (!sao || sao->isGone())
717 // Put player on stack
718 getScriptApiBase(L)->objectrefGetOrCreate(L, sao);
722 // get_objects_inside_radius(pos, radius)
723 int ModApiEnvMod::l_get_objects_inside_radius(lua_State *L)
726 ScriptApiBase *script = getScriptApiBase(L);
729 v3f pos = checkFloatPos(L, 1);
730 float radius = readParam<float>(L, 2) * BS;
731 std::vector<ServerActiveObject *> objs;
733 auto include_obj_cb = [](ServerActiveObject *obj){ return !obj->isGone(); };
734 env->getObjectsInsideRadius(objs, pos, radius, include_obj_cb);
737 lua_createtable(L, objs.size(), 0);
738 for (const auto obj : objs) {
739 // Insert object reference into table
740 script->objectrefGetOrCreate(L, obj);
741 lua_rawseti(L, -2, ++i);
746 // set_timeofday(val)
748 int ModApiEnvMod::l_set_timeofday(lua_State *L)
753 float timeofday_f = readParam<float>(L, 1);
754 luaL_argcheck(L, timeofday_f >= 0.0f && timeofday_f <= 1.0f, 1,
755 "value must be between 0 and 1");
756 int timeofday_mh = (int)(timeofday_f * 24000.0f);
757 // This should be set directly in the environment but currently
758 // such changes aren't immediately sent to the clients, so call
759 // the server instead.
760 //env->setTimeOfDay(timeofday_mh);
761 getServer(L)->setTimeOfDay(timeofday_mh);
765 // get_timeofday() -> 0...1
766 int ModApiEnvMod::l_get_timeofday(lua_State *L)
771 int timeofday_mh = env->getTimeOfDay();
772 float timeofday_f = (float)timeofday_mh / 24000.0f;
773 lua_pushnumber(L, timeofday_f);
777 // get_day_count() -> int
778 int ModApiEnvMod::l_get_day_count(lua_State *L)
782 lua_pushnumber(L, env->getDayCount());
787 int ModApiEnvMod::l_get_gametime(lua_State *L)
791 int game_time = env->getGameTime();
792 lua_pushnumber(L, game_time);
796 void ModApiEnvMod::collectNodeIds(lua_State *L, int idx, const NodeDefManager *ndef,
797 std::vector<content_t> &filter)
799 if (lua_istable(L, idx)) {
801 while (lua_next(L, idx) != 0) {
802 // key at index -2 and value at index -1
803 luaL_checktype(L, -1, LUA_TSTRING);
804 ndef->getIds(readParam<std::string>(L, -1), filter);
805 // removes value, keeps key for next iteration
808 } else if (lua_isstring(L, idx)) {
809 ndef->getIds(readParam<std::string>(L, 3), filter);
813 // find_node_near(pos, radius, nodenames, [search_center]) -> pos or nil
814 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
815 int ModApiEnvMod::l_find_node_near(lua_State *L)
819 const NodeDefManager *ndef = env->getGameDef()->ndef();
820 Map &map = env->getMap();
822 v3s16 pos = read_v3s16(L, 1);
823 int radius = luaL_checkinteger(L, 2);
824 std::vector<content_t> filter;
825 collectNodeIds(L, 3, ndef, filter);
827 int start_radius = (lua_isboolean(L, 4) && readParam<bool>(L, 4)) ? 0 : 1;
830 // Client API limitations
831 if (Client *client = getClient(L))
832 radius = client->CSMClampRadius(pos, radius);
835 for (int d = start_radius; d <= radius; d++) {
836 const std::vector<v3s16> &list = FacePositionCache::getFacePositions(d);
837 for (const v3s16 &i : list) {
839 content_t c = map.getNode(p).getContent();
840 if (CONTAINS(filter, c)) {
849 // find_nodes_in_area(minp, maxp, nodenames, [grouped])
850 int ModApiEnvMod::l_find_nodes_in_area(lua_State *L)
854 v3s16 minp = read_v3s16(L, 1);
855 v3s16 maxp = read_v3s16(L, 2);
856 sortBoxVerticies(minp, maxp);
858 const NodeDefManager *ndef = env->getGameDef()->ndef();
859 Map &map = env->getMap();
862 if (Client *client = getClient(L)) {
863 minp = client->CSMClampPos(minp);
864 maxp = client->CSMClampPos(maxp);
868 v3s16 cube = maxp - minp + 1;
869 // Volume limit equal to 8 default mapchunks, (80 * 2) ^ 3 = 4,096,000
870 if ((u64)cube.X * (u64)cube.Y * (u64)cube.Z > 4096000) {
871 luaL_error(L, "find_nodes_in_area(): area volume"
872 " exceeds allowed value of 4096000");
876 std::vector<content_t> filter;
877 collectNodeIds(L, 3, ndef, filter);
879 bool grouped = lua_isboolean(L, 4) && readParam<bool>(L, 4);
882 // create the table we will be returning
883 lua_createtable(L, 0, filter.size());
884 int base = lua_gettop(L);
886 // create one table for each filter
887 std::vector<u32> idx;
888 idx.resize(filter.size());
889 for (u32 i = 0; i < filter.size(); i++)
893 for (p.X = minp.X; p.X <= maxp.X; p.X++)
894 for (p.Y = minp.Y; p.Y <= maxp.Y; p.Y++)
895 for (p.Z = minp.Z; p.Z <= maxp.Z; p.Z++) {
896 content_t c = map.getNode(p).getContent();
898 auto it = std::find(filter.begin(), filter.end(), c);
899 if (it != filter.end()) {
900 // Calculate index of the table and append the position
901 u32 filt_index = it - filter.begin();
903 lua_rawseti(L, base + 1 + filt_index, ++idx[filt_index]);
907 // last filter table is at top of stack
908 u32 i = filter.size() - 1;
911 // No such node found -> drop the empty table
914 // This node was found -> put table into the return table
915 lua_setfield(L, base, ndef->get(filter[i]).name.c_str());
919 assert(lua_gettop(L) == base);
922 std::vector<u32> individual_count;
923 individual_count.resize(filter.size());
928 for (p.X = minp.X; p.X <= maxp.X; p.X++)
929 for (p.Y = minp.Y; p.Y <= maxp.Y; p.Y++)
930 for (p.Z = minp.Z; p.Z <= maxp.Z; p.Z++) {
931 content_t c = env->getMap().getNode(p).getContent();
933 auto it = std::find(filter.begin(), filter.end(), c);
934 if (it != filter.end()) {
936 lua_rawseti(L, -2, ++i);
938 u32 filt_index = it - filter.begin();
939 individual_count[filt_index]++;
943 lua_createtable(L, 0, filter.size());
944 for (u32 i = 0; i < filter.size(); i++) {
945 lua_pushinteger(L, individual_count[i]);
946 lua_setfield(L, -2, ndef->get(filter[i]).name.c_str());
952 // find_nodes_in_area_under_air(minp, maxp, nodenames) -> list of positions
953 // nodenames: e.g. {"ignore", "group:tree"} or "default:dirt"
954 int ModApiEnvMod::l_find_nodes_in_area_under_air(lua_State *L)
956 /* Note: A similar but generalized (and therefore slower) version of this
957 * function could be created -- e.g. find_nodes_in_area_under -- which
958 * would accept a node name (or ID?) or list of names that the "above node"
965 v3s16 minp = read_v3s16(L, 1);
966 v3s16 maxp = read_v3s16(L, 2);
967 sortBoxVerticies(minp, maxp);
969 const NodeDefManager *ndef = env->getGameDef()->ndef();
970 Map &map = env->getMap();
973 if (Client *client = getClient(L)) {
974 minp = client->CSMClampPos(minp);
975 maxp = client->CSMClampPos(maxp);
979 v3s16 cube = maxp - minp + 1;
980 // Volume limit equal to 8 default mapchunks, (80 * 2) ^ 3 = 4,096,000
981 if ((u64)cube.X * (u64)cube.Y * (u64)cube.Z > 4096000) {
982 luaL_error(L, "find_nodes_in_area_under_air(): area volume"
983 " exceeds allowed value of 4096000");
987 std::vector<content_t> filter;
988 collectNodeIds(L, 3, ndef, filter);
993 for (p.X = minp.X; p.X <= maxp.X; p.X++)
994 for (p.Z = minp.Z; p.Z <= maxp.Z; p.Z++) {
996 content_t c = map.getNode(p).getContent();
997 for (; p.Y <= maxp.Y; p.Y++) {
998 v3s16 psurf(p.X, p.Y + 1, p.Z);
999 content_t csurf = map.getNode(psurf).getContent();
1000 if (c != CONTENT_AIR && csurf == CONTENT_AIR &&
1001 CONTAINS(filter, c)) {
1003 lua_rawseti(L, -2, ++i);
1011 // get_perlin(seeddiff, octaves, persistence, scale)
1012 // returns world-specific PerlinNoise
1013 int ModApiEnvMod::l_get_perlin(lua_State *L)
1015 GET_ENV_PTR_NO_MAP_LOCK;
1019 if (lua_istable(L, 1)) {
1020 read_noiseparams(L, 1, ¶ms);
1022 params.seed = luaL_checkint(L, 1);
1023 params.octaves = luaL_checkint(L, 2);
1024 params.persist = readParam<float>(L, 3);
1025 params.spread = v3f(1, 1, 1) * readParam<float>(L, 4);
1028 params.seed += (int)env->getServerMap().getSeed();
1030 LuaPerlinNoise *n = new LuaPerlinNoise(¶ms);
1031 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
1032 luaL_getmetatable(L, "PerlinNoise");
1033 lua_setmetatable(L, -2);
1037 // get_perlin_map(noiseparams, size)
1038 // returns world-specific PerlinNoiseMap
1039 int ModApiEnvMod::l_get_perlin_map(lua_State *L)
1041 GET_ENV_PTR_NO_MAP_LOCK;
1044 if (!read_noiseparams(L, 1, &np))
1046 v3s16 size = read_v3s16(L, 2);
1048 s32 seed = (s32)(env->getServerMap().getSeed());
1049 LuaPerlinNoiseMap *n = new LuaPerlinNoiseMap(&np, seed, size);
1050 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
1051 luaL_getmetatable(L, "PerlinNoiseMap");
1052 lua_setmetatable(L, -2);
1056 // get_voxel_manip()
1057 // returns voxel manipulator
1058 int ModApiEnvMod::l_get_voxel_manip(lua_State *L)
1062 Map *map = &(env->getMap());
1063 LuaVoxelManip *o = (lua_istable(L, 1) && lua_istable(L, 2)) ?
1064 new LuaVoxelManip(map, read_v3s16(L, 1), read_v3s16(L, 2)) :
1065 new LuaVoxelManip(map);
1067 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1068 luaL_getmetatable(L, "VoxelManip");
1069 lua_setmetatable(L, -2);
1073 // clear_objects([options])
1074 // clear all objects in the environment
1075 // where options = {mode = "full" or "quick"}
1076 int ModApiEnvMod::l_clear_objects(lua_State *L)
1080 ClearObjectsMode mode = CLEAR_OBJECTS_MODE_QUICK;
1081 if (lua_istable(L, 1)) {
1082 mode = (ClearObjectsMode)getenumfield(L, 1, "mode",
1083 ModApiEnvMod::es_ClearObjectsMode, mode);
1086 env->clearObjects(mode);
1090 // line_of_sight(pos1, pos2) -> true/false, pos
1091 int ModApiEnvMod::l_line_of_sight(lua_State *L)
1095 // read position 1 from lua
1096 v3f pos1 = checkFloatPos(L, 1);
1097 // read position 2 from lua
1098 v3f pos2 = checkFloatPos(L, 2);
1102 bool success = env->line_of_sight(pos1, pos2, &p);
1103 lua_pushboolean(L, success);
1111 // fix_light(p1, p2)
1112 int ModApiEnvMod::l_fix_light(lua_State *L)
1116 v3s16 blockpos1 = getContainerPos(read_v3s16(L, 1), MAP_BLOCKSIZE);
1117 v3s16 blockpos2 = getContainerPos(read_v3s16(L, 2), MAP_BLOCKSIZE);
1118 ServerMap &map = env->getServerMap();
1119 std::map<v3s16, MapBlock *> modified_blocks;
1120 bool success = true;
1122 for (blockpos.X = blockpos1.X; blockpos.X <= blockpos2.X; blockpos.X++)
1123 for (blockpos.Y = blockpos1.Y; blockpos.Y <= blockpos2.Y; blockpos.Y++)
1124 for (blockpos.Z = blockpos1.Z; blockpos.Z <= blockpos2.Z; blockpos.Z++) {
1125 success = success & map.repairBlockLight(blockpos, &modified_blocks);
1127 if (!modified_blocks.empty()) {
1129 event.type = MEET_OTHER;
1130 for (auto &modified_block : modified_blocks)
1131 event.modified_blocks.insert(modified_block.first);
1133 map.dispatchEvent(event);
1135 lua_pushboolean(L, success);
1140 int ModApiEnvMod::l_raycast(lua_State *L)
1142 return LuaRaycast::create_object(L);
1145 // load_area(p1, [p2])
1146 // load mapblocks in area p1..p2, but do not generate map
1147 int ModApiEnvMod::l_load_area(lua_State *L)
1152 Map *map = &(env->getMap());
1153 v3s16 bp1 = getNodeBlockPos(check_v3s16(L, 1));
1154 if (!lua_istable(L, 2)) {
1155 map->emergeBlock(bp1);
1157 v3s16 bp2 = getNodeBlockPos(check_v3s16(L, 2));
1158 sortBoxVerticies(bp1, bp2);
1159 for (s16 z = bp1.Z; z <= bp2.Z; z++)
1160 for (s16 y = bp1.Y; y <= bp2.Y; y++)
1161 for (s16 x = bp1.X; x <= bp2.X; x++) {
1162 map->emergeBlock(v3s16(x, y, z));
1169 // emerge_area(p1, p2, [callback, context])
1170 // emerge mapblocks in area p1..p2, calls callback with context upon completion
1171 int ModApiEnvMod::l_emerge_area(lua_State *L)
1175 EmergeCompletionCallback callback = NULL;
1176 ScriptCallbackState *state = NULL;
1178 EmergeManager *emerge = getServer(L)->getEmergeManager();
1180 v3s16 bpmin = getNodeBlockPos(read_v3s16(L, 1));
1181 v3s16 bpmax = getNodeBlockPos(read_v3s16(L, 2));
1182 sortBoxVerticies(bpmin, bpmax);
1184 size_t num_blocks = VoxelArea(bpmin, bpmax).getVolume();
1185 assert(num_blocks != 0);
1187 if (lua_isfunction(L, 3)) {
1188 callback = LuaEmergeAreaCallback;
1190 lua_pushvalue(L, 3);
1191 int callback_ref = luaL_ref(L, LUA_REGISTRYINDEX);
1193 lua_pushvalue(L, 4);
1194 int args_ref = luaL_ref(L, LUA_REGISTRYINDEX);
1196 state = new ScriptCallbackState;
1197 state->script = getServer(L)->getScriptIface();
1198 state->callback_ref = callback_ref;
1199 state->args_ref = args_ref;
1200 state->refcount = num_blocks;
1201 state->origin = getScriptApiBase(L)->getOrigin();
1204 for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
1205 for (s16 y = bpmin.Y; y <= bpmax.Y; y++)
1206 for (s16 x = bpmin.X; x <= bpmax.X; x++) {
1207 emerge->enqueueBlockEmergeEx(v3s16(x, y, z), PEER_ID_INEXISTENT,
1208 BLOCK_EMERGE_ALLOW_GEN | BLOCK_EMERGE_FORCE_QUEUE, callback, state);
1214 // delete_area(p1, p2)
1215 // delete mapblocks in area p1..p2
1216 int ModApiEnvMod::l_delete_area(lua_State *L)
1220 v3s16 bpmin = getNodeBlockPos(read_v3s16(L, 1));
1221 v3s16 bpmax = getNodeBlockPos(read_v3s16(L, 2));
1222 sortBoxVerticies(bpmin, bpmax);
1224 ServerMap &map = env->getServerMap();
1227 event.type = MEET_OTHER;
1229 bool success = true;
1230 for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
1231 for (s16 y = bpmin.Y; y <= bpmax.Y; y++)
1232 for (s16 x = bpmin.X; x <= bpmax.X; x++) {
1234 if (map.deleteBlock(bp)) {
1235 env->setStaticForActiveObjectsInBlock(bp, false);
1236 event.modified_blocks.insert(bp);
1242 map.dispatchEvent(event);
1243 lua_pushboolean(L, success);
1247 // find_path(pos1, pos2, searchdistance,
1248 // max_jump, max_drop, algorithm) -> table containing path
1249 int ModApiEnvMod::l_find_path(lua_State *L)
1253 v3s16 pos1 = read_v3s16(L, 1);
1254 v3s16 pos2 = read_v3s16(L, 2);
1255 unsigned int searchdistance = luaL_checkint(L, 3);
1256 unsigned int max_jump = luaL_checkint(L, 4);
1257 unsigned int max_drop = luaL_checkint(L, 5);
1258 PathAlgorithm algo = PA_PLAIN_NP;
1259 if (!lua_isnoneornil(L, 6)) {
1260 std::string algorithm = luaL_checkstring(L,6);
1262 if (algorithm == "A*")
1265 if (algorithm == "Dijkstra")
1269 std::vector<v3s16> path = get_path(&env->getServerMap(), env->getGameDef()->ndef(), pos1, pos2,
1270 searchdistance, max_jump, max_drop, algo);
1272 if (!path.empty()) {
1273 lua_createtable(L, path.size(), 0);
1274 int top = lua_gettop(L);
1275 unsigned int index = 1;
1276 for (const v3s16 &i : path) {
1277 lua_pushnumber(L,index);
1279 lua_settable(L, top);
1288 // spawn_tree(pos, treedef)
1289 int ModApiEnvMod::l_spawn_tree(lua_State *L)
1293 v3s16 p0 = read_v3s16(L, 1);
1295 treegen::TreeDef tree_def;
1296 std::string trunk,leaves,fruit;
1297 const NodeDefManager *ndef = env->getGameDef()->ndef();
1299 if(lua_istable(L, 2))
1301 getstringfield(L, 2, "axiom", tree_def.initial_axiom);
1302 getstringfield(L, 2, "rules_a", tree_def.rules_a);
1303 getstringfield(L, 2, "rules_b", tree_def.rules_b);
1304 getstringfield(L, 2, "rules_c", tree_def.rules_c);
1305 getstringfield(L, 2, "rules_d", tree_def.rules_d);
1306 getstringfield(L, 2, "trunk", trunk);
1307 tree_def.trunknode=ndef->getId(trunk);
1308 getstringfield(L, 2, "leaves", leaves);
1309 tree_def.leavesnode=ndef->getId(leaves);
1310 tree_def.leaves2_chance=0;
1311 getstringfield(L, 2, "leaves2", leaves);
1312 if (!leaves.empty()) {
1313 tree_def.leaves2node=ndef->getId(leaves);
1314 getintfield(L, 2, "leaves2_chance", tree_def.leaves2_chance);
1316 getintfield(L, 2, "angle", tree_def.angle);
1317 getintfield(L, 2, "iterations", tree_def.iterations);
1318 if (!getintfield(L, 2, "random_level", tree_def.iterations_random_level))
1319 tree_def.iterations_random_level = 0;
1320 getstringfield(L, 2, "trunk_type", tree_def.trunk_type);
1321 getboolfield(L, 2, "thin_branches", tree_def.thin_branches);
1322 tree_def.fruit_chance=0;
1323 getstringfield(L, 2, "fruit", fruit);
1324 if (!fruit.empty()) {
1325 tree_def.fruitnode=ndef->getId(fruit);
1326 getintfield(L, 2, "fruit_chance",tree_def.fruit_chance);
1328 tree_def.explicit_seed = getintfield(L, 2, "seed", tree_def.seed);
1333 ServerMap *map = &env->getServerMap();
1335 if ((e = treegen::spawn_ltree (map, p0, ndef, tree_def)) != treegen::SUCCESS) {
1336 if (e == treegen::UNBALANCED_BRACKETS) {
1337 luaL_error(L, "spawn_tree(): closing ']' has no matching opening bracket");
1339 luaL_error(L, "spawn_tree(): unknown error");
1346 // transforming_liquid_add(pos)
1347 int ModApiEnvMod::l_transforming_liquid_add(lua_State *L)
1351 v3s16 p0 = read_v3s16(L, 1);
1352 env->getMap().transforming_liquid_add(p0);
1356 // forceload_block(blockpos)
1357 // blockpos = {x=num, y=num, z=num}
1358 int ModApiEnvMod::l_forceload_block(lua_State *L)
1362 v3s16 blockpos = read_v3s16(L, 1);
1363 env->getForceloadedBlocks()->insert(blockpos);
1367 // forceload_free_block(blockpos)
1368 // blockpos = {x=num, y=num, z=num}
1369 int ModApiEnvMod::l_forceload_free_block(lua_State *L)
1373 v3s16 blockpos = read_v3s16(L, 1);
1374 env->getForceloadedBlocks()->erase(blockpos);
1378 // get_translated_string(lang_code, string)
1379 int ModApiEnvMod::l_get_translated_string(lua_State * L)
1382 std::string lang_code = luaL_checkstring(L, 1);
1383 std::string string = luaL_checkstring(L, 2);
1385 auto *translations = getServer(L)->getTranslationLanguage(lang_code);
1386 string = wide_to_utf8(translate_string(utf8_to_wide(string), translations));
1387 lua_pushstring(L, string.c_str());
1391 void ModApiEnvMod::Initialize(lua_State *L, int top)
1394 API_FCT(bulk_set_node);
1398 API_FCT(remove_node);
1400 API_FCT(get_node_or_nil);
1401 API_FCT(get_node_light);
1402 API_FCT(get_natural_light);
1403 API_FCT(place_node);
1405 API_FCT(punch_node);
1406 API_FCT(get_node_max_level);
1407 API_FCT(get_node_level);
1408 API_FCT(set_node_level);
1409 API_FCT(add_node_level);
1410 API_FCT(add_entity);
1411 API_FCT(find_nodes_with_meta);
1413 API_FCT(get_node_timer);
1414 API_FCT(get_connected_players);
1415 API_FCT(get_player_by_name);
1416 API_FCT(get_objects_inside_radius);
1417 API_FCT(set_timeofday);
1418 API_FCT(get_timeofday);
1419 API_FCT(get_gametime);
1420 API_FCT(get_day_count);
1421 API_FCT(find_node_near);
1422 API_FCT(find_nodes_in_area);
1423 API_FCT(find_nodes_in_area_under_air);
1426 API_FCT(emerge_area);
1427 API_FCT(delete_area);
1428 API_FCT(get_perlin);
1429 API_FCT(get_perlin_map);
1430 API_FCT(get_voxel_manip);
1431 API_FCT(clear_objects);
1432 API_FCT(spawn_tree);
1434 API_FCT(line_of_sight);
1436 API_FCT(transforming_liquid_add);
1437 API_FCT(forceload_block);
1438 API_FCT(forceload_free_block);
1439 API_FCT(get_translated_string);
1442 void ModApiEnvMod::InitializeClient(lua_State *L, int top)
1444 API_FCT(get_node_light);
1445 API_FCT(get_timeofday);
1446 API_FCT(get_node_max_level);
1447 API_FCT(get_node_level);
1448 API_FCT(find_nodes_with_meta);
1449 API_FCT(find_node_near);
1450 API_FCT(find_nodes_in_area);
1451 API_FCT(find_nodes_in_area_under_air);
1452 API_FCT(line_of_sight);