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]
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,
113 const MapNode n, const float dtime_s)
115 ServerScripting *scriptIface = env->getScriptIface();
116 scriptIface->realityCheck();
118 lua_State *L = scriptIface->getStack();
119 sanity_check(lua_checkstack(L, 20));
120 StackUnroller stack_unroller(L);
122 int error_handler = PUSH_ERROR_HANDLER(L);
124 // Get registered_lbms
125 lua_getglobal(L, "core");
126 lua_getfield(L, -1, "registered_lbms");
127 luaL_checktype(L, -1, LUA_TTABLE);
128 lua_remove(L, -2); // Remove core
130 // Get registered_lbms[m_id]
131 lua_pushinteger(L, m_id);
133 FATAL_ERROR_IF(lua_isnil(L, -1), "Entry with given id not found in registered_lbms table");
134 lua_remove(L, -2); // Remove registered_lbms
136 scriptIface->setOriginFromTable(-1);
139 luaL_checktype(L, -1, LUA_TTABLE);
140 lua_getfield(L, -1, "action");
141 luaL_checktype(L, -1, LUA_TFUNCTION);
142 lua_remove(L, -2); // Remove registered_lbms[m_id]
145 lua_pushnumber(L, dtime_s);
147 int result = lua_pcall(L, 3, 0, error_handler);
149 scriptIface->scriptError(result, "LuaLBM::trigger");
151 lua_pop(L, 1); // Pop error handler
154 int LuaRaycast::l_next(lua_State *L)
160 csm = getClient(L) != nullptr;
163 LuaRaycast *o = checkObject<LuaRaycast>(L, 1);
164 PointedThing pointed;
165 env->continueRaycast(&o->state, &pointed);
166 if (pointed.type == POINTEDTHING_NOTHING)
169 push_pointed_thing(L, pointed, csm, true);
174 int LuaRaycast::create_object(lua_State *L)
176 NO_MAP_LOCK_REQUIRED;
179 bool liquids = false;
181 v3f pos1 = checkFloatPos(L, 1);
182 v3f pos2 = checkFloatPos(L, 2);
183 if (lua_isboolean(L, 3)) {
184 objects = readParam<bool>(L, 3);
186 if (lua_isboolean(L, 4)) {
187 liquids = readParam<bool>(L, 4);
190 LuaRaycast *o = new LuaRaycast(core::line3d<f32>(pos1, pos2),
193 *(void **) (lua_newuserdata(L, sizeof(void *))) = o;
194 luaL_getmetatable(L, className);
195 lua_setmetatable(L, -2);
199 int LuaRaycast::gc_object(lua_State *L)
201 LuaRaycast *o = *(LuaRaycast **) (lua_touserdata(L, 1));
206 void LuaRaycast::Register(lua_State *L)
208 static const luaL_Reg metamethods[] = {
213 registerClass(L, className, methods, metamethods);
215 lua_register(L, className, create_object);
218 const char LuaRaycast::className[] = "Raycast";
219 const luaL_Reg LuaRaycast::methods[] =
221 luamethod(LuaRaycast, next),
225 void LuaEmergeAreaCallback(v3s16 blockpos, EmergeAction action, void *param)
227 ScriptCallbackState *state = (ScriptCallbackState *)param;
228 assert(state != NULL);
229 assert(state->script != NULL);
230 assert(state->refcount > 0);
232 // state must be protected by envlock
233 Server *server = state->script->getServer();
234 MutexAutoLock envlock(server->m_env_mutex);
238 state->script->on_emerge_area_completion(blockpos, action, state);
240 if (state->refcount == 0)
244 // Exported functions
246 // set_node(pos, node)
247 // pos = {x=num, y=num, z=num}
248 int ModApiEnvMod::l_set_node(lua_State *L)
253 v3s16 pos = read_v3s16(L, 1);
254 MapNode n = readnode(L, 2);
256 bool succeeded = env->setNode(pos, n);
257 lua_pushboolean(L, succeeded);
261 // bulk_set_node([pos1, pos2, ...], node)
262 // pos = {x=num, y=num, z=num}
263 int ModApiEnvMod::l_bulk_set_node(lua_State *L)
268 if (!lua_istable(L, 1)) {
272 s32 len = lua_objlen(L, 1);
274 lua_pushboolean(L, true);
278 MapNode n = readnode(L, 2);
281 bool succeeded = true;
282 for (s32 i = 1; i <= len; i++) {
283 lua_rawgeti(L, 1, i);
284 if (!env->setNode(read_v3s16(L, -1), n))
289 lua_pushboolean(L, succeeded);
293 int ModApiEnvMod::l_add_node(lua_State *L)
295 return l_set_node(L);
299 // pos = {x=num, y=num, z=num}
300 int ModApiEnvMod::l_remove_node(lua_State *L)
305 v3s16 pos = read_v3s16(L, 1);
307 bool succeeded = env->removeNode(pos);
308 lua_pushboolean(L, succeeded);
312 // swap_node(pos, node)
313 // pos = {x=num, y=num, z=num}
314 int ModApiEnvMod::l_swap_node(lua_State *L)
319 v3s16 pos = read_v3s16(L, 1);
320 MapNode n = readnode(L, 2);
322 bool succeeded = env->swapNode(pos, n);
323 lua_pushboolean(L, succeeded);
328 // pos = {x=num, y=num, z=num}
329 int ModApiEnvMod::l_get_node(lua_State *L)
334 v3s16 pos = read_v3s16(L, 1);
336 MapNode n = env->getMap().getNode(pos);
342 // get_node_or_nil(pos)
343 // pos = {x=num, y=num, z=num}
344 int ModApiEnvMod::l_get_node_or_nil(lua_State *L)
349 v3s16 pos = read_v3s16(L, 1);
352 MapNode n = env->getMap().getNode(pos, &pos_ok);
362 // get_node_light(pos, timeofday)
363 // pos = {x=num, y=num, z=num}
364 // timeofday: nil = current time, 0 = night, 0.5 = day
365 int ModApiEnvMod::l_get_node_light(lua_State *L)
370 v3s16 pos = read_v3s16(L, 1);
371 u32 time_of_day = env->getTimeOfDay();
372 if(lua_isnumber(L, 2))
373 time_of_day = 24000.0 * lua_tonumber(L, 2);
374 time_of_day %= 24000;
375 u32 dnr = time_to_daynight_ratio(time_of_day, true);
378 MapNode n = env->getMap().getNode(pos, &is_position_ok);
379 if (is_position_ok) {
380 const NodeDefManager *ndef = env->getGameDef()->ndef();
381 lua_pushinteger(L, n.getLightBlend(dnr, ndef->getLightingFlags(n)));
389 // get_natural_light(pos, timeofday)
390 // pos = {x=num, y=num, z=num}
391 // timeofday: nil = current time, 0 = night, 0.5 = day
392 int ModApiEnvMod::l_get_natural_light(lua_State *L)
396 v3s16 pos = read_v3s16(L, 1);
399 MapNode n = env->getMap().getNode(pos, &is_position_ok);
403 // If the daylight is 0, nothing needs to be calculated
404 u8 daylight = n.param1 & 0x0f;
406 lua_pushinteger(L, 0);
411 if (lua_isnumber(L, 2)) {
412 time_of_day = 24000.0 * lua_tonumber(L, 2);
413 time_of_day %= 24000;
415 time_of_day = env->getTimeOfDay();
417 u32 dnr = time_to_daynight_ratio(time_of_day, true);
419 // If it's the same as the artificial light, the sunlight needs to be
420 // searched for because the value may not emanate from the sun
421 if (daylight == n.param1 >> 4)
422 daylight = env->findSunlight(pos);
424 lua_pushinteger(L, dnr * daylight / 1000);
428 // place_node(pos, node)
429 // pos = {x=num, y=num, z=num}
430 int ModApiEnvMod::l_place_node(lua_State *L)
434 ScriptApiItem *scriptIfaceItem = getScriptApi<ScriptApiItem>(L);
435 Server *server = getServer(L);
436 const NodeDefManager *ndef = server->ndef();
437 IItemDefManager *idef = server->idef();
439 v3s16 pos = read_v3s16(L, 1);
440 MapNode n = readnode(L, 2);
442 // Don't attempt to load non-loaded area as of now
443 MapNode n_old = env->getMap().getNode(pos);
444 if(n_old.getContent() == CONTENT_IGNORE){
445 lua_pushboolean(L, false);
448 // Create item to place
449 Optional<ItemStack> item = ItemStack(ndef->get(n).name, 1, 0, idef);
450 // Make pointed position
451 PointedThing pointed;
452 pointed.type = POINTEDTHING_NODE;
453 pointed.node_abovesurface = pos;
454 pointed.node_undersurface = pos + v3s16(0,-1,0);
455 // Place it with a NULL placer (appears in Lua as nil)
456 bool success = scriptIfaceItem->item_OnPlace(item, nullptr, pointed);
457 lua_pushboolean(L, success);
462 // pos = {x=num, y=num, z=num}
463 int ModApiEnvMod::l_dig_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().getNode(pos);
473 if(n.getContent() == CONTENT_IGNORE){
474 lua_pushboolean(L, false);
477 // Dig it out with a NULL digger (appears in Lua as a
478 // non-functional ObjectRef)
479 bool success = scriptIfaceNode->node_on_dig(pos, n, NULL);
480 lua_pushboolean(L, success);
485 // pos = {x=num, y=num, z=num}
486 int ModApiEnvMod::l_punch_node(lua_State *L)
490 ScriptApiNode *scriptIfaceNode = getScriptApi<ScriptApiNode>(L);
492 v3s16 pos = read_v3s16(L, 1);
494 // Don't attempt to load non-loaded area as of now
495 MapNode n = env->getMap().getNode(pos);
496 if(n.getContent() == CONTENT_IGNORE){
497 lua_pushboolean(L, false);
500 // Punch it with a NULL puncher (appears in Lua as a non-functional
502 bool success = scriptIfaceNode->node_on_punch(pos, n, NULL, PointedThing());
503 lua_pushboolean(L, success);
507 // get_node_max_level(pos)
508 // pos = {x=num, y=num, z=num}
509 int ModApiEnvMod::l_get_node_max_level(lua_State *L)
513 v3s16 pos = read_v3s16(L, 1);
514 MapNode n = env->getMap().getNode(pos);
515 lua_pushnumber(L, n.getMaxLevel(env->getGameDef()->ndef()));
519 // get_node_level(pos)
520 // pos = {x=num, y=num, z=num}
521 int ModApiEnvMod::l_get_node_level(lua_State *L)
525 v3s16 pos = read_v3s16(L, 1);
526 MapNode n = env->getMap().getNode(pos);
527 lua_pushnumber(L, n.getLevel(env->getGameDef()->ndef()));
531 // set_node_level(pos, level)
532 // pos = {x=num, y=num, z=num}
534 int ModApiEnvMod::l_set_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().getNode(pos);
543 lua_pushnumber(L, n.setLevel(env->getGameDef()->ndef(), level));
544 env->setNode(pos, n);
548 // add_node_level(pos, level)
549 // pos = {x=num, y=num, z=num}
551 int ModApiEnvMod::l_add_node_level(lua_State *L)
555 v3s16 pos = read_v3s16(L, 1);
557 if(lua_isnumber(L, 2))
558 level = lua_tonumber(L, 2);
559 MapNode n = env->getMap().getNode(pos);
560 lua_pushnumber(L, n.addLevel(env->getGameDef()->ndef(), level));
561 env->setNode(pos, n);
565 // find_nodes_with_meta(pos1, pos2)
566 int ModApiEnvMod::l_find_nodes_with_meta(lua_State *L)
570 std::vector<v3s16> positions = env->getMap().findNodesWithMetadata(
571 check_v3s16(L, 1), check_v3s16(L, 2));
573 lua_createtable(L, positions.size(), 0);
574 for (size_t i = 0; i != positions.size(); i++) {
575 push_v3s16(L, positions[i]);
576 lua_rawseti(L, -2, i + 1);
583 int ModApiEnvMod::l_get_meta(lua_State *L)
588 v3s16 p = read_v3s16(L, 1);
589 NodeMetaRef::create(L, p, env);
593 // get_node_timer(pos)
594 int ModApiEnvMod::l_get_node_timer(lua_State *L)
599 v3s16 p = read_v3s16(L, 1);
600 NodeTimerRef::create(L, p, &env->getServerMap());
604 // add_entity(pos, entityname, [staticdata]) -> ObjectRef or nil
605 // pos = {x=num, y=num, z=num}
606 int ModApiEnvMod::l_add_entity(lua_State *L)
610 v3f pos = checkFloatPos(L, 1);
611 const char *name = luaL_checkstring(L, 2);
612 std::string staticdata = readParam<std::string>(L, 3, "");
614 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, staticdata);
615 int objectid = env->addActiveObject(obj);
616 // If failed to add, return nothing (reads as nil)
620 // If already deleted (can happen in on_activate), return nil
623 getScriptApiBase(L)->objectrefGetOrCreate(L, obj);
627 // add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
628 // pos = {x=num, y=num, z=num}
629 int ModApiEnvMod::l_add_item(lua_State *L)
634 //v3f pos = checkFloatPos(L, 1);
636 ItemStack item = read_item(L, 2,getServer(L)->idef());
637 if(item.empty() || !item.isKnown(getServer(L)->idef()))
640 int error_handler = PUSH_ERROR_HANDLER(L);
642 // Use spawn_item to spawn a __builtin:item
643 lua_getglobal(L, "core");
644 lua_getfield(L, -1, "spawn_item");
645 lua_remove(L, -2); // Remove core
649 lua_pushstring(L, item.getItemString().c_str());
651 PCALL_RESL(L, lua_pcall(L, 2, 1, error_handler));
653 lua_remove(L, error_handler);
657 // get_connected_players()
658 int ModApiEnvMod::l_get_connected_players(lua_State *L)
660 ServerEnvironment *env = (ServerEnvironment *) getEnv(L);
662 log_deprecated(L, "Calling get_connected_players() at mod load time"
664 lua_createtable(L, 0, 0);
668 lua_createtable(L, env->getPlayerCount(), 0);
670 for (RemotePlayer *player : env->getPlayers()) {
671 if (player->getPeerId() == PEER_ID_INEXISTENT)
673 PlayerSAO *sao = player->getPlayerSAO();
674 if (sao && !sao->isGone()) {
675 getScriptApiBase(L)->objectrefGetOrCreate(L, sao);
676 lua_rawseti(L, -2, ++i);
682 // get_player_by_name(name)
683 int ModApiEnvMod::l_get_player_by_name(lua_State *L)
688 const char *name = luaL_checkstring(L, 1);
689 RemotePlayer *player = env->getPlayer(name);
690 if (!player || player->getPeerId() == PEER_ID_INEXISTENT)
692 PlayerSAO *sao = player->getPlayerSAO();
693 if (!sao || sao->isGone())
695 // Put player on stack
696 getScriptApiBase(L)->objectrefGetOrCreate(L, sao);
700 // get_objects_inside_radius(pos, radius)
701 int ModApiEnvMod::l_get_objects_inside_radius(lua_State *L)
704 ScriptApiBase *script = getScriptApiBase(L);
707 v3f pos = checkFloatPos(L, 1);
708 float radius = readParam<float>(L, 2) * BS;
709 std::vector<ServerActiveObject *> objs;
711 auto include_obj_cb = [](ServerActiveObject *obj){ return !obj->isGone(); };
712 env->getObjectsInsideRadius(objs, pos, radius, include_obj_cb);
715 lua_createtable(L, objs.size(), 0);
716 for (const auto obj : objs) {
717 // Insert object reference into table
718 script->objectrefGetOrCreate(L, obj);
719 lua_rawseti(L, -2, ++i);
724 // get_objects_in_area(pos, minp, maxp)
725 int ModApiEnvMod::l_get_objects_in_area(lua_State *L)
728 ScriptApiBase *script = getScriptApiBase(L);
730 v3f minp = read_v3f(L, 1) * BS;
731 v3f maxp = read_v3f(L, 2) * BS;
732 aabb3f box(minp, maxp);
734 std::vector<ServerActiveObject *> objs;
736 auto include_obj_cb = [](ServerActiveObject *obj){ return !obj->isGone(); };
737 env->getObjectsInArea(objs, box, include_obj_cb);
740 lua_createtable(L, objs.size(), 0);
741 for (const auto obj : objs) {
742 // Insert object reference into table
743 script->objectrefGetOrCreate(L, obj);
744 lua_rawseti(L, -2, ++i);
749 // set_timeofday(val)
751 int ModApiEnvMod::l_set_timeofday(lua_State *L)
756 float timeofday_f = readParam<float>(L, 1);
757 luaL_argcheck(L, timeofday_f >= 0.0f && timeofday_f <= 1.0f, 1,
758 "value must be between 0 and 1");
759 int timeofday_mh = (int)(timeofday_f * 24000.0f);
760 // This should be set directly in the environment but currently
761 // such changes aren't immediately sent to the clients, so call
762 // the server instead.
763 //env->setTimeOfDay(timeofday_mh);
764 getServer(L)->setTimeOfDay(timeofday_mh);
768 // get_timeofday() -> 0...1
769 int ModApiEnvMod::l_get_timeofday(lua_State *L)
774 int timeofday_mh = env->getTimeOfDay();
775 float timeofday_f = (float)timeofday_mh / 24000.0f;
776 lua_pushnumber(L, timeofday_f);
780 // get_day_count() -> int
781 int ModApiEnvMod::l_get_day_count(lua_State *L)
785 lua_pushnumber(L, env->getDayCount());
790 int ModApiEnvMod::l_get_gametime(lua_State *L)
794 int game_time = env->getGameTime();
795 lua_pushnumber(L, game_time);
799 void ModApiEnvMod::collectNodeIds(lua_State *L, int idx, const NodeDefManager *ndef,
800 std::vector<content_t> &filter)
802 if (lua_istable(L, idx)) {
804 while (lua_next(L, idx) != 0) {
805 // key at index -2 and value at index -1
806 luaL_checktype(L, -1, LUA_TSTRING);
807 ndef->getIds(readParam<std::string>(L, -1), filter);
808 // removes value, keeps key for next iteration
811 } else if (lua_isstring(L, idx)) {
812 ndef->getIds(readParam<std::string>(L, 3), filter);
816 // find_node_near(pos, radius, nodenames, [search_center]) -> pos or nil
817 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
818 int ModApiEnvMod::l_find_node_near(lua_State *L)
822 const NodeDefManager *ndef = env->getGameDef()->ndef();
823 Map &map = env->getMap();
825 v3s16 pos = read_v3s16(L, 1);
826 int radius = luaL_checkinteger(L, 2);
827 std::vector<content_t> filter;
828 collectNodeIds(L, 3, ndef, filter);
830 int start_radius = (lua_isboolean(L, 4) && readParam<bool>(L, 4)) ? 0 : 1;
833 // Client API limitations
834 if (Client *client = getClient(L))
835 radius = client->CSMClampRadius(pos, radius);
838 for (int d = start_radius; d <= radius; d++) {
839 const std::vector<v3s16> &list = FacePositionCache::getFacePositions(d);
840 for (const v3s16 &i : list) {
842 content_t c = map.getNode(p).getContent();
843 if (CONTAINS(filter, c)) {
852 static void checkArea(v3s16 &minp, v3s16 &maxp)
854 auto volume = VoxelArea(minp, maxp).getVolume();
855 // Volume limit equal to 8 default mapchunks, (80 * 2) ^ 3 = 4,096,000
856 if (volume > 4096000) {
857 throw LuaError("Area volume exceeds allowed value of 4096000");
860 // Clamp to map range to avoid problems
861 #define CLAMP(arg) core::clamp(arg, (s16)-MAX_MAP_GENERATION_LIMIT, (s16)MAX_MAP_GENERATION_LIMIT)
862 minp = v3s16(CLAMP(minp.X), CLAMP(minp.Y), CLAMP(minp.Z));
863 maxp = v3s16(CLAMP(maxp.X), CLAMP(maxp.Y), CLAMP(maxp.Z));
867 // find_nodes_in_area(minp, maxp, nodenames, [grouped])
868 int ModApiEnvMod::l_find_nodes_in_area(lua_State *L)
872 v3s16 minp = read_v3s16(L, 1);
873 v3s16 maxp = read_v3s16(L, 2);
874 sortBoxVerticies(minp, maxp);
876 const NodeDefManager *ndef = env->getGameDef()->ndef();
877 Map &map = env->getMap();
880 if (Client *client = getClient(L)) {
881 minp = client->CSMClampPos(minp);
882 maxp = client->CSMClampPos(maxp);
886 checkArea(minp, maxp);
888 std::vector<content_t> filter;
889 collectNodeIds(L, 3, ndef, filter);
891 bool grouped = lua_isboolean(L, 4) && readParam<bool>(L, 4);
894 // create the table we will be returning
895 lua_createtable(L, 0, filter.size());
896 int base = lua_gettop(L);
898 // create one table for each filter
899 std::vector<u32> idx;
900 idx.resize(filter.size());
901 for (u32 i = 0; i < filter.size(); i++)
904 map.forEachNodeInArea(minp, maxp, [&](v3s16 p, MapNode n) -> bool {
905 content_t c = n.getContent();
907 auto it = std::find(filter.begin(), filter.end(), c);
908 if (it != filter.end()) {
909 // Calculate index of the table and append the position
910 u32 filt_index = it - filter.begin();
912 lua_rawseti(L, base + 1 + filt_index, ++idx[filt_index]);
918 // last filter table is at top of stack
919 u32 i = filter.size() - 1;
922 // No such node found -> drop the empty table
925 // This node was found -> put table into the return table
926 lua_setfield(L, base, ndef->get(filter[i]).name.c_str());
930 assert(lua_gettop(L) == base);
933 std::vector<u32> individual_count;
934 individual_count.resize(filter.size());
938 map.forEachNodeInArea(minp, maxp, [&](v3s16 p, MapNode n) -> bool {
939 content_t c = n.getContent();
941 auto it = std::find(filter.begin(), filter.end(), c);
942 if (it != filter.end()) {
944 lua_rawseti(L, -2, ++i);
946 u32 filt_index = it - filter.begin();
947 individual_count[filt_index]++;
953 lua_createtable(L, 0, filter.size());
954 for (u32 i = 0; i < filter.size(); i++) {
955 lua_pushinteger(L, individual_count[i]);
956 lua_setfield(L, -2, ndef->get(filter[i]).name.c_str());
962 // find_nodes_in_area_under_air(minp, maxp, nodenames) -> list of positions
963 // nodenames: e.g. {"ignore", "group:tree"} or "default:dirt"
964 int ModApiEnvMod::l_find_nodes_in_area_under_air(lua_State *L)
966 /* Note: A similar but generalized (and therefore slower) version of this
967 * function could be created -- e.g. find_nodes_in_area_under -- which
968 * would accept a node name (or ID?) or list of names that the "above node"
975 v3s16 minp = read_v3s16(L, 1);
976 v3s16 maxp = read_v3s16(L, 2);
977 sortBoxVerticies(minp, maxp);
979 const NodeDefManager *ndef = env->getGameDef()->ndef();
980 Map &map = env->getMap();
983 if (Client *client = getClient(L)) {
984 minp = client->CSMClampPos(minp);
985 maxp = client->CSMClampPos(maxp);
989 checkArea(minp, maxp);
991 std::vector<content_t> filter;
992 collectNodeIds(L, 3, ndef, filter);
997 for (p.X = minp.X; p.X <= maxp.X; p.X++)
998 for (p.Z = minp.Z; p.Z <= maxp.Z; p.Z++) {
1000 content_t c = map.getNode(p).getContent();
1001 for (; p.Y <= maxp.Y; p.Y++) {
1002 v3s16 psurf(p.X, p.Y + 1, p.Z);
1003 content_t csurf = map.getNode(psurf).getContent();
1004 if (c != CONTENT_AIR && csurf == CONTENT_AIR &&
1005 CONTAINS(filter, c)) {
1007 lua_rawseti(L, -2, ++i);
1015 // get_perlin(seeddiff, octaves, persistence, scale)
1016 // returns world-specific PerlinNoise
1017 int ModApiEnvMod::l_get_perlin(lua_State *L)
1019 GET_ENV_PTR_NO_MAP_LOCK;
1023 if (lua_istable(L, 1)) {
1024 read_noiseparams(L, 1, ¶ms);
1026 params.seed = luaL_checkint(L, 1);
1027 params.octaves = luaL_checkint(L, 2);
1028 params.persist = readParam<float>(L, 3);
1029 params.spread = v3f(1, 1, 1) * readParam<float>(L, 4);
1032 params.seed += (int)env->getServerMap().getSeed();
1034 LuaPerlinNoise *n = new LuaPerlinNoise(¶ms);
1035 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
1036 luaL_getmetatable(L, "PerlinNoise");
1037 lua_setmetatable(L, -2);
1041 // get_perlin_map(noiseparams, size)
1042 // returns world-specific PerlinNoiseMap
1043 int ModApiEnvMod::l_get_perlin_map(lua_State *L)
1045 GET_ENV_PTR_NO_MAP_LOCK;
1048 if (!read_noiseparams(L, 1, &np))
1050 v3s16 size = read_v3s16(L, 2);
1052 s32 seed = (s32)(env->getServerMap().getSeed());
1053 LuaPerlinNoiseMap *n = new LuaPerlinNoiseMap(&np, seed, size);
1054 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
1055 luaL_getmetatable(L, "PerlinNoiseMap");
1056 lua_setmetatable(L, -2);
1060 // get_voxel_manip()
1061 // returns voxel manipulator
1062 int ModApiEnvMod::l_get_voxel_manip(lua_State *L)
1066 Map *map = &(env->getMap());
1067 LuaVoxelManip *o = (lua_istable(L, 1) && lua_istable(L, 2)) ?
1068 new LuaVoxelManip(map, read_v3s16(L, 1), read_v3s16(L, 2)) :
1069 new LuaVoxelManip(map);
1071 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1072 luaL_getmetatable(L, "VoxelManip");
1073 lua_setmetatable(L, -2);
1077 // clear_objects([options])
1078 // clear all objects in the environment
1079 // where options = {mode = "full" or "quick"}
1080 int ModApiEnvMod::l_clear_objects(lua_State *L)
1084 ClearObjectsMode mode = CLEAR_OBJECTS_MODE_QUICK;
1085 if (lua_istable(L, 1)) {
1086 mode = (ClearObjectsMode)getenumfield(L, 1, "mode",
1087 ModApiEnvMod::es_ClearObjectsMode, mode);
1090 env->clearObjects(mode);
1094 // line_of_sight(pos1, pos2) -> true/false, pos
1095 int ModApiEnvMod::l_line_of_sight(lua_State *L)
1099 // read position 1 from lua
1100 v3f pos1 = checkFloatPos(L, 1);
1101 // read position 2 from lua
1102 v3f pos2 = checkFloatPos(L, 2);
1106 bool success = env->line_of_sight(pos1, pos2, &p);
1107 lua_pushboolean(L, success);
1115 // fix_light(p1, p2)
1116 int ModApiEnvMod::l_fix_light(lua_State *L)
1120 v3s16 blockpos1 = getContainerPos(read_v3s16(L, 1), MAP_BLOCKSIZE);
1121 v3s16 blockpos2 = getContainerPos(read_v3s16(L, 2), MAP_BLOCKSIZE);
1122 ServerMap &map = env->getServerMap();
1123 std::map<v3s16, MapBlock *> modified_blocks;
1124 bool success = true;
1126 for (blockpos.X = blockpos1.X; blockpos.X <= blockpos2.X; blockpos.X++)
1127 for (blockpos.Y = blockpos1.Y; blockpos.Y <= blockpos2.Y; blockpos.Y++)
1128 for (blockpos.Z = blockpos1.Z; blockpos.Z <= blockpos2.Z; blockpos.Z++) {
1129 success = success & map.repairBlockLight(blockpos, &modified_blocks);
1131 if (!modified_blocks.empty()) {
1133 event.type = MEET_OTHER;
1134 for (auto &modified_block : modified_blocks)
1135 event.modified_blocks.insert(modified_block.first);
1137 map.dispatchEvent(event);
1139 lua_pushboolean(L, success);
1144 int ModApiEnvMod::l_raycast(lua_State *L)
1146 return LuaRaycast::create_object(L);
1149 // load_area(p1, [p2])
1150 // load mapblocks in area p1..p2, but do not generate map
1151 int ModApiEnvMod::l_load_area(lua_State *L)
1156 Map *map = &(env->getMap());
1157 v3s16 bp1 = getNodeBlockPos(check_v3s16(L, 1));
1158 if (!lua_istable(L, 2)) {
1159 map->emergeBlock(bp1);
1161 v3s16 bp2 = getNodeBlockPos(check_v3s16(L, 2));
1162 sortBoxVerticies(bp1, bp2);
1163 for (s16 z = bp1.Z; z <= bp2.Z; z++)
1164 for (s16 y = bp1.Y; y <= bp2.Y; y++)
1165 for (s16 x = bp1.X; x <= bp2.X; x++) {
1166 map->emergeBlock(v3s16(x, y, z));
1173 // emerge_area(p1, p2, [callback, context])
1174 // emerge mapblocks in area p1..p2, calls callback with context upon completion
1175 int ModApiEnvMod::l_emerge_area(lua_State *L)
1179 EmergeCompletionCallback callback = NULL;
1180 ScriptCallbackState *state = NULL;
1182 EmergeManager *emerge = getServer(L)->getEmergeManager();
1184 v3s16 bpmin = getNodeBlockPos(read_v3s16(L, 1));
1185 v3s16 bpmax = getNodeBlockPos(read_v3s16(L, 2));
1186 sortBoxVerticies(bpmin, bpmax);
1188 size_t num_blocks = VoxelArea(bpmin, bpmax).getVolume();
1189 if (num_blocks == 0)
1192 if (lua_isfunction(L, 3)) {
1193 callback = LuaEmergeAreaCallback;
1195 lua_pushvalue(L, 3);
1196 int callback_ref = luaL_ref(L, LUA_REGISTRYINDEX);
1198 lua_pushvalue(L, 4);
1199 int args_ref = luaL_ref(L, LUA_REGISTRYINDEX);
1201 state = new ScriptCallbackState;
1202 state->script = getServer(L)->getScriptIface();
1203 state->callback_ref = callback_ref;
1204 state->args_ref = args_ref;
1205 state->refcount = num_blocks;
1206 state->origin = getScriptApiBase(L)->getOrigin();
1209 for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
1210 for (s16 y = bpmin.Y; y <= bpmax.Y; y++)
1211 for (s16 x = bpmin.X; x <= bpmax.X; x++) {
1212 emerge->enqueueBlockEmergeEx(v3s16(x, y, z), PEER_ID_INEXISTENT,
1213 BLOCK_EMERGE_ALLOW_GEN | BLOCK_EMERGE_FORCE_QUEUE, callback, state);
1219 // delete_area(p1, p2)
1220 // delete mapblocks in area p1..p2
1221 int ModApiEnvMod::l_delete_area(lua_State *L)
1225 v3s16 bpmin = getNodeBlockPos(read_v3s16(L, 1));
1226 v3s16 bpmax = getNodeBlockPos(read_v3s16(L, 2));
1227 sortBoxVerticies(bpmin, bpmax);
1229 ServerMap &map = env->getServerMap();
1232 event.type = MEET_OTHER;
1234 bool success = true;
1235 for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
1236 for (s16 y = bpmin.Y; y <= bpmax.Y; y++)
1237 for (s16 x = bpmin.X; x <= bpmax.X; x++) {
1239 if (map.deleteBlock(bp)) {
1240 env->setStaticForActiveObjectsInBlock(bp, false);
1241 event.modified_blocks.insert(bp);
1247 map.dispatchEvent(event);
1248 lua_pushboolean(L, success);
1252 // find_path(pos1, pos2, searchdistance,
1253 // max_jump, max_drop, algorithm) -> table containing path
1254 int ModApiEnvMod::l_find_path(lua_State *L)
1258 v3s16 pos1 = read_v3s16(L, 1);
1259 v3s16 pos2 = read_v3s16(L, 2);
1260 unsigned int searchdistance = luaL_checkint(L, 3);
1261 unsigned int max_jump = luaL_checkint(L, 4);
1262 unsigned int max_drop = luaL_checkint(L, 5);
1263 PathAlgorithm algo = PA_PLAIN_NP;
1264 if (!lua_isnoneornil(L, 6)) {
1265 std::string algorithm = luaL_checkstring(L,6);
1267 if (algorithm == "A*")
1270 if (algorithm == "Dijkstra")
1274 std::vector<v3s16> path = get_path(&env->getServerMap(), env->getGameDef()->ndef(), pos1, pos2,
1275 searchdistance, max_jump, max_drop, algo);
1277 if (!path.empty()) {
1278 lua_createtable(L, path.size(), 0);
1279 int top = lua_gettop(L);
1280 unsigned int index = 1;
1281 for (const v3s16 &i : path) {
1282 lua_pushnumber(L,index);
1284 lua_settable(L, top);
1293 // spawn_tree(pos, treedef)
1294 int ModApiEnvMod::l_spawn_tree(lua_State *L)
1298 v3s16 p0 = read_v3s16(L, 1);
1300 treegen::TreeDef tree_def;
1301 std::string trunk,leaves,fruit;
1302 const NodeDefManager *ndef = env->getGameDef()->ndef();
1304 if(lua_istable(L, 2))
1306 getstringfield(L, 2, "axiom", tree_def.initial_axiom);
1307 getstringfield(L, 2, "rules_a", tree_def.rules_a);
1308 getstringfield(L, 2, "rules_b", tree_def.rules_b);
1309 getstringfield(L, 2, "rules_c", tree_def.rules_c);
1310 getstringfield(L, 2, "rules_d", tree_def.rules_d);
1311 getstringfield(L, 2, "trunk", trunk);
1312 tree_def.trunknode=ndef->getId(trunk);
1313 getstringfield(L, 2, "leaves", leaves);
1314 tree_def.leavesnode=ndef->getId(leaves);
1315 tree_def.leaves2_chance=0;
1316 getstringfield(L, 2, "leaves2", leaves);
1317 if (!leaves.empty()) {
1318 tree_def.leaves2node=ndef->getId(leaves);
1319 getintfield(L, 2, "leaves2_chance", tree_def.leaves2_chance);
1321 getintfield(L, 2, "angle", tree_def.angle);
1322 getintfield(L, 2, "iterations", tree_def.iterations);
1323 if (!getintfield(L, 2, "random_level", tree_def.iterations_random_level))
1324 tree_def.iterations_random_level = 0;
1325 getstringfield(L, 2, "trunk_type", tree_def.trunk_type);
1326 getboolfield(L, 2, "thin_branches", tree_def.thin_branches);
1327 tree_def.fruit_chance=0;
1328 getstringfield(L, 2, "fruit", fruit);
1329 if (!fruit.empty()) {
1330 tree_def.fruitnode=ndef->getId(fruit);
1331 getintfield(L, 2, "fruit_chance",tree_def.fruit_chance);
1333 tree_def.explicit_seed = getintfield(L, 2, "seed", tree_def.seed);
1338 ServerMap *map = &env->getServerMap();
1340 if ((e = treegen::spawn_ltree (map, p0, ndef, tree_def)) != treegen::SUCCESS) {
1341 if (e == treegen::UNBALANCED_BRACKETS) {
1342 luaL_error(L, "spawn_tree(): closing ']' has no matching opening bracket");
1344 luaL_error(L, "spawn_tree(): unknown error");
1351 // transforming_liquid_add(pos)
1352 int ModApiEnvMod::l_transforming_liquid_add(lua_State *L)
1356 v3s16 p0 = read_v3s16(L, 1);
1357 env->getServerMap().transforming_liquid_add(p0);
1361 // forceload_block(blockpos)
1362 // blockpos = {x=num, y=num, z=num}
1363 int ModApiEnvMod::l_forceload_block(lua_State *L)
1367 v3s16 blockpos = read_v3s16(L, 1);
1368 env->getForceloadedBlocks()->insert(blockpos);
1372 // compare_block_status(nodepos)
1373 int ModApiEnvMod::l_compare_block_status(lua_State *L)
1377 v3s16 nodepos = check_v3s16(L, 1);
1378 std::string condition_s = luaL_checkstring(L, 2);
1379 auto status = env->getBlockStatus(getNodeBlockPos(nodepos));
1381 int condition_i = -1;
1382 if (!string_to_enum(es_BlockStatusType, condition_i, condition_s))
1383 return 0; // Unsupported
1385 lua_pushboolean(L, status >= condition_i);
1390 // forceload_free_block(blockpos)
1391 // blockpos = {x=num, y=num, z=num}
1392 int ModApiEnvMod::l_forceload_free_block(lua_State *L)
1396 v3s16 blockpos = read_v3s16(L, 1);
1397 env->getForceloadedBlocks()->erase(blockpos);
1401 // get_translated_string(lang_code, string)
1402 int ModApiEnvMod::l_get_translated_string(lua_State * L)
1405 std::string lang_code = luaL_checkstring(L, 1);
1406 std::string string = luaL_checkstring(L, 2);
1408 auto *translations = getServer(L)->getTranslationLanguage(lang_code);
1409 string = wide_to_utf8(translate_string(utf8_to_wide(string), translations));
1410 lua_pushstring(L, string.c_str());
1414 void ModApiEnvMod::Initialize(lua_State *L, int top)
1417 API_FCT(bulk_set_node);
1421 API_FCT(remove_node);
1423 API_FCT(get_node_or_nil);
1424 API_FCT(get_node_light);
1425 API_FCT(get_natural_light);
1426 API_FCT(place_node);
1428 API_FCT(punch_node);
1429 API_FCT(get_node_max_level);
1430 API_FCT(get_node_level);
1431 API_FCT(set_node_level);
1432 API_FCT(add_node_level);
1433 API_FCT(add_entity);
1434 API_FCT(find_nodes_with_meta);
1436 API_FCT(get_node_timer);
1437 API_FCT(get_connected_players);
1438 API_FCT(get_player_by_name);
1439 API_FCT(get_objects_in_area);
1440 API_FCT(get_objects_inside_radius);
1441 API_FCT(set_timeofday);
1442 API_FCT(get_timeofday);
1443 API_FCT(get_gametime);
1444 API_FCT(get_day_count);
1445 API_FCT(find_node_near);
1446 API_FCT(find_nodes_in_area);
1447 API_FCT(find_nodes_in_area_under_air);
1450 API_FCT(emerge_area);
1451 API_FCT(delete_area);
1452 API_FCT(get_perlin);
1453 API_FCT(get_perlin_map);
1454 API_FCT(get_voxel_manip);
1455 API_FCT(clear_objects);
1456 API_FCT(spawn_tree);
1458 API_FCT(line_of_sight);
1460 API_FCT(transforming_liquid_add);
1461 API_FCT(forceload_block);
1462 API_FCT(forceload_free_block);
1463 API_FCT(compare_block_status);
1464 API_FCT(get_translated_string);
1467 void ModApiEnvMod::InitializeClient(lua_State *L, int top)
1469 API_FCT(get_node_light);
1470 API_FCT(get_timeofday);
1471 API_FCT(get_node_max_level);
1472 API_FCT(get_node_level);
1473 API_FCT(find_nodes_with_meta);
1474 API_FCT(find_node_near);
1475 API_FCT(find_nodes_in_area);
1476 API_FCT(find_nodes_in_area_under_air);
1477 API_FCT(line_of_sight);