From 291a6b70d674d9003f522b5875a60f7e2753e32b Mon Sep 17 00:00:00 2001 From: ANAND Date: Fri, 5 Jun 2020 18:36:35 +0530 Subject: Allow binding dig, place actions to keys; remove LMB/RMB hardcoding Co-authored-by: Sam Caulfield --- src/script/lua_api/l_object.cpp | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) (limited to 'src/script/lua_api/l_object.cpp') diff --git a/src/script/lua_api/l_object.cpp b/src/script/lua_api/l_object.cpp index e7394133a..495d8bced 100644 --- a/src/script/lua_api/l_object.cpp +++ b/src/script/lua_api/l_object.cpp @@ -1455,9 +1455,14 @@ int ObjectRef::l_get_player_control(lua_State *L) lua_setfield(L, -2, "aux1"); lua_pushboolean(L, control.sneak); lua_setfield(L, -2, "sneak"); - lua_pushboolean(L, control.LMB); + lua_pushboolean(L, control.dig); + lua_setfield(L, -2, "dig"); + lua_pushboolean(L, control.place); + lua_setfield(L, -2, "place"); + // Legacy fields to ensure mod compatibility + lua_pushboolean(L, control.dig); lua_setfield(L, -2, "LMB"); - lua_pushboolean(L, control.RMB); + lua_pushboolean(L, control.place); lua_setfield(L, -2, "RMB"); lua_pushboolean(L, control.zoom); lua_setfield(L, -2, "zoom"); -- cgit v1.2.3 From d052593c7ab3c57f83ea250fc10f7c1927962c09 Mon Sep 17 00:00:00 2001 From: karamel59 Date: Thu, 27 Aug 2020 21:47:38 +0200 Subject: Lua API: Register missing get_texture_mod function (#10338) --- src/script/lua_api/l_object.cpp | 1 + 1 file changed, 1 insertion(+) (limited to 'src/script/lua_api/l_object.cpp') diff --git a/src/script/lua_api/l_object.cpp b/src/script/lua_api/l_object.cpp index 495d8bced..24667e769 100644 --- a/src/script/lua_api/l_object.cpp +++ b/src/script/lua_api/l_object.cpp @@ -2299,6 +2299,7 @@ luaL_Reg ObjectRef::methods[] = { luamethod(ObjectRef, set_rotation), luamethod(ObjectRef, get_rotation), luamethod_aliased(ObjectRef, set_texture_mod, settexturemod), + luamethod(ObjectRef, get_texture_mod), luamethod_aliased(ObjectRef, set_sprite, setsprite), luamethod(ObjectRef, get_entity_name), luamethod(ObjectRef, get_luaentity), -- cgit v1.2.3 From 3250b37e32f264db04c1ca449d9feefc22fd38b7 Mon Sep 17 00:00:00 2001 From: rubenwardy Date: Sun, 4 Oct 2020 00:33:45 +0100 Subject: Deprecate get_player_velocity and add_player_velocity (#10173) --- builtin/game/features.lua | 1 + doc/lua_api.txt | 31 +++++++++------- src/script/lua_api/l_base.cpp | 5 ++- src/script/lua_api/l_object.cpp | 82 +++++++++++++++++++---------------------- src/script/lua_api/l_object.h | 6 --- 5 files changed, 58 insertions(+), 67 deletions(-) (limited to 'src/script/lua_api/l_object.cpp') diff --git a/builtin/game/features.lua b/builtin/game/features.lua index a15475333..4d3c90ff0 100644 --- a/builtin/game/features.lua +++ b/builtin/game/features.lua @@ -17,6 +17,7 @@ core.features = { area_store_persistent_ids = true, pathfinder_works = true, object_step_has_moveresult = true, + direct_velocity_on_players = true, } function core.has_feature(arg) diff --git a/doc/lua_api.txt b/doc/lua_api.txt index 5d5e4b93a..c21da1871 100644 --- a/doc/lua_api.txt +++ b/doc/lua_api.txt @@ -4340,6 +4340,8 @@ Utilities pathfinder_works = true, -- Whether Collision info is available to an objects' on_step (5.3.0) object_step_has_moveresult = true, + -- Whether get_velocity() and add_velocity() can be used on players (5.4.0) + direct_velocity_on_players = true, } * `minetest.has_feature(arg)`: returns `boolean, missing_features` @@ -6118,6 +6120,19 @@ object you are working with still exists. * `get_pos()`: returns `{x=num, y=num, z=num}` * `set_pos(pos)`: `pos`=`{x=num, y=num, z=num}` +* `get_velocity()`: returns the velocity, a vector. +* `add_velocity(vel)` + * `vel` is a vector, e.g. `{x=0.0, y=2.3, z=1.0}` + * In comparison to using get_velocity, adding the velocity and then using + set_velocity, add_velocity is supposed to avoid synchronization problems. + Additionally, players also do not support set_velocity. + * If a player: + * Does not apply during free_move. + * Note that since the player speed is normalized at each move step, + increasing e.g. Y velocity beyond what would usually be achieved + (see: physics overrides) will cause existing X/Z velocity to be reduced. + * Example: `add_velocity({x=0, y=6.5, z=0})` is equivalent to + pressing the jump key (assuming default settings) * `move_to(pos, continuous=false)` * Does an interpolated move for Lua entities for visually smooth transitions. * If `continuous` is true, the Lua entity will not be moved to the current @@ -6189,11 +6204,6 @@ object you are working with still exists. no effect and returning `nil`. * `set_velocity(vel)` * `vel` is a vector, e.g. `{x=0.0, y=2.3, z=1.0}` -* `add_velocity(vel)` - * `vel` is a vector, e.g. `{x=0.0, y=2.3, z=1.0}` - * In comparison to using get_velocity, adding the velocity and then using - set_velocity, add_velocity is supposed to avoid synchronization problems. -* `get_velocity()`: returns the velocity, a vector * `set_acceleration(acc)` * `acc` is a vector * `get_acceleration()`: returns the acceleration, a vector @@ -6229,16 +6239,9 @@ object you are working with still exists. #### Player only (no-op for other objects) * `get_player_name()`: returns `""` if is not a player -* `get_player_velocity()`: returns `nil` if is not a player, otherwise a +* `get_player_velocity()`: **DEPRECATED**, use get_velocity() instead. table {x, y, z} representing the player's instantaneous velocity in nodes/s -* `add_player_velocity(vel)` - * Adds to player velocity, this happens client-side and only once. - * Does not apply during free_move. - * Note that since the player speed is normalized at each move step, - increasing e.g. Y velocity beyond what would usually be achieved - (see: physics overrides) will cause existing X/Z velocity to be reduced. - * Example: `add_player_velocity({x=0, y=6.5, z=0})` is equivalent to - pressing the jump key (assuming default settings) +* `add_player_velocity(vel)`: **DEPRECATED**, use add_velocity(vel) instead. * `get_look_dir()`: get camera direction as a unit vector * `get_look_vertical()`: pitch in radians * Angle ranges between -pi/2 and pi/2, which are straight up and down diff --git a/src/script/lua_api/l_base.cpp b/src/script/lua_api/l_base.cpp index 2bee09436..03ef5447a 100644 --- a/src/script/lua_api/l_base.cpp +++ b/src/script/lua_api/l_base.cpp @@ -170,10 +170,11 @@ void ModApiBase::markAliasDeprecated(luaL_Reg *reg) m_deprecated_wrappers.emplace( std::pair(reg->name, original_reg)); reg->func = l_deprecated_function; + } else { + last_func = reg->func; + last_name = reg->name; } - last_func = reg->func; - last_name = reg->name; ++reg; } } diff --git a/src/script/lua_api/l_object.cpp b/src/script/lua_api/l_object.cpp index 24667e769..303b1175b 100644 --- a/src/script/lua_api/l_object.cpp +++ b/src/script/lua_api/l_object.cpp @@ -863,12 +863,21 @@ int ObjectRef::l_add_velocity(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - LuaEntitySAO *co = getluaobject(ref); - if (!co) + v3f vel = checkFloatPos(L, 2); + + ServerActiveObject *obj = getobject(ref); + if (obj == nullptr) return 0; - v3f pos = checkFloatPos(L, 2); - // Do it - co->addVelocity(pos); + + if (obj->getType() == ACTIVEOBJECT_TYPE_LUAENTITY) { + LuaEntitySAO *co = dynamic_cast(obj); + co->addVelocity(vel); + } else if (obj->getType() == ACTIVEOBJECT_TYPE_PLAYER) { + PlayerSAO *player = dynamic_cast(obj); + player->setMaxSpeedOverride(vel); + getServer(L)->SendPlayerSpeed(player->getPeerID(), vel); + } + return 0; } @@ -877,11 +886,23 @@ int ObjectRef::l_get_velocity(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - LuaEntitySAO *co = getluaobject(ref); - if (co == NULL) return 0; - // Do it - v3f v = co->getVelocity(); - pushFloatPos(L, v); + + ServerActiveObject *obj = getobject(ref); + if (obj == nullptr) + return 0; + + if (obj->getType() == ACTIVEOBJECT_TYPE_LUAENTITY) { + LuaEntitySAO *co = dynamic_cast(obj); + v3f v = co->getVelocity(); + pushFloatPos(L, v); + return 1; + } else if (obj->getType() == ACTIVEOBJECT_TYPE_PLAYER) { + RemotePlayer *player = dynamic_cast(obj)->getPlayer(); + push_v3f(L, player->getSpeed() / BS); + return 1; + } + + lua_pushnil(L); return 1; } @@ -1082,38 +1103,6 @@ int ObjectRef::l_get_player_name(lua_State *L) return 1; } -// get_player_velocity(self) -int ObjectRef::l_get_player_velocity(lua_State *L) -{ - NO_MAP_LOCK_REQUIRED; - ObjectRef *ref = checkobject(L, 1); - RemotePlayer *player = getplayer(ref); - if (player == NULL) { - lua_pushnil(L); - return 1; - } - // Do it - push_v3f(L, player->getSpeed() / BS); - return 1; -} - -// add_player_velocity(self, {x=num, y=num, z=num}) -int ObjectRef::l_add_player_velocity(lua_State *L) -{ - NO_MAP_LOCK_REQUIRED; - ObjectRef *ref = checkobject(L, 1); - v3f vel = checkFloatPos(L, 2); - - PlayerSAO *co = getplayersao(ref); - if (!co) - return 0; - - // Do it - co->setMaxSpeedOverride(vel); - getServer(L)->SendPlayerSpeed(co->getPeerID(), vel); - return 0; -} - // get_look_dir(self) int ObjectRef::l_get_look_dir(lua_State *L) { @@ -2288,10 +2277,14 @@ luaL_Reg ObjectRef::methods[] = { luamethod(ObjectRef, get_properties), luamethod(ObjectRef, set_nametag_attributes), luamethod(ObjectRef, get_nametag_attributes), - // LuaEntitySAO-only + luamethod_aliased(ObjectRef, set_velocity, setvelocity), luamethod(ObjectRef, add_velocity), + {"add_player_velocity", ObjectRef::l_add_velocity}, luamethod_aliased(ObjectRef, get_velocity, getvelocity), + {"get_player_velocity", ObjectRef::l_get_velocity}, + + // LuaEntitySAO-only luamethod_aliased(ObjectRef, set_acceleration, setacceleration), luamethod_aliased(ObjectRef, get_acceleration, getacceleration), luamethod_aliased(ObjectRef, set_yaw, setyaw), @@ -2307,8 +2300,7 @@ luaL_Reg ObjectRef::methods[] = { luamethod(ObjectRef, is_player), luamethod(ObjectRef, is_player_connected), luamethod(ObjectRef, get_player_name), - luamethod(ObjectRef, get_player_velocity), - luamethod(ObjectRef, add_player_velocity), + luamethod(ObjectRef, get_look_dir), luamethod(ObjectRef, get_look_pitch), luamethod(ObjectRef, get_look_yaw), diff --git a/src/script/lua_api/l_object.h b/src/script/lua_api/l_object.h index a75c59fd9..126719b1f 100644 --- a/src/script/lua_api/l_object.h +++ b/src/script/lua_api/l_object.h @@ -209,12 +209,6 @@ private: // get_player_name(self) static int l_get_player_name(lua_State *L); - // get_player_velocity(self) - static int l_get_player_velocity(lua_State *L); - - // add_player_velocity(self, {x=num, y=num, z=num}) - static int l_add_player_velocity(lua_State *L); - // get_fov(self) static int l_get_fov(lua_State *L); -- cgit v1.2.3 From 3068853e8a58ccc7370a5ce977c08223601c497a Mon Sep 17 00:00:00 2001 From: Jordan Snelling Date: Sun, 4 Oct 2020 14:10:34 +0100 Subject: Add First Person Attachments (#10360) Fixes some other third person camera specific attachments. Implements a single new flag for entities to be forced visible in first person mode. Old mods do not need to be updated to use the new flag and are fully backwards compatible. --- doc/lua_api.txt | 8 +++--- src/activeobject.h | 4 +-- src/client/content_cao.cpp | 56 ++++++++++++++++++++++++++++++++++++----- src/client/content_cao.h | 8 ++++++ src/client/game.cpp | 3 ++- src/clientiface.cpp | 5 ++-- src/script/lua_api/l_camera.cpp | 3 ++- src/script/lua_api/l_object.cpp | 14 +++++++---- src/server/luaentity_sao.cpp | 4 +-- src/server/player_sao.cpp | 9 ++++--- src/server/unit_sao.cpp | 17 +++++++------ src/server/unit_sao.h | 5 ++-- 12 files changed, 101 insertions(+), 35 deletions(-) (limited to 'src/script/lua_api/l_object.cpp') diff --git a/doc/lua_api.txt b/doc/lua_api.txt index c21da1871..77fb4a654 100644 --- a/doc/lua_api.txt +++ b/doc/lua_api.txt @@ -6167,12 +6167,14 @@ object you are working with still exists. `frame_loop`. * `set_animation_frame_speed(frame_speed)` * `frame_speed`: number, default: `15.0` -* `set_attach(parent, bone, position, rotation)` +* `set_attach(parent, bone, position, rotation, forced_visible)` * `bone`: string * `position`: `{x=num, y=num, z=num}` (relative) * `rotation`: `{x=num, y=num, z=num}` = Rotation on each axis, in degrees -* `get_attach()`: returns parent, bone, position, rotation or nil if it isn't - attached. + * `forced_visible`: Boolean to control whether the attached entity + should appear in first person. +* `get_attach()`: returns parent, bone, position, rotation, forced_visible, + or nil if it isn't attached. * `set_detach()` * `set_bone_position(bone, position, rotation)` * `bone`: string diff --git a/src/activeobject.h b/src/activeobject.h index 85e160d10..0829858ad 100644 --- a/src/activeobject.h +++ b/src/activeobject.h @@ -120,9 +120,9 @@ public: virtual void setAttachment(int parent_id, const std::string &bone, v3f position, - v3f rotation) {} + v3f rotation, bool force_visible) {} virtual void getAttachment(int *parent_id, std::string *bone, v3f *position, - v3f *rotation) const {} + v3f *rotation, bool *force_visible) const {} virtual void clearChildAttachments() {} virtual void clearParentAttachment() {} virtual void addAttachmentChild(int child_id) {} diff --git a/src/client/content_cao.cpp b/src/client/content_cao.cpp index c1715a289..fae06554a 100644 --- a/src/client/content_cao.cpp +++ b/src/client/content_cao.cpp @@ -456,7 +456,8 @@ void GenericCAO::setChildrenVisible(bool toset) for (u16 cao_id : m_attachment_child_ids) { GenericCAO *obj = m_env->getGenericCAO(cao_id); if (obj) { - obj->setVisible(toset); + // Check if the entity is forced to appear in first person. + obj->setVisible(obj->isForcedVisible() ? true : toset); } } } @@ -477,8 +478,6 @@ void GenericCAO::setAttachment(int parent_id, const std::string &bone, v3f posit if (parent) parent->addAttachmentChild(m_id); } - - updateAttachments(); } @@ -498,7 +497,7 @@ void GenericCAO::clearChildAttachments() int child_id = *m_attachment_child_ids.begin(); if (ClientActiveObject *child = m_env->getActiveObject(child_id)) - child->setAttachment(0, "", v3f(), v3f()); + child->setAttachment(0, "", v3f(), v3f(), false); removeAttachmentChild(child_id); } @@ -800,6 +799,7 @@ void GenericCAO::addToScene(ITextureSource *tsrc) updateBonePosition(); updateAttachments(); setNodeLight(m_last_light); + updateMeshCulling(); } void GenericCAO::updateLight(u32 day_night_ratio) @@ -1411,6 +1411,9 @@ void GenericCAO::updateTextures(std::string mod) setMeshColor(mesh, m_prop.colors[0]); } } + // Prevent showing the player after changing texture + if (m_is_local_player) + updateMeshCulling(); } void GenericCAO::updateAnimation() @@ -1739,12 +1742,25 @@ void GenericCAO::processMessage(const std::string &data) std::string bone = deSerializeString16(is); v3f position = readV3F32(is); v3f rotation = readV3F32(is); + m_force_visible = readU8(is); // Returns false for EOF setAttachment(parent_id, bone, position, rotation); + // Forcibly show attachments if required by set_attach + if (m_force_visible) + m_is_visible = true; // localplayer itself can't be attached to localplayer - if (!m_is_local_player) - m_is_visible = !m_attached_to_local; + else if (!m_is_local_player) { + // Objects attached to the local player should be hidden in first + // person provided the forced boolean isn't set. + m_is_visible = !m_attached_to_local || + m_client->getCamera()->getCameraMode() != CAMERA_MODE_FIRST; + m_force_visible = false; + } else { + // Local players need to have this set, + // otherwise first person attachments fail. + m_is_visible = true; + } } else if (cmd == AO_CMD_PUNCHED) { u16 result_hp = readU16(is); @@ -1858,5 +1874,33 @@ std::string GenericCAO::debugInfoText() return os.str(); } +void GenericCAO::updateMeshCulling() +{ + if (!m_is_local_player) + return; + + // Grab the active player scene node so we know there's + // at least a mesh to occlude from the camera. + irr::scene::ISceneNode *node = getSceneNode(); + if (!node) + return; + + if (m_client->getCamera()->getCameraMode() == CAMERA_MODE_FIRST) { + // Hide the mesh by culling both front and + // back faces. Serious hackyness but it works for our + // purposes. This also preserves the skeletal armature. + node->setMaterialFlag(video::EMF_BACK_FACE_CULLING, + true); + node->setMaterialFlag(video::EMF_FRONT_FACE_CULLING, + true); + } else { + // Restore mesh visibility. + node->setMaterialFlag(video::EMF_BACK_FACE_CULLING, + m_prop.backface_culling); + node->setMaterialFlag(video::EMF_FRONT_FACE_CULLING, + false); + } +} + // Prototype GenericCAO proto_GenericCAO(NULL, NULL); diff --git a/src/client/content_cao.h b/src/client/content_cao.h index 974ff9a1e..daf697767 100644 --- a/src/client/content_cao.h +++ b/src/client/content_cao.h @@ -124,6 +124,7 @@ private: float m_step_distance_counter = 0.0f; u8 m_last_light = 255; bool m_is_visible = false; + bool m_force_visible = false; s8 m_glow = 0; // Material video::E_MATERIAL_TYPE m_material_type; @@ -215,6 +216,11 @@ public: m_is_visible = toset; } + inline bool isForcedVisible() const + { + return m_force_visible; + } + void setChildrenVisible(bool toset); void setAttachment(int parent_id, const std::string &bone, v3f position, v3f rotation); void getAttachment(int *parent_id, std::string *bone, v3f *position, @@ -275,4 +281,6 @@ public: { return m_prop.infotext; } + + void updateMeshCulling(); }; diff --git a/src/client/game.cpp b/src/client/game.cpp index 8f9d51417..366464467 100644 --- a/src/client/game.cpp +++ b/src/client/game.cpp @@ -2950,7 +2950,8 @@ void Game::updateCamera(u32 busy_time, f32 dtime) camera->toggleCameraMode(); - playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST); + // Make the player visible depending on camera mode. + playercao->updateMeshCulling(); playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST); } diff --git a/src/clientiface.cpp b/src/clientiface.cpp index 602a44c90..28a0ee770 100644 --- a/src/clientiface.cpp +++ b/src/clientiface.cpp @@ -80,10 +80,11 @@ LuaEntitySAO *getAttachedObject(PlayerSAO *sao, ServerEnvironment *env) int id; std::string bone; v3f dummy; - sao->getAttachment(&id, &bone, &dummy, &dummy); + bool force_visible; + sao->getAttachment(&id, &bone, &dummy, &dummy, &force_visible); ServerActiveObject *ao = env->getActiveObject(id); while (id && ao) { - ao->getAttachment(&id, &bone, &dummy, &dummy); + ao->getAttachment(&id, &bone, &dummy, &dummy, &force_visible); if (id) ao = env->getActiveObject(id); } diff --git a/src/script/lua_api/l_camera.cpp b/src/script/lua_api/l_camera.cpp index bfa60be67..40251154c 100644 --- a/src/script/lua_api/l_camera.cpp +++ b/src/script/lua_api/l_camera.cpp @@ -63,7 +63,8 @@ int LuaCamera::l_set_camera_mode(lua_State *L) return 0; camera->setCameraMode((CameraMode)((int)lua_tonumber(L, 2))); - playercao->setVisible(camera->getCameraMode() > CAMERA_MODE_FIRST); + // Make the player visible depending on camera mode. + playercao->updateMeshCulling(); playercao->setChildrenVisible(camera->getCameraMode() > CAMERA_MODE_FIRST); return 0; } diff --git a/src/script/lua_api/l_object.cpp b/src/script/lua_api/l_object.cpp index 303b1175b..fead4e849 100644 --- a/src/script/lua_api/l_object.cpp +++ b/src/script/lua_api/l_object.cpp @@ -664,7 +664,7 @@ int ObjectRef::l_get_bone_position(lua_State *L) return 2; } -// set_attach(self, parent, bone, position, rotation) +// set_attach(self, parent, bone, position, rotation, force_visible) int ObjectRef::l_set_attach(lua_State *L) { GET_ENV_PTR; @@ -687,7 +687,8 @@ int ObjectRef::l_set_attach(lua_State *L) std::string bone; v3f position = v3f(0, 0, 0); v3f rotation = v3f(0, 0, 0); - co->getAttachment(&parent_id, &bone, &position, &rotation); + bool force_visible; + co->getAttachment(&parent_id, &bone, &position, &rotation, &force_visible); if (parent_id) { ServerActiveObject *old_parent = env->getActiveObject(parent_id); old_parent->removeAttachmentChild(co->getId()); @@ -702,7 +703,8 @@ int ObjectRef::l_set_attach(lua_State *L) rotation = v3f(0, 0, 0); if (!lua_isnil(L, 5)) rotation = read_v3f(L, 5); - co->setAttachment(parent->getId(), bone, position, rotation); + force_visible = readParam(L, 6, false); + co->setAttachment(parent->getId(), bone, position, rotation, force_visible); parent->addAttachmentChild(co->getId()); return 0; } @@ -722,7 +724,8 @@ int ObjectRef::l_get_attach(lua_State *L) std::string bone; v3f position = v3f(0, 0, 0); v3f rotation = v3f(0, 0, 0); - co->getAttachment(&parent_id, &bone, &position, &rotation); + bool force_visible; + co->getAttachment(&parent_id, &bone, &position, &rotation, &force_visible); if (!parent_id) return 0; ServerActiveObject *parent = env->getActiveObject(parent_id); @@ -731,7 +734,8 @@ int ObjectRef::l_get_attach(lua_State *L) lua_pushlstring(L, bone.c_str(), bone.size()); push_v3f(L, position); push_v3f(L, rotation); - return 4; + lua_pushboolean(L, force_visible); + return 5; } // set_detach(self) diff --git a/src/server/luaentity_sao.cpp b/src/server/luaentity_sao.cpp index f20914f7f..b39797531 100644 --- a/src/server/luaentity_sao.cpp +++ b/src/server/luaentity_sao.cpp @@ -238,9 +238,9 @@ std::string LuaEntitySAO::getClientInitializationData(u16 protocol_version) msg_os << serializeString32(generateUpdateAnimationCommand()); // 3 for (const auto &bone_pos : m_bone_position) { msg_os << serializeString32(generateUpdateBonePositionCommand( - bone_pos.first, bone_pos.second.X, bone_pos.second.Y)); // m_bone_position.size + bone_pos.first, bone_pos.second.X, bone_pos.second.Y)); // 3 + N } - msg_os << serializeString32(generateUpdateAttachmentCommand()); // 4 + msg_os << serializeString32(generateUpdateAttachmentCommand()); // 4 + m_bone_position.size int message_count = 4 + m_bone_position.size(); diff --git a/src/server/player_sao.cpp b/src/server/player_sao.cpp index 8d4938c3c..344d18a20 100644 --- a/src/server/player_sao.cpp +++ b/src/server/player_sao.cpp @@ -122,10 +122,10 @@ std::string PlayerSAO::getClientInitializationData(u16 protocol_version) msg_os << serializeString32(generateUpdateAnimationCommand()); // 3 for (const auto &bone_pos : m_bone_position) { msg_os << serializeString32(generateUpdateBonePositionCommand( - bone_pos.first, bone_pos.second.X, bone_pos.second.Y)); // m_bone_position.size + bone_pos.first, bone_pos.second.X, bone_pos.second.Y)); // 3 + N } - msg_os << serializeString32(generateUpdateAttachmentCommand()); // 4 - msg_os << serializeString32(generateUpdatePhysicsOverrideCommand()); // 5 + msg_os << serializeString32(generateUpdateAttachmentCommand()); // 4 + m_bone_position.size + msg_os << serializeString32(generateUpdatePhysicsOverrideCommand()); // 5 + m_bone_position.size int message_count = 5 + m_bone_position.size(); @@ -569,7 +569,8 @@ bool PlayerSAO::checkMovementCheat() int parent_id; std::string bone; v3f attachment_rot; - getAttachment(&parent_id, &bone, &attachment_pos, &attachment_rot); + bool force_visible; + getAttachment(&parent_id, &bone, &attachment_pos, &attachment_rot, &force_visible); } v3f parent_pos = parent->getBasePosition(); diff --git a/src/server/unit_sao.cpp b/src/server/unit_sao.cpp index d906e885e..2371640ca 100644 --- a/src/server/unit_sao.cpp +++ b/src/server/unit_sao.cpp @@ -121,8 +121,8 @@ void UnitSAO::sendOutdatedData() } // clang-format on -void UnitSAO::setAttachment( - int parent_id, const std::string &bone, v3f position, v3f rotation) +void UnitSAO::setAttachment(int parent_id, const std::string &bone, v3f position, + v3f rotation, bool force_visible) { // Attachments need to be handled on both the server and client. // If we just attach on the server, we can only copy the position of the parent. @@ -137,6 +137,7 @@ void UnitSAO::setAttachment( m_attachment_bone = bone; m_attachment_position = position; m_attachment_rotation = rotation; + m_force_visible = force_visible; m_attachment_sent = false; if (parent_id != old_parent) { @@ -145,13 +146,14 @@ void UnitSAO::setAttachment( } } -void UnitSAO::getAttachment( - int *parent_id, std::string *bone, v3f *position, v3f *rotation) const +void UnitSAO::getAttachment(int *parent_id, std::string *bone, v3f *position, + v3f *rotation, bool *force_visible) const { *parent_id = m_attachment_parent_id; *bone = m_attachment_bone; *position = m_attachment_position; *rotation = m_attachment_rotation; + *force_visible = m_force_visible; } void UnitSAO::clearChildAttachments() @@ -159,7 +161,7 @@ void UnitSAO::clearChildAttachments() for (int child_id : m_attachment_child_ids) { // Child can be NULL if it was deleted earlier if (ServerActiveObject *child = m_env->getActiveObject(child_id)) - child->setAttachment(0, "", v3f(0, 0, 0), v3f(0, 0, 0)); + child->setAttachment(0, "", v3f(0, 0, 0), v3f(0, 0, 0), false); } m_attachment_child_ids.clear(); } @@ -169,9 +171,9 @@ void UnitSAO::clearParentAttachment() ServerActiveObject *parent = nullptr; if (m_attachment_parent_id) { parent = m_env->getActiveObject(m_attachment_parent_id); - setAttachment(0, "", m_attachment_position, m_attachment_rotation); + setAttachment(0, "", m_attachment_position, m_attachment_rotation, false); } else { - setAttachment(0, "", v3f(0, 0, 0), v3f(0, 0, 0)); + setAttachment(0, "", v3f(0, 0, 0), v3f(0, 0, 0), false); } // Do it if (parent) @@ -245,6 +247,7 @@ std::string UnitSAO::generateUpdateAttachmentCommand() const os << serializeString16(m_attachment_bone); writeV3F32(os, m_attachment_position); writeV3F32(os, m_attachment_rotation); + writeU8(os, m_force_visible); return os.str(); } diff --git a/src/server/unit_sao.h b/src/server/unit_sao.h index 3cb7f0ad5..a21e055c5 100644 --- a/src/server/unit_sao.h +++ b/src/server/unit_sao.h @@ -64,9 +64,9 @@ public: ServerActiveObject *getParent() const; inline bool isAttached() const { return getParent(); } void setAttachment(int parent_id, const std::string &bone, v3f position, - v3f rotation); + v3f rotation, bool force_visible); void getAttachment(int *parent_id, std::string *bone, v3f *position, - v3f *rotation) const; + v3f *rotation, bool *force_visible) const; void clearChildAttachments(); void clearParentAttachment(); void addAttachmentChild(int child_id); @@ -133,4 +133,5 @@ private: v3f m_attachment_position; v3f m_attachment_rotation; bool m_attachment_sent = false; + bool m_force_visible = false; }; -- cgit v1.2.3 From 81c66d6efb9fb0ab8a03b40e2bc22aa49eff9a04 Mon Sep 17 00:00:00 2001 From: Pierre-Yves Rollo Date: Sun, 4 Oct 2020 15:24:29 +0200 Subject: Minimap as HUD element with API control Features: * Define Minimap available modes (surface/radar, scale) from Lua, using player:set_minimap_modes() * New HUD elements for displaying minimap with custom size and placing * New minimap mode for displaying a texture instead of the map --- doc/lua_api.txt | 33 ++++- src/client/client.cpp | 1 + src/client/client.h | 1 + src/client/game.cpp | 75 +++++------- src/client/hud.cpp | 30 ++++- src/client/hud.h | 2 + src/client/mapblock_mesh.cpp | 2 +- src/client/minimap.cpp | 237 +++++++++++++++++++++++++++--------- src/client/minimap.h | 41 ++++--- src/hud.cpp | 1 + src/hud.h | 13 +- src/network/clientopcodes.cpp | 1 + src/network/clientpackethandler.cpp | 46 ++++++- src/network/networkprotocol.h | 14 ++- src/network/serveropcodes.cpp | 1 + src/script/lua_api/l_minimap.cpp | 24 ++-- src/script/lua_api/l_object.cpp | 62 ++++++++++ src/script/lua_api/l_object.h | 3 + src/server.cpp | 17 +++ src/server.h | 12 ++ 20 files changed, 471 insertions(+), 145 deletions(-) (limited to 'src/script/lua_api/l_object.cpp') diff --git a/doc/lua_api.txt b/doc/lua_api.txt index 77fb4a654..9e9af20da 100644 --- a/doc/lua_api.txt +++ b/doc/lua_api.txt @@ -1484,6 +1484,15 @@ Displays an image oriented or translated according to current heading direction. If translation is chosen, texture is repeated horizontally to fill the whole element. +### `minimap` + +Displays a minimap on the HUD. + +* `size`: Size of the minimap to display. Minimap should be a square to avoid + distortion. +* `alignment`: The alignment of the minimap. +* `offset`: offset in pixels from position. + Representations of simple things ================================ @@ -6366,6 +6375,27 @@ object you are working with still exists. * `hud_set_hotbar_selected_image(texturename)` * sets image for selected item of hotbar * `hud_get_hotbar_selected_image`: returns texturename +* `set_minimap_modes({mode, mode, ...}, selected_mode)` + * Overrides the available minimap modes (and toggle order), and changes the + selected mode. + * `mode` is a table consisting of up to four fields: + * `type`: Available type: + * `off`: Minimap off + * `surface`: Minimap in surface mode + * `radar`: Minimap in radar mode + * `texture`: Texture to be displayed instead of terrain map + (texture is centered around 0,0 and can be scaled). + Texture size is limited to 512 x 512 pixel. + * `label`: Optional label to display on minimap mode toggle + The translation must be handled within the mod. + * `size`: Sidelength or diameter, in number of nodes, of the terrain + displayed in minimap + * `texture`: Only for texture type, name of the texture to display + * `scale`: Only for texture type, scale of the texture map in nodes per + pixel (for example a `scale` of 2 means each pixel represents a 2x2 + nodes square) + * `selected_mode` is the mode index to be selected after modes have been changed + (0 is the first mode). * `set_sky(parameters)` * `parameters` is a table with the following optional fields: * `base_color`: ColorSpec, changes fog in "skybox" and "plain". @@ -8047,7 +8077,8 @@ Used by `Player:hud_add`. Returned by `Player:hud_get`. { hud_elem_type = "image", -- See HUD element types - -- Type of element, can be "image", "text", "statbar", "inventory" or "compass" + -- Type of element, can be "image", "text", "statbar", "inventory", + -- "compass" or "minimap" position = {x=0.5, y=0.5}, -- Left corner position of element diff --git a/src/client/client.cpp b/src/client/client.cpp index d6e529c40..7fafe0da9 100644 --- a/src/client/client.cpp +++ b/src/client/client.cpp @@ -129,6 +129,7 @@ Client::Client( if (g_settings->getBool("enable_minimap")) { m_minimap = new Minimap(this); } + m_cache_save_interval = g_settings->getU16("server_map_save_interval"); } diff --git a/src/client/client.h b/src/client/client.h index 733634db1..8f4aac6e3 100644 --- a/src/client/client.h +++ b/src/client/client.h @@ -223,6 +223,7 @@ public: void handleCommand_CSMRestrictionFlags(NetworkPacket *pkt); void handleCommand_PlayerSpeed(NetworkPacket *pkt); void handleCommand_MediaPush(NetworkPacket *pkt); + void handleCommand_MinimapModes(NetworkPacket *pkt); void ProcessData(NetworkPacket *pkt); diff --git a/src/client/game.cpp b/src/client/game.cpp index 366464467..54e0c9f20 100644 --- a/src/client/game.cpp +++ b/src/client/game.cpp @@ -1416,11 +1416,9 @@ bool Game::createClient(const GameStartData &start_data) } mapper = client->getMinimap(); - if (mapper) { - mapper->setMinimapMode(MINIMAP_MODE_OFF); - if (client->modsLoaded()) - client->getScript()->on_minimap_ready(mapper); - } + + if (mapper && client->modsLoaded()) + client->getScript()->on_minimap_ready(mapper); return true; } @@ -2222,52 +2220,37 @@ void Game::toggleMinimap(bool shift_pressed) if (!mapper || !m_game_ui->m_flags.show_hud || !g_settings->getBool("enable_minimap")) return; - if (shift_pressed) { + if (shift_pressed) mapper->toggleMinimapShape(); - return; - } + else + mapper->nextMode(); + + // TODO: When legacy minimap is deprecated, keep only HUD minimap stuff here + // Not so satisying code to keep compatibility with old fixed mode system + // --> u32 hud_flags = client->getEnv().getLocalPlayer()->hud_flags; - MinimapMode mode = MINIMAP_MODE_OFF; - if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) { - mode = mapper->getMinimapMode(); - mode = (MinimapMode)((int)mode + 1); - // If radar is disabled and in, or switching to, radar mode - if (!(hud_flags & HUD_FLAG_MINIMAP_RADAR_VISIBLE) && mode > 3) - mode = MINIMAP_MODE_OFF; - } + if (!(hud_flags & HUD_FLAG_MINIMAP_VISIBLE)) { + m_game_ui->m_flags.show_minimap = false; + } else { - m_game_ui->m_flags.show_minimap = true; - switch (mode) { - case MINIMAP_MODE_SURFACEx1: - m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x1"); - break; - case MINIMAP_MODE_SURFACEx2: - m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x2"); - break; - case MINIMAP_MODE_SURFACEx4: - m_game_ui->showTranslatedStatusText("Minimap in surface mode, Zoom x4"); - break; - case MINIMAP_MODE_RADARx1: - m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x1"); - break; - case MINIMAP_MODE_RADARx2: - m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x2"); - break; - case MINIMAP_MODE_RADARx4: - m_game_ui->showTranslatedStatusText("Minimap in radar mode, Zoom x4"); - break; - default: - mode = MINIMAP_MODE_OFF; - m_game_ui->m_flags.show_minimap = false; - if (hud_flags & HUD_FLAG_MINIMAP_VISIBLE) - m_game_ui->showTranslatedStatusText("Minimap hidden"); - else - m_game_ui->showTranslatedStatusText("Minimap currently disabled by game or mod"); - } + // If radar is disabled, try to find a non radar mode or fall back to 0 + if (!(hud_flags & HUD_FLAG_MINIMAP_RADAR_VISIBLE)) + while (mapper->getModeIndex() && + mapper->getModeDef().type == MINIMAP_TYPE_RADAR) + mapper->nextMode(); - mapper->setMinimapMode(mode); + m_game_ui->m_flags.show_minimap = mapper->getModeDef().type != + MINIMAP_TYPE_OFF; + } + // <-- + // End of 'not so satifying code' + if ((hud_flags & HUD_FLAG_MINIMAP_VISIBLE) || + (hud && hud->hasElementOfType(HUD_ELEM_MINIMAP))) + m_game_ui->showStatusText(utf8_to_wide(mapper->getModeDef().label)); + else + m_game_ui->showTranslatedStatusText("Minimap currently disabled by game or mod"); } void Game::toggleFog() @@ -3954,7 +3937,7 @@ void Game::updateFrame(ProfilerGraph *graph, RunStats *stats, f32 dtime, /* Update minimap pos and rotation */ - if (mapper && m_game_ui->m_flags.show_minimap && m_game_ui->m_flags.show_hud) { + if (mapper && m_game_ui->m_flags.show_hud) { mapper->setPos(floatToInt(player->getPosition(), BS)); mapper->setAngle(player->getYaw()); } diff --git a/src/client/hud.cpp b/src/client/hud.cpp index d3038230c..f6497fe25 100644 --- a/src/client/hud.cpp +++ b/src/client/hud.cpp @@ -36,6 +36,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "mesh.h" #include "wieldmesh.h" #include "client/renderingengine.h" +#include "client/minimap.h" #ifdef HAVE_TOUCHSCREENGUI #include "gui/touchscreengui.h" @@ -297,6 +298,18 @@ void Hud::drawItems(v2s32 upperleftpos, v2s32 screen_offset, s32 itemcount, } } +bool Hud::hasElementOfType(HudElementType type) +{ + for (size_t i = 0; i != player->maxHudId(); i++) { + HudElement *e = player->getHud(i); + if (!e) + continue; + if (e->type == type) + return true; + } + return false; +} + // Calculates screen position of waypoint. Returns true if waypoint is visible (in front of the player), else false. bool Hud::calculateScreenPos(const v3s16 &camera_offset, HudElement *e, v2s32 *pos) { @@ -491,7 +504,22 @@ void Hud::drawLuaElements(const v3s16 &camera_offset) default: break; } - + break; } + case HUD_ELEM_MINIMAP: { + if (e->size.X <= 0 || e->size.Y <= 0) + break; + if (!client->getMinimap()) + break; + // Draw a minimap of size "size" + v2s32 dstsize(e->size.X * m_scale_factor, + e->size.Y * m_scale_factor); + // (no percent size as minimap would likely be anamorphosed) + v2s32 offset((e->align.X - 1.0) * dstsize.X / 2, + (e->align.Y - 1.0) * dstsize.Y / 2); + core::rect rect(0, 0, dstsize.X, dstsize.Y); + rect += pos + offset + v2s32(e->offset.X * m_scale_factor, + e->offset.Y * m_scale_factor); + client->getMinimap()->drawMinimap(rect); break; } default: infostream << "Hud::drawLuaElements: ignoring drawform " << e->type << diff --git a/src/client/hud.h b/src/client/hud.h index cf83cb16e..d46545d71 100644 --- a/src/client/hud.h +++ b/src/client/hud.h @@ -81,6 +81,8 @@ public: m_selected_face_normal = face_normal; } + bool hasElementOfType(HudElementType type); + void drawLuaElements(const v3s16 &camera_offset); private: diff --git a/src/client/mapblock_mesh.cpp b/src/client/mapblock_mesh.cpp index 2f96ca61f..b59679523 100644 --- a/src/client/mapblock_mesh.cpp +++ b/src/client/mapblock_mesh.cpp @@ -1044,7 +1044,7 @@ MapBlockMesh::MapBlockMesh(MeshMakeData *data, v3s16 camera_offset): m_use_tangent_vertices = data->m_use_tangent_vertices; m_enable_vbo = g_settings->getBool("enable_vbo"); - if (g_settings->getBool("enable_minimap")) { + if (data->m_client->getMinimap()) { m_minimap_mapblock = new MinimapMapblock; m_minimap_mapblock->getMinimapNodes( &data->m_vmanip, data->m_blockpos * MAP_BLOCKSIZE); diff --git a/src/client/minimap.cpp b/src/client/minimap.cpp index 68770ec19..6bae408b4 100644 --- a/src/client/minimap.cpp +++ b/src/client/minimap.cpp @@ -25,7 +25,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "shader.h" #include "mapblock.h" #include "client/renderingengine.h" - +#include "gettext.h" //// //// MinimapUpdateThread @@ -108,8 +108,11 @@ void MinimapUpdateThread::doUpdate() } } - if (data->map_invalidated && data->mode != MINIMAP_MODE_OFF) { - getMap(data->pos, data->map_size, data->scan_height); + + if (data->map_invalidated && ( + data->mode.type == MINIMAP_TYPE_RADAR || + data->mode.type == MINIMAP_TYPE_SURFACE)) { + getMap(data->pos, data->mode.map_size, data->mode.scan_height); data->map_invalidated = false; } } @@ -181,19 +184,26 @@ Minimap::Minimap(Client *client) this->m_ndef = client->getNodeDefManager(); m_angle = 0.f; + m_current_mode_index = 0; // Initialize static settings m_enable_shaders = g_settings->getBool("enable_shaders"); m_surface_mode_scan_height = g_settings->getBool("minimap_double_scan_height") ? 256 : 128; + // Initialize minimap modes + addMode(MINIMAP_TYPE_OFF); + addMode(MINIMAP_TYPE_SURFACE, 256); + addMode(MINIMAP_TYPE_SURFACE, 128); + addMode(MINIMAP_TYPE_SURFACE, 64); + addMode(MINIMAP_TYPE_RADAR, 512); + addMode(MINIMAP_TYPE_RADAR, 256); + addMode(MINIMAP_TYPE_RADAR, 128); + // Initialize minimap data data = new MinimapData; - data->mode = MINIMAP_MODE_OFF; - data->is_radar = false; - data->map_invalidated = true; - data->texture = NULL; - data->heightmap_texture = NULL; + data->map_invalidated = true; + data->minimap_shape_round = g_settings->getBool("minimap_shape_round"); // Get round minimap textures @@ -215,6 +225,8 @@ Minimap::Minimap(Client *client) // Create object marker texture data->object_marker_red = m_tsrc->getTexture("object_marker_red.png"); + setModeIndex(0); + // Create mesh buffer for minimap m_meshbuffer = getMinimapMeshBuffer(); @@ -280,29 +292,101 @@ MinimapShape Minimap::getMinimapShape() return MINIMAP_SHAPE_SQUARE; } -void Minimap::setMinimapMode(MinimapMode mode) +void Minimap::setModeIndex(size_t index) { - static const MinimapModeDef modedefs[MINIMAP_MODE_COUNT] = { - {false, 0, 0}, - {false, m_surface_mode_scan_height, 256}, - {false, m_surface_mode_scan_height, 128}, - {false, m_surface_mode_scan_height, 64}, - {true, 32, 128}, - {true, 32, 64}, - {true, 32, 32} - }; - - if (mode >= MINIMAP_MODE_COUNT) - return; - MutexAutoLock lock(m_mutex); - data->is_radar = modedefs[mode].is_radar; - data->scan_height = modedefs[mode].scan_height; - data->map_size = modedefs[mode].map_size; - data->mode = mode; + if (index < m_modes.size()) { + data->mode = m_modes[index]; + m_current_mode_index = index; + } else { + data->mode = MinimapModeDef{MINIMAP_TYPE_OFF, N_("Minimap hidden"), 0, 0, ""}; + m_current_mode_index = 0; + } + + data->map_invalidated = true; - m_minimap_update_thread->deferUpdate(); + if (m_minimap_update_thread) + m_minimap_update_thread->deferUpdate(); +} + +void Minimap::addMode(MinimapModeDef mode) +{ + // Check validity + if (mode.type == MINIMAP_TYPE_TEXTURE) { + if (mode.texture.empty()) + return; + if (mode.scale < 1) + mode.scale = 1; + } + + int zoom = -1; + + // Build a default standard label + if (mode.label == "") { + switch (mode.type) { + case MINIMAP_TYPE_OFF: + mode.label = N_("Minimap hidden"); + break; + case MINIMAP_TYPE_SURFACE: + mode.label = N_("Minimap in surface mode, Zoom x%d"); + if (mode.map_size > 0) + zoom = 256 / mode.map_size; + break; + case MINIMAP_TYPE_RADAR: + mode.label = N_("Minimap in radar mode, Zoom x%d"); + if (mode.map_size > 0) + zoom = 512 / mode.map_size; + break; + case MINIMAP_TYPE_TEXTURE: + mode.label = N_("Minimap in texture mode"); + break; + default: + break; + } + } + + if (zoom >= 0) { + char label_buf[1024]; + porting::mt_snprintf(label_buf, sizeof(label_buf), + mode.label.c_str(), zoom); + mode.label = label_buf; + } + + m_modes.push_back(mode); +} + +void Minimap::addMode(MinimapType type, u16 size, std::string label, + std::string texture, u16 scale) +{ + MinimapModeDef mode; + mode.type = type; + mode.label = label; + mode.map_size = size; + mode.texture = texture; + mode.scale = scale; + switch (type) { + case MINIMAP_TYPE_SURFACE: + mode.scan_height = m_surface_mode_scan_height; + break; + case MINIMAP_TYPE_RADAR: + mode.scan_height = 32; + break; + default: + mode.scan_height = 0; + } + addMode(mode); +} + +void Minimap::nextMode() +{ + if (m_modes.empty()) + return; + m_current_mode_index++; + if (m_current_mode_index >= m_modes.size()) + m_current_mode_index = 0; + + setModeIndex(m_current_mode_index); } void Minimap::setPos(v3s16 pos) @@ -331,16 +415,16 @@ void Minimap::setAngle(f32 angle) void Minimap::blitMinimapPixelsToImageRadar(video::IImage *map_image) { video::SColor c(240, 0, 0, 0); - for (s16 x = 0; x < data->map_size; x++) - for (s16 z = 0; z < data->map_size; z++) { - MinimapPixel *mmpixel = &data->minimap_scan[x + z * data->map_size]; + for (s16 x = 0; x < data->mode.map_size; x++) + for (s16 z = 0; z < data->mode.map_size; z++) { + MinimapPixel *mmpixel = &data->minimap_scan[x + z * data->mode.map_size]; if (mmpixel->air_count > 0) c.setGreen(core::clamp(core::round32(32 + mmpixel->air_count * 8), 0, 255)); else c.setGreen(0); - map_image->setPixel(x, data->map_size - z - 1, c); + map_image->setPixel(x, data->mode.map_size - z - 1, c); } } @@ -349,9 +433,9 @@ void Minimap::blitMinimapPixelsToImageSurface( { // This variable creation/destruction has a 1% cost on rendering minimap video::SColor tilecolor; - for (s16 x = 0; x < data->map_size; x++) - for (s16 z = 0; z < data->map_size; z++) { - MinimapPixel *mmpixel = &data->minimap_scan[x + z * data->map_size]; + for (s16 x = 0; x < data->mode.map_size; x++) + for (s16 z = 0; z < data->mode.map_size; z++) { + MinimapPixel *mmpixel = &data->minimap_scan[x + z * data->mode.map_size]; const ContentFeatures &f = m_ndef->get(mmpixel->n); const TileDef *tile = &f.tiledef[0]; @@ -367,10 +451,10 @@ void Minimap::blitMinimapPixelsToImageSurface( tilecolor.setBlue(tilecolor.getBlue() * f.minimap_color.getBlue() / 255); tilecolor.setAlpha(240); - map_image->setPixel(x, data->map_size - z - 1, tilecolor); + map_image->setPixel(x, data->mode.map_size - z - 1, tilecolor); u32 h = mmpixel->height; - heightmap_image->setPixel(x,data->map_size - z - 1, + heightmap_image->setPixel(x,data->mode.map_size - z - 1, video::SColor(255, h, h, h)); } } @@ -378,21 +462,46 @@ void Minimap::blitMinimapPixelsToImageSurface( video::ITexture *Minimap::getMinimapTexture() { // update minimap textures when new scan is ready - if (data->map_invalidated) + if (data->map_invalidated && data->mode.type != MINIMAP_TYPE_TEXTURE) return data->texture; // create minimap and heightmap images in memory - core::dimension2d dim(data->map_size, data->map_size); + core::dimension2d dim(data->mode.map_size, data->mode.map_size); video::IImage *map_image = driver->createImage(video::ECF_A8R8G8B8, dim); video::IImage *heightmap_image = driver->createImage(video::ECF_A8R8G8B8, dim); video::IImage *minimap_image = driver->createImage(video::ECF_A8R8G8B8, core::dimension2d(MINIMAP_MAX_SX, MINIMAP_MAX_SY)); // Blit MinimapPixels to images - if (data->is_radar) - blitMinimapPixelsToImageRadar(map_image); - else + switch(data->mode.type) { + case MINIMAP_TYPE_OFF: + break; + case MINIMAP_TYPE_SURFACE: blitMinimapPixelsToImageSurface(map_image, heightmap_image); + break; + case MINIMAP_TYPE_RADAR: + blitMinimapPixelsToImageRadar(map_image); + break; + case MINIMAP_TYPE_TEXTURE: + // Want to use texture source, to : 1 find texture, 2 cache it + video::ITexture* texture = m_tsrc->getTexture(data->mode.texture); + video::IImage* image = driver->createImageFromData( + texture->getColorFormat(), texture->getSize(), texture->lock(), true, false); + texture->unlock(); + + auto dim = image->getDimension(); + + map_image->fill(video::SColor(255, 0, 0, 0)); + + image->copyTo(map_image, + irr::core::vector2d { + ((data->mode.map_size - (static_cast(dim.Width))) >> 1) + - data->pos.X / data->mode.scale, + ((data->mode.map_size - (static_cast(dim.Height))) >> 1) + + data->pos.Z / data->mode.scale + }); + image->drop(); + } map_image->copyToScaling(minimap_image); map_image->drop(); @@ -461,21 +570,31 @@ scene::SMeshBuffer *Minimap::getMinimapMeshBuffer() void Minimap::drawMinimap() { + // Non hud managed minimap drawing (legacy minimap) + v2u32 screensize = RenderingEngine::get_instance()->getWindowSize(); + const u32 size = 0.25 * screensize.Y; + + drawMinimap(core::rect( + screensize.X - size - 10, 10, + screensize.X - 10, size + 10)); +} + +void Minimap::drawMinimap(core::rect rect) { + video::ITexture *minimap_texture = getMinimapTexture(); if (!minimap_texture) return; + if (data->mode.type == MINIMAP_TYPE_OFF) + return; + updateActiveMarkers(); - v2u32 screensize = RenderingEngine::get_instance()->getWindowSize(); - const u32 size = 0.25 * screensize.Y; core::rect oldViewPort = driver->getViewPort(); core::matrix4 oldProjMat = driver->getTransform(video::ETS_PROJECTION); core::matrix4 oldViewMat = driver->getTransform(video::ETS_VIEW); - driver->setViewPort(core::rect( - screensize.X - size - 10, 10, - screensize.X - 10, size + 10)); + driver->setViewPort(rect); driver->setTransform(video::ETS_PROJECTION, core::matrix4()); driver->setTransform(video::ETS_VIEW, core::matrix4()); @@ -488,7 +607,7 @@ void Minimap::drawMinimap() material.TextureLayer[0].Texture = minimap_texture; material.TextureLayer[1].Texture = data->heightmap_texture; - if (m_enable_shaders && !data->is_radar) { + if (m_enable_shaders && data->mode.type == MINIMAP_TYPE_SURFACE) { u16 sid = m_shdrsrc->getShader("minimap_shader", 1, 1); material.MaterialType = m_shdrsrc->getShaderInfo(sid).material; } else { @@ -529,14 +648,14 @@ void Minimap::drawMinimap() driver->setViewPort(oldViewPort); // Draw player markers - v2s32 s_pos(screensize.X - size - 10, 10); + v2s32 s_pos(rect.UpperLeftCorner.X, rect.UpperLeftCorner.Y); core::dimension2di imgsize(data->object_marker_red->getOriginalSize()); core::rect img_rect(0, 0, imgsize.Width, imgsize.Height); static const video::SColor col(255, 255, 255, 255); static const video::SColor c[4] = {col, col, col, col}; f32 sin_angle = std::sin(m_angle * core::DEGTORAD); f32 cos_angle = std::cos(m_angle * core::DEGTORAD); - s32 marker_size2 = 0.025 * (float)size; + s32 marker_size2 = 0.025 * (float)rect.getWidth();; for (std::list::const_iterator i = m_active_markers.begin(); i != m_active_markers.end(); ++i) { @@ -547,8 +666,8 @@ void Minimap::drawMinimap() posf.X = t1; posf.Y = t2; } - posf.X = (posf.X + 0.5) * (float)size; - posf.Y = (posf.Y + 0.5) * (float)size; + posf.X = (posf.X + 0.5) * (float)rect.getWidth(); + posf.Y = (posf.Y + 0.5) * (float)rect.getHeight(); core::rect dest_rect( s_pos.X + posf.X - marker_size2, s_pos.Y + posf.Y - marker_size2, @@ -571,16 +690,16 @@ void Minimap::updateActiveMarkers() for (Nametag *nametag : nametags) { v3s16 pos = floatToInt(nametag->parent_node->getAbsolutePosition() + intToFloat(client->getCamera()->getOffset(), BS), BS); - pos -= data->pos - v3s16(data->map_size / 2, - data->scan_height / 2, - data->map_size / 2); - if (pos.X < 0 || pos.X > data->map_size || - pos.Y < 0 || pos.Y > data->scan_height || - pos.Z < 0 || pos.Z > data->map_size) { + pos -= data->pos - v3s16(data->mode.map_size / 2, + data->mode.scan_height / 2, + data->mode.map_size / 2); + if (pos.X < 0 || pos.X > data->mode.map_size || + pos.Y < 0 || pos.Y > data->mode.scan_height || + pos.Z < 0 || pos.Z > data->mode.map_size) { continue; } - pos.X = ((float)pos.X / data->map_size) * MINIMAP_MAX_SX; - pos.Z = ((float)pos.Z / data->map_size) * MINIMAP_MAX_SY; + pos.X = ((float)pos.X / data->mode.map_size) * MINIMAP_MAX_SX; + pos.Z = ((float)pos.Z / data->mode.map_size) * MINIMAP_MAX_SY; const video::SColor &mask_col = minimap_mask->getPixel(pos.X, pos.Z); if (!mask_col.getAlpha()) { continue; diff --git a/src/client/minimap.h b/src/client/minimap.h index 258d5330d..11374b116 100644 --- a/src/client/minimap.h +++ b/src/client/minimap.h @@ -19,6 +19,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #pragma once +#include "../hud.h" #include "irrlichttypes_extrabloated.h" #include "util/thread.h" #include "voxel.h" @@ -33,26 +34,18 @@ class IShaderSource; #define MINIMAP_MAX_SX 512 #define MINIMAP_MAX_SY 512 -enum MinimapMode { - MINIMAP_MODE_OFF, - MINIMAP_MODE_SURFACEx1, - MINIMAP_MODE_SURFACEx2, - MINIMAP_MODE_SURFACEx4, - MINIMAP_MODE_RADARx1, - MINIMAP_MODE_RADARx2, - MINIMAP_MODE_RADARx4, - MINIMAP_MODE_COUNT, -}; - enum MinimapShape { MINIMAP_SHAPE_SQUARE, MINIMAP_SHAPE_ROUND, }; struct MinimapModeDef { - bool is_radar; + MinimapType type; + std::string label; u16 scan_height; u16 map_size; + std::string texture; + u16 scale; }; struct MinimapPixel { @@ -69,12 +62,9 @@ struct MinimapMapblock { }; struct MinimapData { - bool is_radar; - MinimapMode mode; + MinimapModeDef mode; v3s16 pos; v3s16 old_pos; - u16 scan_height; - u16 map_size; MinimapPixel minimap_scan[MINIMAP_MAX_SX * MINIMAP_MAX_SY]; bool map_invalidated; bool minimap_shape_round; @@ -127,12 +117,22 @@ public: v3s16 getPos() const { return data->pos; } void setAngle(f32 angle); f32 getAngle() const { return m_angle; } - void setMinimapMode(MinimapMode mode); - MinimapMode getMinimapMode() const { return data->mode; } void toggleMinimapShape(); void setMinimapShape(MinimapShape shape); MinimapShape getMinimapShape(); + void clearModes() { m_modes.clear(); }; + void addMode(MinimapModeDef mode); + void addMode(MinimapType type, u16 size = 0, std::string label = "", + std::string texture = "", u16 scale = 1); + + void setModeIndex(size_t index); + size_t getModeIndex() const { return m_current_mode_index; }; + size_t getMaxModeIndex() const { return m_modes.size() - 1; }; + void nextMode(); + + void setModesFromString(std::string modes_string); + MinimapModeDef getModeDef() const { return data->mode; } video::ITexture *getMinimapTexture(); @@ -144,6 +144,7 @@ public: void updateActiveMarkers(); void drawMinimap(); + void drawMinimap(core::rect rect); video::IVideoDriver *driver; Client* client; @@ -153,9 +154,11 @@ private: ITextureSource *m_tsrc; IShaderSource *m_shdrsrc; const NodeDefManager *m_ndef; - MinimapUpdateThread *m_minimap_update_thread; + MinimapUpdateThread *m_minimap_update_thread = nullptr; scene::SMeshBuffer *m_meshbuffer; bool m_enable_shaders; + std::vector m_modes; + size_t m_current_mode_index; u16 m_surface_mode_scan_height; f32 m_angle; std::mutex m_mutex; diff --git a/src/hud.cpp b/src/hud.cpp index 175701342..1791e04df 100644 --- a/src/hud.cpp +++ b/src/hud.cpp @@ -29,6 +29,7 @@ const struct EnumString es_HudElementType[] = {HUD_ELEM_WAYPOINT, "waypoint"}, {HUD_ELEM_IMAGE_WAYPOINT, "image_waypoint"}, {HUD_ELEM_COMPASS, "compass"}, + {HUD_ELEM_MINIMAP, "minimap"}, {0, NULL}, }; diff --git a/src/hud.h b/src/hud.h index 0a6993c1b..a0613ae98 100644 --- a/src/hud.h +++ b/src/hud.h @@ -51,7 +51,6 @@ with this program; if not, write to the Free Software Foundation, Inc., #define HUD_HOTBAR_ITEMCOUNT_DEFAULT 8 #define HUD_HOTBAR_ITEMCOUNT_MAX 32 - #define HOTBAR_IMAGE_SIZE 48 enum HudElementType { @@ -61,7 +60,8 @@ enum HudElementType { HUD_ELEM_INVENTORY = 3, HUD_ELEM_WAYPOINT = 4, HUD_ELEM_IMAGE_WAYPOINT = 5, - HUD_ELEM_COMPASS = 6 + HUD_ELEM_COMPASS = 6, + HUD_ELEM_MINIMAP = 7 }; enum HudElementStat { @@ -108,3 +108,12 @@ extern const EnumString es_HudElementType[]; extern const EnumString es_HudElementStat[]; extern const EnumString es_HudBuiltinElement[]; +// Minimap stuff + +enum MinimapType { + MINIMAP_TYPE_OFF, + MINIMAP_TYPE_SURFACE, + MINIMAP_TYPE_RADAR, + MINIMAP_TYPE_TEXTURE, +}; + diff --git a/src/network/clientopcodes.cpp b/src/network/clientopcodes.cpp index f812a08a1..55cfdd4dc 100644 --- a/src/network/clientopcodes.cpp +++ b/src/network/clientopcodes.cpp @@ -122,6 +122,7 @@ const ToClientCommandHandler toClientCommandTable[TOCLIENT_NUM_MSG_TYPES] = null_command_handler, { "TOCLIENT_SRP_BYTES_S_B", TOCLIENT_STATE_NOT_CONNECTED, &Client::handleCommand_SrpBytesSandB }, // 0x60 { "TOCLIENT_FORMSPEC_PREPEND", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_FormspecPrepend }, // 0x61, + { "TOCLIENT_MINIMAP_MODES", TOCLIENT_STATE_CONNECTED, &Client::handleCommand_MinimapModes }, // 0x62, }; const static ServerCommandFactory null_command_factory = { "TOSERVER_NULL", 0, false }; diff --git a/src/network/clientpackethandler.cpp b/src/network/clientpackethandler.cpp index 5683564a0..65db02300 100644 --- a/src/network/clientpackethandler.cpp +++ b/src/network/clientpackethandler.cpp @@ -1164,15 +1164,24 @@ void Client::handleCommand_HudSetFlags(NetworkPacket* pkt) m_minimap_disabled_by_server = !(player->hud_flags & HUD_FLAG_MINIMAP_VISIBLE); bool m_minimap_radar_disabled_by_server = !(player->hud_flags & HUD_FLAG_MINIMAP_RADAR_VISIBLE); + // Not so satisying code to keep compatibility with old fixed mode system + // --> + // Hide minimap if it has been disabled by the server if (m_minimap && m_minimap_disabled_by_server && was_minimap_visible) // defers a minimap update, therefore only call it if really // needed, by checking that minimap was visible before - m_minimap->setMinimapMode(MINIMAP_MODE_OFF); - - // Switch to surface mode if radar disabled by server - if (m_minimap && m_minimap_radar_disabled_by_server && was_minimap_radar_visible) - m_minimap->setMinimapMode(MINIMAP_MODE_SURFACEx1); + m_minimap->setModeIndex(0); + + // If radar has been disabled, try to find a non radar mode or fall back to 0 + if (m_minimap && m_minimap_radar_disabled_by_server + && was_minimap_radar_visible) { + while (m_minimap->getModeIndex() > 0 && + m_minimap->getModeDef().type == MINIMAP_TYPE_RADAR) + m_minimap->nextMode(); + } + // <-- + // End of 'not so satifying code' } void Client::handleCommand_HudSetParam(NetworkPacket* pkt) @@ -1611,3 +1620,30 @@ void Client::handleCommand_ModChannelSignal(NetworkPacket *pkt) if (valid_signal) m_script->on_modchannel_signal(channel, signal); } + +void Client::handleCommand_MinimapModes(NetworkPacket *pkt) +{ + u16 count; // modes + u16 mode; // wanted current mode index after change + + *pkt >> count >> mode; + + if (m_minimap) + m_minimap->clearModes(); + + for (size_t index = 0; index < count; index++) { + u16 type; + std::string label; + u16 size; + std::string texture; + u16 scale; + + *pkt >> type >> label >> size >> texture >> scale; + + if (m_minimap) + m_minimap->addMode(MinimapType(type), size, label, texture, scale); + } + + if (m_minimap) + m_minimap->setModeIndex(mode); +} diff --git a/src/network/networkprotocol.h b/src/network/networkprotocol.h index 05600cda9..666e75e45 100644 --- a/src/network/networkprotocol.h +++ b/src/network/networkprotocol.h @@ -204,6 +204,7 @@ with this program; if not, write to the Free Software Foundation, Inc., PROTOCOL VERSION 39: Updated set_sky packet Adds new sun, moon and stars packets + Minimap modes */ #define LATEST_PROTOCOL_VERSION 39 @@ -764,7 +765,18 @@ enum ToClientCommand u8[len] formspec */ - TOCLIENT_NUM_MSG_TYPES = 0x62, + TOCLIENT_MINIMAP_MODES = 0x62, + /* + u16 count // modes + u16 mode // wanted current mode index after change + for each mode + u16 type + std::string label + u16 size + std::string extra + */ + + TOCLIENT_NUM_MSG_TYPES = 0x63, }; enum ToServerCommand diff --git a/src/network/serveropcodes.cpp b/src/network/serveropcodes.cpp index 2fc3197c2..aea5d7174 100644 --- a/src/network/serveropcodes.cpp +++ b/src/network/serveropcodes.cpp @@ -221,4 +221,5 @@ const ClientCommandFactory clientCommandFactoryTable[TOCLIENT_NUM_MSG_TYPES] = null_command_factory, // 0x5f { "TOSERVER_SRP_BYTES_S_B", 0, true }, // 0x60 { "TOCLIENT_FORMSPEC_PREPEND", 0, true }, // 0x61 + { "TOCLIENT_MINIMAP_MODES", 0, true }, // 0x62 }; diff --git a/src/script/lua_api/l_minimap.cpp b/src/script/lua_api/l_minimap.cpp index 5fba76eb8..3bbb6e5e3 100644 --- a/src/script/lua_api/l_minimap.cpp +++ b/src/script/lua_api/l_minimap.cpp @@ -89,7 +89,7 @@ int LuaMinimap::l_get_mode(lua_State *L) LuaMinimap *ref = checkobject(L, 1); Minimap *m = getobject(ref); - lua_pushinteger(L, m->getMinimapMode()); + lua_pushinteger(L, m->getModeIndex()); return 1; } @@ -98,13 +98,11 @@ int LuaMinimap::l_set_mode(lua_State *L) LuaMinimap *ref = checkobject(L, 1); Minimap *m = getobject(ref); - s32 mode = lua_tointeger(L, 2); - if (mode < MINIMAP_MODE_OFF || - mode >= MINIMAP_MODE_COUNT) { + u32 mode = lua_tointeger(L, 2); + if (mode >= m->getMaxModeIndex()) return 0; - } - m->setMinimapMode((MinimapMode) mode); + m->setModeIndex(mode); return 1; } @@ -140,8 +138,11 @@ int LuaMinimap::l_show(lua_State *L) LuaMinimap *ref = checkobject(L, 1); Minimap *m = getobject(ref); - if (m->getMinimapMode() == MINIMAP_MODE_OFF) - m->setMinimapMode(MINIMAP_MODE_SURFACEx1); + // This is not very adapted to new minimap mode management. Btw, tried + // to do something compatible. + + if (m->getModeIndex() == 0 && m->getMaxModeIndex() > 0) + m->setModeIndex(1); client->showMinimap(true); return 1; @@ -155,8 +156,11 @@ int LuaMinimap::l_hide(lua_State *L) LuaMinimap *ref = checkobject(L, 1); Minimap *m = getobject(ref); - if (m->getMinimapMode() != MINIMAP_MODE_OFF) - m->setMinimapMode(MINIMAP_MODE_OFF); + // This is not very adapted to new minimap mode management. Btw, tried + // to do something compatible. + + if (m->getModeIndex() != 0) + m->setModeIndex(0); client->showMinimap(false); return 1; diff --git a/src/script/lua_api/l_object.cpp b/src/script/lua_api/l_object.cpp index fead4e849..57ed7e2cd 100644 --- a/src/script/lua_api/l_object.cpp +++ b/src/script/lua_api/l_object.cpp @@ -2199,6 +2199,67 @@ int ObjectRef::l_get_day_night_ratio(lua_State *L) return 1; } +// set_minimap_modes(self, modes, modeindex) +int ObjectRef::l_set_minimap_modes(lua_State *L) +{ + NO_MAP_LOCK_REQUIRED; + + // Arg 1 should be a player + ObjectRef *ref = checkobject(L, 1); + RemotePlayer *player = getplayer(ref); + if (player == NULL) + return 0; + + // Arg 2 should be a table (of tables) + if (!lua_istable(L, 2)) { + return 0; + } + + // Arg 3 should be a number + s16 wantedmode = lua_tonumber(L, 3); + + std::vector modes; + + lua_pushnil(L); + while (lua_next(L, 2) != 0) { + /* key is at index -2, value is at index -1 */ + if (lua_istable(L, -1)) { + bool ok = true; + MinimapMode mode; + std::string type = getstringfield_default(L, -1, "type", ""); + if (type == "off") + mode.type = MINIMAP_TYPE_OFF; + else if (type == "surface") + mode.type = MINIMAP_TYPE_SURFACE; + else if (type == "radar") + mode.type = MINIMAP_TYPE_RADAR; + else if (type == "texture") { + mode.type = MINIMAP_TYPE_TEXTURE; + mode.texture = getstringfield_default(L, -1, "texture", ""); + mode.scale = getintfield_default(L, -1, "scale", 1); + } else { + warningstream << "Minimap mode of unknown type \"" << type.c_str() + << "\" ignored.\n" << std::endl; + ok = false; + } + + if (ok) { + mode.label = getstringfield_default(L, -1, "label", ""); + // Size is limited to 512. Performance gets poor if size too large, and + // segfaults have been experienced. + mode.size = rangelim(getintfield_default(L, -1, "size", 0), 1, 512); + modes.push_back(mode); + } + } + /* removes 'value'; keeps 'key' for next iteration */ + lua_pop(L, 1); + } + lua_pop(L, 1); // Remove key + + getServer(L)->SendMinimapModes(player->getPeerId(), modes, wantedmode); + return 0; +} + ObjectRef::ObjectRef(ServerActiveObject *object): m_object(object) { @@ -2359,5 +2420,6 @@ luaL_Reg ObjectRef::methods[] = { luamethod(ObjectRef, set_eye_offset), luamethod(ObjectRef, get_eye_offset), luamethod(ObjectRef, send_mapblock), + luamethod(ObjectRef, set_minimap_modes), {0,0} }; diff --git a/src/script/lua_api/l_object.h b/src/script/lua_api/l_object.h index 126719b1f..ca03dfa2e 100644 --- a/src/script/lua_api/l_object.h +++ b/src/script/lua_api/l_object.h @@ -377,4 +377,7 @@ private: // send_mapblock(pos) static int l_send_mapblock(lua_State *L); + + // set_minimap_modes(self, modes, wanted_mode) + static int l_set_minimap_modes(lua_State *L); }; diff --git a/src/server.cpp b/src/server.cpp index 982f904f4..8f6257afe 100644 --- a/src/server.cpp +++ b/src/server.cpp @@ -2662,6 +2662,23 @@ void Server::sendRequestedMedia(session_t peer_id, } } +void Server::SendMinimapModes(session_t peer_id, + std::vector &modes, size_t wanted_mode) +{ + RemotePlayer *player = m_env->getPlayer(peer_id); + assert(player); + if (player->getPeerId() == PEER_ID_INEXISTENT) + return; + + NetworkPacket pkt(TOCLIENT_MINIMAP_MODES, 0, peer_id); + pkt << (u16)modes.size() << (u16)wanted_mode; + + for (auto &mode : modes) + pkt << (u16)mode.type << mode.label << mode.size << mode.texture << mode.scale; + + Send(&pkt); +} + void Server::sendDetachedInventory(Inventory *inventory, const std::string &name, session_t peer_id) { NetworkPacket pkt(TOCLIENT_DETACHED_INVENTORY, 0, peer_id); diff --git a/src/server.h b/src/server.h index 258d75eaf..4b3ac5cf7 100644 --- a/src/server.h +++ b/src/server.h @@ -118,6 +118,14 @@ struct ServerPlayingSound std::unordered_set clients; // peer ids }; +struct MinimapMode { + MinimapType type = MINIMAP_TYPE_OFF; + std::string label; + u16 size = 0; + std::string texture; + u16 scale = 1; +}; + class Server : public con::PeerHandler, public MapEventReceiver, public IGameDef { @@ -331,6 +339,10 @@ public: void SendPlayerSpeed(session_t peer_id, const v3f &added_vel); void SendPlayerFov(session_t peer_id); + void SendMinimapModes(session_t peer_id, + std::vector &modes, + size_t wanted_mode); + void sendDetachedInventories(session_t peer_id, bool incremental); virtual bool registerModStorage(ModMetadata *storage); -- cgit v1.2.3 From 2341a4aff1242e978d6fad3772d4d4fb015c040d Mon Sep 17 00:00:00 2001 From: Zughy <63455151+Zughy@users.noreply.github.com> Date: Tue, 13 Oct 2020 21:27:52 +0200 Subject: Add ObjectRef:get_children() (#10480) Co-authored-by: Zughy <4279489-marco_a@users.noreply.gitlab.com> --- doc/lua_api.txt | 2 ++ src/script/lua_api/l_object.cpp | 22 ++++++++++++++++++++++ src/script/lua_api/l_object.h | 3 +++ 3 files changed, 27 insertions(+) (limited to 'src/script/lua_api/l_object.cpp') diff --git a/doc/lua_api.txt b/doc/lua_api.txt index c8b294149..1631d564c 100644 --- a/doc/lua_api.txt +++ b/doc/lua_api.txt @@ -6206,6 +6206,8 @@ object you are working with still exists. should appear in first person. * `get_attach()`: returns parent, bone, position, rotation, forced_visible, or nil if it isn't attached. +* `get_children()`: returns a list of ObjectRefs that are attached to the + object. * `set_detach()` * `set_bone_position(bone, position, rotation)` * `bone`: string diff --git a/src/script/lua_api/l_object.cpp b/src/script/lua_api/l_object.cpp index 57ed7e2cd..96c8c687c 100644 --- a/src/script/lua_api/l_object.cpp +++ b/src/script/lua_api/l_object.cpp @@ -738,6 +738,27 @@ int ObjectRef::l_get_attach(lua_State *L) return 5; } +// get_children(self) +int ObjectRef::l_get_children(lua_State *L) +{ + GET_ENV_PTR; + + ObjectRef *ref = checkobject(L, 1); + ServerActiveObject *sao = getobject(ref); + if (sao == nullptr) + return 0; + + const std::unordered_set child_ids = sao->getAttachmentChildIds(); + int i = 0; + lua_createtable(L, child_ids.size(), 0); + for (const int id : child_ids) { + ServerActiveObject *child = env->getActiveObject(id); + getScriptApiBase(L)->objectrefGetOrCreate(L, child); + lua_rawseti(L, -2, ++i); + } + return 1; +} + // set_detach(self) int ObjectRef::l_set_detach(lua_State *L) { @@ -2337,6 +2358,7 @@ luaL_Reg ObjectRef::methods[] = { luamethod(ObjectRef, get_bone_position), luamethod(ObjectRef, set_attach), luamethod(ObjectRef, get_attach), + luamethod(ObjectRef, get_children), luamethod(ObjectRef, set_detach), luamethod(ObjectRef, set_properties), luamethod(ObjectRef, get_properties), diff --git a/src/script/lua_api/l_object.h b/src/script/lua_api/l_object.h index ca03dfa2e..097a74cae 100644 --- a/src/script/lua_api/l_object.h +++ b/src/script/lua_api/l_object.h @@ -143,6 +143,9 @@ private: // get_attach(self) static int l_get_attach(lua_State *L); + // get_children(self) + static int l_get_children(lua_State *L); + // set_detach(self) static int l_set_detach(lua_State *L); -- cgit v1.2.3 From 33b2c5f5b1c565171296f26395d803b08f4575e9 Mon Sep 17 00:00:00 2001 From: Zughy <63455151+Zughy@users.noreply.github.com> Date: Thu, 22 Oct 2020 17:18:01 +0200 Subject: Clean up l_object.cpp (#10512) Co-authored-by: Zughy <4279489-marco_a@users.noreply.gitlab.com> --- doc/lua_api.txt | 48 +- src/script/lua_api/l_object.cpp | 1163 +++++++++++++++++++-------------------- src/script/lua_api/l_object.h | 56 +- 3 files changed, 602 insertions(+), 665 deletions(-) (limited to 'src/script/lua_api/l_object.cpp') diff --git a/doc/lua_api.txt b/doc/lua_api.txt index 9a46c7b57..daf0da3d2 100644 --- a/doc/lua_api.txt +++ b/doc/lua_api.txt @@ -6217,18 +6217,18 @@ object you are working with still exists. * `rot` is a vector (radians). X is pitch (elevation), Y is yaw (heading) and Z is roll (bank). * `get_rotation()`: returns the rotation, a vector (radians) -* `set_yaw(radians)`: sets the yaw (heading). +* `set_yaw(yaw)`: sets the yaw in radians (heading). * `get_yaw()`: returns number in radians * `set_texture_mod(mod)` * Set a texture modifier to the base texture, for sprites and meshes. * When calling `set_texture_mod` again, the previous one is discarded. * `mod` the texture modifier. See [Texture modifiers]. * `get_texture_mod()` returns current texture modifier -* `set_sprite(p, num_frames, framelength, select_x_by_camera)` +* `set_sprite(start_frame, num_frames, framelength, select_x_by_camera)` * Specifies and starts a sprite animation * Animations iterate along the frame `y` position. - * `p`: {x=column number, y=row number}, the coordinate of the first frame - default: `{x=0, y=0}` + * `start_frame`: {x=column number, y=row number}, the coordinate of the + first frame, default: `{x=0, y=0}` * `num_frames`: Total frames in the texture, default: `1` * `framelength`: Time per animated frame in seconds, default: `0.2` * `select_x_by_camera`: Only for visual = `sprite`. Changes the frame `x` @@ -6391,8 +6391,8 @@ object you are working with still exists. nodes square) * `selected_mode` is the mode index to be selected after modes have been changed (0 is the first mode). -* `set_sky(parameters)` - * `parameters` is a table with the following optional fields: +* `set_sky(sky_parameters)` + * `sky_parameters` is a table with the following optional fields: * `base_color`: ColorSpec, changes fog in "skybox" and "plain". * `type`: Available types: * `"regular"`: Uses 0 textures, `base_color` ignored @@ -6436,8 +6436,8 @@ object you are working with still exists. * `get_sky()`: returns base_color, type, table of textures, clouds. * `get_sky_color()`: returns a table with the `sky_color` parameters as in `set_sky`. -* `set_sun(parameters)`: - * `parameters` is a table with the following optional fields: +* `set_sun(sun_parameters)`: + * `sun_parameters` is a table with the following optional fields: * `visible`: Boolean for whether the sun is visible. (default: `true`) * `texture`: A regular texture for the sun. Setting to `""` @@ -6451,8 +6451,8 @@ object you are working with still exists. * `scale`: Float controlling the overall size of the sun. (default: `1`) * `get_sun()`: returns a table with the current sun parameters as in `set_sun`. -* `set_moon(parameters)`: - * `parameters` is a table with the following optional fields: +* `set_moon(moon_parameters)`: + * `moon_parameters` is a table with the following optional fields: * `visible`: Boolean for whether the moon is visible. (default: `true`) * `texture`: A regular texture for the moon. Setting to `""` @@ -6462,8 +6462,8 @@ object you are working with still exists. * `scale`: Float controlling the overall size of the moon (default: `1`) * `get_moon()`: returns a table with the current moon parameters as in `set_moon`. -* `set_stars(parameters)`: - * `parameters` is a table with the following optional fields: +* `set_stars(star_parameters)`: + * `star_parameters` is a table with the following optional fields: * `visible`: Boolean for whether the stars are visible. (default: `true`) * `count`: Integer number to set the number of stars in @@ -6475,8 +6475,8 @@ object you are working with still exists. * `scale`: Float controlling the overall size of the stars (default: `1`) * `get_stars()`: returns a table with the current stars parameters as in `set_stars`. -* `set_clouds(parameters)`: set cloud parameters - * `parameters` is a table with the following optional fields: +* `set_clouds(cloud_parameters)`: set cloud parameters + * `cloud_parameters` is a table with the following optional fields: * `density`: from `0` (no clouds) to `1` (full clouds) (default `0.4`) * `color`: basic cloud color with alpha channel, ColorSpec (default `#fff0f0e5`). @@ -6494,21 +6494,17 @@ object you are working with still exists. amount. * `nil`: Disables override, defaulting to sunlight based on day-night cycle * `get_day_night_ratio()`: returns the ratio or nil if it isn't overridden -* `set_local_animation(stand/idle, walk, dig, walk+dig, frame_speed=frame_speed)`: - set animation for player model in third person view - - set_local_animation({x=0, y=79}, -- stand/idle animation key frames - {x=168, y=187}, -- walk animation key frames - {x=189, y=198}, -- dig animation key frames - {x=200, y=219}, -- walk+dig animation key frames - frame_speed=30) -- animation frame speed -* `get_local_animation()`: returns stand, walk, dig, dig+walk tables and +* `set_local_animation(idle, walk, dig, walk_while_dig, frame_speed)`: + set animation for player model in third person view. + * Every animation equals to a `{x=starting frame, y=ending frame}` table. + * `frame_speed` sets the animations frame speed. Default is 30. +* `get_local_animation()`: returns idle, walk, dig, walk_while_dig tables and `frame_speed`. -* `set_eye_offset({x=0,y=0,z=0},{x=0,y=0,z=0})`: defines offset value for - camera per player. +* `set_eye_offset(firstperson, thirdperson)`: defines offset vectors for camera + per player. * in first person view * in third person view (max. values `{x=-10/10,y=-10,15,z=-5/5}`) -* `get_eye_offset()`: returns `offset_first` and `offset_third` +* `get_eye_offset()`: returns first and third person offsets. * `send_mapblock(blockpos)`: * Sends a server-side loaded mapblock to the player. * Returns `false` if failed. diff --git a/src/script/lua_api/l_object.cpp b/src/script/lua_api/l_object.cpp index 96c8c687c..c3f0ec8e0 100644 --- a/src/script/lua_api/l_object.cpp +++ b/src/script/lua_api/l_object.cpp @@ -44,43 +44,44 @@ ObjectRef* ObjectRef::checkobject(lua_State *L, int narg) { luaL_checktype(L, narg, LUA_TUSERDATA); void *ud = luaL_checkudata(L, narg, className); - if (!ud) luaL_typerror(L, narg, className); + if (ud == nullptr) + luaL_typerror(L, narg, className); return *(ObjectRef**)ud; // unbox pointer } ServerActiveObject* ObjectRef::getobject(ObjectRef *ref) { - ServerActiveObject *co = ref->m_object; - if (co && co->isGone()) - return NULL; - return co; + ServerActiveObject *sao = ref->m_object; + if (sao && sao->isGone()) + return nullptr; + return sao; } LuaEntitySAO* ObjectRef::getluaobject(ObjectRef *ref) { - ServerActiveObject *obj = getobject(ref); - if (obj == NULL) - return NULL; - if (obj->getType() != ACTIVEOBJECT_TYPE_LUAENTITY) - return NULL; - return (LuaEntitySAO*)obj; + ServerActiveObject *sao = getobject(ref); + if (sao == nullptr) + return nullptr; + if (sao->getType() != ACTIVEOBJECT_TYPE_LUAENTITY) + return nullptr; + return (LuaEntitySAO*)sao; } PlayerSAO* ObjectRef::getplayersao(ObjectRef *ref) { - ServerActiveObject *obj = getobject(ref); - if (obj == NULL) - return NULL; - if (obj->getType() != ACTIVEOBJECT_TYPE_PLAYER) - return NULL; - return (PlayerSAO*)obj; + ServerActiveObject *sao = getobject(ref); + if (sao == nullptr) + return nullptr; + if (sao->getType() != ACTIVEOBJECT_TYPE_PLAYER) + return nullptr; + return (PlayerSAO*)sao; } RemotePlayer *ObjectRef::getplayer(ObjectRef *ref) { PlayerSAO *playersao = getplayersao(ref); - if (playersao == NULL) - return NULL; + if (playersao == nullptr) + return nullptr; return playersao->getPlayer(); } @@ -88,9 +89,8 @@ RemotePlayer *ObjectRef::getplayer(ObjectRef *ref) // garbage collector int ObjectRef::gc_object(lua_State *L) { - ObjectRef *o = *(ObjectRef **)(lua_touserdata(L, 1)); - //infostream<<"ObjectRef::gc_object: o="<getType() == ACTIVEOBJECT_TYPE_PLAYER) + if (sao->getType() == ACTIVEOBJECT_TYPE_PLAYER) return 0; - co->clearChildAttachments(); - co->clearParentAttachment(); + sao->clearChildAttachments(); + sao->clearParentAttachment(); - verbosestream << "ObjectRef::l_remove(): id=" << co->getId() << std::endl; - co->m_pending_removal = true; + verbosestream << "ObjectRef::l_remove(): id=" << sao->getId() << std::endl; + sao->m_pending_removal = true; return 0; } // get_pos(self) -// returns: {x=num, y=num, z=num} int ObjectRef::l_get_pos(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - ServerActiveObject *co = getobject(ref); - if (co == NULL) return 0; - push_v3f(L, co->getBasePosition() / BS); + ServerActiveObject *sao = getobject(ref); + if (sao == nullptr) + return 0; + + push_v3f(L, sao->getBasePosition() / BS); return 1; } @@ -131,28 +132,29 @@ int ObjectRef::l_set_pos(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - ServerActiveObject *co = getobject(ref); - if (co == NULL) return 0; - // pos + ServerActiveObject *sao = getobject(ref); + if (sao == nullptr) + return 0; + v3f pos = checkFloatPos(L, 2); - // Do it - co->setPos(pos); + + sao->setPos(pos); return 0; } -// move_to(self, pos, continuous=false) +// move_to(self, pos, continuous) int ObjectRef::l_move_to(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - ServerActiveObject *co = getobject(ref); - if (co == NULL) return 0; - // pos + ServerActiveObject *sao = getobject(ref); + if (sao == nullptr) + return 0; + v3f pos = checkFloatPos(L, 2); - // continuous bool continuous = readParam(L, 3); - // Do it - co->moveTo(pos, continuous); + + sao->moveTo(pos, continuous); return 0; } @@ -162,32 +164,28 @@ int ObjectRef::l_punch(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); ObjectRef *puncher_ref = checkobject(L, 2); - ServerActiveObject *co = getobject(ref); + ServerActiveObject *sao = getobject(ref); ServerActiveObject *puncher = getobject(puncher_ref); - if (!co || !puncher) + if (sao == nullptr || puncher == nullptr) return 0; - v3f dir; - if (lua_type(L, 5) != LUA_TTABLE) - dir = co->getBasePosition() - puncher->getBasePosition(); - else - dir = read_v3f(L, 5); - float time_from_last_punch = 1000000; - if (lua_isnumber(L, 3)) - time_from_last_punch = lua_tonumber(L, 3); + + float time_from_last_punch = lua_isnil(L, 3) ? + 1000000.0f : readParam(L,3); ToolCapabilities toolcap = read_tool_capabilities(L, 4); - dir.normalize(); + v3f dir = lua_isnil(L, 5) ? + sao->getBasePosition() - puncher->getBasePosition() : check_v3f(L, 5); - u16 src_original_hp = co->getHP(); + dir.normalize(); + u16 src_original_hp = sao->getHP(); u16 dst_origin_hp = puncher->getHP(); - // Do it - u16 wear = co->punch(dir, &toolcap, puncher, time_from_last_punch); + u16 wear = sao->punch(dir, &toolcap, puncher, time_from_last_punch); lua_pushnumber(L, wear); // If the punched is a player, and its HP changed - if (src_original_hp != co->getHP() && - co->getType() == ACTIVEOBJECT_TYPE_PLAYER) { - getServer(L)->SendPlayerHPOrDie((PlayerSAO *)co, + if (src_original_hp != sao->getHP() && + sao->getType() == ACTIVEOBJECT_TYPE_PLAYER) { + getServer(L)->SendPlayerHPOrDie((PlayerSAO *)sao, PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, puncher)); } @@ -195,45 +193,38 @@ int ObjectRef::l_punch(lua_State *L) if (dst_origin_hp != puncher->getHP() && puncher->getType() == ACTIVEOBJECT_TYPE_PLAYER) { getServer(L)->SendPlayerHPOrDie((PlayerSAO *)puncher, - PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, co)); + PlayerHPChangeReason(PlayerHPChangeReason::PLAYER_PUNCH, sao)); } return 1; } -// right_click(self, clicker); clicker = an another ObjectRef +// right_click(self, clicker) int ObjectRef::l_right_click(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); ObjectRef *ref2 = checkobject(L, 2); - ServerActiveObject *co = getobject(ref); - ServerActiveObject *co2 = getobject(ref2); - if (co == NULL) return 0; - if (co2 == NULL) return 0; - // Do it - co->rightClick(co2); + ServerActiveObject *sao = getobject(ref); + ServerActiveObject *sao2 = getobject(ref2); + if (sao == nullptr || sao2 == nullptr) + return 0; + + sao->rightClick(sao2); return 0; } -// set_hp(self, hp) -// hp = number of hitpoints (2 * number of hearts) -// returns: nil +// set_hp(self, hp, reason) int ObjectRef::l_set_hp(lua_State *L) { NO_MAP_LOCK_REQUIRED; - - // Get Object ObjectRef *ref = checkobject(L, 1); - luaL_checknumber(L, 2); - ServerActiveObject *co = getobject(ref); - if (co == NULL) + ServerActiveObject *sao = getobject(ref); + if (sao == nullptr) return 0; - // Get HP - int hp = lua_tonumber(L, 2); - - // Get Reason + int hp = readParam(L, 2); PlayerHPChangeReason reason(PlayerHPChangeReason::SET_HP); + reason.from_mod = true; if (lua_istable(L, 3)) { lua_pushvalue(L, 3); @@ -248,35 +239,28 @@ int ObjectRef::l_set_hp(lua_State *L) reason.lua_reference = luaL_ref(L, LUA_REGISTRYINDEX); } - // Do it - co->setHP(hp, reason); - if (co->getType() == ACTIVEOBJECT_TYPE_PLAYER) - getServer(L)->SendPlayerHPOrDie((PlayerSAO *)co, reason); - + sao->setHP(hp, reason); + if (sao->getType() == ACTIVEOBJECT_TYPE_PLAYER) + getServer(L)->SendPlayerHPOrDie((PlayerSAO *)sao, reason); if (reason.hasLuaReference()) luaL_unref(L, LUA_REGISTRYINDEX, reason.lua_reference); - - // Return return 0; } // get_hp(self) -// returns: number of hitpoints (2 * number of hearts) -// 0 if not applicable to this type of object int ObjectRef::l_get_hp(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - ServerActiveObject *co = getobject(ref); - if (co == NULL) { + ServerActiveObject *sao = getobject(ref); + if (sao == nullptr) { // Default hp is 1 lua_pushnumber(L, 1); return 1; } - int hp = co->getHP(); - /*infostream<<"ObjectRef::l_get_hp(): id="<getId() - <<" hp="<getHP(); + lua_pushnumber(L, hp); return 1; } @@ -286,11 +270,12 @@ int ObjectRef::l_get_inventory(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - ServerActiveObject *co = getobject(ref); - if (co == NULL) return 0; - // Do it - InventoryLocation loc = co->getInventoryLocation(); - if (getServerInventoryMgr(L)->getInventory(loc) != NULL) + ServerActiveObject *sao = getobject(ref); + if (sao == nullptr) + return 0; + + InventoryLocation loc = sao->getInventoryLocation(); + if (getServerInventoryMgr(L)->getInventory(loc) != nullptr) InvRef::create(L, loc); else lua_pushnil(L); // An object may have no inventory (nil) @@ -302,11 +287,11 @@ int ObjectRef::l_get_wield_list(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - ServerActiveObject *co = getobject(ref); - if (!co) + ServerActiveObject *sao = getobject(ref); + if (sao == nullptr) return 0; - lua_pushstring(L, co->getWieldList().c_str()); + lua_pushstring(L, sao->getWieldList().c_str()); return 1; } @@ -315,11 +300,11 @@ int ObjectRef::l_get_wield_index(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - ServerActiveObject *co = getobject(ref); - if (!co) + ServerActiveObject *sao = getobject(ref); + if (sao == nullptr) return 0; - lua_pushinteger(L, co->getWieldIndex() + 1); + lua_pushinteger(L, sao->getWieldIndex() + 1); return 1; } @@ -328,31 +313,33 @@ int ObjectRef::l_get_wielded_item(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - ServerActiveObject *co = getobject(ref); - if (!co) { + ServerActiveObject *sao = getobject(ref); + if (sao == nullptr) { // Empty ItemStack LuaItemStack::create(L, ItemStack()); return 1; } ItemStack selected_item; - co->getWieldedItem(&selected_item, nullptr); + sao->getWieldedItem(&selected_item, nullptr); LuaItemStack::create(L, selected_item); return 1; } -// set_wielded_item(self, itemstack or itemstring or table or nil) +// set_wielded_item(self, item) int ObjectRef::l_set_wielded_item(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - ServerActiveObject *co = getobject(ref); - if (co == NULL) return 0; - // Do it + ServerActiveObject *sao = getobject(ref); + if (sao == nullptr) + return 0; + ItemStack item = read_item(L, 2, getServer(L)->idef()); - bool success = co->setWieldedItem(item); - if (success && co->getType() == ACTIVEOBJECT_TYPE_PLAYER) { - getServer(L)->SendInventory((PlayerSAO *)co, true); + + bool success = sao->setWieldedItem(item); + if (success && sao->getType() == ACTIVEOBJECT_TYPE_PLAYER) { + getServer(L)->SendInventory((PlayerSAO *)sao, true); } lua_pushboolean(L, success); return 1; @@ -363,12 +350,14 @@ int ObjectRef::l_set_armor_groups(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - ServerActiveObject *co = getobject(ref); - if (co == NULL) return 0; - // Do it + ServerActiveObject *sao = getobject(ref); + if (sao == nullptr) + return 0; + ItemGroupList groups; + read_groups(L, 2, groups); - co->setArmorGroups(groups); + sao->setArmorGroups(groups); return 0; } @@ -377,77 +366,11 @@ int ObjectRef::l_get_armor_groups(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - ServerActiveObject *co = getobject(ref); - if (co == NULL) + ServerActiveObject *sao = getobject(ref); + if (sao == nullptr) return 0; - // Do it - push_groups(L, co->getArmorGroups()); - return 1; -} -// set_physics_override(self, physics_override_speed, physics_override_jump, -// physics_override_gravity, sneak, sneak_glitch, new_move) -int ObjectRef::l_set_physics_override(lua_State *L) -{ - NO_MAP_LOCK_REQUIRED; - ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = (PlayerSAO *) getobject(ref); - if (co == NULL) return 0; - // Do it - if (lua_istable(L, 2)) { - co->m_physics_override_speed = getfloatfield_default( - L, 2, "speed", co->m_physics_override_speed); - co->m_physics_override_jump = getfloatfield_default( - L, 2, "jump", co->m_physics_override_jump); - co->m_physics_override_gravity = getfloatfield_default( - L, 2, "gravity", co->m_physics_override_gravity); - co->m_physics_override_sneak = getboolfield_default( - L, 2, "sneak", co->m_physics_override_sneak); - co->m_physics_override_sneak_glitch = getboolfield_default( - L, 2, "sneak_glitch", co->m_physics_override_sneak_glitch); - co->m_physics_override_new_move = getboolfield_default( - L, 2, "new_move", co->m_physics_override_new_move); - co->m_physics_override_sent = false; - } else { - // old, non-table format - if (!lua_isnil(L, 2)) { - co->m_physics_override_speed = lua_tonumber(L, 2); - co->m_physics_override_sent = false; - } - if (!lua_isnil(L, 3)) { - co->m_physics_override_jump = lua_tonumber(L, 3); - co->m_physics_override_sent = false; - } - if (!lua_isnil(L, 4)) { - co->m_physics_override_gravity = lua_tonumber(L, 4); - co->m_physics_override_sent = false; - } - } - return 0; -} - -// get_physics_override(self) -int ObjectRef::l_get_physics_override(lua_State *L) -{ - NO_MAP_LOCK_REQUIRED; - ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = (PlayerSAO *)getobject(ref); - if (co == NULL) - return 0; - // Do it - lua_newtable(L); - lua_pushnumber(L, co->m_physics_override_speed); - lua_setfield(L, -2, "speed"); - lua_pushnumber(L, co->m_physics_override_jump); - lua_setfield(L, -2, "jump"); - lua_pushnumber(L, co->m_physics_override_gravity); - lua_setfield(L, -2, "gravity"); - lua_pushboolean(L, co->m_physics_override_sneak); - lua_setfield(L, -2, "sneak"); - lua_pushboolean(L, co->m_physics_override_sneak_glitch); - lua_setfield(L, -2, "sneak_glitch"); - lua_pushboolean(L, co->m_physics_override_new_move); - lua_setfield(L, -2, "new_move"); + push_groups(L, sao->getArmorGroups()); return 1; } @@ -456,9 +379,10 @@ int ObjectRef::l_set_animation(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - ServerActiveObject *co = getobject(ref); - if (co == NULL) return 0; - // Do it + ServerActiveObject *sao = getobject(ref); + if (sao == nullptr) + return 0; + v2f frames = v2f(1, 1); if (!lua_isnil(L, 2)) frames = readParam(L, 2); @@ -471,7 +395,8 @@ int ObjectRef::l_set_animation(lua_State *L) bool frame_loop = true; if (lua_isboolean(L, 5)) frame_loop = readParam(L, 5); - co->setAnimation(frames, frame_speed, frame_blend, frame_loop); + + sao->setAnimation(frames, frame_speed, frame_blend, frame_loop); return 0; } @@ -480,16 +405,16 @@ int ObjectRef::l_get_animation(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - ServerActiveObject *co = getobject(ref); - if (co == NULL) + ServerActiveObject *sao = getobject(ref); + if (sao == nullptr) return 0; - // Do it + v2f frames = v2f(1,1); float frame_speed = 15; float frame_blend = 0; bool frame_loop = true; - co->getAnimation(&frames, &frame_speed, &frame_blend, &frame_loop); + sao->getAnimation(&frames, &frame_speed, &frame_blend, &frame_loop); push_v2f(L, frames); lua_pushnumber(L, frame_speed); lua_pushnumber(L, frame_blend); @@ -497,23 +422,21 @@ int ObjectRef::l_get_animation(lua_State *L) return 4; } -// set_local_animation(self, {stand/idle}, {walk}, {dig}, {walk+dig}, frame_speed) +// set_local_animation(self, idle, walk, dig, walk_while_dig, frame_speed) int ObjectRef::l_set_local_animation(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (player == NULL) + if (player == nullptr) return 0; - // Do it + v2s32 frames[4]; for (int i=0;i<4;i++) { if (!lua_isnil(L, 2+1)) frames[i] = read_v2s32(L, 2+i); } - float frame_speed = 30; - if (!lua_isnil(L, 6)) - frame_speed = lua_tonumber(L, 6); + float frame_speed = lua_isnil(L, 6) ? 30 : readParam(L, 6); getServer(L)->setLocalPlayerAnimations(player, frames, frame_speed); lua_pushboolean(L, true); @@ -526,7 +449,7 @@ int ObjectRef::l_get_local_animation(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (player == NULL) + if (player == nullptr) return 0; v2s32 frames[4]; @@ -541,27 +464,22 @@ int ObjectRef::l_get_local_animation(lua_State *L) return 5; } -// set_eye_offset(self, v3f first pv, v3f third pv) +// set_eye_offset(self, firstperson, thirdperson) int ObjectRef::l_set_eye_offset(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (player == NULL) + if (player == nullptr) return 0; - // Do it - v3f offset_first = v3f(0, 0, 0); - v3f offset_third = v3f(0, 0, 0); - if (!lua_isnil(L, 2)) - offset_first = read_v3f(L, 2); - if (!lua_isnil(L, 3)) - offset_third = read_v3f(L, 3); + v3f offset_first = read_v3f(L, 2); + v3f offset_third = read_v3f(L, 3); // Prevent abuse of offset values (keep player always visible) offset_third.X = rangelim(offset_third.X,-10,10); offset_third.Z = rangelim(offset_third.Z,-5,5); - /* TODO: if possible: improve the camera colision detetion to allow Y <= -1.5) */ + /* TODO: if possible: improve the camera collision detection to allow Y <= -1.5) */ offset_third.Y = rangelim(offset_third.Y,-10,15); //1.5*BS getServer(L)->setPlayerEyeOffset(player, offset_first, offset_third); @@ -575,9 +493,9 @@ int ObjectRef::l_get_eye_offset(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (player == NULL) + if (player == nullptr) return 0; - // Do it + push_v3f(L, player->eye_offset_first); push_v3f(L, player->eye_offset_third); return 2; @@ -588,14 +506,14 @@ int ObjectRef::l_send_mapblock(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - RemotePlayer *player = getplayer(ref); - if (!player) + if (player == nullptr) return 0; - v3s16 p = read_v3s16(L, 2); + + v3s16 pos = read_v3s16(L, 2); session_t peer_id = player->getPeerId(); - bool r = getServer(L)->SendBlock(peer_id, p); + bool r = getServer(L)->SendBlock(peer_id, pos); lua_pushboolean(L, r); return 1; @@ -606,14 +524,13 @@ int ObjectRef::l_set_animation_frame_speed(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - ServerActiveObject *co = getobject(ref); - if (co == NULL) + ServerActiveObject *sao = getobject(ref); + if (sao == nullptr) return 0; - // Do it if (!lua_isnil(L, 2)) { - float frame_speed = lua_tonumber(L, 2); - co->setAnimationSpeed(frame_speed); + float frame_speed = readParam(L, 2); + sao->setAnimationSpeed(frame_speed); lua_pushboolean(L, true); } else { lua_pushboolean(L, false); @@ -621,24 +538,20 @@ int ObjectRef::l_set_animation_frame_speed(lua_State *L) return 1; } -// set_bone_position(self, std::string bone, v3f position, v3f rotation) +// set_bone_position(self, bone, position, rotation) int ObjectRef::l_set_bone_position(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - ServerActiveObject *co = getobject(ref); - if (co == NULL) return 0; - // Do it - std::string bone; - if (!lua_isnil(L, 2)) - bone = readParam(L, 2); - v3f position = v3f(0, 0, 0); - if (!lua_isnil(L, 3)) - position = check_v3f(L, 3); - v3f rotation = v3f(0, 0, 0); - if (!lua_isnil(L, 4)) - rotation = check_v3f(L, 4); - co->setBonePosition(bone, position, rotation); + ServerActiveObject *sao = getobject(ref); + if (sao == nullptr) + return 0; + + std::string bone = readParam(L, 2); + v3f position = check_v3f(L, 3); + v3f rotation = check_v3f(L, 4); + + sao->setBonePosition(bone, position, rotation); return 0; } @@ -647,17 +560,15 @@ int ObjectRef::l_get_bone_position(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - ServerActiveObject *co = getobject(ref); - if (co == NULL) + ServerActiveObject *sao = getobject(ref); + if (sao == nullptr) return 0; - // Do it - std::string bone; - if (!lua_isnil(L, 2)) - bone = readParam(L, 2); + + std::string bone = readParam(L, 2); v3f position = v3f(0, 0, 0); v3f rotation = v3f(0, 0, 0); - co->getBonePosition(bone, &position, &rotation); + sao->getBonePosition(bone, &position, &rotation); push_v3f(L, position); push_v3f(L, rotation); @@ -668,44 +579,34 @@ int ObjectRef::l_get_bone_position(lua_State *L) int ObjectRef::l_set_attach(lua_State *L) { GET_ENV_PTR; - ObjectRef *ref = checkobject(L, 1); ObjectRef *parent_ref = checkobject(L, 2); - ServerActiveObject *co = getobject(ref); + ServerActiveObject *sao = getobject(ref); ServerActiveObject *parent = getobject(parent_ref); - if (co == NULL) + if (sao == nullptr || parent == nullptr) return 0; - - if (parent == NULL) - return 0; - - if (co == parent) + if (sao == parent) throw LuaError("ObjectRef::set_attach: attaching object to itself is not allowed."); - // Do it int parent_id = 0; std::string bone; v3f position = v3f(0, 0, 0); v3f rotation = v3f(0, 0, 0); bool force_visible; - co->getAttachment(&parent_id, &bone, &position, &rotation, &force_visible); + + sao->getAttachment(&parent_id, &bone, &position, &rotation, &force_visible); if (parent_id) { ServerActiveObject *old_parent = env->getActiveObject(parent_id); - old_parent->removeAttachmentChild(co->getId()); + old_parent->removeAttachmentChild(sao->getId()); } - bone = ""; - if (!lua_isnil(L, 3)) - bone = readParam(L, 3); - position = v3f(0, 0, 0); - if (!lua_isnil(L, 4)) - position = read_v3f(L, 4); - rotation = v3f(0, 0, 0); - if (!lua_isnil(L, 5)) - rotation = read_v3f(L, 5); + bone = readParam(L, 3, ""); + position = read_v3f(L, 4); + rotation = read_v3f(L, 5); force_visible = readParam(L, 6, false); - co->setAttachment(parent->getId(), bone, position, rotation, force_visible); - parent->addAttachmentChild(co->getId()); + + sao->setAttachment(parent->getId(), bone, position, rotation, force_visible); + parent->addAttachmentChild(sao->getId()); return 0; } @@ -713,23 +614,22 @@ int ObjectRef::l_set_attach(lua_State *L) int ObjectRef::l_get_attach(lua_State *L) { GET_ENV_PTR; - ObjectRef *ref = checkobject(L, 1); - ServerActiveObject *co = getobject(ref); - if (co == NULL) + ServerActiveObject *sao = getobject(ref); + if (sao == nullptr) return 0; - // Do it int parent_id = 0; std::string bone; v3f position = v3f(0, 0, 0); v3f rotation = v3f(0, 0, 0); bool force_visible; - co->getAttachment(&parent_id, &bone, &position, &rotation, &force_visible); - if (!parent_id) + + sao->getAttachment(&parent_id, &bone, &position, &rotation, &force_visible); + if (parent_id == 0) return 0; - ServerActiveObject *parent = env->getActiveObject(parent_id); + ServerActiveObject *parent = env->getActiveObject(parent_id); getScriptApiBase(L)->objectrefGetOrCreate(L, parent); lua_pushlstring(L, bone.c_str(), bone.size()); push_v3f(L, position); @@ -742,7 +642,6 @@ int ObjectRef::l_get_attach(lua_State *L) int ObjectRef::l_get_children(lua_State *L) { GET_ENV_PTR; - ObjectRef *ref = checkobject(L, 1); ServerActiveObject *sao = getobject(ref); if (sao == nullptr) @@ -750,6 +649,7 @@ int ObjectRef::l_get_children(lua_State *L) const std::unordered_set child_ids = sao->getAttachmentChildIds(); int i = 0; + lua_createtable(L, child_ids.size(), 0); for (const int id : child_ids) { ServerActiveObject *child = env->getActiveObject(id); @@ -763,13 +663,12 @@ int ObjectRef::l_get_children(lua_State *L) int ObjectRef::l_set_detach(lua_State *L) { GET_ENV_PTR; - ObjectRef *ref = checkobject(L, 1); - ServerActiveObject *co = getobject(ref); - if (co == NULL) + ServerActiveObject *sao = getobject(ref); + if (sao == nullptr) return 0; - co->clearParentAttachment(); + sao->clearParentAttachment(); return 0; } @@ -778,16 +677,16 @@ int ObjectRef::l_set_properties(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - ServerActiveObject *co = getobject(ref); - if (!co) + ServerActiveObject *sao = getobject(ref); + if (sao == nullptr) return 0; - ObjectProperties *prop = co->accessObjectProperties(); - if (!prop) + ObjectProperties *prop = sao->accessObjectProperties(); + if (prop == nullptr) return 0; - read_object_properties(L, 2, co, prop, getServer(L)->idef()); - co->notifyObjectPropertiesModified(); + read_object_properties(L, 2, sao, prop, getServer(L)->idef()); + sao->notifyObjectPropertiesModified(); return 0; } @@ -796,12 +695,14 @@ int ObjectRef::l_get_properties(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - ServerActiveObject *co = getobject(ref); - if (co == NULL) + ServerActiveObject *sao = getobject(ref); + if (sao == nullptr) return 0; - ObjectProperties *prop = co->accessObjectProperties(); - if (!prop) + + ObjectProperties *prop = sao->accessObjectProperties(); + if (prop == nullptr) return 0; + push_object_properties(L, prop); return 1; } @@ -812,7 +713,7 @@ int ObjectRef::l_is_player(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - lua_pushboolean(L, (player != NULL)); + lua_pushboolean(L, (player != nullptr)); return 1; } @@ -821,12 +722,12 @@ int ObjectRef::l_set_nametag_attributes(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - ServerActiveObject *co = getobject(ref); - - if (co == NULL) + ServerActiveObject *sao = getobject(ref); + if (sao == nullptr) return 0; - ObjectProperties *prop = co->accessObjectProperties(); - if (!prop) + + ObjectProperties *prop = sao->accessObjectProperties(); + if (prop == nullptr) return 0; lua_getfield(L, 2, "color"); @@ -840,7 +741,7 @@ int ObjectRef::l_set_nametag_attributes(lua_State *L) std::string nametag = getstringfield_default(L, 2, "text", ""); prop->nametag = nametag; - co->notifyObjectPropertiesModified(); + sao->notifyObjectPropertiesModified(); lua_pushboolean(L, true); return 1; } @@ -850,11 +751,11 @@ int ObjectRef::l_get_nametag_attributes(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - ServerActiveObject *co = getobject(ref); - - if (co == NULL) + ServerActiveObject *sao = getobject(ref); + if (sao == nullptr) return 0; - ObjectProperties *prop = co->accessObjectProperties(); + + ObjectProperties *prop = sao->accessObjectProperties(); if (!prop) return 0; @@ -870,37 +771,39 @@ int ObjectRef::l_get_nametag_attributes(lua_State *L) /* LuaEntitySAO-only */ -// set_velocity(self, {x=num, y=num, z=num}) +// set_velocity(self, velocity) int ObjectRef::l_set_velocity(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - LuaEntitySAO *co = getluaobject(ref); - if (co == NULL) return 0; - v3f pos = checkFloatPos(L, 2); - // Do it - co->setVelocity(pos); + LuaEntitySAO *sao = getluaobject(ref); + if (sao == nullptr) + return 0; + + v3f vel = checkFloatPos(L, 2); + + sao->setVelocity(vel); return 0; } -// add_velocity(self, {x=num, y=num, z=num}) +// add_velocity(self, velocity) int ObjectRef::l_add_velocity(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - v3f vel = checkFloatPos(L, 2); - - ServerActiveObject *obj = getobject(ref); - if (obj == nullptr) + ServerActiveObject *sao = getobject(ref); + if (sao == nullptr) return 0; - if (obj->getType() == ACTIVEOBJECT_TYPE_LUAENTITY) { - LuaEntitySAO *co = dynamic_cast(obj); - co->addVelocity(vel); - } else if (obj->getType() == ACTIVEOBJECT_TYPE_PLAYER) { - PlayerSAO *player = dynamic_cast(obj); - player->setMaxSpeedOverride(vel); - getServer(L)->SendPlayerSpeed(player->getPeerID(), vel); + v3f vel = checkFloatPos(L, 2); + + if (sao->getType() == ACTIVEOBJECT_TYPE_LUAENTITY) { + LuaEntitySAO *entitysao = dynamic_cast(sao); + entitysao->addVelocity(vel); + } else if (sao->getType() == ACTIVEOBJECT_TYPE_PLAYER) { + PlayerSAO *playersao = dynamic_cast(sao); + playersao->setMaxSpeedOverride(vel); + getServer(L)->SendPlayerSpeed(playersao->getPeerID(), vel); } return 0; @@ -911,18 +814,17 @@ int ObjectRef::l_get_velocity(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - - ServerActiveObject *obj = getobject(ref); - if (obj == nullptr) + ServerActiveObject *sao = getobject(ref); + if (sao == nullptr) return 0; - if (obj->getType() == ACTIVEOBJECT_TYPE_LUAENTITY) { - LuaEntitySAO *co = dynamic_cast(obj); - v3f v = co->getVelocity(); - pushFloatPos(L, v); + if (sao->getType() == ACTIVEOBJECT_TYPE_LUAENTITY) { + LuaEntitySAO *entitysao = dynamic_cast(sao); + v3f vel = entitysao->getVelocity(); + pushFloatPos(L, vel); return 1; - } else if (obj->getType() == ACTIVEOBJECT_TYPE_PLAYER) { - RemotePlayer *player = dynamic_cast(obj)->getPlayer(); + } else if (sao->getType() == ACTIVEOBJECT_TYPE_PLAYER) { + RemotePlayer *player = dynamic_cast(sao)->getPlayer(); push_v3f(L, player->getSpeed() / BS); return 1; } @@ -931,17 +833,18 @@ int ObjectRef::l_get_velocity(lua_State *L) return 1; } -// set_acceleration(self, {x=num, y=num, z=num}) +// set_acceleration(self, acceleration) int ObjectRef::l_set_acceleration(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - LuaEntitySAO *co = getluaobject(ref); - if (co == NULL) return 0; - // pos - v3f pos = checkFloatPos(L, 2); - // Do it - co->setAcceleration(pos); + LuaEntitySAO *entitysao = getluaobject(ref); + if (entitysao == nullptr) + return 0; + + v3f acceleration = checkFloatPos(L, 2); + + entitysao->setAcceleration(acceleration); return 0; } @@ -950,59 +853,61 @@ int ObjectRef::l_get_acceleration(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - LuaEntitySAO *co = getluaobject(ref); - if (co == NULL) return 0; - // Do it - v3f v = co->getAcceleration(); - pushFloatPos(L, v); + LuaEntitySAO *entitysao = getluaobject(ref); + if (entitysao == nullptr) + return 0; + + v3f acceleration = entitysao->getAcceleration(); + pushFloatPos(L, acceleration); return 1; } -// set_rotation(self, {x=num, y=num, z=num}) -// Each 'num' is in radians +// set_rotation(self, rotation) int ObjectRef::l_set_rotation(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - LuaEntitySAO *co = getluaobject(ref); - if (!co) + LuaEntitySAO *entitysao = getluaobject(ref); + if (entitysao == nullptr) return 0; v3f rotation = check_v3f(L, 2) * core::RADTODEG; - co->setRotation(rotation); + + entitysao->setRotation(rotation); return 0; } // get_rotation(self) -// returns: {x=num, y=num, z=num} -// Each 'num' is in radians int ObjectRef::l_get_rotation(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - LuaEntitySAO *co = getluaobject(ref); - if (!co) + LuaEntitySAO *entitysao = getluaobject(ref); + if (entitysao == nullptr) return 0; + v3f rotation = entitysao->getRotation() * core::DEGTORAD; + lua_newtable(L); - v3f rotation = co->getRotation() * core::DEGTORAD; push_v3f(L, rotation); return 1; } -// set_yaw(self, radians) +// set_yaw(self, yaw) int ObjectRef::l_set_yaw(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - LuaEntitySAO *co = getluaobject(ref); + LuaEntitySAO *entitysao = getluaobject(ref); + if (entitysao == nullptr) + return 0; - if (co == NULL) return 0; if (isNaN(L, 2)) throw LuaError("ObjectRef::set_yaw: NaN value is not allowed."); float yaw = readParam(L, 2) * core::RADTODEG; - co->setRotation(v3f(0, yaw, 0)); + + entitysao->setRotation(v3f(0, yaw, 0)); return 0; } @@ -1011,11 +916,12 @@ int ObjectRef::l_get_yaw(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - LuaEntitySAO *co = getluaobject(ref); - if (!co) + LuaEntitySAO *entitysao = getluaobject(ref); + if (entitysao == nullptr) return 0; - float yaw = co->getRotation().Y * core::DEGTORAD; + float yaw = entitysao->getRotation().Y * core::DEGTORAD; + lua_pushnumber(L, yaw); return 1; } @@ -1025,11 +931,13 @@ int ObjectRef::l_set_texture_mod(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - LuaEntitySAO *co = getluaobject(ref); - if (co == NULL) return 0; - // Do it - std::string mod = luaL_checkstring(L, 2); - co->setTextureMod(mod); + LuaEntitySAO *entitysao = getluaobject(ref); + if (entitysao == nullptr) + return 0; + + std::string mod = readParam(L, 2); + + entitysao->setTextureMod(mod); return 0; } @@ -1038,36 +946,31 @@ int ObjectRef::l_get_texture_mod(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - LuaEntitySAO *co = getluaobject(ref); - if (co == NULL) return 0; - // Do it - std::string mod = co->getTextureMod(); + LuaEntitySAO *entitysao = getluaobject(ref); + if (entitysao == nullptr) + return 0; + + std::string mod = entitysao->getTextureMod(); + lua_pushstring(L, mod.c_str()); return 1; } -// set_sprite(self, p={x=0,y=0}, num_frames=1, framelength=0.2, -// select_horiz_by_yawpitch=false) +// set_sprite(self, start_frame, num_frames, framelength, select_x_by_camera) int ObjectRef::l_set_sprite(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - LuaEntitySAO *co = getluaobject(ref); - if (co == NULL) return 0; - // Do it - v2s16 p(0,0); - if (!lua_isnil(L, 2)) - p = readParam(L, 2); - int num_frames = 1; - if (!lua_isnil(L, 3)) - num_frames = lua_tonumber(L, 3); - float framelength = 0.2; - if (!lua_isnil(L, 4)) - framelength = lua_tonumber(L, 4); - bool select_horiz_by_yawpitch = false; - if (!lua_isnil(L, 5)) - select_horiz_by_yawpitch = readParam(L, 5); - co->setSprite(p, num_frames, framelength, select_horiz_by_yawpitch); + LuaEntitySAO *entitysao = getluaobject(ref); + if (entitysao == nullptr) + return 0; + + v2s16 start_frame = lua_isnil(L, 2) ? v2s16(0,0) : readParam(L, 2); + int num_frames = lua_isnil(L, 3) ? 1 : luaL_checkint(L, 3); + float framelength = lua_isnil(L, 4) ? 0.2 : lua_tonumber(L, 4); + bool select_x_by_camera = readParam(L, 5, false); + + entitysao->setSprite(start_frame, num_frames, framelength, select_x_by_camera); return 0; } @@ -1077,11 +980,13 @@ int ObjectRef::l_get_entity_name(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - LuaEntitySAO *co = getluaobject(ref); + LuaEntitySAO *entitysao = getluaobject(ref); log_deprecated(L,"Deprecated call to \"get_entity_name"); - if (co == NULL) return 0; - // Do it - std::string name = co->getName(); + if (entitysao == nullptr) + return 0; + + std::string name = entitysao->getName(); + lua_pushstring(L, name.c_str()); return 1; } @@ -1091,39 +996,27 @@ int ObjectRef::l_get_luaentity(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - LuaEntitySAO *co = getluaobject(ref); - if (co == NULL) return 0; - // Do it - luaentity_get(L, co->getId()); + LuaEntitySAO *entitysao = getluaobject(ref); + if (entitysao == nullptr) + return 0; + + luaentity_get(L, entitysao->getId()); return 1; } /* Player-only */ -// is_player_connected(self) -int ObjectRef::l_is_player_connected(lua_State *L) -{ - NO_MAP_LOCK_REQUIRED; - // This method was once added for a bugfix, but never documented - log_deprecated(L, "is_player_connected is undocumented and " - "will be removed in a future release"); - ObjectRef *ref = checkobject(L, 1); - RemotePlayer *player = getplayer(ref); - lua_pushboolean(L, (player != NULL && player->getPeerId() != PEER_ID_INEXISTENT)); - return 1; -} - // get_player_name(self) int ObjectRef::l_get_player_name(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (player == NULL) { + if (player == nullptr) { lua_pushlstring(L, "", 0); return 1; } - // Do it + lua_pushstring(L, player->getName()); return 1; } @@ -1133,13 +1026,15 @@ int ObjectRef::l_get_look_dir(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - PlayerSAO* co = getplayersao(ref); - if (co == NULL) return 0; - // Do it - float pitch = co->getRadLookPitchDep(); - float yaw = co->getRadYawDep(); + PlayerSAO* playersao = getplayersao(ref); + if (playersao == nullptr) + return 0; + + float pitch = playersao->getRadLookPitchDep(); + float yaw = playersao->getRadYawDep(); v3f v(std::cos(pitch) * std::cos(yaw), std::sin(pitch), std::cos(pitch) * std::sin(yaw)); + push_v3f(L, v); return 1; } @@ -1154,10 +1049,11 @@ int ObjectRef::l_get_look_pitch(lua_State *L) "Deprecated call to get_look_pitch, use get_look_vertical instead"); ObjectRef *ref = checkobject(L, 1); - PlayerSAO* co = getplayersao(ref); - if (co == NULL) return 0; - // Do it - lua_pushnumber(L, co->getRadLookPitchDep()); + PlayerSAO* playersao = getplayersao(ref); + if (playersao == nullptr) + return 0; + + lua_pushnumber(L, playersao->getRadLookPitchDep()); return 1; } @@ -1171,34 +1067,37 @@ int ObjectRef::l_get_look_yaw(lua_State *L) "Deprecated call to get_look_yaw, use get_look_horizontal instead"); ObjectRef *ref = checkobject(L, 1); - PlayerSAO* co = getplayersao(ref); - if (co == NULL) return 0; - // Do it - lua_pushnumber(L, co->getRadYawDep()); + PlayerSAO* playersao = getplayersao(ref); + if (playersao == nullptr) + return 0; + + lua_pushnumber(L, playersao->getRadYawDep()); return 1; } -// get_look_pitch2(self) +// get_look_vertical(self) int ObjectRef::l_get_look_vertical(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - PlayerSAO* co = getplayersao(ref); - if (co == NULL) return 0; - // Do it - lua_pushnumber(L, co->getRadLookPitch()); + PlayerSAO* playersao = getplayersao(ref); + if (playersao == nullptr) + return 0; + + lua_pushnumber(L, playersao->getRadLookPitch()); return 1; } -// get_look_yaw2(self) +// get_look_horizontal(self) int ObjectRef::l_get_look_horizontal(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - PlayerSAO* co = getplayersao(ref); - if (co == NULL) return 0; - // Do it - lua_pushnumber(L, co->getRadRotation().Y); + PlayerSAO* playersao = getplayersao(ref); + if (playersao == nullptr) + return 0; + + lua_pushnumber(L, playersao->getRadRotation().Y); return 1; } @@ -1207,11 +1106,13 @@ int ObjectRef::l_set_look_vertical(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - PlayerSAO* co = getplayersao(ref); - if (co == NULL) return 0; + PlayerSAO* playersao = getplayersao(ref); + if (playersao == nullptr) + return 0; + float pitch = readParam(L, 2) * core::RADTODEG; - // Do it - co->setLookPitchAndSend(pitch); + + playersao->setLookPitchAndSend(pitch); return 1; } @@ -1220,11 +1121,13 @@ int ObjectRef::l_set_look_horizontal(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - PlayerSAO* co = getplayersao(ref); - if (co == NULL) return 0; + PlayerSAO* playersao = getplayersao(ref); + if (playersao == nullptr) + return 0; + float yaw = readParam(L, 2) * core::RADTODEG; - // Do it - co->setPlayerYawAndSend(yaw); + + playersao->setPlayerYawAndSend(yaw); return 1; } @@ -1238,11 +1141,13 @@ int ObjectRef::l_set_look_pitch(lua_State *L) "Deprecated call to set_look_pitch, use set_look_vertical instead."); ObjectRef *ref = checkobject(L, 1); - PlayerSAO* co = getplayersao(ref); - if (co == NULL) return 0; + PlayerSAO* playersao = getplayersao(ref); + if (playersao == nullptr) + return 0; + float pitch = readParam(L, 2) * core::RADTODEG; - // Do it - co->setLookPitchAndSend(pitch); + + playersao->setLookPitchAndSend(pitch); return 1; } @@ -1256,30 +1161,32 @@ int ObjectRef::l_set_look_yaw(lua_State *L) "Deprecated call to set_look_yaw, use set_look_horizontal instead."); ObjectRef *ref = checkobject(L, 1); - PlayerSAO* co = getplayersao(ref); - if (co == NULL) return 0; + PlayerSAO* playersao = getplayersao(ref); + if (playersao == nullptr) + return 0; + float yaw = readParam(L, 2) * core::RADTODEG; - // Do it - co->setPlayerYawAndSend(yaw); + + playersao->setPlayerYawAndSend(yaw); return 1; } -// set_fov(self, degrees[, is_multiplier, transition_time]) +// set_fov(self, degrees, is_multiplier, transition_time) int ObjectRef::l_set_fov(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (!player) + if (player == nullptr) return 0; - player->setFov({ - static_cast(luaL_checknumber(L, 2)), - readParam(L, 3, false), - lua_isnumber(L, 4) ? static_cast(luaL_checknumber(L, 4)) : 0.0f - }); - getServer(L)->SendPlayerFov(player->getPeerId()); + float degrees = static_cast(luaL_checknumber(L, 2)); + bool is_multiplier = readParam(L, 3, false); + float transition_time = lua_isnumber(L, 4) ? + static_cast(luaL_checknumber(L, 4)) : 0.0f; + player->setFov({degrees, is_multiplier, transition_time}); + getServer(L)->SendPlayerFov(player->getPeerId()); return 0; } @@ -1289,14 +1196,14 @@ int ObjectRef::l_get_fov(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (!player) + if (player == nullptr) return 0; PlayerFovSpec fov_spec = player->getFov(); + lua_pushnumber(L, fov_spec.fov); lua_pushboolean(L, fov_spec.is_multiplier); lua_pushnumber(L, fov_spec.transition_time); - return 3; } @@ -1305,11 +1212,13 @@ int ObjectRef::l_set_breath(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - PlayerSAO* co = getplayersao(ref); - if (co == NULL) return 0; + PlayerSAO* playersao = getplayersao(ref); + if (playersao == nullptr) + return 0; + u16 breath = luaL_checknumber(L, 2); - co->setBreath(breath); + playersao->setBreath(breath); return 0; } @@ -1318,11 +1227,13 @@ int ObjectRef::l_get_breath(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); - PlayerSAO* co = getplayersao(ref); - if (co == NULL) return 0; - // Do it - u16 breath = co->getBreath(); - lua_pushinteger (L, breath); + PlayerSAO* playersao = getplayersao(ref); + if (playersao == nullptr) + return 0; + + u16 breath = playersao->getBreath(); + + lua_pushinteger(L, breath); return 1; } @@ -1333,16 +1244,16 @@ int ObjectRef::l_set_attribute(lua_State *L) "Deprecated call to set_attribute, use MetaDataRef methods instead."); ObjectRef *ref = checkobject(L, 1); - PlayerSAO* co = getplayersao(ref); - if (co == NULL) + PlayerSAO* playersao = getplayersao(ref); + if (playersao == nullptr) return 0; std::string attr = luaL_checkstring(L, 2); if (lua_isnil(L, 3)) { - co->getMeta().removeString(attr); + playersao->getMeta().removeString(attr); } else { std::string value = luaL_checkstring(L, 3); - co->getMeta().setString(attr, value); + playersao->getMeta().setString(attr, value); } return 1; } @@ -1354,14 +1265,14 @@ int ObjectRef::l_get_attribute(lua_State *L) "Deprecated call to get_attribute, use MetaDataRef methods instead."); ObjectRef *ref = checkobject(L, 1); - PlayerSAO* co = getplayersao(ref); - if (co == NULL) + PlayerSAO* playersao = getplayersao(ref); + if (playersao == nullptr) return 0; std::string attr = luaL_checkstring(L, 2); std::string value; - if (co->getMeta().getStringToRef(attr, value)) { + if (playersao->getMeta().getStringToRef(attr, value)) { lua_pushstring(L, value.c_str()); return 1; } @@ -1374,11 +1285,11 @@ int ObjectRef::l_get_attribute(lua_State *L) int ObjectRef::l_get_meta(lua_State *L) { ObjectRef *ref = checkobject(L, 1); - PlayerSAO *co = getplayersao(ref); - if (co == NULL) + PlayerSAO *playersao = getplayersao(ref); + if (playersao == nullptr) return 0; - PlayerMetaRef::create(L, &co->getMeta()); + PlayerMetaRef::create(L, &playersao->getMeta()); return 1; } @@ -1389,7 +1300,9 @@ int ObjectRef::l_set_inventory_formspec(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (player == NULL) return 0; + if (player == nullptr) + return 0; + std::string formspec = luaL_checkstring(L, 2); player->inventory_formspec = formspec; @@ -1404,9 +1317,11 @@ int ObjectRef::l_get_inventory_formspec(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (player == NULL) return 0; + if (player == nullptr) + return 0; std::string formspec = player->inventory_formspec; + lua_pushlstring(L, formspec.c_str(), formspec.size()); return 1; } @@ -1417,7 +1332,7 @@ int ObjectRef::l_set_formspec_prepend(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (player == NULL) + if (player == nullptr) return 0; std::string formspec = luaL_checkstring(L, 2); @@ -1428,16 +1343,17 @@ int ObjectRef::l_set_formspec_prepend(lua_State *L) return 1; } -// get_formspec_prepend(self) -> formspec +// get_formspec_prepend(self) int ObjectRef::l_get_formspec_prepend(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (player == NULL) + if (player == nullptr) return 0; std::string formspec = player->formspec_prepend; + lua_pushlstring(L, formspec.c_str(), formspec.size()); return 1; } @@ -1448,7 +1364,7 @@ int ObjectRef::l_get_player_control(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (player == NULL) { + if (player == nullptr) { lua_pushlstring(L, "", 0); return 1; } @@ -1489,22 +1405,73 @@ int ObjectRef::l_get_player_control_bits(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (player == NULL) { + if (player == nullptr) { lua_pushlstring(L, "", 0); return 1; } - // Do it + lua_pushnumber(L, player->keyPressed); return 1; } -// hud_add(self, form) +// set_physics_override(self, override_table) +int ObjectRef::l_set_physics_override(lua_State *L) +{ + NO_MAP_LOCK_REQUIRED; + ObjectRef *ref = checkobject(L, 1); + PlayerSAO *playersao = (PlayerSAO *) getobject(ref); + if (playersao == nullptr) + return 0; + + luaL_checktype(L, 2, LUA_TTABLE); + playersao->m_physics_override_speed = getfloatfield_default( + L, 2, "speed", playersao->m_physics_override_speed); + playersao->m_physics_override_jump = getfloatfield_default( + L, 2, "jump", playersao->m_physics_override_jump); + playersao->m_physics_override_gravity = getfloatfield_default( + L, 2, "gravity", playersao->m_physics_override_gravity); + playersao->m_physics_override_sneak = getboolfield_default( + L, 2, "sneak", playersao->m_physics_override_sneak); + playersao->m_physics_override_sneak_glitch = getboolfield_default( + L, 2, "sneak_glitch", playersao->m_physics_override_sneak_glitch); + playersao->m_physics_override_new_move = getboolfield_default( + L, 2, "new_move", playersao->m_physics_override_new_move); + playersao->m_physics_override_sent = false; + return 0; +} + +// get_physics_override(self) +int ObjectRef::l_get_physics_override(lua_State *L) +{ + NO_MAP_LOCK_REQUIRED; + ObjectRef *ref = checkobject(L, 1); + PlayerSAO *playersao = (PlayerSAO *)getobject(ref); + if (playersao == nullptr) + return 0; + + lua_newtable(L); + lua_pushnumber(L, playersao->m_physics_override_speed); + lua_setfield(L, -2, "speed"); + lua_pushnumber(L, playersao->m_physics_override_jump); + lua_setfield(L, -2, "jump"); + lua_pushnumber(L, playersao->m_physics_override_gravity); + lua_setfield(L, -2, "gravity"); + lua_pushboolean(L, playersao->m_physics_override_sneak); + lua_setfield(L, -2, "sneak"); + lua_pushboolean(L, playersao->m_physics_override_sneak_glitch); + lua_setfield(L, -2, "sneak_glitch"); + lua_pushboolean(L, playersao->m_physics_override_new_move); + lua_setfield(L, -2, "new_move"); + return 1; +} + +// hud_add(self, hud) int ObjectRef::l_hud_add(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (player == NULL) + if (player == nullptr) return 0; HudElement *elem = new HudElement; @@ -1526,12 +1493,10 @@ int ObjectRef::l_hud_remove(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (player == NULL) + if (player == nullptr) return 0; - u32 id = -1; - if (!lua_isnil(L, 2)) - id = lua_tonumber(L, 2); + u32 id = luaL_checkint(L, 2); if (!getServer(L)->hudRemove(player, id)) return 0; @@ -1546,17 +1511,17 @@ int ObjectRef::l_hud_change(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (player == NULL) + if (player == nullptr) return 0; - u32 id = lua_isnumber(L, 2) ? lua_tonumber(L, 2) : -1; + u32 id = luaL_checkint(L, 2); - HudElement *e = player->getHud(id); - if (!e) + HudElement *elem = player->getHud(id); + if (elem == nullptr) return 0; - void *value = NULL; - HudElementStat stat = read_hud_change(L, e, &value); + void *value = nullptr; + HudElementStat stat = read_hud_change(L, elem, &value); getServer(L)->hudChange(player, id, stat, value); @@ -1570,15 +1535,16 @@ int ObjectRef::l_hud_get(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (player == NULL) + if (player == nullptr) return 0; - u32 id = lua_tonumber(L, -1); + u32 id = luaL_checkint(L, 2); - HudElement *e = player->getHud(id); - if (!e) + HudElement *elem = player->getHud(id); + if (elem == nullptr) return 0; - push_hud_element(L, e); + + push_hud_element(L, elem); return 1; } @@ -1588,7 +1554,7 @@ int ObjectRef::l_hud_set_flags(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (player == NULL) + if (player == nullptr) return 0; u32 flags = 0; @@ -1609,12 +1575,13 @@ int ObjectRef::l_hud_set_flags(lua_State *L) return 1; } +// hud_get_flags(self) int ObjectRef::l_hud_get_flags(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (player == NULL) + if (player == nullptr) return 0; lua_newtable(L); @@ -1632,7 +1599,6 @@ int ObjectRef::l_hud_get_flags(lua_State *L) lua_setfield(L, -2, "minimap"); lua_pushboolean(L, player->hud_flags & HUD_FLAG_MINIMAP_RADAR_VISIBLE); lua_setfield(L, -2, "minimap_radar"); - return 1; } @@ -1642,10 +1608,10 @@ int ObjectRef::l_hud_set_hotbar_itemcount(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (player == NULL) + if (player == nullptr) return 0; - s32 hotbar_itemcount = lua_tonumber(L, 2); + s32 hotbar_itemcount = luaL_checkint(L, 2); if (!getServer(L)->hudSetHotbarItemcount(player, hotbar_itemcount)) return 0; @@ -1660,7 +1626,7 @@ int ObjectRef::l_hud_get_hotbar_itemcount(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (player == NULL) + if (player == nullptr) return 0; lua_pushnumber(L, player->getHotbarItemcount()); @@ -1673,7 +1639,7 @@ int ObjectRef::l_hud_set_hotbar_image(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (player == NULL) + if (player == nullptr) return 0; std::string name = readParam(L, 2); @@ -1688,10 +1654,11 @@ int ObjectRef::l_hud_get_hotbar_image(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (player == NULL) + if (player == nullptr) return 0; const std::string &name = player->getHotbarImage(); + lua_pushlstring(L, name.c_str(), name.size()); return 1; } @@ -1702,7 +1669,7 @@ int ObjectRef::l_hud_set_hotbar_selected_image(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (player == NULL) + if (player == nullptr) return 0; std::string name = readParam(L, 2); @@ -1717,44 +1684,45 @@ int ObjectRef::l_hud_get_hotbar_selected_image(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (player == NULL) + if (player == nullptr) return 0; const std::string &name = player->getHotbarSelectedImage(); + lua_pushlstring(L, name.c_str(), name.size()); return 1; } -// set_sky(self, {base_color=, type=, textures=, clouds=, sky_colors={}}) +// set_sky(self, sky_parameters) int ObjectRef::l_set_sky(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (!player) + if (player == nullptr) return 0; + SkyboxParams sky_params = player->getSkyParams(); bool is_colorspec = is_color_table(L, 2); - SkyboxParams skybox_params = player->getSkyParams(); if (lua_istable(L, 2) && !is_colorspec) { lua_getfield(L, 2, "base_color"); if (!lua_isnil(L, -1)) - read_color(L, -1, &skybox_params.bgcolor); + read_color(L, -1, &sky_params.bgcolor); lua_pop(L, 1); lua_getfield(L, 2, "type"); if (!lua_isnil(L, -1)) - skybox_params.type = luaL_checkstring(L, -1); + sky_params.type = luaL_checkstring(L, -1); lua_pop(L, 1); lua_getfield(L, 2, "textures"); - skybox_params.textures.clear(); - if (lua_istable(L, -1) && skybox_params.type == "skybox") { + sky_params.textures.clear(); + if (lua_istable(L, -1) && sky_params.type == "skybox") { lua_pushnil(L); while (lua_next(L, -2) != 0) { // Key is at index -2 and value at index -1 - skybox_params.textures.emplace_back(readParam(L, -1)); + sky_params.textures.emplace_back(readParam(L, -1)); // Removes the value, but keeps the key for iteration lua_pop(L, 1); } @@ -1767,56 +1735,56 @@ int ObjectRef::l_set_sky(lua_State *L) using "regular" or "plain" skybox modes as textures aren't needed. */ - if (skybox_params.textures.size() != 6 && skybox_params.textures.size() > 0) + if (sky_params.textures.size() != 6 && sky_params.textures.size() > 0) throw LuaError("Skybox expects 6 textures!"); - skybox_params.clouds = getboolfield_default(L, 2, - "clouds", skybox_params.clouds); + sky_params.clouds = getboolfield_default(L, 2, + "clouds", sky_params.clouds); lua_getfield(L, 2, "sky_color"); if (lua_istable(L, -1)) { lua_getfield(L, -1, "day_sky"); - read_color(L, -1, &skybox_params.sky_color.day_sky); + read_color(L, -1, &sky_params.sky_color.day_sky); lua_pop(L, 1); lua_getfield(L, -1, "day_horizon"); - read_color(L, -1, &skybox_params.sky_color.day_horizon); + read_color(L, -1, &sky_params.sky_color.day_horizon); lua_pop(L, 1); lua_getfield(L, -1, "dawn_sky"); - read_color(L, -1, &skybox_params.sky_color.dawn_sky); + read_color(L, -1, &sky_params.sky_color.dawn_sky); lua_pop(L, 1); lua_getfield(L, -1, "dawn_horizon"); - read_color(L, -1, &skybox_params.sky_color.dawn_horizon); + read_color(L, -1, &sky_params.sky_color.dawn_horizon); lua_pop(L, 1); lua_getfield(L, -1, "night_sky"); - read_color(L, -1, &skybox_params.sky_color.night_sky); + read_color(L, -1, &sky_params.sky_color.night_sky); lua_pop(L, 1); lua_getfield(L, -1, "night_horizon"); - read_color(L, -1, &skybox_params.sky_color.night_horizon); + read_color(L, -1, &sky_params.sky_color.night_horizon); lua_pop(L, 1); lua_getfield(L, -1, "indoors"); - read_color(L, -1, &skybox_params.sky_color.indoors); + read_color(L, -1, &sky_params.sky_color.indoors); lua_pop(L, 1); // Prevent flickering clouds at dawn/dusk: - skybox_params.fog_sun_tint = video::SColor(255, 255, 255, 255); + sky_params.fog_sun_tint = video::SColor(255, 255, 255, 255); lua_getfield(L, -1, "fog_sun_tint"); - read_color(L, -1, &skybox_params.fog_sun_tint); + read_color(L, -1, &sky_params.fog_sun_tint); lua_pop(L, 1); - skybox_params.fog_moon_tint = video::SColor(255, 255, 255, 255); + sky_params.fog_moon_tint = video::SColor(255, 255, 255, 255); lua_getfield(L, -1, "fog_moon_tint"); - read_color(L, -1, &skybox_params.fog_moon_tint); + read_color(L, -1, &sky_params.fog_moon_tint); lua_pop(L, 1); lua_getfield(L, -1, "fog_tint_type"); if (!lua_isnil(L, -1)) - skybox_params.fog_tint_type = luaL_checkstring(L, -1); + sky_params.fog_tint_type = luaL_checkstring(L, -1); lua_pop(L, 1); // Because we need to leave the "sky_color" table. @@ -1832,14 +1800,14 @@ int ObjectRef::l_set_sky(lua_State *L) StarParams star_params = player->getStarParams(); // Prevent erroneous background colors - skybox_params.bgcolor = video::SColor(255, 255, 255, 255); - read_color(L, 2, &skybox_params.bgcolor); + sky_params.bgcolor = video::SColor(255, 255, 255, 255); + read_color(L, 2, &sky_params.bgcolor); - skybox_params.type = luaL_checkstring(L, 3); + sky_params.type = luaL_checkstring(L, 3); // Preserve old behaviour of the sun, moon and stars // when using the old set_sky call. - if (skybox_params.type == "regular") { + if (sky_params.type == "regular") { sun_params.visible = true; sun_params.sunrise_visible = true; moon_params.visible = true; @@ -1851,31 +1819,31 @@ int ObjectRef::l_set_sky(lua_State *L) star_params.visible = false; } - skybox_params.textures.clear(); + sky_params.textures.clear(); if (lua_istable(L, 4)) { lua_pushnil(L); while (lua_next(L, 4) != 0) { // Key at index -2, and value at index -1 if (lua_isstring(L, -1)) - skybox_params.textures.emplace_back(readParam(L, -1)); + sky_params.textures.emplace_back(readParam(L, -1)); else - skybox_params.textures.emplace_back(""); + sky_params.textures.emplace_back(""); // Remove the value, keep the key for the next iteration lua_pop(L, 1); } } - if (skybox_params.type == "skybox" && skybox_params.textures.size() != 6) + if (sky_params.type == "skybox" && sky_params.textures.size() != 6) throw LuaError("Skybox expects 6 textures."); - skybox_params.clouds = true; + sky_params.clouds = true; if (lua_isboolean(L, 5)) - skybox_params.clouds = readParam(L, 5); + sky_params.clouds = readParam(L, 5); getServer(L)->setSun(player, sun_params); getServer(L)->setMoon(player, moon_params); getServer(L)->setStars(player, star_params); } - getServer(L)->setSky(player, skybox_params); + getServer(L)->setSky(player, sky_params); lua_pushboolean(L, true); return 1; } @@ -1886,18 +1854,17 @@ int ObjectRef::l_get_sky(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - - if (!player) + if (player == nullptr) return 0; - SkyboxParams skybox_params; - skybox_params = player->getSkyParams(); + + SkyboxParams skybox_params = player->getSkyParams(); push_ARGB8(L, skybox_params.bgcolor); lua_pushlstring(L, skybox_params.type.c_str(), skybox_params.type.size()); lua_newtable(L); s16 i = 1; - for (const std::string& texture : skybox_params.textures) { + for (const std::string &texture : skybox_params.textures) { lua_pushlstring(L, texture.c_str(), texture.size()); lua_rawseti(L, -2, i++); } @@ -1911,11 +1878,10 @@ int ObjectRef::l_get_sky_color(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - - if (!player) + if (player == nullptr) return 0; - const SkyboxParams& skybox_params = player->getSkyParams(); + const SkyboxParams &skybox_params = player->getSkyParams(); lua_newtable(L); if (skybox_params.type == "regular") { @@ -1943,18 +1909,16 @@ int ObjectRef::l_get_sky_color(lua_State *L) return 1; } -// set_sun(self, {visible, texture=, tonemap=, sunrise=, rotation=, scale=}) +// set_sun(self, sun_parameters) int ObjectRef::l_set_sun(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (!player) - return 0; - - if (!lua_istable(L, 2)) + if (player == nullptr) return 0; + luaL_checktype(L, 2, LUA_TTABLE); SunParams sun_params = player->getSunParams(); sun_params.visible = getboolfield_default(L, 2, @@ -1981,8 +1945,9 @@ int ObjectRef::l_get_sun(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (!player) + if (player == nullptr) return 0; + const SunParams &sun_params = player->getSunParams(); lua_newtable(L); @@ -1998,21 +1963,19 @@ int ObjectRef::l_get_sun(lua_State *L) lua_setfield(L, -2, "sunrise_visible"); lua_pushnumber(L, sun_params.scale); lua_setfield(L, -2, "scale"); - return 1; } -// set_moon(self, {visible, texture=, tonemap=, sunrise=, rotation=, scale=}) +// set_moon(self, moon_parameters) int ObjectRef::l_set_moon(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (!player) - return 0; - if (!lua_istable(L, 2)) + if (player == nullptr) return 0; + luaL_checktype(L, 2, LUA_TTABLE); MoonParams moon_params = player->getMoonParams(); moon_params.visible = getboolfield_default(L, 2, @@ -2035,8 +1998,9 @@ int ObjectRef::l_get_moon(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (!player) + if (player == nullptr) return 0; + const MoonParams &moon_params = player->getMoonParams(); lua_newtable(L); @@ -2048,21 +2012,19 @@ int ObjectRef::l_get_moon(lua_State *L) lua_setfield(L, -2, "tonemap"); lua_pushnumber(L, moon_params.scale); lua_setfield(L, -2, "scale"); - return 1; } -// set_stars(self, {visible, count=, starcolor=, rotation=, scale=}) +// set_stars(self, star_parameters) int ObjectRef::l_set_stars(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (!player) - return 0; - if (!lua_istable(L, 2)) + if (player == nullptr) return 0; + luaL_checktype(L, 2, LUA_TTABLE); StarParams star_params = player->getStarParams(); star_params.visible = getboolfield_default(L, 2, @@ -2089,8 +2051,9 @@ int ObjectRef::l_get_stars(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (!player) + if (player == nullptr) return 0; + const StarParams &star_params = player->getStarParams(); lua_newtable(L); @@ -2102,21 +2065,19 @@ int ObjectRef::l_get_stars(lua_State *L) lua_setfield(L, -2, "star_color"); lua_pushnumber(L, star_params.scale); lua_setfield(L, -2, "scale"); - return 1; } -// set_clouds(self, {density=, color=, ambient=, height=, thickness=, speed=}) +// set_clouds(self, cloud_parameters) int ObjectRef::l_set_clouds(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (!player) - return 0; - if (!lua_istable(L, 2)) + if (player == nullptr) return 0; + luaL_checktype(L, 2, LUA_TTABLE); CloudParams cloud_params = player->getCloudParams(); cloud_params.density = getfloatfield_default(L, 2, "density", cloud_params.density); @@ -2152,8 +2113,9 @@ int ObjectRef::l_get_clouds(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (!player) + if (player == nullptr) return 0; + const CloudParams &cloud_params = player->getCloudParams(); lua_newtable(L); @@ -2173,25 +2135,27 @@ int ObjectRef::l_get_clouds(lua_State *L) lua_pushnumber(L, cloud_params.speed.Y); lua_setfield(L, -2, "y"); lua_setfield(L, -2, "speed"); - return 1; } -// override_day_night_ratio(self, brightness=0...1) +// override_day_night_ratio(self, ratio) int ObjectRef::l_override_day_night_ratio(lua_State *L) { NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (player == NULL) + if (player == nullptr) return 0; bool do_override = false; float ratio = 0.0f; + if (!lua_isnil(L, 2)) { do_override = true; ratio = readParam(L, 2); + luaL_argcheck(L, ratio >= 0.0f && ratio <= 1.0f, 1, + "value must be between 0 and 1"); } getServer(L)->overrideDayNightRatio(player, do_override, ratio); @@ -2205,7 +2169,7 @@ int ObjectRef::l_get_day_night_ratio(lua_State *L) NO_MAP_LOCK_REQUIRED; ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (player == NULL) + if (player == nullptr) return 0; bool do_override; @@ -2220,26 +2184,18 @@ int ObjectRef::l_get_day_night_ratio(lua_State *L) return 1; } -// set_minimap_modes(self, modes, modeindex) +// set_minimap_modes(self, modes, selected_mode) int ObjectRef::l_set_minimap_modes(lua_State *L) { NO_MAP_LOCK_REQUIRED; - - // Arg 1 should be a player ObjectRef *ref = checkobject(L, 1); RemotePlayer *player = getplayer(ref); - if (player == NULL) + if (player == nullptr) return 0; - // Arg 2 should be a table (of tables) - if (!lua_istable(L, 2)) { - return 0; - } - - // Arg 3 should be a number - s16 wantedmode = lua_tonumber(L, 3); - + luaL_checktype(L, 2, LUA_TTABLE); std::vector modes; + s16 selected_mode = luaL_checkint(L, 3); lua_pushnil(L); while (lua_next(L, 2) != 0) { @@ -2277,31 +2233,28 @@ int ObjectRef::l_set_minimap_modes(lua_State *L) } lua_pop(L, 1); // Remove key - getServer(L)->SendMinimapModes(player->getPeerId(), modes, wantedmode); + getServer(L)->SendMinimapModes(player->getPeerId(), modes, selected_mode); return 0; } ObjectRef::ObjectRef(ServerActiveObject *object): m_object(object) -{ - //infostream<<"ObjectRef created for id="<getId()< formspec + // get_inventory_formspec(self) static int l_get_inventory_formspec(lua_State *L); // set_formspec_prepend(self, formspec) static int l_set_formspec_prepend(lua_State *L); - // get_formspec_prepend(self) -> formspec + // get_formspec_prepend(self) static int l_get_formspec_prepend(lua_State *L); // get_player_control(self) @@ -321,7 +313,7 @@ private: // hud_get_hotbar_selected_image(self) static int l_hud_get_hotbar_selected_image(lua_State *L); - // set_sky({base_color=, type=, textures=, clouds=, sky_colors={}}) + // set_sky(self, sky_parameters) static int l_set_sky(lua_State *L); // get_sky(self) @@ -330,25 +322,25 @@ private: // get_sky_color(self) static int l_get_sky_color(lua_State* L); - // set_sun(self, {visible, texture=, tonemap=, sunrise=, rotation=, scale=}) + // set_sun(self, sun_parameters) static int l_set_sun(lua_State *L); // get_sun(self) static int l_get_sun(lua_State *L); - // set_moon(self, {visible, texture=, tonemap=, rotation, scale=}) + // set_moon(self, moon_parameters) static int l_set_moon(lua_State *L); // get_moon(self) static int l_get_moon(lua_State *L); - // set_stars(self, {visible, count=, starcolor=, rotation, scale=}) + // set_stars(self, star_parameters) static int l_set_stars(lua_State *L); // get_stars(self) static int l_get_stars(lua_State *L); - // set_clouds(self, {density=, color=, ambient=, height=, thickness=, speed=}) + // set_clouds(self, cloud_parameters) static int l_set_clouds(lua_State *L); // get_clouds(self) @@ -360,13 +352,13 @@ private: // get_day_night_ratio(self) static int l_get_day_night_ratio(lua_State *L); - // set_local_animation(self, {stand/idle}, {walk}, {dig}, {walk+dig}, frame_speed) + // set_local_animation(self, idle, walk, dig, walk_while_dig, frame_speed) static int l_set_local_animation(lua_State *L); // get_local_animation(self) static int l_get_local_animation(lua_State *L); - // set_eye_offset(self, v3f first pv, v3f third pv) + // set_eye_offset(self, firstperson, thirdperson) static int l_set_eye_offset(lua_State *L); // get_eye_offset(self) -- cgit v1.2.3 From 89dd05fdf35ce465fcc2b3588337f79f818a78aa Mon Sep 17 00:00:00 2001 From: rubenwardy Date: Sat, 31 Oct 2020 18:19:23 +0000 Subject: Fix segfault in deprecation logging due to tail call, log by default (#10174) --- builtin/settingtypes.txt | 6 ++-- src/defaultsettings.cpp | 4 --- src/script/common/c_internal.cpp | 20 +++++++------ src/script/common/c_internal.h | 20 +++++++++++++ src/script/lua_api/l_base.cpp | 61 +++++++--------------------------------- src/script/lua_api/l_base.h | 21 +++++++++----- src/script/lua_api/l_internal.h | 11 +++++++- src/script/lua_api/l_noise.cpp | 2 -- src/script/lua_api/l_object.cpp | 6 ++-- 9 files changed, 71 insertions(+), 80 deletions(-) (limited to 'src/script/lua_api/l_object.cpp') diff --git a/builtin/settingtypes.txt b/builtin/settingtypes.txt index 36446f808..0b650c722 100644 --- a/builtin/settingtypes.txt +++ b/builtin/settingtypes.txt @@ -1220,10 +1220,10 @@ movement_gravity (Gravity) float 9.81 [**Advanced] # Handling for deprecated Lua API calls: -# - legacy: (try to) mimic old behaviour (default for release). -# - log: mimic and log backtrace of deprecated call (default for debug). +# - none: Do not log deprecated calls +# - log: mimic and log backtrace of deprecated call (default). # - error: abort on usage of deprecated call (suggested for mod developers). -deprecated_lua_api_handling (Deprecated Lua API handling) enum legacy legacy,log,error +deprecated_lua_api_handling (Deprecated Lua API handling) enum log none,log,error # Number of extra blocks that can be loaded by /clearobjects at once. # This is a trade-off between sqlite transaction overhead and diff --git a/src/defaultsettings.cpp b/src/defaultsettings.cpp index 6c7d4be97..fcdf6b536 100644 --- a/src/defaultsettings.cpp +++ b/src/defaultsettings.cpp @@ -358,11 +358,7 @@ void set_default_settings(Settings *settings) settings->setDefault("disallow_empty_password", "false"); settings->setDefault("disable_anticheat", "false"); settings->setDefault("enable_rollback_recording", "false"); -#ifdef NDEBUG - settings->setDefault("deprecated_lua_api_handling", "legacy"); -#else settings->setDefault("deprecated_lua_api_handling", "log"); -#endif settings->setDefault("kick_msg_shutdown", "Server shutting down."); settings->setDefault("kick_msg_crash", "This server has experienced an internal error. You will now be disconnected."); diff --git a/src/script/common/c_internal.cpp b/src/script/common/c_internal.cpp index 6df1f8b7b..ad5f836c5 100644 --- a/src/script/common/c_internal.cpp +++ b/src/script/common/c_internal.cpp @@ -155,24 +155,28 @@ static void script_log(lua_State *L, const std::string &message, infostream << script_get_backtrace(L) << std::endl; } -void log_deprecated(lua_State *L, const std::string &message, int stack_depth) +DeprecatedHandlingMode get_deprecated_handling_mode() { static thread_local bool configured = false; - static thread_local bool do_log = false; - static thread_local bool do_error = false; + static thread_local DeprecatedHandlingMode ret = DeprecatedHandlingMode::Ignore; // Only read settings on first call if (!configured) { std::string value = g_settings->get("deprecated_lua_api_handling"); if (value == "log") { - do_log = true; + ret = DeprecatedHandlingMode::Log; } else if (value == "error") { - do_log = true; - do_error = true; + ret = DeprecatedHandlingMode::Error; } configured = true; } - if (do_log) - script_log(L, message, warningstream, do_error, stack_depth); + return ret; +} + +void log_deprecated(lua_State *L, const std::string &message, int stack_depth) +{ + DeprecatedHandlingMode mode = get_deprecated_handling_mode(); + if (mode != DeprecatedHandlingMode::Ignore) + script_log(L, message, warningstream, mode == DeprecatedHandlingMode::Error, stack_depth); } diff --git a/src/script/common/c_internal.h b/src/script/common/c_internal.h index 442546332..452c2dd5e 100644 --- a/src/script/common/c_internal.h +++ b/src/script/common/c_internal.h @@ -114,5 +114,25 @@ void script_error(lua_State *L, int pcall_result, const char *mod, const char *f void script_run_callbacks_f(lua_State *L, int nargs, RunCallbacksMode mode, const char *fxn); +enum class DeprecatedHandlingMode { + Ignore, + Log, + Error +}; + +/** + * Reads `deprecated_lua_api_handling` in settings, returns cached value. + * + * @return DeprecatedHandlingMode + */ +DeprecatedHandlingMode get_deprecated_handling_mode(); + +/** + * Handles a deprecation warning based on user settings + * + * @param L Lua State + * @param message The deprecation method + * @param stack_depth How far on the stack to the first user function (ie: not builtin or core) + */ void log_deprecated(lua_State *L, const std::string &message, int stack_depth=1); diff --git a/src/script/lua_api/l_base.cpp b/src/script/lua_api/l_base.cpp index 03ef5447a..f842671b8 100644 --- a/src/script/lua_api/l_base.cpp +++ b/src/script/lua_api/l_base.cpp @@ -100,32 +100,21 @@ bool ModApiBase::registerFunction(lua_State *L, const char *name, return true; } -std::unordered_map ModApiBase::m_deprecated_wrappers; -bool ModApiBase::m_error_deprecated_calls = false; - -int ModApiBase::l_deprecated_function(lua_State *L) +int ModApiBase::l_deprecated_function(lua_State *L, const char *good, const char *bad, lua_CFunction func) { thread_local std::vector deprecated_logged; + DeprecatedHandlingMode dep_mode = get_deprecated_handling_mode(); + if (dep_mode == DeprecatedHandlingMode::Ignore) + return func(L); + u64 start_time = porting::getTimeUs(); lua_Debug ar; - // Get function name for lookup - FATAL_ERROR_IF(!lua_getstack(L, 0, &ar), "lua_getstack() failed"); - FATAL_ERROR_IF(!lua_getinfo(L, "n", &ar), "lua_getinfo() failed"); - - // Combine name with line and script backtrace + // Get caller name with line and script backtrace FATAL_ERROR_IF(!lua_getstack(L, 1, &ar), "lua_getstack() failed"); FATAL_ERROR_IF(!lua_getinfo(L, "Sl", &ar), "lua_getinfo() failed"); - // Get parent class to get the wrappers map - luaL_checktype(L, 1, LUA_TUSERDATA); - void *ud = lua_touserdata(L, 1); - ModApiBase *o = *(ModApiBase**)ud; - - // New function and new function name - auto it = o->m_deprecated_wrappers.find(ar.name); - // Get backtrace and hash it to reduce the warning flood std::string backtrace = ar.short_src; backtrace.append(":").append(std::to_string(ar.currentline)); @@ -135,46 +124,16 @@ int ModApiBase::l_deprecated_function(lua_State *L) == deprecated_logged.end()) { deprecated_logged.emplace_back(hash); - warningstream << "Call to deprecated function '" << ar.name << "', please use '" - << it->second.name << "' at " << backtrace << std::endl; + warningstream << "Call to deprecated function '" << bad << "', please use '" + << good << "' at " << backtrace << std::endl; - if (m_error_deprecated_calls) + if (dep_mode == DeprecatedHandlingMode::Error) script_error(L, LUA_ERRRUN, NULL, NULL); } u64 end_time = porting::getTimeUs(); g_profiler->avg("l_deprecated_function", end_time - start_time); - return it->second.func(L); + return func(L); } -void ModApiBase::markAliasDeprecated(luaL_Reg *reg) -{ - std::string value = g_settings->get("deprecated_lua_api_handling"); - m_error_deprecated_calls = value == "error"; - - if (!m_error_deprecated_calls && value != "log") - return; - - const char *last_name = nullptr; - lua_CFunction last_func = nullptr; - - // ! Null termination ! - while (reg->func) { - if (last_func == reg->func) { - // Duplicate found - luaL_Reg original_reg; - // Do not inline struct. Breaks MSVC or is error-prone - original_reg.name = last_name; - original_reg.func = reg->func; - m_deprecated_wrappers.emplace( - std::pair(reg->name, original_reg)); - reg->func = l_deprecated_function; - } else { - last_func = reg->func; - last_name = reg->name; - } - - ++reg; - } -} diff --git a/src/script/lua_api/l_base.h b/src/script/lua_api/l_base.h index 65fce8481..aa5905d26 100644 --- a/src/script/lua_api/l_base.h +++ b/src/script/lua_api/l_base.h @@ -41,7 +41,6 @@ class Environment; class ServerInventoryManager; class ModApiBase : protected LuaHelper { - public: static ScriptApiBase* getScriptApiBase(lua_State *L); static Server* getServer(lua_State *L); @@ -75,10 +74,18 @@ public: lua_CFunction func, int top); - static int l_deprecated_function(lua_State *L); - static void markAliasDeprecated(luaL_Reg *reg); -private: - // = { , } - static std::unordered_map m_deprecated_wrappers; - static bool m_error_deprecated_calls; + /** + * A wrapper for deprecated functions. + * + * When called, handles the deprecation according to user settings and then calls `func`. + * + * @throws Lua Error if required by the user settings. + * + * @param L Lua state + * @param good Name of good function/method + * @param bad Name of deprecated function/method + * @param func Actual implementation of function + * @return value from `func` + */ + static int l_deprecated_function(lua_State *L, const char *good, const char *bad, lua_CFunction func); }; diff --git a/src/script/lua_api/l_internal.h b/src/script/lua_api/l_internal.h index a86eeaf79..a10c259ba 100644 --- a/src/script/lua_api/l_internal.h +++ b/src/script/lua_api/l_internal.h @@ -29,7 +29,16 @@ with this program; if not, write to the Free Software Foundation, Inc., #include "common/c_internal.h" #define luamethod(class, name) {#name, class::l_##name} -#define luamethod_aliased(class, name, alias) {#name, class::l_##name}, {#alias, class::l_##name} + +#define luamethod_dep(class, good, bad) \ + {#bad, [](lua_State *L) -> int { \ + return l_deprecated_function(L, #bad, #good, &class::l_##good); \ + }} + +#define luamethod_aliased(class, name, alias) \ + luamethod(class, name), \ + luamethod_dep(class, name, alias) + #define API_FCT(name) registerFunction(L, #name, l_##name, top) // For future use diff --git a/src/script/lua_api/l_noise.cpp b/src/script/lua_api/l_noise.cpp index 9aeb15709..e0861126a 100644 --- a/src/script/lua_api/l_noise.cpp +++ b/src/script/lua_api/l_noise.cpp @@ -122,7 +122,6 @@ void LuaPerlinNoise::Register(lua_State *L) lua_pop(L, 1); - markAliasDeprecated(methods); luaL_openlib(L, 0, methods, 0); lua_pop(L, 1); @@ -381,7 +380,6 @@ void LuaPerlinNoiseMap::Register(lua_State *L) lua_pop(L, 1); - markAliasDeprecated(methods); luaL_openlib(L, 0, methods, 0); lua_pop(L, 1); diff --git a/src/script/lua_api/l_object.cpp b/src/script/lua_api/l_object.cpp index c3f0ec8e0..beb8dd339 100644 --- a/src/script/lua_api/l_object.cpp +++ b/src/script/lua_api/l_object.cpp @@ -2278,7 +2278,6 @@ void ObjectRef::Register(lua_State *L) lua_pop(L, 1); // drop metatable - markAliasDeprecated(methods); luaL_openlib(L, 0, methods, 0); // fill methodtable lua_pop(L, 1); // drop methodtable } @@ -2316,10 +2315,9 @@ luaL_Reg ObjectRef::methods[] = { luamethod(ObjectRef, get_nametag_attributes), luamethod_aliased(ObjectRef, set_velocity, setvelocity), - luamethod(ObjectRef, add_velocity), - {"add_player_velocity", ObjectRef::l_add_velocity}, + luamethod_aliased(ObjectRef, add_velocity, add_player_velocity), luamethod_aliased(ObjectRef, get_velocity, getvelocity), - {"get_player_velocity", ObjectRef::l_get_velocity}, + luamethod_dep(ObjectRef, get_velocity, get_player_velocity), // LuaEntitySAO-only luamethod_aliased(ObjectRef, set_acceleration, setacceleration), -- cgit v1.2.3 From 72b93ec0d75e97ec343e5b936b858d686580677d Mon Sep 17 00:00:00 2001 From: Zughy <63455151+Zughy@users.noreply.github.com> Date: Wed, 4 Nov 2020 21:43:18 +0100 Subject: Fix ObjectRef errors due to lua_isnil() (#10564) Treat 'none' values as 'nil' --- src/script/common/helper.cpp | 44 ++++++++++++++++++++++------------------- src/script/common/helper.h | 5 ++++- src/script/lua_api/l_object.cpp | 32 +++++++++++------------------- 3 files changed, 39 insertions(+), 42 deletions(-) (limited to 'src/script/lua_api/l_object.cpp') diff --git a/src/script/common/helper.cpp b/src/script/common/helper.cpp index f53a2b7e8..488144790 100644 --- a/src/script/common/helper.cpp +++ b/src/script/common/helper.cpp @@ -21,6 +21,7 @@ with this program; if not, write to the Free Software Foundation, Inc., #include #include #include +#include #include "c_types.h" #include "c_internal.h" @@ -54,17 +55,14 @@ template <> bool LuaHelper::readParam(lua_State *L, int index) return lua_toboolean(L, index) != 0; } -template <> bool LuaHelper::readParam(lua_State *L, int index, const bool &default_value) +template <> s16 LuaHelper::readParam(lua_State *L, int index) { - if (lua_isnil(L, index)) - return default_value; - - return lua_toboolean(L, index) != 0; + return lua_tonumber(L, index); } -template <> s16 LuaHelper::readParam(lua_State *L, int index) +template <> int LuaHelper::readParam(lua_State *L, int index) { - return lua_tonumber(L, index); + return luaL_checkint(L, index); } template <> float LuaHelper::readParam(lua_State *L, int index) @@ -105,6 +103,25 @@ template <> v2f LuaHelper::readParam(lua_State *L, int index) return p; } +template <> v3f LuaHelper::readParam(lua_State *L, int index) +{ + v3f p; + CHECK_POS_TAB(index); + lua_getfield(L, index, "x"); + CHECK_POS_COORD("x"); + p.X = readParam(L, -1); + lua_pop(L, 1); + lua_getfield(L, index, "y"); + CHECK_POS_COORD("y"); + p.Y = readParam(L, -1); + lua_pop(L, 1); + lua_getfield(L, index, "z"); + CHECK_POS_COORD("z"); + p.Z = readParam(L, -1); + lua_pop(L, 1); + return p; +} + template <> std::string LuaHelper::readParam(lua_State *L, int index) { size_t length; @@ -113,16 +130,3 @@ template <> std::string LuaHelper::readParam(lua_State *L, int index) result.assign(str, length); return result; } - -template <> -std::string LuaHelper::readParam( - lua_State *L, int index, const std::string &default_value) -{ - std::string result; - const char *str = lua_tostring(L, index); - if (str) - result.append(str); - else - result = default_value; - return result; -} diff --git a/src/script/common/helper.h b/src/script/common/helper.h index d639d6e16..7a794dc9b 100644 --- a/src/script/common/helper.h +++ b/src/script/common/helper.h @@ -50,5 +50,8 @@ protected: * @return read value from Lua or default value if nil */ template - static T readParam(lua_State *L, int index, const T &default_value); + static inline T readParam(lua_State *L, int index, const T &default_value) + { + return lua_isnoneornil(L, index) ? default_value : readParam(L, index); + } }; diff --git a/src/script/lua_api/l_object.cpp b/src/script/lua_api/l_object.cpp index beb8dd339..a6a7c05f9 100644 --- a/src/script/lua_api/l_object.cpp +++ b/src/script/lua_api/l_object.cpp @@ -169,11 +169,9 @@ int ObjectRef::l_punch(lua_State *L) if (sao == nullptr || puncher == nullptr) return 0; - float time_from_last_punch = lua_isnil(L, 3) ? - 1000000.0f : readParam(L,3); + float time_from_last_punch = readParam(L, 3, 1000000.0f); ToolCapabilities toolcap = read_tool_capabilities(L, 4); - v3f dir = lua_isnil(L, 5) ? - sao->getBasePosition() - puncher->getBasePosition() : check_v3f(L, 5); + v3f dir = readParam(L, 5, sao->getBasePosition() - puncher->getBasePosition()); dir.normalize(); u16 src_original_hp = sao->getHP(); @@ -383,20 +381,12 @@ int ObjectRef::l_set_animation(lua_State *L) if (sao == nullptr) return 0; - v2f frames = v2f(1, 1); - if (!lua_isnil(L, 2)) - frames = readParam(L, 2); - float frame_speed = 15; - if (!lua_isnil(L, 3)) - frame_speed = lua_tonumber(L, 3); - float frame_blend = 0; - if (!lua_isnil(L, 4)) - frame_blend = lua_tonumber(L, 4); - bool frame_loop = true; - if (lua_isboolean(L, 5)) - frame_loop = readParam(L, 5); + v2f frame_range = readParam(L, 2, v2f(1, 1)); + float frame_speed = readParam(L, 3, 15.0f); + float frame_blend = readParam(L, 4, 0.0f); + bool frame_loop = readParam(L, 5, true); - sao->setAnimation(frames, frame_speed, frame_blend, frame_loop); + sao->setAnimation(frame_range, frame_speed, frame_blend, frame_loop); return 0; } @@ -436,7 +426,7 @@ int ObjectRef::l_set_local_animation(lua_State *L) if (!lua_isnil(L, 2+1)) frames[i] = read_v2s32(L, 2+i); } - float frame_speed = lua_isnil(L, 6) ? 30 : readParam(L, 6); + float frame_speed = readParam(L, 6, 30.0f); getServer(L)->setLocalPlayerAnimations(player, frames, frame_speed); lua_pushboolean(L, true); @@ -965,9 +955,9 @@ int ObjectRef::l_set_sprite(lua_State *L) if (entitysao == nullptr) return 0; - v2s16 start_frame = lua_isnil(L, 2) ? v2s16(0,0) : readParam(L, 2); - int num_frames = lua_isnil(L, 3) ? 1 : luaL_checkint(L, 3); - float framelength = lua_isnil(L, 4) ? 0.2 : lua_tonumber(L, 4); + v2s16 start_frame = readParam(L, 2, v2s16(0,0)); + int num_frames = readParam(L, 3, 1); + float framelength = readParam(L, 4, 0.2f); bool select_x_by_camera = readParam(L, 5, false); entitysao->setSprite(start_frame, num_frames, framelength, select_x_by_camera); -- cgit v1.2.3 From fca4db4184ac054c53446c0960ec578ebc6b5857 Mon Sep 17 00:00:00 2001 From: SmallJoker Date: Tue, 10 Nov 2020 21:02:53 +0100 Subject: ObjectRef: Re-add legacy code for set_physics_override (#10585) These arguments are used at least by MTG beds and homedecor_common. A deprecation warning is shown to safely remove it in a future release. --- src/script/lua_api/l_object.cpp | 42 +++++++++++++++++++++++++++-------------- 1 file changed, 28 insertions(+), 14 deletions(-) (limited to 'src/script/lua_api/l_object.cpp') diff --git a/src/script/lua_api/l_object.cpp b/src/script/lua_api/l_object.cpp index a6a7c05f9..bc59bd55c 100644 --- a/src/script/lua_api/l_object.cpp +++ b/src/script/lua_api/l_object.cpp @@ -1413,20 +1413,34 @@ int ObjectRef::l_set_physics_override(lua_State *L) if (playersao == nullptr) return 0; - luaL_checktype(L, 2, LUA_TTABLE); - playersao->m_physics_override_speed = getfloatfield_default( - L, 2, "speed", playersao->m_physics_override_speed); - playersao->m_physics_override_jump = getfloatfield_default( - L, 2, "jump", playersao->m_physics_override_jump); - playersao->m_physics_override_gravity = getfloatfield_default( - L, 2, "gravity", playersao->m_physics_override_gravity); - playersao->m_physics_override_sneak = getboolfield_default( - L, 2, "sneak", playersao->m_physics_override_sneak); - playersao->m_physics_override_sneak_glitch = getboolfield_default( - L, 2, "sneak_glitch", playersao->m_physics_override_sneak_glitch); - playersao->m_physics_override_new_move = getboolfield_default( - L, 2, "new_move", playersao->m_physics_override_new_move); - playersao->m_physics_override_sent = false; + if (lua_istable(L, 2)) { + bool modified = false; + modified |= getfloatfield(L, 2, "speed", playersao->m_physics_override_speed); + modified |= getfloatfield(L, 2, "jump", playersao->m_physics_override_jump); + modified |= getfloatfield(L, 2, "gravity", playersao->m_physics_override_gravity); + modified |= getboolfield(L, 2, "sneak", playersao->m_physics_override_sneak); + modified |= getboolfield(L, 2, "sneak_glitch", playersao->m_physics_override_sneak_glitch); + modified |= getboolfield(L, 2, "new_move", playersao->m_physics_override_new_move); + if (modified) + playersao->m_physics_override_sent = false; + } else { + // old, non-table format + // TODO: Remove this code after version 5.4.0 + log_deprecated(L, "Deprecated use of set_physics_override(num, num, num)"); + + if (!lua_isnil(L, 2)) { + playersao->m_physics_override_speed = lua_tonumber(L, 2); + playersao->m_physics_override_sent = false; + } + if (!lua_isnil(L, 3)) { + playersao->m_physics_override_jump = lua_tonumber(L, 3); + playersao->m_physics_override_sent = false; + } + if (!lua_isnil(L, 4)) { + playersao->m_physics_override_gravity = lua_tonumber(L, 4); + playersao->m_physics_override_sent = false; + } + } return 0; } -- cgit v1.2.3