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"
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 INodeDefManager *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 int ModApiEnvMod::l_add_node(lua_State *L)
278 return l_set_node(L);
282 // pos = {x=num, y=num, z=num}
283 int ModApiEnvMod::l_remove_node(lua_State *L)
288 v3s16 pos = read_v3s16(L, 1);
290 bool succeeded = env->removeNode(pos);
291 lua_pushboolean(L, succeeded);
295 // swap_node(pos, node)
296 // pos = {x=num, y=num, z=num}
297 int ModApiEnvMod::l_swap_node(lua_State *L)
301 INodeDefManager *ndef = env->getGameDef()->ndef();
303 v3s16 pos = read_v3s16(L, 1);
304 MapNode n = readnode(L, 2, ndef);
306 bool succeeded = env->swapNode(pos, n);
307 lua_pushboolean(L, succeeded);
312 // pos = {x=num, y=num, z=num}
313 int ModApiEnvMod::l_get_node(lua_State *L)
318 v3s16 pos = read_v3s16(L, 1);
320 MapNode n = env->getMap().getNodeNoEx(pos);
322 pushnode(L, n, env->getGameDef()->ndef());
326 // get_node_or_nil(pos)
327 // pos = {x=num, y=num, z=num}
328 int ModApiEnvMod::l_get_node_or_nil(lua_State *L)
333 v3s16 pos = read_v3s16(L, 1);
336 MapNode n = env->getMap().getNodeNoEx(pos, &pos_ok);
339 pushnode(L, n, env->getGameDef()->ndef());
346 // get_node_light(pos, timeofday)
347 // pos = {x=num, y=num, z=num}
348 // timeofday: nil = current time, 0 = night, 0.5 = day
349 int ModApiEnvMod::l_get_node_light(lua_State *L)
354 v3s16 pos = read_v3s16(L, 1);
355 u32 time_of_day = env->getTimeOfDay();
356 if(lua_isnumber(L, 2))
357 time_of_day = 24000.0 * lua_tonumber(L, 2);
358 time_of_day %= 24000;
359 u32 dnr = time_to_daynight_ratio(time_of_day, true);
362 MapNode n = env->getMap().getNodeNoEx(pos, &is_position_ok);
363 if (is_position_ok) {
364 INodeDefManager *ndef = env->getGameDef()->ndef();
365 lua_pushinteger(L, n.getLightBlend(dnr, ndef));
372 // place_node(pos, node)
373 // pos = {x=num, y=num, z=num}
374 int ModApiEnvMod::l_place_node(lua_State *L)
378 ScriptApiItem *scriptIfaceItem = getScriptApi<ScriptApiItem>(L);
379 Server *server = getServer(L);
380 INodeDefManager *ndef = server->ndef();
381 IItemDefManager *idef = server->idef();
383 v3s16 pos = read_v3s16(L, 1);
384 MapNode n = readnode(L, 2, ndef);
386 // Don't attempt to load non-loaded area as of now
387 MapNode n_old = env->getMap().getNodeNoEx(pos);
388 if(n_old.getContent() == CONTENT_IGNORE){
389 lua_pushboolean(L, false);
392 // Create item to place
393 ItemStack item(ndef->get(n).name, 1, 0, idef);
394 // Make pointed position
395 PointedThing pointed;
396 pointed.type = POINTEDTHING_NODE;
397 pointed.node_abovesurface = pos;
398 pointed.node_undersurface = pos + v3s16(0,-1,0);
399 // Place it with a NULL placer (appears in Lua as a non-functional
401 bool success = scriptIfaceItem->item_OnPlace(item, NULL, pointed);
402 lua_pushboolean(L, success);
407 // pos = {x=num, y=num, z=num}
408 int ModApiEnvMod::l_dig_node(lua_State *L)
412 ScriptApiNode *scriptIfaceNode = getScriptApi<ScriptApiNode>(L);
414 v3s16 pos = read_v3s16(L, 1);
416 // Don't attempt to load non-loaded area as of now
417 MapNode n = env->getMap().getNodeNoEx(pos);
418 if(n.getContent() == CONTENT_IGNORE){
419 lua_pushboolean(L, false);
422 // Dig it out with a NULL digger (appears in Lua as a
423 // non-functional ObjectRef)
424 bool success = scriptIfaceNode->node_on_dig(pos, n, NULL);
425 lua_pushboolean(L, success);
430 // pos = {x=num, y=num, z=num}
431 int ModApiEnvMod::l_punch_node(lua_State *L)
435 ScriptApiNode *scriptIfaceNode = getScriptApi<ScriptApiNode>(L);
437 v3s16 pos = read_v3s16(L, 1);
439 // Don't attempt to load non-loaded area as of now
440 MapNode n = env->getMap().getNodeNoEx(pos);
441 if(n.getContent() == CONTENT_IGNORE){
442 lua_pushboolean(L, false);
445 // Punch it with a NULL puncher (appears in Lua as a non-functional
447 bool success = scriptIfaceNode->node_on_punch(pos, n, NULL, PointedThing());
448 lua_pushboolean(L, success);
452 // get_node_max_level(pos)
453 // pos = {x=num, y=num, z=num}
454 int ModApiEnvMod::l_get_node_max_level(lua_State *L)
456 Environment *env = getEnv(L);
461 v3s16 pos = read_v3s16(L, 1);
462 MapNode n = env->getMap().getNodeNoEx(pos);
463 lua_pushnumber(L, n.getMaxLevel(env->getGameDef()->ndef()));
467 // get_node_level(pos)
468 // pos = {x=num, y=num, z=num}
469 int ModApiEnvMod::l_get_node_level(lua_State *L)
471 Environment *env = getEnv(L);
476 v3s16 pos = read_v3s16(L, 1);
477 MapNode n = env->getMap().getNodeNoEx(pos);
478 lua_pushnumber(L, n.getLevel(env->getGameDef()->ndef()));
482 // set_node_level(pos, level)
483 // pos = {x=num, y=num, z=num}
485 int ModApiEnvMod::l_set_node_level(lua_State *L)
489 v3s16 pos = read_v3s16(L, 1);
491 if(lua_isnumber(L, 2))
492 level = lua_tonumber(L, 2);
493 MapNode n = env->getMap().getNodeNoEx(pos);
494 lua_pushnumber(L, n.setLevel(env->getGameDef()->ndef(), level));
495 env->setNode(pos, n);
499 // add_node_level(pos, level)
500 // pos = {x=num, y=num, z=num}
502 int ModApiEnvMod::l_add_node_level(lua_State *L)
506 v3s16 pos = read_v3s16(L, 1);
508 if(lua_isnumber(L, 2))
509 level = lua_tonumber(L, 2);
510 MapNode n = env->getMap().getNodeNoEx(pos);
511 lua_pushnumber(L, n.addLevel(env->getGameDef()->ndef(), level));
512 env->setNode(pos, n);
516 // find_nodes_with_meta(pos1, pos2)
517 int ModApiEnvMod::l_find_nodes_with_meta(lua_State *L)
521 std::vector<v3s16> positions = env->getMap().findNodesWithMetadata(
522 check_v3s16(L, 1), check_v3s16(L, 2));
525 for (size_t i = 0; i != positions.size(); i++) {
526 push_v3s16(L, positions[i]);
527 lua_rawseti(L, -2, i + 1);
534 int ModApiEnvMod::l_get_meta(lua_State *L)
539 v3s16 p = read_v3s16(L, 1);
540 NodeMetaRef::create(L, p, env);
544 // get_node_timer(pos)
545 int ModApiEnvMod::l_get_node_timer(lua_State *L)
550 v3s16 p = read_v3s16(L, 1);
551 NodeTimerRef::create(L, p, env);
555 // add_entity(pos, entityname, [staticdata]) -> ObjectRef or nil
556 // pos = {x=num, y=num, z=num}
557 int ModApiEnvMod::l_add_entity(lua_State *L)
562 v3f pos = checkFloatPos(L, 1);
564 const char *name = luaL_checkstring(L, 2);
566 const char *staticdata = luaL_optstring(L, 3, "");
568 ServerActiveObject *obj = new LuaEntitySAO(env, pos, name, staticdata);
569 int objectid = env->addActiveObject(obj);
570 // If failed to add, return nothing (reads as nil)
574 getScriptApiBase(L)->objectrefGetOrCreate(L, obj);
578 // add_item(pos, itemstack or itemstring or table) -> ObjectRef or nil
579 // pos = {x=num, y=num, z=num}
580 int ModApiEnvMod::l_add_item(lua_State *L)
585 //v3f pos = checkFloatPos(L, 1);
587 ItemStack item = read_item(L, 2,getServer(L)->idef());
588 if(item.empty() || !item.isKnown(getServer(L)->idef()))
591 int error_handler = PUSH_ERROR_HANDLER(L);
593 // Use spawn_item to spawn a __builtin:item
594 lua_getglobal(L, "core");
595 lua_getfield(L, -1, "spawn_item");
596 lua_remove(L, -2); // Remove core
600 lua_pushstring(L, item.getItemString().c_str());
602 PCALL_RESL(L, lua_pcall(L, 2, 1, error_handler));
604 lua_remove(L, error_handler);
608 // get_player_by_name(name)
609 int ModApiEnvMod::l_get_player_by_name(lua_State *L)
614 const char *name = luaL_checkstring(L, 1);
615 RemotePlayer *player = dynamic_cast<RemotePlayer *>(env->getPlayer(name));
620 PlayerSAO *sao = player->getPlayerSAO();
625 // Put player on stack
626 getScriptApiBase(L)->objectrefGetOrCreate(L, sao);
630 // get_objects_inside_radius(pos, radius)
631 int ModApiEnvMod::l_get_objects_inside_radius(lua_State *L)
636 v3f pos = checkFloatPos(L, 1);
637 float radius = luaL_checknumber(L, 2) * BS;
638 std::vector<u16> ids;
639 env->getObjectsInsideRadius(ids, pos, radius);
640 ScriptApiBase *script = getScriptApiBase(L);
641 lua_createtable(L, ids.size(), 0);
642 std::vector<u16>::const_iterator iter = ids.begin();
643 for(u32 i = 0; iter != ids.end(); ++iter) {
644 ServerActiveObject *obj = env->getActiveObject(*iter);
645 // Insert object reference into table
646 script->objectrefGetOrCreate(L, obj);
647 lua_rawseti(L, -2, ++i);
652 // set_timeofday(val)
654 int ModApiEnvMod::l_set_timeofday(lua_State *L)
659 float timeofday_f = luaL_checknumber(L, 1);
660 sanity_check(timeofday_f >= 0.0 && timeofday_f <= 1.0);
661 int timeofday_mh = (int)(timeofday_f * 24000.0);
662 // This should be set directly in the environment but currently
663 // such changes aren't immediately sent to the clients, so call
664 // the server instead.
665 //env->setTimeOfDay(timeofday_mh);
666 getServer(L)->setTimeOfDay(timeofday_mh);
670 // get_timeofday() -> 0...1
671 int ModApiEnvMod::l_get_timeofday(lua_State *L)
673 Environment *env = getEnv(L);
679 int timeofday_mh = env->getTimeOfDay();
680 float timeofday_f = (float)timeofday_mh / 24000.0f;
681 lua_pushnumber(L, timeofday_f);
685 // get_day_count() -> int
686 int ModApiEnvMod::l_get_day_count(lua_State *L)
688 Environment *env = getEnv(L);
693 lua_pushnumber(L, env->getDayCount());
698 int ModApiEnvMod::l_get_gametime(lua_State *L)
702 int game_time = env->getGameTime();
703 lua_pushnumber(L, game_time);
708 // find_node_near(pos, radius, nodenames, search_center) -> pos or nil
709 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
710 int ModApiEnvMod::l_find_node_near(lua_State *L)
712 Environment *env = getEnv(L);
717 INodeDefManager *ndef = getGameDef(L)->ndef();
718 v3s16 pos = read_v3s16(L, 1);
719 int radius = luaL_checkinteger(L, 2);
720 std::set<content_t> filter;
721 if (lua_istable(L, 3)) {
723 while (lua_next(L, 3) != 0) {
724 // key at index -2 and value at index -1
725 luaL_checktype(L, -1, LUA_TSTRING);
726 ndef->getIds(lua_tostring(L, -1), filter);
727 // removes value, keeps key for next iteration
730 } else if (lua_isstring(L, 3)) {
731 ndef->getIds(lua_tostring(L, 3), filter);
734 int start_radius = (lua_toboolean(L, 4)) ? 0 : 1;
737 // Client API limitations
739 getClient(L)->checkCSMFlavourLimit(CSMFlavourLimit::CSM_FL_LOOKUP_NODES)) {
740 radius = std::max<int>(radius, getClient(L)->getCSMNodeRangeLimit());
744 for (int d = start_radius; d <= radius; d++) {
745 std::vector<v3s16> list = FacePositionCache::getFacePositions(d);
746 for (const v3s16 &i : list) {
748 content_t c = env->getMap().getNodeNoEx(p).getContent();
749 if (filter.count(c) != 0) {
758 // find_nodes_in_area(minp, maxp, nodenames) -> list of positions
759 // nodenames: eg. {"ignore", "group:tree"} or "default:dirt"
760 int ModApiEnvMod::l_find_nodes_in_area(lua_State *L)
764 INodeDefManager *ndef = getServer(L)->ndef();
765 v3s16 minp = read_v3s16(L, 1);
766 v3s16 maxp = read_v3s16(L, 2);
767 sortBoxVerticies(minp, maxp);
769 v3s16 cube = maxp - minp + 1;
771 /* Limit for too large areas, assume default values
772 * and give tolerances of 1 node on each side
773 * (chunksize * MAP_BLOCKSIZE + 2)^3 = 551368
775 if ((u64)cube.X * (u64)cube.Y * (u64)cube.Z > 551368) {
776 luaL_error(L, "find_nodes_in_area(): area volume"
777 " exceeds allowed value of 551368");
781 std::set<content_t> filter;
782 if (lua_istable(L, 3)) {
784 while (lua_next(L, 3) != 0) {
785 // key at index -2 and value at index -1
786 luaL_checktype(L, -1, LUA_TSTRING);
787 ndef->getIds(lua_tostring(L, -1), filter);
788 // removes value, keeps key for next iteration
791 } else if (lua_isstring(L, 3)) {
792 ndef->getIds(lua_tostring(L, 3), filter);
795 std::unordered_map<content_t, u32> individual_count;
799 for (s16 x = minp.X; x <= maxp.X; x++)
800 for (s16 y = minp.Y; y <= maxp.Y; y++)
801 for (s16 z = minp.Z; z <= maxp.Z; z++) {
803 content_t c = env->getMap().getNodeNoEx(p).getContent();
804 if (filter.count(c) != 0) {
806 lua_rawseti(L, -2, ++i);
807 individual_count[c]++;
811 for (content_t it : filter) {
812 lua_pushnumber(L, individual_count[it]);
813 lua_setfield(L, -2, ndef->get(it).name.c_str());
818 // find_nodes_in_area_under_air(minp, maxp, nodenames) -> list of positions
819 // nodenames: e.g. {"ignore", "group:tree"} or "default:dirt"
820 int ModApiEnvMod::l_find_nodes_in_area_under_air(lua_State *L)
822 /* Note: A similar but generalized (and therefore slower) version of this
823 * function could be created -- e.g. find_nodes_in_area_under -- which
824 * would accept a node name (or ID?) or list of names that the "above node"
831 INodeDefManager *ndef = getServer(L)->ndef();
832 v3s16 minp = read_v3s16(L, 1);
833 v3s16 maxp = read_v3s16(L, 2);
834 sortBoxVerticies(minp, maxp);
836 v3s16 cube = maxp - minp + 1;
838 /* Limit for too large areas, assume default values
839 * and give tolerances of 1 node on each side
840 * (chunksize * MAP_BLOCKSIZE + 2)^3 = 551368
842 if ((u64)cube.X * (u64)cube.Y * (u64)cube.Z > 551368) {
843 luaL_error(L, "find_nodes_in_area_under_air(): area volume"
844 " exceeds allowed value of 551368");
848 std::set<content_t> filter;
850 if (lua_istable(L, 3)) {
852 while (lua_next(L, 3) != 0) {
853 // key at index -2 and value at index -1
854 luaL_checktype(L, -1, LUA_TSTRING);
855 ndef->getIds(lua_tostring(L, -1), filter);
856 // removes value, keeps key for next iteration
859 } else if (lua_isstring(L, 3)) {
860 ndef->getIds(lua_tostring(L, 3), filter);
865 for (s16 x = minp.X; x <= maxp.X; x++)
866 for (s16 z = minp.Z; z <= maxp.Z; z++) {
869 content_t c = env->getMap().getNodeNoEx(p).getContent();
870 for (; y <= maxp.Y; y++) {
871 v3s16 psurf(x, y + 1, z);
872 content_t csurf = env->getMap().getNodeNoEx(psurf).getContent();
873 if (c != CONTENT_AIR && csurf == CONTENT_AIR &&
874 filter.count(c) != 0) {
875 push_v3s16(L, v3s16(x, y, z));
876 lua_rawseti(L, -2, ++i);
884 // get_perlin(seeddiff, octaves, persistence, scale)
885 // returns world-specific PerlinNoise
886 int ModApiEnvMod::l_get_perlin(lua_State *L)
888 GET_ENV_PTR_NO_MAP_LOCK;
892 if (lua_istable(L, 1)) {
893 read_noiseparams(L, 1, ¶ms);
895 params.seed = luaL_checkint(L, 1);
896 params.octaves = luaL_checkint(L, 2);
897 params.persist = luaL_checknumber(L, 3);
898 params.spread = v3f(1, 1, 1) * luaL_checknumber(L, 4);
901 params.seed += (int)env->getServerMap().getSeed();
903 LuaPerlinNoise *n = new LuaPerlinNoise(¶ms);
904 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
905 luaL_getmetatable(L, "PerlinNoise");
906 lua_setmetatable(L, -2);
910 // get_perlin_map(noiseparams, size)
911 // returns world-specific PerlinNoiseMap
912 int ModApiEnvMod::l_get_perlin_map(lua_State *L)
914 GET_ENV_PTR_NO_MAP_LOCK;
917 if (!read_noiseparams(L, 1, &np))
919 v3s16 size = read_v3s16(L, 2);
921 s32 seed = (s32)(env->getServerMap().getSeed());
922 LuaPerlinNoiseMap *n = new LuaPerlinNoiseMap(&np, seed, size);
923 *(void **)(lua_newuserdata(L, sizeof(void *))) = n;
924 luaL_getmetatable(L, "PerlinNoiseMap");
925 lua_setmetatable(L, -2);
930 // returns voxel manipulator
931 int ModApiEnvMod::l_get_voxel_manip(lua_State *L)
935 Map *map = &(env->getMap());
936 LuaVoxelManip *o = (lua_istable(L, 1) && lua_istable(L, 2)) ?
937 new LuaVoxelManip(map, read_v3s16(L, 1), read_v3s16(L, 2)) :
938 new LuaVoxelManip(map);
940 *(void **)(lua_newuserdata(L, sizeof(void *))) = o;
941 luaL_getmetatable(L, "VoxelManip");
942 lua_setmetatable(L, -2);
946 // clear_objects([options])
947 // clear all objects in the environment
948 // where options = {mode = "full" or "quick"}
949 int ModApiEnvMod::l_clear_objects(lua_State *L)
953 ClearObjectsMode mode = CLEAR_OBJECTS_MODE_FULL;
954 if (lua_istable(L, 1)) {
955 mode = (ClearObjectsMode)getenumfield(L, 1, "mode",
956 ModApiEnvMod::es_ClearObjectsMode, mode);
959 env->clearObjects(mode);
963 // line_of_sight(pos1, pos2, stepsize) -> true/false, pos
964 int ModApiEnvMod::l_line_of_sight(lua_State *L)
966 float stepsize = 1.0;
970 // read position 1 from lua
971 v3f pos1 = checkFloatPos(L, 1);
972 // read position 2 from lua
973 v3f pos2 = checkFloatPos(L, 2);
974 //read step size from lua
975 if (lua_isnumber(L, 3)) {
976 stepsize = lua_tonumber(L, 3);
980 bool success = env->line_of_sight(pos1, pos2, stepsize, &p);
981 lua_pushboolean(L, success);
990 int ModApiEnvMod::l_fix_light(lua_State *L)
994 v3s16 blockpos1 = getContainerPos(read_v3s16(L, 1), MAP_BLOCKSIZE);
995 v3s16 blockpos2 = getContainerPos(read_v3s16(L, 2), MAP_BLOCKSIZE);
996 ServerMap &map = env->getServerMap();
997 std::map<v3s16, MapBlock *> modified_blocks;
1000 for (blockpos.X = blockpos1.X; blockpos.X <= blockpos2.X; blockpos.X++)
1001 for (blockpos.Y = blockpos1.Y; blockpos.Y <= blockpos2.Y; blockpos.Y++)
1002 for (blockpos.Z = blockpos1.Z; blockpos.Z <= blockpos2.Z; blockpos.Z++) {
1003 success = success & map.repairBlockLight(blockpos, &modified_blocks);
1005 if (!modified_blocks.empty()) {
1007 event.type = MEET_OTHER;
1008 for (auto &modified_block : modified_blocks)
1009 event.modified_blocks.insert(modified_block.first);
1011 map.dispatchEvent(&event);
1013 lua_pushboolean(L, success);
1018 int ModApiEnvMod::l_raycast(lua_State *L)
1020 return LuaRaycast::create_object(L);
1023 // emerge_area(p1, p2, [callback, context])
1024 // emerge mapblocks in area p1..p2, calls callback with context upon completion
1025 int ModApiEnvMod::l_emerge_area(lua_State *L)
1029 EmergeCompletionCallback callback = NULL;
1030 ScriptCallbackState *state = NULL;
1032 EmergeManager *emerge = getServer(L)->getEmergeManager();
1034 v3s16 bpmin = getNodeBlockPos(read_v3s16(L, 1));
1035 v3s16 bpmax = getNodeBlockPos(read_v3s16(L, 2));
1036 sortBoxVerticies(bpmin, bpmax);
1038 size_t num_blocks = VoxelArea(bpmin, bpmax).getVolume();
1039 assert(num_blocks != 0);
1041 if (lua_isfunction(L, 3)) {
1042 callback = LuaEmergeAreaCallback;
1044 lua_pushvalue(L, 3);
1045 int callback_ref = luaL_ref(L, LUA_REGISTRYINDEX);
1047 lua_pushvalue(L, 4);
1048 int args_ref = luaL_ref(L, LUA_REGISTRYINDEX);
1050 state = new ScriptCallbackState;
1051 state->script = getServer(L)->getScriptIface();
1052 state->callback_ref = callback_ref;
1053 state->args_ref = args_ref;
1054 state->refcount = num_blocks;
1055 state->origin = getScriptApiBase(L)->getOrigin();
1058 for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
1059 for (s16 y = bpmin.Y; y <= bpmax.Y; y++)
1060 for (s16 x = bpmin.X; x <= bpmax.X; x++) {
1061 emerge->enqueueBlockEmergeEx(v3s16(x, y, z), PEER_ID_INEXISTENT,
1062 BLOCK_EMERGE_ALLOW_GEN | BLOCK_EMERGE_FORCE_QUEUE, callback, state);
1068 // delete_area(p1, p2)
1069 // delete mapblocks in area p1..p2
1070 int ModApiEnvMod::l_delete_area(lua_State *L)
1074 v3s16 bpmin = getNodeBlockPos(read_v3s16(L, 1));
1075 v3s16 bpmax = getNodeBlockPos(read_v3s16(L, 2));
1076 sortBoxVerticies(bpmin, bpmax);
1078 ServerMap &map = env->getServerMap();
1081 event.type = MEET_OTHER;
1083 bool success = true;
1084 for (s16 z = bpmin.Z; z <= bpmax.Z; z++)
1085 for (s16 y = bpmin.Y; y <= bpmax.Y; y++)
1086 for (s16 x = bpmin.X; x <= bpmax.X; x++) {
1088 if (map.deleteBlock(bp)) {
1089 env->setStaticForActiveObjectsInBlock(bp, false);
1090 event.modified_blocks.insert(bp);
1096 map.dispatchEvent(&event);
1097 lua_pushboolean(L, success);
1101 // find_path(pos1, pos2, searchdistance,
1102 // max_jump, max_drop, algorithm) -> table containing path
1103 int ModApiEnvMod::l_find_path(lua_State *L)
1107 v3s16 pos1 = read_v3s16(L, 1);
1108 v3s16 pos2 = read_v3s16(L, 2);
1109 unsigned int searchdistance = luaL_checkint(L, 3);
1110 unsigned int max_jump = luaL_checkint(L, 4);
1111 unsigned int max_drop = luaL_checkint(L, 5);
1112 PathAlgorithm algo = PA_PLAIN_NP;
1113 if (!lua_isnil(L, 6)) {
1114 std::string algorithm = luaL_checkstring(L,6);
1116 if (algorithm == "A*")
1119 if (algorithm == "Dijkstra")
1123 std::vector<v3s16> path = get_path(env, pos1, pos2,
1124 searchdistance, max_jump, max_drop, algo);
1126 if (!path.empty()) {
1128 int top = lua_gettop(L);
1129 unsigned int index = 1;
1130 for (const v3s16 &i : path) {
1131 lua_pushnumber(L,index);
1133 lua_settable(L, top);
1142 // spawn_tree(pos, treedef)
1143 int ModApiEnvMod::l_spawn_tree(lua_State *L)
1147 v3s16 p0 = read_v3s16(L, 1);
1149 treegen::TreeDef tree_def;
1150 std::string trunk,leaves,fruit;
1151 INodeDefManager *ndef = env->getGameDef()->ndef();
1153 if(lua_istable(L, 2))
1155 getstringfield(L, 2, "axiom", tree_def.initial_axiom);
1156 getstringfield(L, 2, "rules_a", tree_def.rules_a);
1157 getstringfield(L, 2, "rules_b", tree_def.rules_b);
1158 getstringfield(L, 2, "rules_c", tree_def.rules_c);
1159 getstringfield(L, 2, "rules_d", tree_def.rules_d);
1160 getstringfield(L, 2, "trunk", trunk);
1161 tree_def.trunknode=ndef->getId(trunk);
1162 getstringfield(L, 2, "leaves", leaves);
1163 tree_def.leavesnode=ndef->getId(leaves);
1164 tree_def.leaves2_chance=0;
1165 getstringfield(L, 2, "leaves2", leaves);
1166 if (!leaves.empty()) {
1167 tree_def.leaves2node=ndef->getId(leaves);
1168 getintfield(L, 2, "leaves2_chance", tree_def.leaves2_chance);
1170 getintfield(L, 2, "angle", tree_def.angle);
1171 getintfield(L, 2, "iterations", tree_def.iterations);
1172 if (!getintfield(L, 2, "random_level", tree_def.iterations_random_level))
1173 tree_def.iterations_random_level = 0;
1174 getstringfield(L, 2, "trunk_type", tree_def.trunk_type);
1175 getboolfield(L, 2, "thin_branches", tree_def.thin_branches);
1176 tree_def.fruit_chance=0;
1177 getstringfield(L, 2, "fruit", fruit);
1178 if (!fruit.empty()) {
1179 tree_def.fruitnode=ndef->getId(fruit);
1180 getintfield(L, 2, "fruit_chance",tree_def.fruit_chance);
1182 tree_def.explicit_seed = getintfield(L, 2, "seed", tree_def.seed);
1188 if ((e = treegen::spawn_ltree (env, p0, ndef, tree_def)) != treegen::SUCCESS) {
1189 if (e == treegen::UNBALANCED_BRACKETS) {
1190 luaL_error(L, "spawn_tree(): closing ']' has no matching opening bracket");
1192 luaL_error(L, "spawn_tree(): unknown error");
1199 // transforming_liquid_add(pos)
1200 int ModApiEnvMod::l_transforming_liquid_add(lua_State *L)
1204 v3s16 p0 = read_v3s16(L, 1);
1205 env->getMap().transforming_liquid_add(p0);
1209 // forceload_block(blockpos)
1210 // blockpos = {x=num, y=num, z=num}
1211 int ModApiEnvMod::l_forceload_block(lua_State *L)
1215 v3s16 blockpos = read_v3s16(L, 1);
1216 env->getForceloadedBlocks()->insert(blockpos);
1220 // forceload_free_block(blockpos)
1221 // blockpos = {x=num, y=num, z=num}
1222 int ModApiEnvMod::l_forceload_free_block(lua_State *L)
1226 v3s16 blockpos = read_v3s16(L, 1);
1227 env->getForceloadedBlocks()->erase(blockpos);
1231 void ModApiEnvMod::Initialize(lua_State *L, int top)
1237 API_FCT(remove_node);
1239 API_FCT(get_node_or_nil);
1240 API_FCT(get_node_light);
1241 API_FCT(place_node);
1243 API_FCT(punch_node);
1244 API_FCT(get_node_max_level);
1245 API_FCT(get_node_level);
1246 API_FCT(set_node_level);
1247 API_FCT(add_node_level);
1248 API_FCT(add_entity);
1249 API_FCT(find_nodes_with_meta);
1251 API_FCT(get_node_timer);
1252 API_FCT(get_player_by_name);
1253 API_FCT(get_objects_inside_radius);
1254 API_FCT(set_timeofday);
1255 API_FCT(get_timeofday);
1256 API_FCT(get_gametime);
1257 API_FCT(get_day_count);
1258 API_FCT(find_node_near);
1259 API_FCT(find_nodes_in_area);
1260 API_FCT(find_nodes_in_area_under_air);
1262 API_FCT(emerge_area);
1263 API_FCT(delete_area);
1264 API_FCT(get_perlin);
1265 API_FCT(get_perlin_map);
1266 API_FCT(get_voxel_manip);
1267 API_FCT(clear_objects);
1268 API_FCT(spawn_tree);
1270 API_FCT(line_of_sight);
1272 API_FCT(transforming_liquid_add);
1273 API_FCT(forceload_block);
1274 API_FCT(forceload_free_block);
1277 void ModApiEnvMod::InitializeClient(lua_State *L, int top)
1279 API_FCT(get_timeofday);
1280 API_FCT(get_day_count);
1281 API_FCT(get_node_max_level);
1282 API_FCT(get_node_level);
1283 API_FCT(find_node_near);