3 Copyright (C) 2013 celeron55, Perttu Ahola <celeron55@gmail.com>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU Lesser General Public License as published by
7 the Free Software Foundation; either version 2.1 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU Lesser General Public License for more details.
15 You should have received a copy of the GNU Lesser General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 #include "lua_api/l_env.h"
21 #include "lua_api/l_internal.h"
22 #include "lua_api/l_nodemeta.h"
23 #include "lua_api/l_nodetimer.h"
24 #include "lua_api/l_noise.h"
25 #include "lua_api/l_vmanip.h"
26 #include "common/c_converter.h"
27 #include "common/c_content.h"
29 #include "scripting_server.h"
30 #include "environment.h"
34 #include "daynightratio.h"
35 #include "util/pointedthing.h"
36 #include "content_sao.h"
37 #include "mapgen/treegen.h"
39 #include "pathfinder.h"
40 #include "face_position_cache.h"
41 #include "remoteplayer.h"
46 struct EnumString ModApiEnvMod::es_ClearObjectsMode[] =
48 {CLEAR_OBJECTS_MODE_FULL, "full"},
49 {CLEAR_OBJECTS_MODE_QUICK, "quick"},
53 ///////////////////////////////////////////////////////////////////////////////
56 void LuaABM::trigger(ServerEnvironment *env, v3s16 p, MapNode n,
57 u32 active_object_count, u32 active_object_count_wider)
59 ServerScripting *scriptIface = env->getScriptIface();
60 scriptIface->realityCheck();
62 lua_State *L = scriptIface->getStack();
63 sanity_check(lua_checkstack(L, 20));
64 StackUnroller stack_unroller(L);
66 int error_handler = PUSH_ERROR_HANDLER(L);
68 // Get registered_abms
69 lua_getglobal(L, "core");
70 lua_getfield(L, -1, "registered_abms");
71 luaL_checktype(L, -1, LUA_TTABLE);
72 lua_remove(L, -2); // Remove core
74 // Get registered_abms[m_id]
75 lua_pushnumber(L, m_id);
79 lua_remove(L, -2); // Remove registered_abms
81 scriptIface->setOriginFromTable(-1);
84 luaL_checktype(L, -1, LUA_TTABLE);
85 lua_getfield(L, -1, "action");
86 luaL_checktype(L, -1, LUA_TFUNCTION);
87 lua_remove(L, -2); // Remove registered_abms[m_id]
89 pushnode(L, n, env->getGameDef()->ndef());
90 lua_pushnumber(L, active_object_count);
91 lua_pushnumber(L, active_object_count_wider);
93 int result = lua_pcall(L, 4, 0, error_handler);
95 scriptIface->scriptError(result, "LuaABM::trigger");
97 lua_pop(L, 1); // Pop error handler
100 void LuaLBM::trigger(ServerEnvironment *env, v3s16 p, MapNode n)
102 ServerScripting *scriptIface = env->getScriptIface();
103 scriptIface->realityCheck();
105 lua_State *L = scriptIface->getStack();
106 sanity_check(lua_checkstack(L, 20));
107 StackUnroller stack_unroller(L);
109 int error_handler = PUSH_ERROR_HANDLER(L);
111 // Get registered_lbms
112 lua_getglobal(L, "core");
113 lua_getfield(L, -1, "registered_lbms");
114 luaL_checktype(L, -1, LUA_TTABLE);
115 lua_remove(L, -2); // Remove core
117 // Get registered_lbms[m_id]
118 lua_pushnumber(L, m_id);
120 FATAL_ERROR_IF(lua_isnil(L, -1), "Entry with given id not found in registered_lbms table");
121 lua_remove(L, -2); // Remove registered_lbms
123 scriptIface->setOriginFromTable(-1);
126 luaL_checktype(L, -1, LUA_TTABLE);
127 lua_getfield(L, -1, "action");
128 luaL_checktype(L, -1, LUA_TFUNCTION);
129 lua_remove(L, -2); // Remove registered_lbms[m_id]
131 pushnode(L, n, env->getGameDef()->ndef());
133 int result = lua_pcall(L, 2, 0, error_handler);
135 scriptIface->scriptError(result, "LuaLBM::trigger");
137 lua_pop(L, 1); // Pop error handler
140 int LuaRaycast::l_next(lua_State *L)
144 ScriptApiItem *script = getScriptApi<ScriptApiItem>(L);
147 LuaRaycast *o = checkobject(L, 1);
148 PointedThing pointed;
149 env->continueRaycast(&o->state, &pointed);
150 if (pointed.type == POINTEDTHING_NOTHING)
153 script->pushPointedThing(pointed);
158 int LuaRaycast::create_object(lua_State *L)
160 NO_MAP_LOCK_REQUIRED;
163 bool liquids = false;
165 v3f pos1 = checkFloatPos(L, 1);
166 v3f pos2 = checkFloatPos(L, 2);
167 if (lua_isboolean(L, 3)) {
168 objects = lua_toboolean(L, 3);
170 if (lua_isboolean(L, 4)) {
171 liquids = lua_toboolean(L, 4);
174 LuaRaycast *o = new LuaRaycast(core::line3d<f32>(pos1, pos2),
177 *(void **) (lua_newuserdata(L, sizeof(void *))) = o;
178 luaL_getmetatable(L, className);
179 lua_setmetatable(L, -2);
183 LuaRaycast *LuaRaycast::checkobject(lua_State *L, int narg)
185 NO_MAP_LOCK_REQUIRED;
187 luaL_checktype(L, narg, LUA_TUSERDATA);
188 void *ud = luaL_checkudata(L, narg, className);
190 luaL_typerror(L, narg, className);
191 return *(LuaRaycast **) ud;
194 int LuaRaycast::gc_object(lua_State *L)
196 LuaRaycast *o = *(LuaRaycast **) (lua_touserdata(L, 1));
201 void LuaRaycast::Register(lua_State *L)
204 int methodtable = lua_gettop(L);
205 luaL_newmetatable(L, className);
206 int metatable = lua_gettop(L);
208 lua_pushliteral(L, "__metatable");
209 lua_pushvalue(L, methodtable);
210 lua_settable(L, metatable);
212 lua_pushliteral(L, "__index");
213 lua_pushvalue(L, methodtable);
214 lua_settable(L, metatable);
216 lua_pushliteral(L, "__gc");
217 lua_pushcfunction(L, gc_object);
218 lua_settable(L, metatable);
220 lua_pushliteral(L, "__call");
221 lua_pushcfunction(L, l_next);
222 lua_settable(L, metatable);
226 luaL_openlib(L, 0, methods, 0);
229 lua_register(L, className, create_object);
232 const char LuaRaycast::className[] = "Raycast";
233 const luaL_Reg LuaRaycast::methods[] =
235 luamethod(LuaRaycast, next),
239 void LuaEmergeAreaCallback(v3s16 blockpos, EmergeAction action, void *param)
241 ScriptCallbackState *state = (ScriptCallbackState *)param;
242 assert(state != NULL);
243 assert(state->script != NULL);
244 assert(state->refcount > 0);
246 // state must be protected by envlock
247 Server *server = state->script->getServer();
248 MutexAutoLock envlock(server->m_env_mutex);
252 state->script->on_emerge_area_completion(blockpos, action, state);
254 if (state->refcount == 0)
258 // Exported functions
260 // set_node(pos, node)
261 // pos = {x=num, y=num, z=num}
262 int ModApiEnvMod::l_set_node(lua_State *L)
266 const NodeDefManager *ndef = env->getGameDef()->ndef();
268 v3s16 pos = read_v3s16(L, 1);
269 MapNode n = readnode(L, 2, ndef);
271 bool succeeded = env->setNode(pos, n);
272 lua_pushboolean(L, succeeded);
276 // bulk_set_node([pos1, pos2, ...], node)
277 // pos = {x=num, y=num, z=num}
278 int ModApiEnvMod::l_bulk_set_node(lua_State *L)
282 const NodeDefManager *ndef = env->getGameDef()->ndef();
284 if (!lua_istable(L, 1)) {
288 s32 len = lua_objlen(L, 1);
290 lua_pushboolean(L, true);
294 MapNode n = readnode(L, 2, ndef);
297 bool succeeded = true;
298 for (s32 i = 1; i <= len; i++) {
299 lua_rawgeti(L, 1, i);
300 if (!env->setNode(read_v3s16(L, -1), n))
305 lua_pushboolean(L, succeeded);
309 int ModApiEnvMod::l_add_node(lua_State *L)
311 return l_set_node(L);
315 // pos = {x=num, y=num, z=num}
316 int ModApiEnvMod::l_remove_node(lua_State *L)
321 v3s16 pos = read_v3s16(L, 1);
323 bool succeeded = env->removeNode(pos);
324 lua_pushboolean(L, succeeded);
328 // swap_node(pos, node)
329 // pos = {x=num, y=num, z=num}
330 int ModApiEnvMod::l_swap_node(lua_State *L)
334 const NodeDefManager *ndef = env->getGameDef()->ndef();
336 v3s16 pos = read_v3s16(L, 1);
337 MapNode n = readnode(L, 2, ndef);
339 bool succeeded = env->swapNode(pos, n);
340 lua_pushboolean(L, succeeded);
345 // pos = {x=num, y=num, z=num}
346 int ModApiEnvMod::l_get_node(lua_State *L)
351 v3s16 pos = read_v3s16(L, 1);
353 MapNode n = env->getMap().getNodeNoEx(pos);
355 pushnode(L, n, env->getGameDef()->ndef());
359 // get_node_or_nil(pos)
360 // pos = {x=num, y=num, z=num}
361 int ModApiEnvMod::l_get_node_or_nil(lua_State *L)
366 v3s16 pos = read_v3s16(L, 1);
369 MapNode n = env->getMap().getNodeNoEx(pos, &pos_ok);
372 pushnode(L, n, env->getGameDef()->ndef());
379 // get_node_light(pos, timeofday)
380 // pos = {x=num, y=num, z=num}
381 // timeofday: nil = current time, 0 = night, 0.5 = day
382 int ModApiEnvMod::l_get_node_light(lua_State *L)
387 v3s16 pos = read_v3s16(L, 1);
388 u32 time_of_day = env->getTimeOfDay();
389 if(lua_isnumber(L, 2))
390 time_of_day = 24000.0 * lua_tonumber(L, 2);
391 time_of_day %= 24000;
392 u32 dnr = time_to_daynight_ratio(time_of_day, true);
395 MapNode n = env->getMap().getNodeNoEx(pos, &is_position_ok);
396 if (is_position_ok) {
397 const NodeDefManager *ndef = env->getGameDef()->ndef();
398 lua_pushinteger(L, n.getLightBlend(dnr, ndef));
405 // place_node(pos, node)
406 // pos = {x=num, y=num, z=num}
407 int ModApiEnvMod::l_place_node(lua_State *L)
411 ScriptApiItem *scriptIfaceItem = getScriptApi<ScriptApiItem>(L);
412 Server *server = getServer(L);
413 const NodeDefManager *ndef = server->ndef();
414 IItemDefManager *idef = server->idef();
416 v3s16 pos = read_v3s16(L, 1);
417 MapNode n = readnode(L, 2, ndef);
419 // Don't attempt to load non-loaded area as of now
420 MapNode n_old = env->getMap().getNodeNoEx(pos);
421 if(n_old.getContent() == CONTENT_IGNORE){
422 lua_pushboolean(L, false);
425 // Create item to place
426 ItemStack item(ndef->get(n).name, 1, 0, idef);
427 // Make pointed position
428 PointedThing pointed;
429 pointed.type = POINTEDTHING_NODE;
430 pointed.node_abovesurface = pos;
431 pointed.node_undersurface = pos + v3s16(0,-1,0);
432 // Place it with a NULL placer (appears in Lua as nil)
433 bool success = scriptIfaceItem->item_OnPlace(item, nullptr, pointed);
434 lua_pushboolean(L, success);
439 // pos = {x=num, y=num, z=num}
440 int ModApiEnvMod::l_dig_node(lua_State *L)
444 ScriptApiNode *scriptIfaceNode = getScriptApi<ScriptApiNode>(L);
446 v3s16 pos = read_v3s16(L, 1);
448 // Don't attempt to load non-loaded area as of now
449 MapNode n = env->getMap().getNodeNoEx(pos);
450 if(n.getContent() == CONTENT_IGNORE){
451 lua_pushboolean(L, false);
454 // Dig it out with a NULL digger (appears in Lua as a
455 // non-functional ObjectRef)
456 bool success = scriptIfaceNode->node_on_dig(pos, n, NULL);
457 lua_pushboolean(L, success);
462 // pos = {x=num, y=num, z=num}
463 int ModApiEnvMod::l_punch_node(lua_State *L)
467 ScriptApiNode *scriptIfaceNode = getScriptApi<ScriptApiNode>(L);
469 v3s16 pos = read_v3s16(L, 1);
471 // Don't attempt to load non-loaded area as of now
472 MapNode n = env->getMap().getNodeNoEx(pos);
473 if(n.getContent() == CONTENT_IGNORE){
474 lua_pushboolean(L, false);
477 // Punch it with a NULL puncher (appears in Lua as a non-functional
479 bool success = scriptIfaceNode->node_on_punch(pos, n, NULL, PointedThing());
480 lua_pushboolean(L, success);
484 // get_node_max_level(pos)
485 // pos = {x=num, y=num, z=num}
486 int ModApiEnvMod::l_get_node_max_level(lua_State *L)
488 Environment *env = getEnv(L);
493 v3s16 pos = read_v3s16(L, 1);
494 MapNode n = env->getMap().getNodeNoEx(pos);
495 lua_pushnumber(L, n.getMaxLevel(env->getGameDef()->ndef()));
499 // get_node_level(pos)
500 // pos = {x=num, y=num, z=num}
501 int ModApiEnvMod::l_get_node_level(lua_State *L)
503 Environment *env = getEnv(L);
508 v3s16 pos = read_v3s16(L, 1);
509 MapNode n = env->getMap().getNodeNoEx(pos);
510 lua_pushnumber(L, n.getLevel(env->getGameDef()->ndef()));
514 // set_node_level(pos, level)
515 // pos = {x=num, y=num, z=num}
517 int ModApiEnvMod::l_set_node_level(lua_State *L)
521 v3s16 pos = read_v3s16(L, 1);
523 if(lua_isnumber(L, 2))
524 level = lua_tonumber(L, 2);
525 MapNode n = env->getMap().getNodeNoEx(pos);
526 lua_pushnumber(L, n.setLevel(env->getGameDef()->ndef(), level));
527 env->setNode(pos, n);
531 // add_node_level(pos, level)
532 // pos = {x=num, y=num, z=num}
534 int ModApiEnvMod::l_add_node_level(lua_State *L)
538 v3s16 pos = read_v3s16(L, 1);
540 if(lua_isnumber(L, 2))
541 level = lua_tonumber(L, 2);
542 MapNode n = env->getMap().getNodeNoEx(pos);
543 lua_pushnumber(L, n.addLevel(env->getGameDef()->ndef(), level));
544 env->setNode(pos, n);
548 // find_nodes_with_meta(pos1, pos2)
549 int ModApiEnvMod::l_find_nodes_with_meta(lua_State *L)
553 std::vector<v3s16> positions = env->getMap().findNodesWithMetadata(
554 check_v3s16(L, 1), check_v3s16(L, 2));
557 for (size_t i = 0; i != positions.size(); i++) {
558 push_v3s16(L, positions[i]);
559 lua_rawseti(L, -2, i + 1);
566 int ModApiEnvMod::l_get_meta(lua_State *L)
571 v3s16 p = read_v3s16(L, 1);
572 NodeMetaRef::create(L, p, env);
576 // get_node_timer(pos)
577 int ModApiEnvMod::l_get_node_timer(lua_State *L)
582 v3s16 p = read_v3s16(L, 1);
583 NodeTimerRef::create(L, p, env);
587 // add_entity(pos, entityname, [staticdata]) -> ObjectRef or nil
588 // pos = {x=num, y=num, z=num}
589 int ModApiEnvMod::l_add_entity(lua_State *L)
594 v3f pos = checkFloatPos(L, 1);
596 const char *name = luaL_checkstring(L, 2);
598 const char *staticdata = luaL_optstring(L, 3, "");
600 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, staticdata);
601 int objectid = env->addActiveObject(obj);
602 // If failed to add, return nothing (reads as nil)
606 getScriptApiBase(L)->objectrefGetOrCreate(L, obj);
610 // add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
611 // pos = {x=num, y=num, z=num}
612 int ModApiEnvMod::l_add_item(lua_State *L)
617 //v3f pos = checkFloatPos(L, 1);
619 ItemStack item = read_item(L, 2,getServer(L)->idef());
620 if(item.empty() || !item.isKnown(getServer(L)->idef()))
623 int error_handler = PUSH_ERROR_HANDLER(L);
625 // Use spawn_item to spawn a __builtin:item
626 lua_getglobal(L, "core");
627 lua_getfield(L, -1, "spawn_item");
628 lua_remove(L, -2); // Remove core
632 lua_pushstring(L, item.getItemString().c_str());
634 PCALL_RESL(L, lua_pcall(L, 2, 1, error_handler));
636 lua_remove(L, error_handler);
640 // get_player_by_name(name)
641 int ModApiEnvMod::l_get_player_by_name(lua_State *L)
646 const char *name = luaL_checkstring(L, 1);
647 RemotePlayer *player = dynamic_cast<RemotePlayer *>(env->getPlayer(name));
652 PlayerSAO *sao = player->getPlayerSAO();
657 // Put player on stack
658 getScriptApiBase(L)->objectrefGetOrCreate(L, sao);
662 // get_objects_inside_radius(pos, radius)
663 int ModApiEnvMod::l_get_objects_inside_radius(lua_State *L)
668 v3f pos = checkFloatPos(L, 1);
669 float radius = luaL_checknumber(L, 2) * BS;
670 std::vector<u16> ids;
671 env->getObjectsInsideRadius(ids, pos, radius);
672 ScriptApiBase *script = getScriptApiBase(L);
673 lua_createtable(L, ids.size(), 0);
674 std::vector<u16>::const_iterator iter = ids.begin();
675 for(u32 i = 0; iter != ids.end(); ++iter) {
676 ServerActiveObject *obj = env->getActiveObject(*iter);
677 if (!obj->isGone()) {
678 // Insert object reference into table
679 script->objectrefGetOrCreate(L, obj);
680 lua_rawseti(L, -2, ++i);
686 // set_timeofday(val)
688 int ModApiEnvMod::l_set_timeofday(lua_State *L)
693 float timeofday_f = luaL_checknumber(L, 1);
694 sanity_check(timeofday_f >= 0.0 && timeofday_f <= 1.0);
695 int timeofday_mh = (int)(timeofday_f * 24000.0);
696 // This should be set directly in the environment but currently
697 // such changes aren't immediately sent to the clients, so call
698 // the server instead.
699 //env->setTimeOfDay(timeofday_mh);
700 getServer(L)->setTimeOfDay(timeofday_mh);
704 // get_timeofday() -> 0...1
705 int ModApiEnvMod::l_get_timeofday(lua_State *L)
707 Environment *env = getEnv(L);
713 int timeofday_mh = env->getTimeOfDay();
714 float timeofday_f = (float)timeofday_mh / 24000.0f;
715 lua_pushnumber(L, timeofday_f);
719 // get_day_count() -> int
720 int ModApiEnvMod::l_get_day_count(lua_State *L)
722 Environment *env = getEnv(L);
727 lua_pushnumber(L, env->getDayCount());
732 int ModApiEnvMod::l_get_gametime(lua_State *L)
736 int game_time = env->getGameTime();
737 lua_pushnumber(L, game_time);
742 // find_node_near(pos, radius, nodenames, search_center) -> pos or nil
743 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
744 int ModApiEnvMod::l_find_node_near(lua_State *L)
746 Environment *env = getEnv(L);
751 const NodeDefManager *ndef = getGameDef(L)->ndef();
752 v3s16 pos = read_v3s16(L, 1);
753 int radius = luaL_checkinteger(L, 2);
754 std::vector<content_t> filter;
755 if (lua_istable(L, 3)) {
757 while (lua_next(L, 3) != 0) {
758 // key at index -2 and value at index -1
759 luaL_checktype(L, -1, LUA_TSTRING);
760 ndef->getIds(lua_tostring(L, -1), filter);
761 // removes value, keeps key for next iteration
764 } else if (lua_isstring(L, 3)) {
765 ndef->getIds(lua_tostring(L, 3), filter);
768 int start_radius = (lua_toboolean(L, 4)) ? 0 : 1;
771 // Client API limitations
773 getClient(L)->checkCSMFlavourLimit(CSMFlavourLimit::CSM_FL_LOOKUP_NODES)) {
774 radius = std::max<int>(radius, getClient(L)->getCSMNodeRangeLimit());
778 for (int d = start_radius; d <= radius; d++) {
779 std::vector<v3s16> list = FacePositionCache::getFacePositions(d);
780 for (const v3s16 &i : list) {
782 content_t c = env->getMap().getNodeNoEx(p).getContent();
783 if (CONTAINS(filter, c)) {
792 // find_nodes_in_area(minp, maxp, nodenames) -> list of positions
793 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
794 int ModApiEnvMod::l_find_nodes_in_area(lua_State *L)
798 const NodeDefManager *ndef = getServer(L)->ndef();
799 v3s16 minp = read_v3s16(L, 1);
800 v3s16 maxp = read_v3s16(L, 2);
801 sortBoxVerticies(minp, maxp);
803 v3s16 cube = maxp - minp + 1;
805 /* Limit for too large areas, assume default values
806 * and give tolerances of 1 node on each side
807 * (chunksize * MAP_BLOCKSIZE + 2)^3 = 551368
809 if ((u64)cube.X * (u64)cube.Y * (u64)cube.Z > 551368) {
810 luaL_error(L, "find_nodes_in_area(): area volume"
811 " exceeds allowed value of 551368");
815 std::vector<content_t> filter;
816 if (lua_istable(L, 3)) {
818 while (lua_next(L, 3) != 0) {
819 // key at index -2 and value at index -1
820 luaL_checktype(L, -1, LUA_TSTRING);
821 ndef->getIds(lua_tostring(L, -1), filter);
822 // removes value, keeps key for next iteration
825 } else if (lua_isstring(L, 3)) {
826 ndef->getIds(lua_tostring(L, 3), filter);
829 std::vector<u32> individual_count;
830 individual_count.resize(filter.size());
834 for (s16 x = minp.X; x <= maxp.X; x++)
835 for (s16 y = minp.Y; y <= maxp.Y; y++)
836 for (s16 z = minp.Z; z <= maxp.Z; z++) {
838 content_t c = env->getMap().getNodeNoEx(p).getContent();
840 std::vector<content_t>::iterator it = std::find(filter.begin(), filter.end(), c);
841 if (it != filter.end()) {
843 lua_rawseti(L, -2, ++i);
845 u32 filt_index = it - filter.begin();
846 individual_count[filt_index]++;
850 for (u32 i = 0; i < filter.size(); i++) {
851 lua_pushnumber(L, individual_count[i]);
852 lua_setfield(L, -2, ndef->get(filter[i]).name.c_str());
857 // find_nodes_in_area_under_air(minp, maxp, nodenames) -> list of positions
858 // nodenames: e.g. {"ignore", "group:tree"} or "default:dirt"
859 int ModApiEnvMod::l_find_nodes_in_area_under_air(lua_State *L)
861 /* Note: A similar but generalized (and therefore slower) version of this
862 * function could be created -- e.g. find_nodes_in_area_under -- which
863 * would accept a node name (or ID?) or list of names that the "above node"
870 const NodeDefManager *ndef = getServer(L)->ndef();
871 v3s16 minp = read_v3s16(L, 1);
872 v3s16 maxp = read_v3s16(L, 2);
873 sortBoxVerticies(minp, maxp);
875 v3s16 cube = maxp - minp + 1;
877 /* Limit for too large areas, assume default values
878 * and give tolerances of 1 node on each side
879 * (chunksize * MAP_BLOCKSIZE + 2)^3 = 551368
881 if ((u64)cube.X * (u64)cube.Y * (u64)cube.Z > 551368) {
882 luaL_error(L, "find_nodes_in_area_under_air(): area volume"
883 " exceeds allowed value of 551368");
887 std::vector<content_t> filter;
889 if (lua_istable(L, 3)) {
891 while (lua_next(L, 3) != 0) {
892 // key at index -2 and value at index -1
893 luaL_checktype(L, -1, LUA_TSTRING);
894 ndef->getIds(lua_tostring(L, -1), filter);
895 // removes value, keeps key for next iteration
898 } else if (lua_isstring(L, 3)) {
899 ndef->getIds(lua_tostring(L, 3), filter);
904 for (s16 x = minp.X; x <= maxp.X; x++)
905 for (s16 z = minp.Z; z <= maxp.Z; z++) {
908 content_t c = env->getMap().getNodeNoEx(p).getContent();
909 for (; y <= maxp.Y; y++) {
910 v3s16 psurf(x, y + 1, z);
911 content_t csurf = env->getMap().getNodeNoEx(psurf).getContent();
912 if (c != CONTENT_AIR && csurf == CONTENT_AIR &&
913 CONTAINS(filter, c)) {
914 push_v3s16(L, v3s16(x, y, z));
915 lua_rawseti(L, -2, ++i);
923 // get_perlin(seeddiff, octaves, persistence, scale)
924 // returns world-specific PerlinNoise
925 int ModApiEnvMod::l_get_perlin(lua_State *L)
927 GET_ENV_PTR_NO_MAP_LOCK;
931 if (lua_istable(L, 1)) {
932 read_noiseparams(L, 1, ¶ms);
934 params.seed = luaL_checkint(L, 1);
935 params.octaves = luaL_checkint(L, 2);
936 params.persist = luaL_checknumber(L, 3);
937 params.spread = v3f(1, 1, 1) * luaL_checknumber(L, 4);
940 params.seed += (int)env->getServerMap().getSeed();
942 LuaPerlinNoise *n = new LuaPerlinNoise(¶ms);
943 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
944 luaL_getmetatable(L, "PerlinNoise");
945 lua_setmetatable(L, -2);
949 // get_perlin_map(noiseparams, size)
950 // returns world-specific PerlinNoiseMap
951 int ModApiEnvMod::l_get_perlin_map(lua_State *L)
953 GET_ENV_PTR_NO_MAP_LOCK;
956 if (!read_noiseparams(L, 1, &np))
958 v3s16 size = read_v3s16(L, 2);
960 s32 seed = (s32)(env->getServerMap().getSeed());
961 LuaPerlinNoiseMap *n = new LuaPerlinNoiseMap(&np, seed, size);
962 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
963 luaL_getmetatable(L, "PerlinNoiseMap");
964 lua_setmetatable(L, -2);
969 // returns voxel manipulator
970 int ModApiEnvMod::l_get_voxel_manip(lua_State *L)
974 Map *map = &(env->getMap());
975 LuaVoxelManip *o = (lua_istable(L, 1) && lua_istable(L, 2)) ?
976 new LuaVoxelManip(map, read_v3s16(L, 1), read_v3s16(L, 2)) :
977 new LuaVoxelManip(map);
979 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
980 luaL_getmetatable(L, "VoxelManip");
981 lua_setmetatable(L, -2);
985 // clear_objects([options])
986 // clear all objects in the environment
987 // where options = {mode = "full" or "quick"}
988 int ModApiEnvMod::l_clear_objects(lua_State *L)
992 ClearObjectsMode mode = CLEAR_OBJECTS_MODE_QUICK;
993 if (lua_istable(L, 1)) {
994 mode = (ClearObjectsMode)getenumfield(L, 1, "mode",
995 ModApiEnvMod::es_ClearObjectsMode, mode);
998 env->clearObjects(mode);
1002 // line_of_sight(pos1, pos2) -> true/false, pos
1003 int ModApiEnvMod::l_line_of_sight(lua_State *L)
1007 // read position 1 from lua
1008 v3f pos1 = checkFloatPos(L, 1);
1009 // read position 2 from lua
1010 v3f pos2 = checkFloatPos(L, 2);
1014 bool success = env->line_of_sight(pos1, pos2, &p);
1015 lua_pushboolean(L, success);
1023 // fix_light(p1, p2)
1024 int ModApiEnvMod::l_fix_light(lua_State *L)
1028 v3s16 blockpos1 = getContainerPos(read_v3s16(L, 1), MAP_BLOCKSIZE);
1029 v3s16 blockpos2 = getContainerPos(read_v3s16(L, 2), MAP_BLOCKSIZE);
1030 ServerMap &map = env->getServerMap();
1031 std::map<v3s16, MapBlock *> modified_blocks;
1032 bool success = true;
1034 for (blockpos.X = blockpos1.X; blockpos.X <= blockpos2.X; blockpos.X++)
1035 for (blockpos.Y = blockpos1.Y; blockpos.Y <= blockpos2.Y; blockpos.Y++)
1036 for (blockpos.Z = blockpos1.Z; blockpos.Z <= blockpos2.Z; blockpos.Z++) {
1037 success = success & map.repairBlockLight(blockpos, &modified_blocks);
1039 if (!modified_blocks.empty()) {
1041 event.type = MEET_OTHER;
1042 for (auto &modified_block : modified_blocks)
1043 event.modified_blocks.insert(modified_block.first);
1045 map.dispatchEvent(&event);
1047 lua_pushboolean(L, success);
1052 int ModApiEnvMod::l_raycast(lua_State *L)
1054 return LuaRaycast::create_object(L);
1057 // emerge_area(p1, p2, [callback, context])
1058 // emerge mapblocks in area p1..p2, calls callback with context upon completion
1059 int ModApiEnvMod::l_emerge_area(lua_State *L)
1063 EmergeCompletionCallback callback = NULL;
1064 ScriptCallbackState *state = NULL;
1066 EmergeManager *emerge = getServer(L)->getEmergeManager();
1068 v3s16 bpmin = getNodeBlockPos(read_v3s16(L, 1));
1069 v3s16 bpmax = getNodeBlockPos(read_v3s16(L, 2));
1070 sortBoxVerticies(bpmin, bpmax);
1072 size_t num_blocks = VoxelArea(bpmin, bpmax).getVolume();
1073 assert(num_blocks != 0);
1075 if (lua_isfunction(L, 3)) {
1076 callback = LuaEmergeAreaCallback;
1078 lua_pushvalue(L, 3);
1079 int callback_ref = luaL_ref(L, LUA_REGISTRYINDEX);
1081 lua_pushvalue(L, 4);
1082 int args_ref = luaL_ref(L, LUA_REGISTRYINDEX);
1084 state = new ScriptCallbackState;
1085 state->script = getServer(L)->getScriptIface();
1086 state->callback_ref = callback_ref;
1087 state->args_ref = args_ref;
1088 state->refcount = num_blocks;
1089 state->origin = getScriptApiBase(L)->getOrigin();
1092 for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
1093 for (s16 y = bpmin.Y; y <= bpmax.Y; y++)
1094 for (s16 x = bpmin.X; x <= bpmax.X; x++) {
1095 emerge->enqueueBlockEmergeEx(v3s16(x, y, z), PEER_ID_INEXISTENT,
1096 BLOCK_EMERGE_ALLOW_GEN | BLOCK_EMERGE_FORCE_QUEUE, callback, state);
1102 // delete_area(p1, p2)
1103 // delete mapblocks in area p1..p2
1104 int ModApiEnvMod::l_delete_area(lua_State *L)
1108 v3s16 bpmin = getNodeBlockPos(read_v3s16(L, 1));
1109 v3s16 bpmax = getNodeBlockPos(read_v3s16(L, 2));
1110 sortBoxVerticies(bpmin, bpmax);
1112 ServerMap &map = env->getServerMap();
1115 event.type = MEET_OTHER;
1117 bool success = true;
1118 for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
1119 for (s16 y = bpmin.Y; y <= bpmax.Y; y++)
1120 for (s16 x = bpmin.X; x <= bpmax.X; x++) {
1122 if (map.deleteBlock(bp)) {
1123 env->setStaticForActiveObjectsInBlock(bp, false);
1124 event.modified_blocks.insert(bp);
1130 map.dispatchEvent(&event);
1131 lua_pushboolean(L, success);
1135 // find_path(pos1, pos2, searchdistance,
1136 // max_jump, max_drop, algorithm) -> table containing path
1137 int ModApiEnvMod::l_find_path(lua_State *L)
1141 v3s16 pos1 = read_v3s16(L, 1);
1142 v3s16 pos2 = read_v3s16(L, 2);
1143 unsigned int searchdistance = luaL_checkint(L, 3);
1144 unsigned int max_jump = luaL_checkint(L, 4);
1145 unsigned int max_drop = luaL_checkint(L, 5);
1146 PathAlgorithm algo = PA_PLAIN_NP;
1147 if (!lua_isnil(L, 6)) {
1148 std::string algorithm = luaL_checkstring(L,6);
1150 if (algorithm == "A*")
1153 if (algorithm == "Dijkstra")
1157 std::vector<v3s16> path = get_path(env, pos1, pos2,
1158 searchdistance, max_jump, max_drop, algo);
1160 if (!path.empty()) {
1162 int top = lua_gettop(L);
1163 unsigned int index = 1;
1164 for (const v3s16 &i : path) {
1165 lua_pushnumber(L,index);
1167 lua_settable(L, top);
1176 // spawn_tree(pos, treedef)
1177 int ModApiEnvMod::l_spawn_tree(lua_State *L)
1181 v3s16 p0 = read_v3s16(L, 1);
1183 treegen::TreeDef tree_def;
1184 std::string trunk,leaves,fruit;
1185 const NodeDefManager *ndef = env->getGameDef()->ndef();
1187 if(lua_istable(L, 2))
1189 getstringfield(L, 2, "axiom", tree_def.initial_axiom);
1190 getstringfield(L, 2, "rules_a", tree_def.rules_a);
1191 getstringfield(L, 2, "rules_b", tree_def.rules_b);
1192 getstringfield(L, 2, "rules_c", tree_def.rules_c);
1193 getstringfield(L, 2, "rules_d", tree_def.rules_d);
1194 getstringfield(L, 2, "trunk", trunk);
1195 tree_def.trunknode=ndef->getId(trunk);
1196 getstringfield(L, 2, "leaves", leaves);
1197 tree_def.leavesnode=ndef->getId(leaves);
1198 tree_def.leaves2_chance=0;
1199 getstringfield(L, 2, "leaves2", leaves);
1200 if (!leaves.empty()) {
1201 tree_def.leaves2node=ndef->getId(leaves);
1202 getintfield(L, 2, "leaves2_chance", tree_def.leaves2_chance);
1204 getintfield(L, 2, "angle", tree_def.angle);
1205 getintfield(L, 2, "iterations", tree_def.iterations);
1206 if (!getintfield(L, 2, "random_level", tree_def.iterations_random_level))
1207 tree_def.iterations_random_level = 0;
1208 getstringfield(L, 2, "trunk_type", tree_def.trunk_type);
1209 getboolfield(L, 2, "thin_branches", tree_def.thin_branches);
1210 tree_def.fruit_chance=0;
1211 getstringfield(L, 2, "fruit", fruit);
1212 if (!fruit.empty()) {
1213 tree_def.fruitnode=ndef->getId(fruit);
1214 getintfield(L, 2, "fruit_chance",tree_def.fruit_chance);
1216 tree_def.explicit_seed = getintfield(L, 2, "seed", tree_def.seed);
1222 if ((e = treegen::spawn_ltree (env, p0, ndef, tree_def)) != treegen::SUCCESS) {
1223 if (e == treegen::UNBALANCED_BRACKETS) {
1224 luaL_error(L, "spawn_tree(): closing ']' has no matching opening bracket");
1226 luaL_error(L, "spawn_tree(): unknown error");
1233 // transforming_liquid_add(pos)
1234 int ModApiEnvMod::l_transforming_liquid_add(lua_State *L)
1238 v3s16 p0 = read_v3s16(L, 1);
1239 env->getMap().transforming_liquid_add(p0);
1243 // forceload_block(blockpos)
1244 // blockpos = {x=num, y=num, z=num}
1245 int ModApiEnvMod::l_forceload_block(lua_State *L)
1249 v3s16 blockpos = read_v3s16(L, 1);
1250 env->getForceloadedBlocks()->insert(blockpos);
1254 // forceload_free_block(blockpos)
1255 // blockpos = {x=num, y=num, z=num}
1256 int ModApiEnvMod::l_forceload_free_block(lua_State *L)
1260 v3s16 blockpos = read_v3s16(L, 1);
1261 env->getForceloadedBlocks()->erase(blockpos);
1265 void ModApiEnvMod::Initialize(lua_State *L, int top)
1268 API_FCT(bulk_set_node);
1272 API_FCT(remove_node);
1274 API_FCT(get_node_or_nil);
1275 API_FCT(get_node_light);
1276 API_FCT(place_node);
1278 API_FCT(punch_node);
1279 API_FCT(get_node_max_level);
1280 API_FCT(get_node_level);
1281 API_FCT(set_node_level);
1282 API_FCT(add_node_level);
1283 API_FCT(add_entity);
1284 API_FCT(find_nodes_with_meta);
1286 API_FCT(get_node_timer);
1287 API_FCT(get_player_by_name);
1288 API_FCT(get_objects_inside_radius);
1289 API_FCT(set_timeofday);
1290 API_FCT(get_timeofday);
1291 API_FCT(get_gametime);
1292 API_FCT(get_day_count);
1293 API_FCT(find_node_near);
1294 API_FCT(find_nodes_in_area);
1295 API_FCT(find_nodes_in_area_under_air);
1297 API_FCT(emerge_area);
1298 API_FCT(delete_area);
1299 API_FCT(get_perlin);
1300 API_FCT(get_perlin_map);
1301 API_FCT(get_voxel_manip);
1302 API_FCT(clear_objects);
1303 API_FCT(spawn_tree);
1305 API_FCT(line_of_sight);
1307 API_FCT(transforming_liquid_add);
1308 API_FCT(forceload_block);
1309 API_FCT(forceload_free_block);
1312 void ModApiEnvMod::InitializeClient(lua_State *L, int top)
1314 API_FCT(get_timeofday);
1315 API_FCT(get_day_count);
1316 API_FCT(get_node_max_level);
1317 API_FCT(get_node_level);
1318 API_FCT(find_node_near);