3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "lua_api/l_env.h"
21 #include "lua_api/l_internal.h"
22 #include "lua_api/l_nodemeta.h"
23 #include "lua_api/l_nodetimer.h"
24 #include "lua_api/l_noise.h"
25 #include "lua_api/l_vmanip.h"
26 #include "common/c_converter.h"
27 #include "common/c_content.h"
29 #include "scripting_server.h"
30 #include "environment.h"
34 #include "daynightratio.h"
35 #include "util/pointedthing.h"
36 #include "content_sao.h"
37 #include "mapgen/treegen.h"
39 #include "pathfinder.h"
40 #include "face_position_cache.h"
41 #include "remoteplayer.h"
43 #include "client/client.h"
46 struct EnumString ModApiEnvMod::es_ClearObjectsMode[] =
48 {CLEAR_OBJECTS_MODE_FULL, "full"},
49 {CLEAR_OBJECTS_MODE_QUICK, "quick"},
53 ///////////////////////////////////////////////////////////////////////////////
56 void LuaABM::trigger(ServerEnvironment *env, v3s16 p, MapNode n,
57 u32 active_object_count, u32 active_object_count_wider)
59 ServerScripting *scriptIface = env->getScriptIface();
60 scriptIface->realityCheck();
62 lua_State *L = scriptIface->getStack();
63 sanity_check(lua_checkstack(L, 20));
64 StackUnroller stack_unroller(L);
66 int error_handler = PUSH_ERROR_HANDLER(L);
68 // Get registered_abms
69 lua_getglobal(L, "core");
70 lua_getfield(L, -1, "registered_abms");
71 luaL_checktype(L, -1, LUA_TTABLE);
72 lua_remove(L, -2); // Remove core
74 // Get registered_abms[m_id]
75 lua_pushnumber(L, m_id);
79 lua_remove(L, -2); // Remove registered_abms
81 scriptIface->setOriginFromTable(-1);
84 luaL_checktype(L, -1, LUA_TTABLE);
85 lua_getfield(L, -1, "action");
86 luaL_checktype(L, -1, LUA_TFUNCTION);
87 lua_remove(L, -2); // Remove registered_abms[m_id]
89 pushnode(L, n, env->getGameDef()->ndef());
90 lua_pushnumber(L, active_object_count);
91 lua_pushnumber(L, active_object_count_wider);
93 int result = lua_pcall(L, 4, 0, error_handler);
95 scriptIface->scriptError(result, "LuaABM::trigger");
97 lua_pop(L, 1); // Pop error handler
100 void LuaLBM::trigger(ServerEnvironment *env, v3s16 p, MapNode n)
102 ServerScripting *scriptIface = env->getScriptIface();
103 scriptIface->realityCheck();
105 lua_State *L = scriptIface->getStack();
106 sanity_check(lua_checkstack(L, 20));
107 StackUnroller stack_unroller(L);
109 int error_handler = PUSH_ERROR_HANDLER(L);
111 // Get registered_lbms
112 lua_getglobal(L, "core");
113 lua_getfield(L, -1, "registered_lbms");
114 luaL_checktype(L, -1, LUA_TTABLE);
115 lua_remove(L, -2); // Remove core
117 // Get registered_lbms[m_id]
118 lua_pushnumber(L, m_id);
120 FATAL_ERROR_IF(lua_isnil(L, -1), "Entry with given id not found in registered_lbms table");
121 lua_remove(L, -2); // Remove registered_lbms
123 scriptIface->setOriginFromTable(-1);
126 luaL_checktype(L, -1, LUA_TTABLE);
127 lua_getfield(L, -1, "action");
128 luaL_checktype(L, -1, LUA_TFUNCTION);
129 lua_remove(L, -2); // Remove registered_lbms[m_id]
131 pushnode(L, n, env->getGameDef()->ndef());
133 int result = lua_pcall(L, 2, 0, error_handler);
135 scriptIface->scriptError(result, "LuaLBM::trigger");
137 lua_pop(L, 1); // Pop error handler
140 int LuaRaycast::l_next(lua_State *L)
147 csm = getClient(L) != nullptr;
150 LuaRaycast *o = checkobject(L, 1);
151 PointedThing pointed;
152 env->continueRaycast(&o->state, &pointed);
153 if (pointed.type == POINTEDTHING_NOTHING)
156 push_pointed_thing(L, pointed, csm, true);
161 int LuaRaycast::create_object(lua_State *L)
163 NO_MAP_LOCK_REQUIRED;
166 bool liquids = false;
168 v3f pos1 = checkFloatPos(L, 1);
169 v3f pos2 = checkFloatPos(L, 2);
170 if (lua_isboolean(L, 3)) {
171 objects = readParam<bool>(L, 3);
173 if (lua_isboolean(L, 4)) {
174 liquids = readParam<bool>(L, 4);
177 LuaRaycast *o = new LuaRaycast(core::line3d<f32>(pos1, pos2),
180 *(void **) (lua_newuserdata(L, sizeof(void *))) = o;
181 luaL_getmetatable(L, className);
182 lua_setmetatable(L, -2);
186 LuaRaycast *LuaRaycast::checkobject(lua_State *L, int narg)
188 NO_MAP_LOCK_REQUIRED;
190 luaL_checktype(L, narg, LUA_TUSERDATA);
191 void *ud = luaL_checkudata(L, narg, className);
193 luaL_typerror(L, narg, className);
194 return *(LuaRaycast **) ud;
197 int LuaRaycast::gc_object(lua_State *L)
199 LuaRaycast *o = *(LuaRaycast **) (lua_touserdata(L, 1));
204 void LuaRaycast::Register(lua_State *L)
207 int methodtable = lua_gettop(L);
208 luaL_newmetatable(L, className);
209 int metatable = lua_gettop(L);
211 lua_pushliteral(L, "__metatable");
212 lua_pushvalue(L, methodtable);
213 lua_settable(L, metatable);
215 lua_pushliteral(L, "__index");
216 lua_pushvalue(L, methodtable);
217 lua_settable(L, metatable);
219 lua_pushliteral(L, "__gc");
220 lua_pushcfunction(L, gc_object);
221 lua_settable(L, metatable);
223 lua_pushliteral(L, "__call");
224 lua_pushcfunction(L, l_next);
225 lua_settable(L, metatable);
229 luaL_openlib(L, 0, methods, 0);
232 lua_register(L, className, create_object);
235 const char LuaRaycast::className[] = "Raycast";
236 const luaL_Reg LuaRaycast::methods[] =
238 luamethod(LuaRaycast, next),
242 void LuaEmergeAreaCallback(v3s16 blockpos, EmergeAction action, void *param)
244 ScriptCallbackState *state = (ScriptCallbackState *)param;
245 assert(state != NULL);
246 assert(state->script != NULL);
247 assert(state->refcount > 0);
249 // state must be protected by envlock
250 Server *server = state->script->getServer();
251 MutexAutoLock envlock(server->m_env_mutex);
255 state->script->on_emerge_area_completion(blockpos, action, state);
257 if (state->refcount == 0)
261 // Exported functions
263 // set_node(pos, node)
264 // pos = {x=num, y=num, z=num}
265 int ModApiEnvMod::l_set_node(lua_State *L)
269 const NodeDefManager *ndef = env->getGameDef()->ndef();
271 v3s16 pos = read_v3s16(L, 1);
272 MapNode n = readnode(L, 2, ndef);
274 bool succeeded = env->setNode(pos, n);
275 lua_pushboolean(L, succeeded);
279 // bulk_set_node([pos1, pos2, ...], node)
280 // pos = {x=num, y=num, z=num}
281 int ModApiEnvMod::l_bulk_set_node(lua_State *L)
285 const NodeDefManager *ndef = env->getGameDef()->ndef();
287 if (!lua_istable(L, 1)) {
291 s32 len = lua_objlen(L, 1);
293 lua_pushboolean(L, true);
297 MapNode n = readnode(L, 2, ndef);
300 bool succeeded = true;
301 for (s32 i = 1; i <= len; i++) {
302 lua_rawgeti(L, 1, i);
303 if (!env->setNode(read_v3s16(L, -1), n))
308 lua_pushboolean(L, succeeded);
312 int ModApiEnvMod::l_add_node(lua_State *L)
314 return l_set_node(L);
318 // pos = {x=num, y=num, z=num}
319 int ModApiEnvMod::l_remove_node(lua_State *L)
324 v3s16 pos = read_v3s16(L, 1);
326 bool succeeded = env->removeNode(pos);
327 lua_pushboolean(L, succeeded);
331 // swap_node(pos, node)
332 // pos = {x=num, y=num, z=num}
333 int ModApiEnvMod::l_swap_node(lua_State *L)
337 const NodeDefManager *ndef = env->getGameDef()->ndef();
339 v3s16 pos = read_v3s16(L, 1);
340 MapNode n = readnode(L, 2, ndef);
342 bool succeeded = env->swapNode(pos, n);
343 lua_pushboolean(L, succeeded);
348 // pos = {x=num, y=num, z=num}
349 int ModApiEnvMod::l_get_node(lua_State *L)
354 v3s16 pos = read_v3s16(L, 1);
356 MapNode n = env->getMap().getNode(pos);
358 pushnode(L, n, env->getGameDef()->ndef());
362 // get_node_or_nil(pos)
363 // pos = {x=num, y=num, z=num}
364 int ModApiEnvMod::l_get_node_or_nil(lua_State *L)
369 v3s16 pos = read_v3s16(L, 1);
372 MapNode n = env->getMap().getNode(pos, &pos_ok);
375 pushnode(L, n, env->getGameDef()->ndef());
382 // get_node_light(pos, timeofday)
383 // pos = {x=num, y=num, z=num}
384 // timeofday: nil = current time, 0 = night, 0.5 = day
385 int ModApiEnvMod::l_get_node_light(lua_State *L)
390 v3s16 pos = read_v3s16(L, 1);
391 u32 time_of_day = env->getTimeOfDay();
392 if(lua_isnumber(L, 2))
393 time_of_day = 24000.0 * lua_tonumber(L, 2);
394 time_of_day %= 24000;
395 u32 dnr = time_to_daynight_ratio(time_of_day, true);
398 MapNode n = env->getMap().getNode(pos, &is_position_ok);
399 if (is_position_ok) {
400 const NodeDefManager *ndef = env->getGameDef()->ndef();
401 lua_pushinteger(L, n.getLightBlend(dnr, ndef));
408 // place_node(pos, node)
409 // pos = {x=num, y=num, z=num}
410 int ModApiEnvMod::l_place_node(lua_State *L)
414 ScriptApiItem *scriptIfaceItem = getScriptApi<ScriptApiItem>(L);
415 Server *server = getServer(L);
416 const NodeDefManager *ndef = server->ndef();
417 IItemDefManager *idef = server->idef();
419 v3s16 pos = read_v3s16(L, 1);
420 MapNode n = readnode(L, 2, ndef);
422 // Don't attempt to load non-loaded area as of now
423 MapNode n_old = env->getMap().getNode(pos);
424 if(n_old.getContent() == CONTENT_IGNORE){
425 lua_pushboolean(L, false);
428 // Create item to place
429 ItemStack item(ndef->get(n).name, 1, 0, idef);
430 // Make pointed position
431 PointedThing pointed;
432 pointed.type = POINTEDTHING_NODE;
433 pointed.node_abovesurface = pos;
434 pointed.node_undersurface = pos + v3s16(0,-1,0);
435 // Place it with a NULL placer (appears in Lua as nil)
436 bool success = scriptIfaceItem->item_OnPlace(item, nullptr, pointed);
437 lua_pushboolean(L, success);
442 // pos = {x=num, y=num, z=num}
443 int ModApiEnvMod::l_dig_node(lua_State *L)
447 ScriptApiNode *scriptIfaceNode = getScriptApi<ScriptApiNode>(L);
449 v3s16 pos = read_v3s16(L, 1);
451 // Don't attempt to load non-loaded area as of now
452 MapNode n = env->getMap().getNode(pos);
453 if(n.getContent() == CONTENT_IGNORE){
454 lua_pushboolean(L, false);
457 // Dig it out with a NULL digger (appears in Lua as a
458 // non-functional ObjectRef)
459 bool success = scriptIfaceNode->node_on_dig(pos, n, NULL);
460 lua_pushboolean(L, success);
465 // pos = {x=num, y=num, z=num}
466 int ModApiEnvMod::l_punch_node(lua_State *L)
470 ScriptApiNode *scriptIfaceNode = getScriptApi<ScriptApiNode>(L);
472 v3s16 pos = read_v3s16(L, 1);
474 // Don't attempt to load non-loaded area as of now
475 MapNode n = env->getMap().getNode(pos);
476 if(n.getContent() == CONTENT_IGNORE){
477 lua_pushboolean(L, false);
480 // Punch it with a NULL puncher (appears in Lua as a non-functional
482 bool success = scriptIfaceNode->node_on_punch(pos, n, NULL, PointedThing());
483 lua_pushboolean(L, success);
487 // get_node_max_level(pos)
488 // pos = {x=num, y=num, z=num}
489 int ModApiEnvMod::l_get_node_max_level(lua_State *L)
491 Environment *env = getEnv(L);
496 v3s16 pos = read_v3s16(L, 1);
497 MapNode n = env->getMap().getNode(pos);
498 lua_pushnumber(L, n.getMaxLevel(env->getGameDef()->ndef()));
502 // get_node_level(pos)
503 // pos = {x=num, y=num, z=num}
504 int ModApiEnvMod::l_get_node_level(lua_State *L)
506 Environment *env = getEnv(L);
511 v3s16 pos = read_v3s16(L, 1);
512 MapNode n = env->getMap().getNode(pos);
513 lua_pushnumber(L, n.getLevel(env->getGameDef()->ndef()));
517 // set_node_level(pos, level)
518 // pos = {x=num, y=num, z=num}
520 int ModApiEnvMod::l_set_node_level(lua_State *L)
524 v3s16 pos = read_v3s16(L, 1);
526 if(lua_isnumber(L, 2))
527 level = lua_tonumber(L, 2);
528 MapNode n = env->getMap().getNode(pos);
529 lua_pushnumber(L, n.setLevel(env->getGameDef()->ndef(), level));
530 env->setNode(pos, n);
534 // add_node_level(pos, level)
535 // pos = {x=num, y=num, z=num}
537 int ModApiEnvMod::l_add_node_level(lua_State *L)
541 v3s16 pos = read_v3s16(L, 1);
543 if(lua_isnumber(L, 2))
544 level = lua_tonumber(L, 2);
545 MapNode n = env->getMap().getNode(pos);
546 lua_pushnumber(L, n.addLevel(env->getGameDef()->ndef(), level));
547 env->setNode(pos, n);
551 // find_nodes_with_meta(pos1, pos2)
552 int ModApiEnvMod::l_find_nodes_with_meta(lua_State *L)
556 std::vector<v3s16> positions = env->getMap().findNodesWithMetadata(
557 check_v3s16(L, 1), check_v3s16(L, 2));
560 for (size_t i = 0; i != positions.size(); i++) {
561 push_v3s16(L, positions[i]);
562 lua_rawseti(L, -2, i + 1);
569 int ModApiEnvMod::l_get_meta(lua_State *L)
574 v3s16 p = read_v3s16(L, 1);
575 NodeMetaRef::create(L, p, env);
579 // get_node_timer(pos)
580 int ModApiEnvMod::l_get_node_timer(lua_State *L)
585 v3s16 p = read_v3s16(L, 1);
586 NodeTimerRef::create(L, p, env);
590 // add_entity(pos, entityname, [staticdata]) -> ObjectRef or nil
591 // pos = {x=num, y=num, z=num}
592 int ModApiEnvMod::l_add_entity(lua_State *L)
597 v3f pos = checkFloatPos(L, 1);
599 const char *name = luaL_checkstring(L, 2);
601 const char *staticdata = luaL_optstring(L, 3, "");
603 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, staticdata);
604 int objectid = env->addActiveObject(obj);
605 // If failed to add, return nothing (reads as nil)
609 getScriptApiBase(L)->objectrefGetOrCreate(L, obj);
613 // add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
614 // pos = {x=num, y=num, z=num}
615 int ModApiEnvMod::l_add_item(lua_State *L)
620 //v3f pos = checkFloatPos(L, 1);
622 ItemStack item = read_item(L, 2,getServer(L)->idef());
623 if(item.empty() || !item.isKnown(getServer(L)->idef()))
626 int error_handler = PUSH_ERROR_HANDLER(L);
628 // Use spawn_item to spawn a __builtin:item
629 lua_getglobal(L, "core");
630 lua_getfield(L, -1, "spawn_item");
631 lua_remove(L, -2); // Remove core
635 lua_pushstring(L, item.getItemString().c_str());
637 PCALL_RESL(L, lua_pcall(L, 2, 1, error_handler));
639 lua_remove(L, error_handler);
643 // get_connected_players()
644 int ModApiEnvMod::l_get_connected_players(lua_State *L)
648 lua_createtable(L, env->getPlayerCount(), 0);
650 for (RemotePlayer *player : env->getPlayers()) {
651 if (player->getPeerId() == PEER_ID_INEXISTENT)
653 PlayerSAO *sao = player->getPlayerSAO();
655 getScriptApiBase(L)->objectrefGetOrCreate(L, sao);
656 lua_rawseti(L, -2, ++i);
662 // get_player_by_name(name)
663 int ModApiEnvMod::l_get_player_by_name(lua_State *L)
668 const char *name = luaL_checkstring(L, 1);
669 RemotePlayer *player = env->getPlayer(name);
674 PlayerSAO *sao = player->getPlayerSAO();
679 // Put player on stack
680 getScriptApiBase(L)->objectrefGetOrCreate(L, sao);
684 // get_objects_inside_radius(pos, radius)
685 int ModApiEnvMod::l_get_objects_inside_radius(lua_State *L)
690 v3f pos = checkFloatPos(L, 1);
691 float radius = readParam<float>(L, 2) * BS;
692 std::vector<u16> ids;
693 env->getObjectsInsideRadius(ids, pos, radius);
694 ScriptApiBase *script = getScriptApiBase(L);
695 lua_createtable(L, ids.size(), 0);
696 std::vector<u16>::const_iterator iter = ids.begin();
697 for(u32 i = 0; iter != ids.end(); ++iter) {
698 ServerActiveObject *obj = env->getActiveObject(*iter);
699 if (!obj->isGone()) {
700 // Insert object reference into table
701 script->objectrefGetOrCreate(L, obj);
702 lua_rawseti(L, -2, ++i);
708 // set_timeofday(val)
710 int ModApiEnvMod::l_set_timeofday(lua_State *L)
715 float timeofday_f = readParam<float>(L, 1);
716 sanity_check(timeofday_f >= 0.0 && timeofday_f <= 1.0);
717 int timeofday_mh = (int)(timeofday_f * 24000.0);
718 // This should be set directly in the environment but currently
719 // such changes aren't immediately sent to the clients, so call
720 // the server instead.
721 //env->setTimeOfDay(timeofday_mh);
722 getServer(L)->setTimeOfDay(timeofday_mh);
726 // get_timeofday() -> 0...1
727 int ModApiEnvMod::l_get_timeofday(lua_State *L)
729 Environment *env = getEnv(L);
735 int timeofday_mh = env->getTimeOfDay();
736 float timeofday_f = (float)timeofday_mh / 24000.0f;
737 lua_pushnumber(L, timeofday_f);
741 // get_day_count() -> int
742 int ModApiEnvMod::l_get_day_count(lua_State *L)
744 Environment *env = getEnv(L);
749 lua_pushnumber(L, env->getDayCount());
754 int ModApiEnvMod::l_get_gametime(lua_State *L)
758 int game_time = env->getGameTime();
759 lua_pushnumber(L, game_time);
764 // find_node_near(pos, radius, nodenames, search_center) -> pos or nil
765 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
766 int ModApiEnvMod::l_find_node_near(lua_State *L)
768 Environment *env = getEnv(L);
773 const NodeDefManager *ndef = getGameDef(L)->ndef();
774 v3s16 pos = read_v3s16(L, 1);
775 int radius = luaL_checkinteger(L, 2);
776 std::vector<content_t> filter;
777 if (lua_istable(L, 3)) {
779 while (lua_next(L, 3) != 0) {
780 // key at index -2 and value at index -1
781 luaL_checktype(L, -1, LUA_TSTRING);
782 ndef->getIds(readParam<std::string>(L, -1), filter);
783 // removes value, keeps key for next iteration
786 } else if (lua_isstring(L, 3)) {
787 ndef->getIds(readParam<std::string>(L, 3), filter);
790 int start_radius = (lua_isboolean(L, 4) && readParam<bool>(L, 4)) ? 0 : 1;
793 // Client API limitations
795 radius = getClient(L)->CSMClampRadius(pos, radius);
798 for (int d = start_radius; d <= radius; d++) {
799 std::vector<v3s16> list = FacePositionCache::getFacePositions(d);
800 for (const v3s16 &i : list) {
802 content_t c = env->getMap().getNode(p).getContent();
803 if (CONTAINS(filter, c)) {
812 // find_nodes_in_area(minp, maxp, nodenames) -> list of positions
813 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
814 int ModApiEnvMod::l_find_nodes_in_area(lua_State *L)
818 v3s16 minp = read_v3s16(L, 1);
819 v3s16 maxp = read_v3s16(L, 2);
820 sortBoxVerticies(minp, maxp);
823 const NodeDefManager *ndef = getClient(L) ? getClient(L)->ndef() : getServer(L)->ndef();
825 minp = getClient(L)->CSMClampPos(minp);
826 maxp = getClient(L)->CSMClampPos(maxp);
829 const NodeDefManager *ndef = getServer(L)->ndef();
832 v3s16 cube = maxp - minp + 1;
833 // Volume limit equal to 8 default mapchunks, (80 * 2) ^ 3 = 4,096,000
834 if ((u64)cube.X * (u64)cube.Y * (u64)cube.Z > 4096000) {
835 luaL_error(L, "find_nodes_in_area(): area volume"
836 " exceeds allowed value of 4096000");
840 std::vector<content_t> filter;
841 if (lua_istable(L, 3)) {
843 while (lua_next(L, 3) != 0) {
844 // key at index -2 and value at index -1
845 luaL_checktype(L, -1, LUA_TSTRING);
846 ndef->getIds(readParam<std::string>(L, -1), filter);
847 // removes value, keeps key for next iteration
850 } else if (lua_isstring(L, 3)) {
851 ndef->getIds(readParam<std::string>(L, 3), filter);
854 std::vector<u32> individual_count;
855 individual_count.resize(filter.size());
859 for (s16 x = minp.X; x <= maxp.X; x++)
860 for (s16 y = minp.Y; y <= maxp.Y; y++)
861 for (s16 z = minp.Z; z <= maxp.Z; z++) {
863 content_t c = env->getMap().getNode(p).getContent();
865 std::vector<content_t>::iterator it = std::find(filter.begin(), filter.end(), c);
866 if (it != filter.end()) {
868 lua_rawseti(L, -2, ++i);
870 u32 filt_index = it - filter.begin();
871 individual_count[filt_index]++;
875 for (u32 i = 0; i < filter.size(); i++) {
876 lua_pushnumber(L, individual_count[i]);
877 lua_setfield(L, -2, ndef->get(filter[i]).name.c_str());
882 // find_nodes_in_area_under_air(minp, maxp, nodenames) -> list of positions
883 // nodenames: e.g. {"ignore", "group:tree"} or "default:dirt"
884 int ModApiEnvMod::l_find_nodes_in_area_under_air(lua_State *L)
886 /* Note: A similar but generalized (and therefore slower) version of this
887 * function could be created -- e.g. find_nodes_in_area_under -- which
888 * would accept a node name (or ID?) or list of names that the "above node"
895 v3s16 minp = read_v3s16(L, 1);
896 v3s16 maxp = read_v3s16(L, 2);
897 sortBoxVerticies(minp, maxp);
900 const NodeDefManager *ndef = getClient(L) ? getClient(L)->ndef() : getServer(L)->ndef();
902 minp = getClient(L)->CSMClampPos(minp);
903 maxp = getClient(L)->CSMClampPos(maxp);
906 const NodeDefManager *ndef = getServer(L)->ndef();
909 v3s16 cube = maxp - minp + 1;
910 // Volume limit equal to 8 default mapchunks, (80 * 2) ^ 3 = 4,096,000
911 if ((u64)cube.X * (u64)cube.Y * (u64)cube.Z > 4096000) {
912 luaL_error(L, "find_nodes_in_area_under_air(): area volume"
913 " exceeds allowed value of 4096000");
917 std::vector<content_t> filter;
919 if (lua_istable(L, 3)) {
921 while (lua_next(L, 3) != 0) {
922 // key at index -2 and value at index -1
923 luaL_checktype(L, -1, LUA_TSTRING);
924 ndef->getIds(readParam<std::string>(L, -1), filter);
925 // removes value, keeps key for next iteration
928 } else if (lua_isstring(L, 3)) {
929 ndef->getIds(readParam<std::string>(L, 3), filter);
934 for (s16 x = minp.X; x <= maxp.X; x++)
935 for (s16 z = minp.Z; z <= maxp.Z; z++) {
938 content_t c = env->getMap().getNode(p).getContent();
939 for (; y <= maxp.Y; y++) {
940 v3s16 psurf(x, y + 1, z);
941 content_t csurf = env->getMap().getNode(psurf).getContent();
942 if (c != CONTENT_AIR && csurf == CONTENT_AIR &&
943 CONTAINS(filter, c)) {
944 push_v3s16(L, v3s16(x, y, z));
945 lua_rawseti(L, -2, ++i);
953 // get_perlin(seeddiff, octaves, persistence, scale)
954 // returns world-specific PerlinNoise
955 int ModApiEnvMod::l_get_perlin(lua_State *L)
957 GET_ENV_PTR_NO_MAP_LOCK;
961 if (lua_istable(L, 1)) {
962 read_noiseparams(L, 1, ¶ms);
964 params.seed = luaL_checkint(L, 1);
965 params.octaves = luaL_checkint(L, 2);
966 params.persist = readParam<float>(L, 3);
967 params.spread = v3f(1, 1, 1) * readParam<float>(L, 4);
970 params.seed += (int)env->getServerMap().getSeed();
972 LuaPerlinNoise *n = new LuaPerlinNoise(¶ms);
973 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
974 luaL_getmetatable(L, "PerlinNoise");
975 lua_setmetatable(L, -2);
979 // get_perlin_map(noiseparams, size)
980 // returns world-specific PerlinNoiseMap
981 int ModApiEnvMod::l_get_perlin_map(lua_State *L)
983 GET_ENV_PTR_NO_MAP_LOCK;
986 if (!read_noiseparams(L, 1, &np))
988 v3s16 size = read_v3s16(L, 2);
990 s32 seed = (s32)(env->getServerMap().getSeed());
991 LuaPerlinNoiseMap *n = new LuaPerlinNoiseMap(&np, seed, size);
992 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
993 luaL_getmetatable(L, "PerlinNoiseMap");
994 lua_setmetatable(L, -2);
999 // returns voxel manipulator
1000 int ModApiEnvMod::l_get_voxel_manip(lua_State *L)
1004 Map *map = &(env->getMap());
1005 LuaVoxelManip *o = (lua_istable(L, 1) && lua_istable(L, 2)) ?
1006 new LuaVoxelManip(map, read_v3s16(L, 1), read_v3s16(L, 2)) :
1007 new LuaVoxelManip(map);
1009 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
1010 luaL_getmetatable(L, "VoxelManip");
1011 lua_setmetatable(L, -2);
1015 // clear_objects([options])
1016 // clear all objects in the environment
1017 // where options = {mode = "full" or "quick"}
1018 int ModApiEnvMod::l_clear_objects(lua_State *L)
1022 ClearObjectsMode mode = CLEAR_OBJECTS_MODE_QUICK;
1023 if (lua_istable(L, 1)) {
1024 mode = (ClearObjectsMode)getenumfield(L, 1, "mode",
1025 ModApiEnvMod::es_ClearObjectsMode, mode);
1028 env->clearObjects(mode);
1032 // line_of_sight(pos1, pos2) -> true/false, pos
1033 int ModApiEnvMod::l_line_of_sight(lua_State *L)
1037 // read position 1 from lua
1038 v3f pos1 = checkFloatPos(L, 1);
1039 // read position 2 from lua
1040 v3f pos2 = checkFloatPos(L, 2);
1044 bool success = env->line_of_sight(pos1, pos2, &p);
1045 lua_pushboolean(L, success);
1053 // fix_light(p1, p2)
1054 int ModApiEnvMod::l_fix_light(lua_State *L)
1058 v3s16 blockpos1 = getContainerPos(read_v3s16(L, 1), MAP_BLOCKSIZE);
1059 v3s16 blockpos2 = getContainerPos(read_v3s16(L, 2), MAP_BLOCKSIZE);
1060 ServerMap &map = env->getServerMap();
1061 std::map<v3s16, MapBlock *> modified_blocks;
1062 bool success = true;
1064 for (blockpos.X = blockpos1.X; blockpos.X <= blockpos2.X; blockpos.X++)
1065 for (blockpos.Y = blockpos1.Y; blockpos.Y <= blockpos2.Y; blockpos.Y++)
1066 for (blockpos.Z = blockpos1.Z; blockpos.Z <= blockpos2.Z; blockpos.Z++) {
1067 success = success & map.repairBlockLight(blockpos, &modified_blocks);
1069 if (!modified_blocks.empty()) {
1071 event.type = MEET_OTHER;
1072 for (auto &modified_block : modified_blocks)
1073 event.modified_blocks.insert(modified_block.first);
1075 map.dispatchEvent(event);
1077 lua_pushboolean(L, success);
1082 int ModApiEnvMod::l_raycast(lua_State *L)
1084 return LuaRaycast::create_object(L);
1087 // load_area(p1, [p2])
1088 // load mapblocks in area p1..p2, but do not generate map
1089 int ModApiEnvMod::l_load_area(lua_State *L)
1094 Map *map = &(env->getMap());
1095 v3s16 bp1 = getNodeBlockPos(check_v3s16(L, 1));
1096 if (!lua_istable(L, 2)) {
1097 map->emergeBlock(bp1);
1099 v3s16 bp2 = getNodeBlockPos(check_v3s16(L, 2));
1100 sortBoxVerticies(bp1, bp2);
1101 for (s16 z = bp1.Z; z <= bp2.Z; z++)
1102 for (s16 y = bp1.Y; y <= bp2.Y; y++)
1103 for (s16 x = bp1.X; x <= bp2.X; x++) {
1104 map->emergeBlock(v3s16(x, y, z));
1111 // emerge_area(p1, p2, [callback, context])
1112 // emerge mapblocks in area p1..p2, calls callback with context upon completion
1113 int ModApiEnvMod::l_emerge_area(lua_State *L)
1117 EmergeCompletionCallback callback = NULL;
1118 ScriptCallbackState *state = NULL;
1120 EmergeManager *emerge = getServer(L)->getEmergeManager();
1122 v3s16 bpmin = getNodeBlockPos(read_v3s16(L, 1));
1123 v3s16 bpmax = getNodeBlockPos(read_v3s16(L, 2));
1124 sortBoxVerticies(bpmin, bpmax);
1126 size_t num_blocks = VoxelArea(bpmin, bpmax).getVolume();
1127 assert(num_blocks != 0);
1129 if (lua_isfunction(L, 3)) {
1130 callback = LuaEmergeAreaCallback;
1132 lua_pushvalue(L, 3);
1133 int callback_ref = luaL_ref(L, LUA_REGISTRYINDEX);
1135 lua_pushvalue(L, 4);
1136 int args_ref = luaL_ref(L, LUA_REGISTRYINDEX);
1138 state = new ScriptCallbackState;
1139 state->script = getServer(L)->getScriptIface();
1140 state->callback_ref = callback_ref;
1141 state->args_ref = args_ref;
1142 state->refcount = num_blocks;
1143 state->origin = getScriptApiBase(L)->getOrigin();
1146 for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
1147 for (s16 y = bpmin.Y; y <= bpmax.Y; y++)
1148 for (s16 x = bpmin.X; x <= bpmax.X; x++) {
1149 emerge->enqueueBlockEmergeEx(v3s16(x, y, z), PEER_ID_INEXISTENT,
1150 BLOCK_EMERGE_ALLOW_GEN | BLOCK_EMERGE_FORCE_QUEUE, callback, state);
1156 // delete_area(p1, p2)
1157 // delete mapblocks in area p1..p2
1158 int ModApiEnvMod::l_delete_area(lua_State *L)
1162 v3s16 bpmin = getNodeBlockPos(read_v3s16(L, 1));
1163 v3s16 bpmax = getNodeBlockPos(read_v3s16(L, 2));
1164 sortBoxVerticies(bpmin, bpmax);
1166 ServerMap &map = env->getServerMap();
1169 event.type = MEET_OTHER;
1171 bool success = true;
1172 for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
1173 for (s16 y = bpmin.Y; y <= bpmax.Y; y++)
1174 for (s16 x = bpmin.X; x <= bpmax.X; x++) {
1176 if (map.deleteBlock(bp)) {
1177 env->setStaticForActiveObjectsInBlock(bp, false);
1178 event.modified_blocks.insert(bp);
1184 map.dispatchEvent(event);
1185 lua_pushboolean(L, success);
1189 // find_path(pos1, pos2, searchdistance,
1190 // max_jump, max_drop, algorithm) -> table containing path
1191 int ModApiEnvMod::l_find_path(lua_State *L)
1195 v3s16 pos1 = read_v3s16(L, 1);
1196 v3s16 pos2 = read_v3s16(L, 2);
1197 unsigned int searchdistance = luaL_checkint(L, 3);
1198 unsigned int max_jump = luaL_checkint(L, 4);
1199 unsigned int max_drop = luaL_checkint(L, 5);
1200 PathAlgorithm algo = PA_PLAIN_NP;
1201 if (!lua_isnil(L, 6)) {
1202 std::string algorithm = luaL_checkstring(L,6);
1204 if (algorithm == "A*")
1207 if (algorithm == "Dijkstra")
1211 std::vector<v3s16> path = get_path(env, pos1, pos2,
1212 searchdistance, max_jump, max_drop, algo);
1214 if (!path.empty()) {
1216 int top = lua_gettop(L);
1217 unsigned int index = 1;
1218 for (const v3s16 &i : path) {
1219 lua_pushnumber(L,index);
1221 lua_settable(L, top);
1230 // spawn_tree(pos, treedef)
1231 int ModApiEnvMod::l_spawn_tree(lua_State *L)
1235 v3s16 p0 = read_v3s16(L, 1);
1237 treegen::TreeDef tree_def;
1238 std::string trunk,leaves,fruit;
1239 const NodeDefManager *ndef = env->getGameDef()->ndef();
1241 if(lua_istable(L, 2))
1243 getstringfield(L, 2, "axiom", tree_def.initial_axiom);
1244 getstringfield(L, 2, "rules_a", tree_def.rules_a);
1245 getstringfield(L, 2, "rules_b", tree_def.rules_b);
1246 getstringfield(L, 2, "rules_c", tree_def.rules_c);
1247 getstringfield(L, 2, "rules_d", tree_def.rules_d);
1248 getstringfield(L, 2, "trunk", trunk);
1249 tree_def.trunknode=ndef->getId(trunk);
1250 getstringfield(L, 2, "leaves", leaves);
1251 tree_def.leavesnode=ndef->getId(leaves);
1252 tree_def.leaves2_chance=0;
1253 getstringfield(L, 2, "leaves2", leaves);
1254 if (!leaves.empty()) {
1255 tree_def.leaves2node=ndef->getId(leaves);
1256 getintfield(L, 2, "leaves2_chance", tree_def.leaves2_chance);
1258 getintfield(L, 2, "angle", tree_def.angle);
1259 getintfield(L, 2, "iterations", tree_def.iterations);
1260 if (!getintfield(L, 2, "random_level", tree_def.iterations_random_level))
1261 tree_def.iterations_random_level = 0;
1262 getstringfield(L, 2, "trunk_type", tree_def.trunk_type);
1263 getboolfield(L, 2, "thin_branches", tree_def.thin_branches);
1264 tree_def.fruit_chance=0;
1265 getstringfield(L, 2, "fruit", fruit);
1266 if (!fruit.empty()) {
1267 tree_def.fruitnode=ndef->getId(fruit);
1268 getintfield(L, 2, "fruit_chance",tree_def.fruit_chance);
1270 tree_def.explicit_seed = getintfield(L, 2, "seed", tree_def.seed);
1276 if ((e = treegen::spawn_ltree (env, p0, ndef, tree_def)) != treegen::SUCCESS) {
1277 if (e == treegen::UNBALANCED_BRACKETS) {
1278 luaL_error(L, "spawn_tree(): closing ']' has no matching opening bracket");
1280 luaL_error(L, "spawn_tree(): unknown error");
1287 // transforming_liquid_add(pos)
1288 int ModApiEnvMod::l_transforming_liquid_add(lua_State *L)
1292 v3s16 p0 = read_v3s16(L, 1);
1293 env->getMap().transforming_liquid_add(p0);
1297 // forceload_block(blockpos)
1298 // blockpos = {x=num, y=num, z=num}
1299 int ModApiEnvMod::l_forceload_block(lua_State *L)
1303 v3s16 blockpos = read_v3s16(L, 1);
1304 env->getForceloadedBlocks()->insert(blockpos);
1308 // forceload_free_block(blockpos)
1309 // blockpos = {x=num, y=num, z=num}
1310 int ModApiEnvMod::l_forceload_free_block(lua_State *L)
1314 v3s16 blockpos = read_v3s16(L, 1);
1315 env->getForceloadedBlocks()->erase(blockpos);
1319 void ModApiEnvMod::Initialize(lua_State *L, int top)
1322 API_FCT(bulk_set_node);
1326 API_FCT(remove_node);
1328 API_FCT(get_node_or_nil);
1329 API_FCT(get_node_light);
1330 API_FCT(place_node);
1332 API_FCT(punch_node);
1333 API_FCT(get_node_max_level);
1334 API_FCT(get_node_level);
1335 API_FCT(set_node_level);
1336 API_FCT(add_node_level);
1337 API_FCT(add_entity);
1338 API_FCT(find_nodes_with_meta);
1340 API_FCT(get_node_timer);
1341 API_FCT(get_connected_players);
1342 API_FCT(get_player_by_name);
1343 API_FCT(get_objects_inside_radius);
1344 API_FCT(set_timeofday);
1345 API_FCT(get_timeofday);
1346 API_FCT(get_gametime);
1347 API_FCT(get_day_count);
1348 API_FCT(find_node_near);
1349 API_FCT(find_nodes_in_area);
1350 API_FCT(find_nodes_in_area_under_air);
1353 API_FCT(emerge_area);
1354 API_FCT(delete_area);
1355 API_FCT(get_perlin);
1356 API_FCT(get_perlin_map);
1357 API_FCT(get_voxel_manip);
1358 API_FCT(clear_objects);
1359 API_FCT(spawn_tree);
1361 API_FCT(line_of_sight);
1363 API_FCT(transforming_liquid_add);
1364 API_FCT(forceload_block);
1365 API_FCT(forceload_free_block);
1368 void ModApiEnvMod::InitializeClient(lua_State *L, int top)
1370 API_FCT(get_node_light);
1371 API_FCT(get_timeofday);
1372 API_FCT(get_node_max_level);
1373 API_FCT(get_node_level);
1374 API_FCT(find_nodes_with_meta);
1375 API_FCT(find_node_near);
1376 API_FCT(find_nodes_in_area);
1377 API_FCT(find_nodes_in_area_under_air);
1378 API_FCT(line_of_sight);