From 677812aab0232e96274a692dbad7fe4e1bf0715d Mon Sep 17 00:00:00 2001 From: ShrBox Date: Thu, 18 Dec 2025 23:25:38 +0800 Subject: [PATCH 01/27] chore: update xmake.lua --- xmake.lua | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/xmake.lua b/xmake.lua index 1950689f..16954061 100644 --- a/xmake.lua +++ b/xmake.lua @@ -1,11 +1,11 @@ add_rules("mode.debug", "mode.release") -add_repositories("levimc-repo https://github.com/LiteLDev/xmake-repo.git") +add_repositories("levimc-repo " .. (get_config("levimc_repo") or "https://github.com/LiteLDev/xmake-repo.git")) if is_config("target_type", "server") then - add_requires("levilamina 1.7.0", {configs = {target_type = "server"}}) + add_requires("levilamina eb5a505faf11dfbc86cee806386ef135e979bace", {configs = {target_type = "server"}}) else - add_requires("levilamina 1.7.0", {configs = {target_type = "client"}}) + add_requires("levilamina eb5a505faf11dfbc86cee806386ef135e979bace", {configs = {target_type = "client"}}) end add_requires("levibuildscript") @@ -48,6 +48,12 @@ if not has_config("vs_runtime") then set_runtimes("MD") end +option("levimc_repo") + set_default("https://github.com/LiteLDev/xmake-repo.git") + set_showmenu(true) + set_description("Set the levimc-repo path or url") +option_end() + option("publish") set_default(false) set_showmenu(true) @@ -114,6 +120,11 @@ target("legacy-script-engine") "src/legacy", "$(builddir)/config" ) + if is_config("target_type", "server") then + add_defines("LL_PLAT_S") + else + add_defines("LL_PLAT_C") + end if has_config("publish") then add_defines("LSE_VERSION_PUBLISH") end From f71014dda0a02b4174aa375ce46589913122487c Mon Sep 17 00:00:00 2001 From: ShrBox Date: Tue, 13 Jan 2026 18:42:46 +0800 Subject: [PATCH 02/27] refactor: support latest CommandRegistrar --- src/legacy/api/CommandAPI.cpp | 26 +++++++++++++------------- src/legacy/api/CommandAPI.h | 2 +- src/legacy/main/BuiltinCommands.cpp | 2 +- xmake.lua | 4 ++-- 4 files changed, 17 insertions(+), 17 deletions(-) diff --git a/src/legacy/api/CommandAPI.cpp b/src/legacy/api/CommandAPI.cpp index 901dde86..e662f9c3 100644 --- a/src/legacy/api/CommandAPI.cpp +++ b/src/legacy/api/CommandAPI.cpp @@ -265,7 +265,7 @@ Local McClass::newCommand(const Arguments& args) { ); } } - auto& command = CommandRegistrar::getInstance().getOrCreateCommand(name, desc, permission, flag); + auto& command = CommandRegistrar::getInstance(false).getOrCreateCommand(name, desc, permission, flag); if (!alias.empty()) { command.alias(alias); } @@ -308,7 +308,7 @@ Local CommandClass::setAlias(const Arguments& args) { std::string alias = args[0].asString().toString(); if (ll::getGamingStatus() == ll::GamingStatus::Starting) { ll::coro::keepThis([commandName(commandName), alias]() -> ll::coro::CoroTask<> { - ll::command::CommandRegistrar::getInstance().getOrCreateCommand(commandName).alias(alias); + ll::command::CommandRegistrar::getInstance(false).getOrCreateCommand(commandName).alias(alias); co_return; }).launch(ll::thread::ServerThreadExecutor::getDefault()); return Boolean::newBoolean(true); @@ -335,12 +335,12 @@ Local CommandClass::setEnum(const Arguments& args) { } if (ll::getGamingStatus() == ll::GamingStatus::Starting) { ll::coro::keepThis([enumName, enumValues]() -> ll::coro::CoroTask<> { - CommandRegistrar::getInstance().tryRegisterRuntimeEnum(enumName, std::move(enumValues)); + CommandRegistrar::getInstance(false).tryRegisterRuntimeEnum(enumName, std::move(enumValues)); co_return; }).launch(ll::thread::ServerThreadExecutor::getDefault()); return String::newString(enumName); } else { - if (CommandRegistrar::getInstance().tryRegisterRuntimeEnum(enumName, std::move(enumValues))) { + if (CommandRegistrar::getInstance(false).tryRegisterRuntimeEnum(enumName, std::move(enumValues))) { return String::newString(enumName); } } @@ -517,7 +517,7 @@ Local CommandClass::addOverload(const Arguments& args) { ll::coro::keepThis( [paramNames, commandName(commandName), overloadFunc, e(EngineScope::currentEngine())]() -> ll::coro::CoroTask<> { - auto cmd = ll::command::CommandRegistrar::getInstance() + auto cmd = ll::command::CommandRegistrar::getInstance(false) .getOrCreateCommand(commandName) .runtimeOverload(getEngineData(e)->plugin); for (auto& paramName : paramNames) { @@ -533,7 +533,7 @@ Local CommandClass::addOverload(const Arguments& args) { ll::coro::keepThis( [commandName(commandName), e(EngineScope::currentEngine())]() -> ll::coro::CoroTask<> { getEngineData(e)->plugin->registeredCommands[commandName].push_back({}); - auto cmd = ll::command::CommandRegistrar::getInstance() + auto cmd = ll::command::CommandRegistrar::getInstance(false) .getOrCreateCommand(commandName) .runtimeOverload(getEngineData(e)->plugin); cmd.execute(onExecute); @@ -591,7 +591,7 @@ Local CommandClass::addOverload(const Arguments& args) { ll::coro::keepThis( [commandName(commandName), e(EngineScope::currentEngine())]() -> ll::coro::CoroTask<> { getEngineData(e)->plugin->registeredCommands[commandName].push_back({}); - auto cmd = ll::command::CommandRegistrar::getInstance() + auto cmd = ll::command::CommandRegistrar::getInstance(false) .getOrCreateCommand(commandName) .runtimeOverload(getEngineData(e)->plugin); cmd.execute(onExecute); @@ -691,11 +691,11 @@ Local CommandClass::setSoftEnum(const Arguments& args) { auto enums = parseStringList(args[1].asArray()); if (ll::getGamingStatus() == ll::GamingStatus::Starting) { ll::coro::keepThis([name, enums]() -> ll::coro::CoroTask<> { - CommandRegistrar::getInstance().tryRegisterSoftEnum(name, std::move(enums)); + CommandRegistrar::getInstance(false).tryRegisterSoftEnum(name, std::move(enums)); co_return; }).launch(ll::thread::ServerThreadExecutor::getDefault()); } else { - CommandRegistrar::getInstance().tryRegisterSoftEnum(name, std::move(enums)); + CommandRegistrar::getInstance(false).tryRegisterSoftEnum(name, std::move(enums)); } return Boolean::newBoolean(true); } @@ -711,11 +711,11 @@ Local CommandClass::addSoftEnumValues(const Arguments& args) { auto enums = parseStringList(args[1].asArray()); if (ll::getGamingStatus() == ll::GamingStatus::Starting) { ll::coro::keepThis([name, enums]() -> ll::coro::CoroTask<> { - CommandRegistrar::getInstance().addSoftEnumValues(name, std::move(enums)); + CommandRegistrar::getInstance(false).addSoftEnumValues(name, std::move(enums)); co_return; }).launch(ll::thread::ServerThreadExecutor::getDefault()); } else { - CommandRegistrar::getInstance().addSoftEnumValues(name, std::move(enums)); + CommandRegistrar::getInstance(false).addSoftEnumValues(name, std::move(enums)); } return Boolean::newBoolean(true); } @@ -731,11 +731,11 @@ Local CommandClass::removeSoftEnumValues(const Arguments& args) { auto enums = parseStringList(args[1].asArray()); if (ll::getGamingStatus() == ll::GamingStatus::Starting) { ll::coro::keepThis([name, enums]() -> ll::coro::CoroTask<> { - CommandRegistrar::getInstance().removeSoftEnumValues(name, std::move(enums)); + CommandRegistrar::getInstance(false).removeSoftEnumValues(name, std::move(enums)); co_return; }).launch(ll::thread::ServerThreadExecutor::getDefault()); } else { - CommandRegistrar::getInstance().removeSoftEnumValues(name, std::move(enums)); + CommandRegistrar::getInstance(false).removeSoftEnumValues(name, std::move(enums)); } return Boolean::newBoolean(true); } diff --git a/src/legacy/api/CommandAPI.h b/src/legacy/api/CommandAPI.h index 6e8ba34b..1e014b2f 100644 --- a/src/legacy/api/CommandAPI.h +++ b/src/legacy/api/CommandAPI.h @@ -51,7 +51,7 @@ class CommandClass : public ScriptClass { std::string commandName; std::string description; inline ll::command::CommandHandle& get() { - return ll::command::CommandRegistrar::getInstance().getOrCreateCommand(commandName); + return ll::command::CommandRegistrar::getInstance(false).getOrCreateCommand(commandName); } inline std::vector parseStringList(Local arr) { if (arr.size() == 0 || !arr.get(0).isString()) return {}; diff --git a/src/legacy/main/BuiltinCommands.cpp b/src/legacy/main/BuiltinCommands.cpp index 4cfd7e20..df954403 100644 --- a/src/legacy/main/BuiltinCommands.cpp +++ b/src/legacy/main/BuiltinCommands.cpp @@ -57,7 +57,7 @@ void RegisterDebugCommand() { DebugCmdLogger->setFormatter(ll::makePolymorphic()); // Node.js engine doesn't support debug engine, Python engine don't need to register command. #if (!defined LSE_BACKEND_NODEJS) && (!defined LSE_BACKEND_PYTHON) - auto& command = ll::command::CommandRegistrar::getInstance() + auto& command = ll::command::CommandRegistrar::getInstance(false) .getOrCreateCommand(LLSE_DEBUG_CMD, "Debug LegacyScriptEngine", CommandPermissionLevel::Owner); command.overload().optional("eval").execute( [](CommandOrigin const&, CommandOutput& output, EngineDebugCommand const& param) { diff --git a/xmake.lua b/xmake.lua index 729fe222..190e6d5b 100644 --- a/xmake.lua +++ b/xmake.lua @@ -3,9 +3,9 @@ add_rules("mode.debug", "mode.release") add_repositories("levimc-repo " .. (get_config("levimc_repo") or "https://github.com/LiteLDev/xmake-repo.git")) if is_config("target_type", "server") then - add_requires("levilamina eb5a505faf11dfbc86cee806386ef135e979bace", {configs = {target_type = "server"}}) + add_requires("levilamina dad11c69b20f644ab7192d45add4e0be1d54d432", {configs = {target_type = "server"}}) else - add_requires("levilamina eb5a505faf11dfbc86cee806386ef135e979bace", {configs = {target_type = "client"}}) + add_requires("levilamina dad11c69b20f644ab7192d45add4e0be1d54d432", {configs = {target_type = "client"}}) end add_requires("levibuildscript") From 86b1783341dab761b1fbe54321c13a098cf40244 Mon Sep 17 00:00:00 2001 From: ShrBox Date: Tue, 13 Jan 2026 19:48:39 +0800 Subject: [PATCH 03/27] fix: fix onUseItemOn on client feat: add debugCommandLevel config --- src/legacy/api/EventAPI.cpp | 3 ++- src/legacy/main/BuiltinCommands.cpp | 7 +++++-- src/lse/Config.h | 3 ++- 3 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/legacy/api/EventAPI.cpp b/src/legacy/api/EventAPI.cpp index f5a0d173..21778d54 100644 --- a/src/legacy/api/EventAPI.cpp +++ b/src/legacy/api/EventAPI.cpp @@ -389,7 +389,8 @@ void EnableEventListener(int eventId) { EVENT_TYPES::onUseItemOn, PlayerClass::newPlayer(&ev.self()), ItemClass::newItem(&ev.item()), - BlockClass::newBlock(ev.block(), ev.blockPos(), ev.self().getDimensionId().id), + ev.block() ? BlockClass::newBlock(ev.block(), ev.blockPos(), ev.self().getDimensionId().id) + : BlockClass::newBlock(ev.blockPos(), ev.self().getDimensionId().id), Number::newNumber((schar)ev.face()), FloatPos::newPos(ev.clickPos(), ev.self().getDimensionId().id) )) { diff --git a/src/legacy/main/BuiltinCommands.cpp b/src/legacy/main/BuiltinCommands.cpp index df954403..021cecb0 100644 --- a/src/legacy/main/BuiltinCommands.cpp +++ b/src/legacy/main/BuiltinCommands.cpp @@ -57,8 +57,11 @@ void RegisterDebugCommand() { DebugCmdLogger->setFormatter(ll::makePolymorphic()); // Node.js engine doesn't support debug engine, Python engine don't need to register command. #if (!defined LSE_BACKEND_NODEJS) && (!defined LSE_BACKEND_PYTHON) - auto& command = ll::command::CommandRegistrar::getInstance(false) - .getOrCreateCommand(LLSE_DEBUG_CMD, "Debug LegacyScriptEngine", CommandPermissionLevel::Owner); + auto& command = ll::command::CommandRegistrar::getInstance(false).getOrCreateCommand( + LLSE_DEBUG_CMD, + "Debug LegacyScriptEngine", + static_cast(lse::LegacyScriptEngine::getInstance().getConfig().debugCommandLevel) + ); command.overload().optional("eval").execute( [](CommandOrigin const&, CommandOutput& output, EngineDebugCommand const& param) { auto& logger = lse::LegacyScriptEngine::getInstance().getSelf().getLogger(); diff --git a/src/lse/Config.h b/src/lse/Config.h index dda510cc..05f1c019 100644 --- a/src/lse/Config.h +++ b/src/lse/Config.h @@ -5,12 +5,13 @@ namespace lse { struct Config { - int version = 1; + int version = 2; bool migratePlugins = true; #ifdef LSE_BACKEND_NODEJS // fix addons that build with node-gyp version < 11.1.0, default: true std::optional fixLegacyAddons{std::nullopt}; #endif + int debugCommandLevel = 4; }; } // namespace lse From e108ee10fa1f9ab2eba5822d0441b323e5c49de9 Mon Sep 17 00:00:00 2001 From: ShrBox Date: Tue, 13 Jan 2026 22:56:06 +0800 Subject: [PATCH 04/27] fix: fix onAte on client --- src/lse/events/PlayerEvents.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/lse/events/PlayerEvents.cpp b/src/lse/events/PlayerEvents.cpp index e6734ead..b78c865e 100644 --- a/src/lse/events/PlayerEvents.cpp +++ b/src/lse/events/PlayerEvents.cpp @@ -7,6 +7,7 @@ #include "ll/api/memory/Hook.h" #include "ll/api/memory/Memory.h" #include "ll/api/service/Bedrock.h" +#include "mc/common/SharedPtr.h" #include "mc/deps/ecs/WeakEntityRef.h" #include "mc/network/ServerPlayerBlockUseHandler.h" #include "mc/server/ServerPlayer.h" @@ -292,7 +293,7 @@ LL_TYPE_INSTANCE_HOOK( LL_TYPE_INSTANCE_HOOK(EatHook, HookPriority::Normal, Player, &Player::completeUsingItem, void) { IF_LISTENED(EVENT_TYPES::onAte) { const std::set item_names{"minecraft:potion", "minecraft:milk_bucket", "minecraft:medicine"}; - auto checked = mItemInUse->mItem->getItem()->isFood() || item_names.contains(mItemInUse->mItem->getTypeName()); + auto checked = mItemInUse->mItem->mItem.lock()->isFood() || item_names.contains(mItemInUse->mItem->getTypeName()); if (checked && !CallEvent(EVENT_TYPES::onAte, PlayerClass::newPlayer(this), ItemClass::newItem(&*mItemInUse->mItem))) stopUsingItem(); From 33fb6eb9eca3fe310942faf4399b327eb5bea348 Mon Sep 17 00:00:00 2001 From: ShrBox Date: Wed, 14 Jan 2026 14:08:33 +0800 Subject: [PATCH 05/27] Revert "fix: fix onAte on client" This reverts commit e108ee10fa1f9ab2eba5822d0441b323e5c49de9. --- src/lse/events/PlayerEvents.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/lse/events/PlayerEvents.cpp b/src/lse/events/PlayerEvents.cpp index b78c865e..e6734ead 100644 --- a/src/lse/events/PlayerEvents.cpp +++ b/src/lse/events/PlayerEvents.cpp @@ -7,7 +7,6 @@ #include "ll/api/memory/Hook.h" #include "ll/api/memory/Memory.h" #include "ll/api/service/Bedrock.h" -#include "mc/common/SharedPtr.h" #include "mc/deps/ecs/WeakEntityRef.h" #include "mc/network/ServerPlayerBlockUseHandler.h" #include "mc/server/ServerPlayer.h" @@ -293,7 +292,7 @@ LL_TYPE_INSTANCE_HOOK( LL_TYPE_INSTANCE_HOOK(EatHook, HookPriority::Normal, Player, &Player::completeUsingItem, void) { IF_LISTENED(EVENT_TYPES::onAte) { const std::set item_names{"minecraft:potion", "minecraft:milk_bucket", "minecraft:medicine"}; - auto checked = mItemInUse->mItem->mItem.lock()->isFood() || item_names.contains(mItemInUse->mItem->getTypeName()); + auto checked = mItemInUse->mItem->getItem()->isFood() || item_names.contains(mItemInUse->mItem->getTypeName()); if (checked && !CallEvent(EVENT_TYPES::onAte, PlayerClass::newPlayer(this), ItemClass::newItem(&*mItemInUse->mItem))) stopUsingItem(); From edcd9eb6f7dbb6a48f6926f6485f076bf01aa3cb Mon Sep 17 00:00:00 2001 From: ShrBox Date: Wed, 14 Jan 2026 14:49:38 +0800 Subject: [PATCH 06/27] fix: fix onAte --- src/lse/events/PlayerEvents.cpp | 28 +++++++++++++++++----------- 1 file changed, 17 insertions(+), 11 deletions(-) diff --git a/src/lse/events/PlayerEvents.cpp b/src/lse/events/PlayerEvents.cpp index e6734ead..25cdce5e 100644 --- a/src/lse/events/PlayerEvents.cpp +++ b/src/lse/events/PlayerEvents.cpp @@ -9,6 +9,7 @@ #include "ll/api/service/Bedrock.h" #include "mc/deps/ecs/WeakEntityRef.h" #include "mc/network/ServerPlayerBlockUseHandler.h" +#include "mc/server/ServerInstance.h" #include "mc/server/ServerPlayer.h" #include "mc/server/module/VanillaServerGameplayEventListener.h" #include "mc/world/ContainerID.h" @@ -19,8 +20,6 @@ #include "mc/world/actor/player/Inventory.h" #include "mc/world/actor/player/Player.h" #include "mc/world/actor/player/PlayerInventory.h" -#include "mc/world/actor/player/PlayerItemInUse.h" -#include "mc/world/effect/EffectDuration.h" #include "mc/world/effect/MobEffectInstance.h" #include "mc/world/events/BlockEventCoordinator.h" #include "mc/world/events/EventResult.h" @@ -290,16 +289,23 @@ LL_TYPE_INSTANCE_HOOK( } LL_TYPE_INSTANCE_HOOK(EatHook, HookPriority::Normal, Player, &Player::completeUsingItem, void) { - IF_LISTENED(EVENT_TYPES::onAte) { - const std::set item_names{"minecraft:potion", "minecraft:milk_bucket", "minecraft:medicine"}; - auto checked = mItemInUse->mItem->getItem()->isFood() || item_names.contains(mItemInUse->mItem->getTypeName()); - if (checked - && !CallEvent(EVENT_TYPES::onAte, PlayerClass::newPlayer(this), ItemClass::newItem(&*mItemInUse->mItem))) - stopUsingItem(); - else origin(); - return; + if (std::this_thread::get_id() == ll::service::getServerInstance()->mServerInstanceThread->get_id()) { + IF_LISTENED(EVENT_TYPES::onAte) { + const std::set item_names{"minecraft:potion", "minecraft:milk_bucket", "minecraft:medicine"}; + auto checked = + mItemInUse->mItem->getItem()->isFood() || item_names.contains(mItemInUse->mItem->getTypeName()); + if (checked + && !CallEvent( + EVENT_TYPES::onAte, + PlayerClass::newPlayer(this), + ItemClass::newItem(&*mItemInUse->mItem) + )) + stopUsingItem(); + else origin(); + return; + } + IF_LISTENED_END(EVENT_TYPES::onAte); } - IF_LISTENED_END(EVENT_TYPES::onAte); origin(); } From 3386acdfca708081587a0ec4a2423f2729e80f00 Mon Sep 17 00:00:00 2001 From: ShrBox Date: Fri, 16 Jan 2026 20:31:20 +0800 Subject: [PATCH 07/27] chore: update workflows chore: update manifest.json & tooth.json refactor: remove MoreGlobal DBStorage --- .github/workflows/build.yml | 7 +- .github/workflows/release.yml | 21 ++++-- manifest.json | 1 + src/legacy/api/PlayerAPI.cpp | 21 +++--- src/lse/Entry.cpp | 7 +- src/lse/api/MoreGlobal.cpp | 26 +------ src/lse/api/MoreGlobal.h | 7 +- src/lse/events/EntityEvents.cpp | 3 - src/lse/events/PlayerEvents.cpp | 27 -------- tooth.json | 116 +++++++++++++++++++++++++++++++- xmake.lua | 6 +- 11 files changed, 154 insertions(+), 88 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 2d124d4f..a84092d6 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -21,6 +21,9 @@ jobs: - lua - python - quickjs + target_type: + - client + - server steps: - uses: actions/checkout@v4 @@ -38,13 +41,13 @@ jobs: xmake repo -u - run: | - xmake f -a x64 -m release -p windows -v -y --backend=${{ matrix.backend }} + xmake f -a x64 -m release -p windows -v -y --target_type=${{ matrix.target_type }} --backend=${{ matrix.backend }} - run: | xmake -y - uses: actions/upload-artifact@v4 with: - name: legacy-script-engine-${{ matrix.backend }}-windows-x64-${{ github.sha }} + name: legacy-script-engine-${{ github.sha }}-${{ matrix.target_type }}-${{ matrix.backend }}-windows-x64 path: | bin/ diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b6dcdba4..36483dbf 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -13,6 +13,9 @@ jobs: - lua - python - quickjs + target_type: + - client + - server steps: - uses: actions/checkout@v4 @@ -30,14 +33,14 @@ jobs: xmake repo -u - run: | - xmake f -a x64 -m release -p windows -v -y --backend=${{ matrix.backend }} --publish=true + xmake f -a x64 -m release -p windows -v -y --target_type=${{ matrix.target_type }} --backend=${{ matrix.backend }} --publish=true - run: | xmake -y - uses: actions/upload-artifact@v4 with: - name: legacy-script-engine-${{ matrix.backend }}-windows-x64-${{ github.sha }} + name: legacy-script-engine-${{ github.sha }}-${{ matrix.target_type }}-${{ matrix.backend }}-windows-x64 path: | bin/ @@ -50,6 +53,9 @@ jobs: - lua - python - quickjs + target_type: + - client + - server runs-on: windows-latest steps: - uses: actions/checkout@v4 @@ -62,7 +68,7 @@ jobs: - uses: actions/download-artifact@v4 with: - name: legacy-script-engine-${{ matrix.backend }}-windows-x64-${{ github.sha }} + name: legacy-script-engine-${{ github.sha }}-${{ matrix.target_type }}-${{ matrix.backend }}-windows-x64 path: artifact - run: | @@ -102,12 +108,15 @@ jobs: - lua - python - quickjs + target_type: + - client + - server steps: - uses: actions/checkout@v4 - uses: actions/download-artifact@v4 with: - name: legacy-script-engine-${{ matrix.backend }}-windows-x64-${{ github.sha }} + name: legacy-script-engine-${{ github.sha }}-${{ matrix.target_type }}-${{ matrix.backend }}-windows-x64 path: release/ - run: | @@ -116,10 +125,10 @@ jobs: - name: Archive release run: | cd release - zip -r ../legacy-script-engine-${{ matrix.backend }}-windows-x64.zip * + zip -r ../legacy-script-engine-${{ matrix.target_type }}-${{ matrix.backend }}-windows-x64.zip * cd .. - uses: softprops/action-gh-release@v1 with: files: | - legacy-script-engine-${{ matrix.backend }}-windows-x64.zip + legacy-script-engine-${{ matrix.target_type }}-${{ matrix.backend }}-windows-x64.zip diff --git a/manifest.json b/manifest.json index 3925c982..1aa92d2e 100644 --- a/manifest.json +++ b/manifest.json @@ -3,6 +3,7 @@ "entry": "${modFile}", "version": "${modVersion}", "type": "native", + "platform": "${modPlatform}", "description": "A plugin engine for running LLSE plugins on LeviLamina", "author": "LiteLDev", "dependencies": [ diff --git a/src/legacy/api/PlayerAPI.cpp b/src/legacy/api/PlayerAPI.cpp index 530e4ebd..bf8905f2 100644 --- a/src/legacy/api/PlayerAPI.cpp +++ b/src/legacy/api/PlayerAPI.cpp @@ -353,8 +353,8 @@ Local McClass::getPlayerNbt(const Arguments& args) { CHECK_ARGS_COUNT(args, 1); CHECK_ARG_TYPE(args[0], ValueKind::kString); try { - auto uuid = mce::UUID::fromString(args[0].asString().toString()); - DBStorage* db = MoreGlobal::dbStorage; + auto uuid = mce::UUID::fromString(args[0].asString().toString()); + auto db = ll::service::getDBStorage(); if (db && db->hasKey("player_" + uuid.asString(), DBHelpers::Category::Player)) { std::unique_ptr playerTag = db->getCompoundTag("player_" + uuid.asString(), DBHelpers::Category::Player); @@ -380,7 +380,7 @@ Local McClass::setPlayerNbt(const Arguments& args) { if (player && tag) { player->load(*tag, MoreGlobal::defaultDataLoadHelper()); } else if (tag) { - DBStorage* db = MoreGlobal::dbStorage; + auto db = ll::service::getDBStorage(); if (db && db->hasKey("player_" + uuid.asString(), DBHelpers::Category::Player)) { std::unique_ptr playerTag = db->getCompoundTag("player_" + uuid.asString(), DBHelpers::Category::Player); @@ -421,7 +421,7 @@ Local McClass::setPlayerNbtTags(const Arguments& args) { } player->load(loadedTag, MoreGlobal::defaultDataLoadHelper()); } else if (tag) { - DBStorage* db = MoreGlobal::dbStorage; + auto db = ll::service::getDBStorage(); if (db && db->hasKey("player_" + uuid.asString(), DBHelpers::Category::Player)) { std::unique_ptr playerTag = db->getCompoundTag("player_" + uuid.asString(), DBHelpers::Category::Player); @@ -492,7 +492,7 @@ Local McClass::getPlayerScore(const Arguments& args) { auto obj = args[1].asString().toString(); Scoreboard& scoreboard = ll::service::getLevel()->getScoreboard(); Objective* objective = scoreboard.getObjective(obj); - DBStorage* db = MoreGlobal::dbStorage; + auto db = ll::service::getDBStorage(); if (!objective || !db || !db->hasKey("player_" + args[0].asString().toString(), DBHelpers::Category::Player)) { return Number::newNumber(0); } @@ -527,7 +527,7 @@ Local McClass::setPlayerScore(const Arguments& args) { try { Scoreboard& scoreboard = ll::service::getLevel()->getScoreboard(); Objective* objective = scoreboard.getObjective(args[1].asString().toString()); - DBStorage* db = MoreGlobal::dbStorage; + auto db = ll::service::getDBStorage(); if (!objective || !db || !db->hasKey("player_" + args[0].asString().toString(), DBHelpers::Category::Player)) { return Boolean::newBoolean(false); } @@ -565,7 +565,7 @@ Local McClass::addPlayerScore(const Arguments& args) { try { Scoreboard& scoreboard = ll::service::getLevel()->getScoreboard(); Objective* objective = scoreboard.getObjective(args[1].asString().toString()); - DBStorage* db = MoreGlobal::dbStorage; + auto db = ll::service::getDBStorage(); if (!objective || !db || !db->hasKey("player_" + args[0].asString().toString(), DBHelpers::Category::Player)) { return Boolean::newBoolean(false); } @@ -603,7 +603,7 @@ Local McClass::reducePlayerScore(const Arguments& args) { try { Scoreboard& scoreboard = ll::service::getLevel()->getScoreboard(); Objective* objective = scoreboard.getObjective(args[1].asString().toString()); - DBStorage* db = MoreGlobal::dbStorage; + auto db = ll::service::getDBStorage(); if (!objective || !db || !db->hasKey("player_" + args[0].asString().toString(), DBHelpers::Category::Player)) { return Boolean::newBoolean(false); } @@ -645,7 +645,7 @@ Local McClass::deletePlayerScore(const Arguments& args) { try { Scoreboard& scoreboard = ll::service::getLevel()->getScoreboard(); Objective* objective = scoreboard.getObjective(args[1].asString().toString()); - DBStorage* db = MoreGlobal::dbStorage; + auto db = ll::service::getDBStorage(); if (!objective || !db || !db->hasKey("player_" + args[0].asString().toString(), DBHelpers::Category::Player)) { return Boolean::newBoolean(false); } @@ -3279,8 +3279,7 @@ Local PlayerClass::getBlockFromViewVector(const Arguments& args) { Block const& bl = player->getDimensionBlockSource().getBlock(bp); BlockType const& legacy = bl.getBlockType(); // isEmpty() - if (bl.isAir() - || (legacy.mProperties == BlockProperty::None && legacy.mMaterial.mType == MaterialType::Any)) { + if (bl.isAir() || (legacy.mProperties == BlockProperty::None && legacy.mMaterial.mType == MaterialType::Any)) { return Local(); } return BlockClass::newBlock(bl, bp, player->getDimensionBlockSource()); diff --git a/src/lse/Entry.cpp b/src/lse/Entry.cpp index ea4018c8..2287c01c 100644 --- a/src/lse/Entry.cpp +++ b/src/lse/Entry.cpp @@ -13,7 +13,6 @@ #include "ll/api/mod/RegisterHelper.h" #include "ll/api/service/PlayerInfo.h" #include "ll/api/utils/ErrorUtils.h" -#include "lse/api/MoreGlobal.h" #include #include @@ -72,9 +71,6 @@ LegacyScriptEngine& LegacyScriptEngine::getInstance() { bool LegacyScriptEngine::enable() { auto& logger = getSelf().getLogger(); try { - if (!api::MoreGlobal::onEnable()) { - logger.error("Failed to enable MoreGlobal"_tr()); - } ll::service::PlayerInfo::getInstance(); RegisterDebugCommand(); } catch (...) { @@ -96,7 +92,6 @@ void initializeLegacyStuff() { InitBasicEventListeners(); InitMessageSystem(); - api::MoreGlobal::onLoad(); } bool LegacyScriptEngine::load() { @@ -186,4 +181,4 @@ void registerPluginManager(const std::shared_ptr& pm) { } // namespace lse -LL_REGISTER_MOD(lse::LegacyScriptEngine, lse::LegacyScriptEngine::getInstance()); \ No newline at end of file +LL_REGISTER_MOD(lse::LegacyScriptEngine, lse::LegacyScriptEngine::getInstance()); diff --git a/src/lse/api/MoreGlobal.cpp b/src/lse/api/MoreGlobal.cpp index 5f4aeaf9..5008c185 100644 --- a/src/lse/api/MoreGlobal.cpp +++ b/src/lse/api/MoreGlobal.cpp @@ -2,34 +2,10 @@ #include "ll/api/memory/Hook.h" #include "mc/dataloadhelper/DefaultDataLoadHelper.h" -#include "mc/world/level/storage/DBStorage.h" -#include "mc/world/level/storage/DBStorageConfig.h" namespace lse::api::MoreGlobal { -DBStorage* dbStorage; + DefaultDataLoadHelper helper; DefaultDataLoadHelper& defaultDataLoadHelper() { return helper; } -LL_TYPE_INSTANCE_HOOK( - DBStorageHook, - HookPriority::Normal, - DBStorage, - &DBStorage::$ctor, - void*, - ::DBStorageConfig config, - ::Bedrock::NotNullNonOwnerPtr<::LevelDbEnv> levelDbEnv -) { - void* ori = origin(std::move(config), levelDbEnv); - MoreGlobal::dbStorage = (DBStorage*)ori; - return ori; -}; - -void onLoad() { DBStorageHook::hook(); } - -bool onEnable() { - if (dbStorage && DBStorageHook::unhook()) { - return true; - } - return false; -} } // namespace lse::api::MoreGlobal diff --git a/src/lse/api/MoreGlobal.h b/src/lse/api/MoreGlobal.h index bdd35541..ad501bc7 100644 --- a/src/lse/api/MoreGlobal.h +++ b/src/lse/api/MoreGlobal.h @@ -1,8 +1,7 @@ #include "mc/dataloadhelper/DefaultDataLoadHelper.h" -class DBStorage; + namespace lse::api::MoreGlobal { -extern DBStorage* dbStorage; + extern DefaultDataLoadHelper& defaultDataLoadHelper(); -extern void onLoad(); -extern bool onEnable(); + }; // namespace lse::api::MoreGlobal diff --git a/src/lse/events/EntityEvents.cpp b/src/lse/events/EntityEvents.cpp index c409e1c0..ba3629fb 100644 --- a/src/lse/events/EntityEvents.cpp +++ b/src/lse/events/EntityEvents.cpp @@ -9,7 +9,6 @@ #include "ll/api/service/GamingStatus.h" #include "lse/api/helper/BlockHelper.h" #include "mc/common/Globals.h" -#include "mc/deps/ecs/gamerefs_entity/EntityContext.h" #include "mc/deps/shared_types/legacy/actor/ActorDamageCause.h" #include "mc/entity/components_json_legacy/NpcComponent.h" #include "mc/entity/components_json_legacy/ProjectileComponent.h" @@ -21,12 +20,10 @@ #include "mc/world/actor/Mob.h" #include "mc/world/actor/VanillaActorRendererId.h" #include "mc/world/actor/boss/WitherBoss.h" -#include "mc/world/actor/npc/ActionContainer.h" #include "mc/world/actor/npc/CommandAction.h" #include "mc/world/actor/npc/StoredCommand.h" #include "mc/world/actor/npc/UrlAction.h" #include "mc/world/actor/player/Player.h" -#include "mc/world/effect/EffectDuration.h" #include "mc/world/effect/MobEffectInstance.h" #include "mc/world/events/ActorEventCoordinator.h" #include "mc/world/item/CrossbowItem.h" diff --git a/src/lse/events/PlayerEvents.cpp b/src/lse/events/PlayerEvents.cpp index 25cdce5e..40589cc6 100644 --- a/src/lse/events/PlayerEvents.cpp +++ b/src/lse/events/PlayerEvents.cpp @@ -507,33 +507,6 @@ LL_TYPE_INSTANCE_HOOK( return origin(item, entity, pos); } -// LL_TYPE_INSTANCE_HOOK( -// UseBucketTakeHook3, -// HookPriority::Normal, -// BucketItem, -// &BucketItem::_useOn, -// InteractionResult, -// ItemStack& instance, -// Actor& entity, -// BlockPos pos, -// uchar face, -// Vec3 const& clickPos -// ) { -// IF_LISTENED(EVENT_TYPES::onUseBucketTake) { -// CallEventRtnValue( -// EVENT_TYPES::onUseBucketTake, -// InteractionResult{InteractionResult::Result::Fail}, -// PlayerClass::newPlayer(), -// ItemClass::newItem(&instance, false), -// EntityClass::newEntity(&entity), -// Number::newNumber(face), -// FloatPos::newPos(pos, entity.getDimensionId().id) -// ); -// } -// IF_LISTENED_END(EVENT_TYPES::onUseBucketTake); -// return origin(instance, entity, pos, face, clickPos); -// } - LL_TYPE_INSTANCE_HOOK(ConsumeTotemHook, HookPriority::Normal, Player, &Player::$consumeTotem, bool) { IF_LISTENED(EVENT_TYPES::onConsumeTotem) { if (!CallEvent(EVENT_TYPES::onConsumeTotem, PlayerClass::newPlayer(this))) { diff --git a/tooth.json b/tooth.json index b635f672..239fd081 100644 --- a/tooth.json +++ b/tooth.json @@ -21,6 +21,14 @@ "github.com/LiteLDev/LegacyScriptEngine#lua": "{{version}}" } }, + { + "label": "client", + "platform": "win-x64", + "dependencies": { + "github.com/LiteLDev/LegacyScriptEngine#quickjs-client": "{{version}}", + "github.com/LiteLDev/LegacyScriptEngine#lua-client": "{{version}}" + } + }, { "label": "nodejs", "platform": "win-x64", @@ -126,6 +134,112 @@ ] } ] + }, + { + "label": "nodejs-client", + "platform": "win-x64", + "dependencies": { + "github.com/LiteLDev/LegacyRemoteCall#client": "0.16.*", + "github.com/LiteLDev/LegacyMoney#client": "0.16.*", + "git.levimc.org/ShrBox/7-zip": "24.*" + }, + "assets": [ + { + "type": "zip", + "urls": [ + "https://{{tooth}}/releases/download/v{{version}}/legacy-script-engine-nodejs-windows-x64.zip" + ], + "placements": [ + { + "type": "dir", + "src": "legacy-script-engine-nodejs/", + "dest": "mods/legacy-script-engine-nodejs/" + } + ] + }, + { + "type": "zip", + "urls": [ + "https://github.com/LiteLDev/node/releases/download/v22.12.0/node-prebuilt.zip" + ], + "placements": [ + { + "type": "dir", + "src": "", + "dest": "mods/legacy-script-engine-nodejs/" + } + ] + } + ] + }, + { + "label": "quickjs-client", + "platform": "win-x64", + "dependencies": { + "github.com/LiteLDev/LegacyRemoteCall#client": "0.16.*", + "github.com/LiteLDev/LegacyMoney#client": "0.16.*" + }, + "assets": [ + { + "type": "zip", + "urls": [ + "https://{{tooth}}/releases/download/v{{version}}/legacy-script-engine-quickjs-windows-x64.zip" + ], + "placements": [ + { + "type": "dir", + "src": "legacy-script-engine-quickjs/", + "dest": "mods/legacy-script-engine-quickjs/" + } + ] + } + ] + }, + { + "label": "lua-client", + "platform": "win-x64", + "dependencies": { + "github.com/LiteLDev/LegacyRemoteCall#client": "0.16.*", + "github.com/LiteLDev/LegacyMoney#client": "0.16.*" + }, + "assets": [ + { + "type": "zip", + "urls": [ + "https://{{tooth}}/releases/download/v{{version}}/legacy-script-engine-lua-windows-x64.zip" + ], + "placements": [ + { + "type": "dir", + "src": "legacy-script-engine-lua/", + "dest": "mods/legacy-script-engine-lua/" + } + ] + } + ] + }, + { + "label": "python-client", + "platform": "win-x64", + "dependencies": { + "github.com/LiteLDev/LegacyRemoteCall#client": "0.16.*", + "github.com/LiteLDev/LegacyMoney#client": "0.16.*" + }, + "assets": [ + { + "type": "zip", + "urls": [ + "https://{{tooth}}/releases/download/v{{version}}/legacy-script-engine-python-windows-x64.zip" + ], + "placements": [ + { + "type": "dir", + "src": "legacy-script-engine-python/", + "dest": "mods/legacy-script-engine-python/" + } + ] + } + ] } ] -} \ No newline at end of file +} diff --git a/xmake.lua b/xmake.lua index 190e6d5b..9bf54ff4 100644 --- a/xmake.lua +++ b/xmake.lua @@ -3,9 +3,9 @@ add_rules("mode.debug", "mode.release") add_repositories("levimc-repo " .. (get_config("levimc_repo") or "https://github.com/LiteLDev/xmake-repo.git")) if is_config("target_type", "server") then - add_requires("levilamina dad11c69b20f644ab7192d45add4e0be1d54d432", {configs = {target_type = "server"}}) + add_requires("levilamina 1.8.0-rc.1", {configs = {target_type = "server"}}) else - add_requires("levilamina dad11c69b20f644ab7192d45add4e0be1d54d432", {configs = {target_type = "client"}}) + add_requires("levilamina 1.8.0-rc.1", {configs = {target_type = "client"}}) end add_requires("levibuildscript") @@ -225,4 +225,4 @@ target("legacy-script-engine") os.mkdir(outputPath) os.cp(langPath, outputPath) end) - end \ No newline at end of file + end From fedea8fa001b6636ee7c1a08b9521bed8b71ffd3 Mon Sep 17 00:00:00 2001 From: ShrBox Date: Sun, 18 Jan 2026 20:12:11 +0800 Subject: [PATCH 08/27] chore: update tooth.json & CHANGELOG.md update CHANGELOG.md --- CHANGELOG.md | 5 +++++ tooth.json | 34 +++++++++++++++++----------------- xmake.lua | 4 ++-- 3 files changed, 24 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 95c9011f..52a9cb89 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,11 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Changed + +- Supported LeviLamina 1.8.0-rc.2 +- Added client support + ## [0.16.7] - 2026-01-13 ### Changed diff --git a/tooth.json b/tooth.json index 239fd081..07c476af 100644 --- a/tooth.json +++ b/tooth.json @@ -2,7 +2,7 @@ "format_version": 3, "format_uuid": "289f771f-2c9a-4d73-9f3f-8492495a924d", "tooth": "github.com/LiteLDev/LegacyScriptEngine", - "version": "0.16.7", + "version": "0.17.0-rc.1", "info": { "name": "LegacyScriptEngine", "description": "A plugin engine for running LLSE plugins on LeviLamina", @@ -33,8 +33,8 @@ "label": "nodejs", "platform": "win-x64", "dependencies": { - "github.com/LiteLDev/LegacyRemoteCall": "0.16.*", - "github.com/LiteLDev/LegacyMoney": "0.16.*", + "github.com/LiteLDev/LegacyRemoteCall": "0.17.0-rc.1", + "github.com/LiteLDev/LegacyMoney": "0.17.0-rc.1", "git.levimc.org/ShrBox/7-zip": "24.*" }, "assets": [ @@ -70,8 +70,8 @@ "label": "quickjs", "platform": "win-x64", "dependencies": { - "github.com/LiteLDev/LegacyRemoteCall": "0.16.*", - "github.com/LiteLDev/LegacyMoney": "0.16.*" + "github.com/LiteLDev/LegacyRemoteCall": "0.17.0-rc.1", + "github.com/LiteLDev/LegacyMoney": "0.17.0-rc.1" }, "assets": [ { @@ -93,8 +93,8 @@ "label": "lua", "platform": "win-x64", "dependencies": { - "github.com/LiteLDev/LegacyRemoteCall": "0.16.*", - "github.com/LiteLDev/LegacyMoney": "0.16.*" + "github.com/LiteLDev/LegacyRemoteCall": "0.17.0-rc.1", + "github.com/LiteLDev/LegacyMoney": "0.17.0-rc.1" }, "assets": [ { @@ -116,8 +116,8 @@ "label": "python", "platform": "win-x64", "dependencies": { - "github.com/LiteLDev/LegacyRemoteCall": "0.16.*", - "github.com/LiteLDev/LegacyMoney": "0.16.*" + "github.com/LiteLDev/LegacyRemoteCall": "0.17.0-rc.1", + "github.com/LiteLDev/LegacyMoney": "0.17.0-rc.1" }, "assets": [ { @@ -139,8 +139,8 @@ "label": "nodejs-client", "platform": "win-x64", "dependencies": { - "github.com/LiteLDev/LegacyRemoteCall#client": "0.16.*", - "github.com/LiteLDev/LegacyMoney#client": "0.16.*", + "github.com/LiteLDev/LegacyRemoteCall#client": "0.17.0-rc.1", + "github.com/LiteLDev/LegacyMoney#client": "0.17.0-rc.1", "git.levimc.org/ShrBox/7-zip": "24.*" }, "assets": [ @@ -176,8 +176,8 @@ "label": "quickjs-client", "platform": "win-x64", "dependencies": { - "github.com/LiteLDev/LegacyRemoteCall#client": "0.16.*", - "github.com/LiteLDev/LegacyMoney#client": "0.16.*" + "github.com/LiteLDev/LegacyRemoteCall#client": "0.17.0-rc.1", + "github.com/LiteLDev/LegacyMoney#client": "0.17.0-rc.1" }, "assets": [ { @@ -199,8 +199,8 @@ "label": "lua-client", "platform": "win-x64", "dependencies": { - "github.com/LiteLDev/LegacyRemoteCall#client": "0.16.*", - "github.com/LiteLDev/LegacyMoney#client": "0.16.*" + "github.com/LiteLDev/LegacyRemoteCall#client": "0.17.0-rc.1", + "github.com/LiteLDev/LegacyMoney#client": "0.17.0-rc.1" }, "assets": [ { @@ -222,8 +222,8 @@ "label": "python-client", "platform": "win-x64", "dependencies": { - "github.com/LiteLDev/LegacyRemoteCall#client": "0.16.*", - "github.com/LiteLDev/LegacyMoney#client": "0.16.*" + "github.com/LiteLDev/LegacyRemoteCall#client": "0.17.0-rc.1", + "github.com/LiteLDev/LegacyMoney#client": "0.17.0-rc.1" }, "assets": [ { diff --git a/xmake.lua b/xmake.lua index 9bf54ff4..c662292c 100644 --- a/xmake.lua +++ b/xmake.lua @@ -3,9 +3,9 @@ add_rules("mode.debug", "mode.release") add_repositories("levimc-repo " .. (get_config("levimc_repo") or "https://github.com/LiteLDev/xmake-repo.git")) if is_config("target_type", "server") then - add_requires("levilamina 1.8.0-rc.1", {configs = {target_type = "server"}}) + add_requires("levilamina 1.8.0-rc.2", {configs = {target_type = "server"}}) else - add_requires("levilamina 1.8.0-rc.1", {configs = {target_type = "client"}}) + add_requires("levilamina 1.8.0-rc.2", {configs = {target_type = "client"}}) end add_requires("levibuildscript") From b7ed3a36e9aec2f61140327ada9e1e7e63d007ca Mon Sep 17 00:00:00 2001 From: ShrBox Date: Sun, 18 Jan 2026 20:13:08 +0800 Subject: [PATCH 09/27] chore: update .gitignore --- .gitignore | 1 + 1 file changed, 1 insertion(+) diff --git a/.gitignore b/.gitignore index 6ca4a2b5..a66c74e9 100644 --- a/.gitignore +++ b/.gitignore @@ -552,6 +552,7 @@ fabric.properties /.xmake/ /build/ /CMakeLists.txt +/cmake-build-*/ # Project specific ignores From 241186e843bedc0a7005355058affe42f2313ce9 Mon Sep 17 00:00:00 2001 From: ShrBox Date: Sun, 18 Jan 2026 20:29:12 +0800 Subject: [PATCH 10/27] chore: rename legacy-script-engine to LegacyScriptEngine for release zip --- .github/workflows/build.yml | 2 +- .github/workflows/release.yml | 10 +++++----- tooth.json | 16 ++++++++-------- xmake.lua | 2 +- 4 files changed, 15 insertions(+), 15 deletions(-) diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index a84092d6..791f086e 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -48,6 +48,6 @@ jobs: - uses: actions/upload-artifact@v4 with: - name: legacy-script-engine-${{ github.sha }}-${{ matrix.target_type }}-${{ matrix.backend }}-windows-x64 + name: ${{ github.event.repository.name }}-${{ github.sha }}-${{ matrix.target_type }}-${{ matrix.backend }}-windows-x64 path: | bin/ diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 36483dbf..a4d46b85 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -40,7 +40,7 @@ jobs: - uses: actions/upload-artifact@v4 with: - name: legacy-script-engine-${{ github.sha }}-${{ matrix.target_type }}-${{ matrix.backend }}-windows-x64 + name: ${{ github.event.repository.name }}-${{ github.sha }}-${{ matrix.target_type }}-${{ matrix.backend }}-windows-x64 path: | bin/ @@ -68,7 +68,7 @@ jobs: - uses: actions/download-artifact@v4 with: - name: legacy-script-engine-${{ github.sha }}-${{ matrix.target_type }}-${{ matrix.backend }}-windows-x64 + name: ${{ github.event.repository.name }}-${{ github.sha }}-${{ matrix.target_type }}-${{ matrix.backend }}-windows-x64 path: artifact - run: | @@ -116,7 +116,7 @@ jobs: - uses: actions/download-artifact@v4 with: - name: legacy-script-engine-${{ github.sha }}-${{ matrix.target_type }}-${{ matrix.backend }}-windows-x64 + name: ${{ github.event.repository.name }}-${{ github.sha }}-${{ matrix.target_type }}-${{ matrix.backend }}-windows-x64 path: release/ - run: | @@ -125,10 +125,10 @@ jobs: - name: Archive release run: | cd release - zip -r ../legacy-script-engine-${{ matrix.target_type }}-${{ matrix.backend }}-windows-x64.zip * + zip -r ../${{ github.event.repository.name }}-${{ matrix.target_type }}-${{ matrix.backend }}-windows-x64.zip * cd .. - uses: softprops/action-gh-release@v1 with: files: | - legacy-script-engine-${{ matrix.target_type }}-${{ matrix.backend }}-windows-x64.zip + ${{ github.event.repository.name }}-${{ matrix.target_type }}-${{ matrix.backend }}-windows-x64.zip diff --git a/tooth.json b/tooth.json index 07c476af..cdf9eb75 100644 --- a/tooth.json +++ b/tooth.json @@ -41,7 +41,7 @@ { "type": "zip", "urls": [ - "https://{{tooth}}/releases/download/v{{version}}/legacy-script-engine-nodejs-windows-x64.zip" + "https://{{tooth}}/releases/download/v{{version}}/LegacyScriptEngine-server-nodejs-windows-x64.zip" ], "placements": [ { @@ -77,7 +77,7 @@ { "type": "zip", "urls": [ - "https://{{tooth}}/releases/download/v{{version}}/legacy-script-engine-quickjs-windows-x64.zip" + "https://{{tooth}}/releases/download/v{{version}}/LegacyScriptEngine-server-quickjs-windows-x64.zip" ], "placements": [ { @@ -100,7 +100,7 @@ { "type": "zip", "urls": [ - "https://{{tooth}}/releases/download/v{{version}}/legacy-script-engine-lua-windows-x64.zip" + "https://{{tooth}}/releases/download/v{{version}}/LegacyScriptEngine-server-lua-windows-x64.zip" ], "placements": [ { @@ -123,7 +123,7 @@ { "type": "zip", "urls": [ - "https://{{tooth}}/releases/download/v{{version}}/legacy-script-engine-python-windows-x64.zip" + "https://{{tooth}}/releases/download/v{{version}}/LegacyScriptEngine-server-python-windows-x64.zip" ], "placements": [ { @@ -147,7 +147,7 @@ { "type": "zip", "urls": [ - "https://{{tooth}}/releases/download/v{{version}}/legacy-script-engine-nodejs-windows-x64.zip" + "https://{{tooth}}/releases/download/v{{version}}/LegacyScriptEngine-client-nodejs-windows-x64.zip" ], "placements": [ { @@ -183,7 +183,7 @@ { "type": "zip", "urls": [ - "https://{{tooth}}/releases/download/v{{version}}/legacy-script-engine-quickjs-windows-x64.zip" + "https://{{tooth}}/releases/download/v{{version}}/LegacyScriptEngine-client-quickjs-windows-x64.zip" ], "placements": [ { @@ -206,7 +206,7 @@ { "type": "zip", "urls": [ - "https://{{tooth}}/releases/download/v{{version}}/legacy-script-engine-lua-windows-x64.zip" + "https://{{tooth}}/releases/download/v{{version}}/LegacyScriptEngine-client-lua-windows-x64.zip" ], "placements": [ { @@ -229,7 +229,7 @@ { "type": "zip", "urls": [ - "https://{{tooth}}/releases/download/v{{version}}/legacy-script-engine-python-windows-x64.zip" + "https://{{tooth}}/releases/download/v{{version}}/LegacyScriptEngine-client-python-windows-x64.zip" ], "placements": [ { diff --git a/xmake.lua b/xmake.lua index c662292c..2e79284e 100644 --- a/xmake.lua +++ b/xmake.lua @@ -70,7 +70,7 @@ option("backend") set_default("lua") set_values("lua", "quickjs", "python", "nodejs") -target("legacy-script-engine") +target("LegacyScriptEngine") add_rules("@levibuildscript/linkrule") add_cxflags( "/EHa", From 4c05c1ff8ab6f95716328ea9faea1736d6527999 Mon Sep 17 00:00:00 2001 From: ShrBox Date: Sun, 18 Jan 2026 21:48:42 +0800 Subject: [PATCH 11/27] feat: add lse::LegacyScriptEngine::getLogger() --- src/legacy/api/APIHelp.cpp | 2 +- src/legacy/api/APIHelp.h | 60 +++++++++---------- src/legacy/api/CommandAPI.cpp | 6 +- src/legacy/api/CommandCompatibleAPI.cpp | 2 +- src/legacy/api/DataAPI.cpp | 60 +++++++++---------- src/legacy/api/DatabaseAPI.cpp | 14 ++--- src/legacy/api/EventAPI.cpp | 10 ++-- src/legacy/api/EventAPI.h | 38 ++++++------ src/legacy/api/NbtAPI.cpp | 4 +- src/legacy/api/NetworkAPI.cpp | 24 ++++---- src/legacy/api/PlayerAPI.cpp | 8 +-- src/legacy/api/RemoteCallAPI.cpp | 6 +- src/legacy/api/SimulatedPlayerAPI.cpp | 6 +- src/legacy/api/SystemAPI.cpp | 4 +- src/legacy/engine/GlobalShareData.cpp | 4 +- src/legacy/engine/MessageSystem.cpp | 60 +++++++++---------- src/legacy/engine/RemoteCall.cpp | 42 ++++++------- src/legacy/engine/TimeTaskSystem.cpp | 20 +++---- src/legacy/legacyapi/db/Session.cpp | 12 ++-- .../legacyapi/db/impl/mysql/Session.cpp | 20 +++---- src/legacy/legacyapi/db/impl/mysql/Stmt.cpp | 32 +++++----- .../legacyapi/db/impl/sqlite/Session.cpp | 14 ++--- src/legacy/legacyapi/db/impl/sqlite/Stmt.cpp | 26 ++++---- src/legacy/main/BuiltinCommands.cpp | 4 +- src/legacy/main/NodeJsHelper.cpp | 30 +++++----- src/legacy/main/PythonHelper.cpp | 4 +- src/legacy/utils/IniHelper.cpp | 4 +- src/legacy/utils/JsonHelper.h | 12 ++-- src/lse/Entry.h | 2 + src/lse/PluginManager.cpp | 4 +- 30 files changed, 268 insertions(+), 266 deletions(-) diff --git a/src/legacy/api/APIHelp.cpp b/src/legacy/api/APIHelp.cpp index 67ed8517..f0f9391b 100644 --- a/src/legacy/api/APIHelp.cpp +++ b/src/legacy/api/APIHelp.cpp @@ -332,7 +332,7 @@ Local JsonToValue(std::string jsonStr) { auto j = ordered_json::parse(jsonStr, nullptr, true, true); return JsonToValue(j); } catch (const ordered_json::exception& e) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().warn( + lse::LegacyScriptEngine::getLogger().warn( "{}{}", "JSON parse error"_tr(), ll::string_utils::tou8str(e.what()) diff --git a/src/legacy/api/APIHelp.h b/src/legacy/api/APIHelp.h index 38c30668..ec4fa1b0 100644 --- a/src/legacy/api/APIHelp.h +++ b/src/legacy/api/APIHelp.h @@ -25,19 +25,19 @@ std::string ValueKindToString(const ValueKind& kind); // 输出脚本调用堆栈,API名称,以及插件名 inline void CREATE_EXCEPTION_WITH_SCRIPT_INFO(std::string const& func = {}, std::string const& msg = {}) { auto e = script::Exception(msg); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "script::Exception: {0}\n{1}", e.message(), e.stacktrace() ); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("In API: " + func); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("In Plugin: " + getEngineOwnData()->pluginName); + lse::LegacyScriptEngine::getLogger().error("In API: " + func); + lse::LegacyScriptEngine::getLogger().error("In Plugin: " + getEngineOwnData()->pluginName); } inline void LOG_ERROR_WITH_SCRIPT_INFO(std::string const& func = {}, std::string const& msg = {}) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error(msg); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("In API: " + func); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("In Plugin: " + getEngineOwnData()->pluginName); + lse::LegacyScriptEngine::getLogger().error(msg); + lse::LegacyScriptEngine::getLogger().error("In API: " + func); + lse::LegacyScriptEngine::getLogger().error("In Plugin: " + getEngineOwnData()->pluginName); } // 参数类型错误输出 @@ -72,13 +72,13 @@ inline void LOG_WRONG_ARGS_COUNT(std::string const& func = {}) { // 截获引擎异常 #define CATCH(LOG) \ catch (const Exception& e) { \ - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error(e.stacktrace()); \ + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); \ + lse::LegacyScriptEngine::getLogger().error(e.stacktrace()); \ LOG_ERROR_WITH_SCRIPT_INFO(__FUNCTION__, LOG); \ return Local(); \ } \ catch (...) { \ - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); \ + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); \ LOG_ERROR_WITH_SCRIPT_INFO(__FUNCTION__, LOG); \ return Local(); \ } @@ -107,13 +107,13 @@ inline void LOG_WRONG_ARGS_COUNT(std::string const& func = {}) { // 截获引擎异常_Constructor #define CATCH_C(LOG) \ catch (const Exception& e) { \ - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error(e.stacktrace()); \ + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); \ + lse::LegacyScriptEngine::getLogger().error(e.stacktrace()); \ LOG_ERROR_WITH_SCRIPT_INFO(__FUNCTION__, LOG); \ return nullptr; \ } \ catch (...) { \ - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); \ + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); \ LOG_ERROR_WITH_SCRIPT_INFO(__FUNCTION__, LOG); \ return nullptr; \ } @@ -121,13 +121,13 @@ inline void LOG_WRONG_ARGS_COUNT(std::string const& func = {}) { // 截获引擎异常_Setter #define CATCH_S(LOG) \ catch (const Exception& e) { \ - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error(e.stacktrace()); \ + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); \ + lse::LegacyScriptEngine::getLogger().error(e.stacktrace()); \ LOG_ERROR_WITH_SCRIPT_INFO(__FUNCTION__, LOG); \ return; \ } \ catch (...) { \ - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); \ + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); \ LOG_ERROR_WITH_SCRIPT_INFO(__FUNCTION__, LOG); \ return; \ } @@ -135,33 +135,33 @@ inline void LOG_WRONG_ARGS_COUNT(std::string const& func = {}) { // 截获引擎异常_Constructor #define CATCH_WITHOUT_RETURN(LOG) \ catch (const Exception& e) { \ - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error(e.stacktrace()); \ + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); \ + lse::LegacyScriptEngine::getLogger().error(e.stacktrace()); \ LOG_ERROR_WITH_SCRIPT_INFO(__FUNCTION__, LOG); \ } \ catch (...) { \ - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); \ + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); \ LOG_ERROR_WITH_SCRIPT_INFO(__FUNCTION__, LOG); \ } // 截获回调函数异常 #define CATCH_IN_CALLBACK(callback) \ catch (const Exception& e) { \ - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error(e.stacktrace()); \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( \ + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); \ + lse::LegacyScriptEngine::getLogger().error(e.stacktrace()); \ + lse::LegacyScriptEngine::getLogger().error( \ std::string("In callback for ") + callback \ ); \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( \ + lse::LegacyScriptEngine::getLogger().error( \ "In Plugin: " + getEngineOwnData()->pluginName \ ); \ } \ catch (...) { \ - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( \ + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); \ + lse::LegacyScriptEngine::getLogger().error( \ std::string("In callback for ") + callback \ ); \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( \ + lse::LegacyScriptEngine::getLogger().error( \ "In Plugin: " + getEngineOwnData()->pluginName \ ); \ } @@ -252,7 +252,7 @@ struct EnumDefineBuilder { } return arr; } catch (const std::exception&) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Error in " __FUNCTION__); + lse::LegacyScriptEngine::getLogger().error("Error in " __FUNCTION__); } return Local(); } @@ -265,7 +265,7 @@ struct EnumDefineBuilder { } return obj; } catch (const std::exception&) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Error in " __FUNCTION__); + lse::LegacyScriptEngine::getLogger().error("Error in " __FUNCTION__); } return Local(); } @@ -280,7 +280,7 @@ struct EnumDefineBuilder { return String::newString(magic_enum::enum_name(static_cast(args[0].asNumber().toInt32()))); return Local(); } catch (const std::exception&) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Error in " __FUNCTION__); + lse::LegacyScriptEngine::getLogger().error("Error in " __FUNCTION__); } return Local(); } @@ -289,7 +289,7 @@ struct EnumDefineBuilder { try { return String::newString(typeid(Type).name() + 5); } catch (const std::exception&) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Error in " __FUNCTION__); + lse::LegacyScriptEngine::getLogger().error("Error in " __FUNCTION__); } return Local(); } @@ -302,7 +302,7 @@ struct EnumDefineBuilder { try { return Number::newNumber(static_cast(val)); } catch (const std::exception&) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Error in get {}.{}", enumName, name diff --git a/src/legacy/api/CommandAPI.cpp b/src/legacy/api/CommandAPI.cpp index e662f9c3..dd96a3b7 100644 --- a/src/legacy/api/CommandAPI.cpp +++ b/src/legacy/api/CommandAPI.cpp @@ -260,7 +260,7 @@ Local McClass::newCommand(const Arguments& args) { if (registry) { auto instance = registry->findCommand(name); if (instance) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().warn( + lse::LegacyScriptEngine::getLogger().warn( "Runtime command {} already exists, changes will not beapplied except for setOverload!"_tr(name) ); } @@ -352,7 +352,7 @@ Local CommandClass::setEnum(const Arguments& args) { void onExecute(CommandOrigin const& origin, CommandOutput& output, RuntimeCommand const& runtime) { std::string commandName = runtime.getCommandName(); if (localShareData->commandCallbacks.find(commandName) == localShareData->commandCallbacks.end()) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().warn( + lse::LegacyScriptEngine::getLogger().warn( "Command {} failed to execute, is the plugin unloaded?"_tr(commandName) ); return; @@ -366,7 +366,7 @@ void onExecute(CommandOrigin const& origin, CommandOutput& output, RuntimeComman auto& registeredCommands = getEngineOwnData()->plugin->registeredCommands; if (registeredCommands.find(commandName) == registeredCommands.end()) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().warn( + lse::LegacyScriptEngine::getLogger().warn( "Could not find {} in registered commands."_tr(commandName) ); return; diff --git a/src/legacy/api/CommandCompatibleAPI.cpp b/src/legacy/api/CommandCompatibleAPI.cpp index 1aa594f1..b4a6fff8 100644 --- a/src/legacy/api/CommandCompatibleAPI.cpp +++ b/src/legacy/api/CommandCompatibleAPI.cpp @@ -100,7 +100,7 @@ Local McClass::regConsoleCmd(const Arguments& args) { // Helper bool SendCmdOutput(const std::string& output) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().info(output); + lse::LegacyScriptEngine::getLogger().info(output); return true; } // Helper diff --git a/src/legacy/api/DataAPI.cpp b/src/legacy/api/DataAPI.cpp index 10d0b3c3..da9fa1a9 100644 --- a/src/legacy/api/DataAPI.cpp +++ b/src/legacy/api/DataAPI.cpp @@ -206,8 +206,8 @@ Local ConfJsonClass::reload(const Arguments&) { try { return Boolean::newBoolean(reload()); } catch (const ordered_json::exception& e) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Fail to parse json content in file!"); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + lse::LegacyScriptEngine::getLogger().error("Fail to parse json content in file!"); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); return Boolean::newBoolean(false); } CATCH("Fail in confJsonReload!"); @@ -254,8 +254,8 @@ bool ConfJsonClass::reload() { try { jsonConf = ordered_json::parse(*jsonTexts, nullptr, true, true); } catch (...) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Fail in confJsonReload!"); - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + lse::LegacyScriptEngine::getLogger().error("Fail in confJsonReload!"); + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); return false; } @@ -534,12 +534,12 @@ Local MoneyClass::set(const Arguments& args) { EconomySystem::setMoney(args[0].asString().toString(), args[1].asNumber().toInt64()) ); } catch (const std::invalid_argument& e) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Bad argument in MoneySet!"); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + lse::LegacyScriptEngine::getLogger().error("Bad argument in MoneySet!"); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); return Boolean::newBoolean(false); } catch (const std::out_of_range& e) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Bad argument in MoneySet!"); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + lse::LegacyScriptEngine::getLogger().error("Bad argument in MoneySet!"); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); return Boolean::newBoolean(false); } CATCH("Fail in MoneySet!"); @@ -552,12 +552,12 @@ Local MoneyClass::get(const Arguments& args) { try { return Number::newNumber(EconomySystem::getMoney(args[0].asString().toString())); } catch (const std::invalid_argument& e) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Bad argument in MoneyGet!"); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + lse::LegacyScriptEngine::getLogger().error("Bad argument in MoneyGet!"); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); return Number::newNumber(0); } catch (const std::out_of_range& e) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Bad argument in MoneyGet!"); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + lse::LegacyScriptEngine::getLogger().error("Bad argument in MoneyGet!"); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); return Number::newNumber(0); } CATCH("Fail in MoneyGet!"); @@ -573,12 +573,12 @@ Local MoneyClass::add(const Arguments& args) { EconomySystem::addMoney(args[0].asString().toString(), args[1].asNumber().toInt64()) ); } catch (const std::invalid_argument& e) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Bad argument in MoneyAdd!"); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + lse::LegacyScriptEngine::getLogger().error("Bad argument in MoneyAdd!"); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); return Boolean::newBoolean(false); } catch (const std::out_of_range& e) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Bad argument in MoneyAdd!"); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + lse::LegacyScriptEngine::getLogger().error("Bad argument in MoneyAdd!"); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); return Boolean::newBoolean(false); } CATCH("Fail in MoneyAdd!"); @@ -594,12 +594,12 @@ Local MoneyClass::reduce(const Arguments& args) { EconomySystem::reduceMoney(args[0].asString().toString(), args[1].asNumber().toInt64()) ); } catch (const std::invalid_argument& e) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Bad argument in MoneyReduce!"); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + lse::LegacyScriptEngine::getLogger().error("Bad argument in MoneyReduce!"); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); return Boolean::newBoolean(false); } catch (const std::out_of_range& e) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Bad argument in MoneyReduce!"); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + lse::LegacyScriptEngine::getLogger().error("Bad argument in MoneyReduce!"); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); return Boolean::newBoolean(false); } CATCH("Fail in MoneyReduce!"); @@ -623,12 +623,12 @@ Local MoneyClass::trans(const Arguments& args) { ) ); } catch (const std::invalid_argument& e) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Bad argument in MoneyTrans!"); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + lse::LegacyScriptEngine::getLogger().error("Bad argument in MoneyTrans!"); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); return Boolean::newBoolean(false); } catch (const std::out_of_range& e) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Bad argument in MoneyTrans!"); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + lse::LegacyScriptEngine::getLogger().error("Bad argument in MoneyTrans!"); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); return Boolean::newBoolean(false); } CATCH("Fail in MoneyTrans!"); @@ -665,12 +665,12 @@ Local MoneyClass::getHistory(const Arguments& args) { string res{EconomySystem::getMoneyHist(args[0].asString().toString(), args[1].asNumber().toInt32())}; return objectificationMoneyHistory(res); } catch (const std::invalid_argument& e) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Bad argument in MoneyGetHistory!"); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + lse::LegacyScriptEngine::getLogger().error("Bad argument in MoneyGetHistory!"); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); return Local(); } catch (const std::out_of_range& e) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Bad argument in MoneyGetHistory!"); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + lse::LegacyScriptEngine::getLogger().error("Bad argument in MoneyGetHistory!"); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); return Local(); } CATCH("Fail in MoneyGetHistory!"); @@ -837,7 +837,7 @@ Local DataClass::toJson(const Arguments& args) { try { return String::newString(ValueToJson(args[0], spaces)); } catch (...) { - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); LOG_ERROR_WITH_SCRIPT_INFO(__FUNCTION__, "Failed to transform into Json."); return Local(); } @@ -853,7 +853,7 @@ Local DataClass::parseJson(const Arguments& args) { try { return JsonToValue(args[0].asString().toString()); } catch (...) { - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); LOG_ERROR_WITH_SCRIPT_INFO(__FUNCTION__, "Failed to parse from Json."); return Local(); } diff --git a/src/legacy/api/DatabaseAPI.cpp b/src/legacy/api/DatabaseAPI.cpp index 2e0925ac..fdee2520 100644 --- a/src/legacy/api/DatabaseAPI.cpp +++ b/src/legacy/api/DatabaseAPI.cpp @@ -4,9 +4,9 @@ using namespace DB; #define CATCH_AND_THROW(LOG) \ catch (const Exception& e) { \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error(LOG); \ - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( \ + lse::LegacyScriptEngine::getLogger().error(LOG); \ + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); \ + lse::LegacyScriptEngine::getLogger().error( \ "In Plugin: " + getEngineOwnData()->pluginName \ ); \ return Local(); \ @@ -15,10 +15,10 @@ using namespace DB; throw Exception(ll::string_utils::tou8str(e.what())); \ } \ catch (...) { \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Uncaught Exception Detected!"); \ - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("In API: " __FUNCTION__); \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( \ + lse::LegacyScriptEngine::getLogger().error("Uncaught Exception Detected!"); \ + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); \ + lse::LegacyScriptEngine::getLogger().error("In API: " __FUNCTION__); \ + lse::LegacyScriptEngine::getLogger().error( \ "In Plugin: " + getEngineOwnData()->pluginName \ ); \ return Local(); \ diff --git a/src/legacy/api/EventAPI.cpp b/src/legacy/api/EventAPI.cpp index 21778d54..fe2ff3d1 100644 --- a/src/legacy/api/EventAPI.cpp +++ b/src/legacy/api/EventAPI.cpp @@ -101,8 +101,8 @@ LLSEAddEventListener(ScriptEngine* engine, const string& eventName, const Local< } return {listener}; } catch (...) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Event {} not found!"_tr(eventName)); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error("Event {} not found!"_tr(eventName)); + lse::LegacyScriptEngine::getLogger().error( "In Plugin: " + getEngineData(engine)->pluginName ); return std::nullopt; @@ -663,7 +663,7 @@ void EnableEventListener(int eventId) { break; case EVENT_TYPES::onMobSpawn: - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().warn( + lse::LegacyScriptEngine::getLogger().warn( "Event 'onMobSpawn' is outdated, please use 'onMobTrySpawn' instead." ); bus.emplaceListener([](SpawningMobEvent& ev) { @@ -898,10 +898,10 @@ void InitBasicEventListeners() { } } } catch (...) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Error occurred in Engine Message Loop!" ); - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); } #endif diff --git a/src/legacy/api/EventAPI.h b/src/legacy/api/EventAPI.h index b2354424..6fd65f96 100644 --- a/src/legacy/api/EventAPI.h +++ b/src/legacy/api/EventAPI.h @@ -176,17 +176,17 @@ void CallEventImpl(EventListener& listener, bool& returnValue, EVENT_TYPES type, returnValue = false; } } catch (const Exception& e) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("CallEvent Callback Failed!"); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("In Event: " + EventTypeToString(type)); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error("CallEvent Callback Failed!"); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); + lse::LegacyScriptEngine::getLogger().error("In Event: " + EventTypeToString(type)); + lse::LegacyScriptEngine::getLogger().error( "In Plugin: " + getEngineOwnData()->pluginName ); } catch (...) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("CallEvent Callback Failed!"); - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("In Event: " + EventTypeToString(type)); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error("CallEvent Callback Failed!"); + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); + lse::LegacyScriptEngine::getLogger().error("In Event: " + EventTypeToString(type)); + lse::LegacyScriptEngine::getLogger().error( "In Plugin: " + getEngineOwnData()->pluginName ); } @@ -205,17 +205,17 @@ void FakeCallEventImpl(EventListener& listener, ScriptEngine* engine, EVENT_TYPE try { listener.func.get().call({}, args...); } catch (const Exception& e) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("FakeCallEvent Callback Failed!"); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("In Event: " + EventTypeToString(type)); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error("FakeCallEvent Callback Failed!"); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); + lse::LegacyScriptEngine::getLogger().error("In Event: " + EventTypeToString(type)); + lse::LegacyScriptEngine::getLogger().error( "In Plugin: " + getEngineOwnData()->pluginName ); } catch (...) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("FakeCallEvent Callback Failed!"); - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("In Event: " + EventTypeToString(type)); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error("FakeCallEvent Callback Failed!"); + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); + lse::LegacyScriptEngine::getLogger().error("In Event: " + EventTypeToString(type)); + lse::LegacyScriptEngine::getLogger().error( "In Plugin: " + getEngineOwnData()->pluginName ); } @@ -228,8 +228,8 @@ void FakeCallEventImpl(EventListener& listener, ScriptEngine* engine, EVENT_TYPE try #define IF_LISTENED_END(TYPE) \ catch (...) { \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Event Callback Failed!"); \ - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("In Event: " + EventTypeToString(TYPE)); \ + lse::LegacyScriptEngine::getLogger().error("Event Callback Failed!"); \ + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); \ + lse::LegacyScriptEngine::getLogger().error("In Event: " + EventTypeToString(TYPE)); \ } \ } diff --git a/src/legacy/api/NbtAPI.cpp b/src/legacy/api/NbtAPI.cpp index fcb786fc..08067af7 100644 --- a/src/legacy/api/NbtAPI.cpp +++ b/src/legacy/api/NbtAPI.cpp @@ -1335,7 +1335,7 @@ Local NbtListClass::getTag(const Arguments& args) { } Local res; - // lse::LegacyScriptEngine::getInstance().getSelf().getLogger().info( + // lse::LegacyScriptEngine::getLogger().info( // "getListTag Type {}", // magic_enum::enum_name(getPtr()->at(index)->getId()) // ); @@ -1739,7 +1739,7 @@ Local NbtCompoundClass::getTag(const Arguments& args) { auto key = args[0].asString().toString(); Local res; - // lse::LegacyScriptEngine::getInstance().getSelf().getLogger().info( + // lse::LegacyScriptEngine::getLogger().info( // "getCompoundTag Type {}", // magic_enum::enum_name(getPtr()->at(key).getId()) // ); diff --git a/src/legacy/api/NetworkAPI.cpp b/src/legacy/api/NetworkAPI.cpp index de8e6755..747422c5 100644 --- a/src/legacy/api/NetworkAPI.cpp +++ b/src/legacy/api/NetworkAPI.cpp @@ -23,13 +23,13 @@ using namespace ll::coro; #define CATCH_CALLBACK(LOG) \ catch (const Exception& e) { \ EngineScope enter(engine); \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error(LOG); \ - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); \ + lse::LegacyScriptEngine::getLogger().error(LOG); \ + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); \ return; \ } \ catch (...) { \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error(LOG); \ - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); \ + lse::LegacyScriptEngine::getLogger().error(LOG); \ + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); \ EngineScope enter(engine); \ LOG_ERROR_WITH_SCRIPT_INFO(__FUNCTION__); \ return; \ @@ -38,13 +38,13 @@ using namespace ll::coro; #define CATCH_CALLBACK_IN_CORO(LOG) \ catch (const Exception& e) { \ EngineScope enterCoro(engine); \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error(LOG); \ - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); \ + lse::LegacyScriptEngine::getLogger().error(LOG); \ + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); \ co_return; \ } \ catch (...) { \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error(LOG); \ - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); \ + lse::LegacyScriptEngine::getLogger().error(LOG); \ + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); \ EngineScope enterCoro(engine); \ LOG_ERROR_WITH_SCRIPT_INFO(__FUNCTION__); \ co_return; \ @@ -361,11 +361,11 @@ Local WSClientClass::connectAsync(const Arguments& args) { if (callback.isEmpty()) return; NewTimeout(callback.get(), {Boolean::newBoolean(result)}, 0); } catch (...) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "WSClientClass::connectAsync Failed!" ); - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("In Plugin: " + pluginName); + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); + lse::LegacyScriptEngine::getLogger().error("In Plugin: " + pluginName); } }).detach(); return Boolean::newBoolean(true); @@ -771,7 +771,7 @@ Local HttpServerClass::listen(const Arguments& args) { svr->stop(); svr->listen(addr, port); } catch (...) { - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); } }).detach(); return this->getScriptObject(); // return self diff --git a/src/legacy/api/PlayerAPI.cpp b/src/legacy/api/PlayerAPI.cpp index bf8905f2..8e0d1829 100644 --- a/src/legacy/api/PlayerAPI.cpp +++ b/src/legacy/api/PlayerAPI.cpp @@ -830,7 +830,7 @@ Local PlayerClass::getXuid() { try { xuid = player->getXuid(); } catch (...) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("Fail in getXuid!"); + lse::LegacyScriptEngine::getLogger().debug("Fail in getXuid!"); xuid = ll::service::PlayerInfo::getInstance().fromName(player->getRealName())->xuid; } return String::newString(xuid); @@ -847,7 +847,7 @@ Local PlayerClass::getUuid() { try { uuid = player->getUuid().asString(); } catch (...) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("Fail in getUuid!"); + lse::LegacyScriptEngine::getLogger().debug("Fail in getUuid!"); uuid = ll::service::PlayerInfo::getInstance().fromName(player->getRealName())->uuid.asString(); } return String::newString(uuid); @@ -2585,10 +2585,10 @@ Local PlayerClass::sendCustomForm(const Arguments& args) { return Number::newNumber(3); } catch (const ordered_json::exception& e) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to parse Json string in sendCustomForm!" ); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); return {}; } CATCH("Fail in sendCustomForm!"); diff --git a/src/legacy/api/RemoteCallAPI.cpp b/src/legacy/api/RemoteCallAPI.cpp index b8894e27..625c8476 100644 --- a/src/legacy/api/RemoteCallAPI.cpp +++ b/src/legacy/api/RemoteCallAPI.cpp @@ -177,12 +177,12 @@ Local extract(RemoteCall::ValueType&& val) { Local MakeRemoteCall(const string& nameSpace, const string& funcName, const Arguments& args) { auto& func = RemoteCall::importFunc(nameSpace, funcName); if (!func) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to import! Function [{}::{}] has not been exported!", nameSpace, funcName ); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "In plugin <{}>", getEngineOwnData()->pluginName ); @@ -216,7 +216,7 @@ bool LLSEExportFunc( try { auto iter = getEngineData(engine)->exportFuncs.find(identifier); if (iter == getEngineData(engine)->exportFuncs.end()) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug(""); + lse::LegacyScriptEngine::getLogger().debug(""); return ""; } auto scriptCallback = iter->second.callback.get(); diff --git a/src/legacy/api/SimulatedPlayerAPI.cpp b/src/legacy/api/SimulatedPlayerAPI.cpp index 1d1ddb60..469bfdf8 100644 --- a/src/legacy/api/SimulatedPlayerAPI.cpp +++ b/src/legacy/api/SimulatedPlayerAPI.cpp @@ -389,7 +389,7 @@ Local PlayerClass::simulateLookAt(const Arguments& args) { sp->simulateLookAt(pos->getBlockPos(), lookDuration); return Boolean::newBoolean(true); } - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + lse::LegacyScriptEngine::getLogger().debug( "Can't simulate look at other dimension!" ); return Boolean::newBoolean(false); @@ -400,7 +400,7 @@ Local PlayerClass::simulateLookAt(const Arguments& args) { sp->simulateLookAt(pos->getVec3(), (sim::LookDuration)lookDuration); return Boolean::newBoolean(true); } - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + lse::LegacyScriptEngine::getLogger().debug( "Can't simulate look at other dimension!" ); return Boolean::newBoolean(false); @@ -412,7 +412,7 @@ Local PlayerClass::simulateLookAt(const Arguments& args) { sp->simulateLookAt(pos->getBlockPos(), (sim::LookDuration)lookDuration); return Boolean::newBoolean(true); } - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + lse::LegacyScriptEngine::getLogger().debug( "Can't simulate look at other dimension!" ); return Boolean::newBoolean(false); diff --git a/src/legacy/api/SystemAPI.cpp b/src/legacy/api/SystemAPI.cpp index 3b35cca9..8bb8942b 100644 --- a/src/legacy/api/SystemAPI.cpp +++ b/src/legacy/api/SystemAPI.cpp @@ -84,8 +84,8 @@ bool NewProcess( try { if (callback) callback(static_cast(exitCode), std::move(strOutput)); } catch (...) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("NewProcess Callback Failed!"); - ll::utils::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + lse::LegacyScriptEngine::getLogger().error("NewProcess Callback Failed!"); + ll::utils::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); } }).detach(); diff --git a/src/legacy/engine/GlobalShareData.cpp b/src/legacy/engine/GlobalShareData.cpp index 81809f06..cb8d08f0 100644 --- a/src/legacy/engine/GlobalShareData.cpp +++ b/src/legacy/engine/GlobalShareData.cpp @@ -23,14 +23,14 @@ void InitGlobalShareData() { (LLSE_GLOBAL_DATA_NAME + std::to_wstring(GetCurrentProcessId())).c_str() ); if (hGlobalData == NULL) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Failed to initialize file mapping"_tr()); + lse::LegacyScriptEngine::getLogger().error("Failed to initialize file mapping"_tr()); localShareData->isFirstInstance = true; return; } LPVOID address = MapViewOfFile(hGlobalData, FILE_MAP_READ | FILE_MAP_WRITE, 0, 0, 0); if (address == NULL) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Failed to initialize map file"_tr()); + lse::LegacyScriptEngine::getLogger().error("Failed to initialize map file"_tr()); localShareData->isFirstInstance = true; return; } diff --git a/src/legacy/engine/MessageSystem.cpp b/src/legacy/engine/MessageSystem.cpp index fc43faf3..2b4194a3 100644 --- a/src/legacy/engine/MessageSystem.cpp +++ b/src/legacy/engine/MessageSystem.cpp @@ -105,18 +105,18 @@ ModuleMessageResult ModuleMessage::broadcastLocal(MessageType type, string data, engineList.push_back(engine); } catch (const Exception& e) { EngineScope scope(engine.get()); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to post message to plugin {}", getEngineData(engine)->pluginName ); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); } catch (...) { EngineScope scope(engine.get()); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to post message to plugin {}", getEngineData(engine)->pluginName ); - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); } } return ModuleMessageResult(msgId, engineList); @@ -136,18 +136,18 @@ ModuleMessageResult ModuleMessage::broadcastGlobal(MessageType type, string data engineList.push_back(engine); } catch (const Exception& e) { EngineScope scope(engine.get()); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to post message to plugin {}", getEngineData(engine)->pluginName ); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); } catch (...) { EngineScope scope(engine.get()); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to post message to plugin {}", getEngineData(engine)->pluginName ); - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); } } return ModuleMessageResult(msgId, engineList); @@ -168,18 +168,18 @@ ModuleMessageResult ModuleMessage::broadcastTo(std::string toModuleType, Message engineList.push_back(engine); } catch (const Exception& e) { EngineScope scope(engine.get()); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to post message to plugin {}", getEngineData(engine)->pluginName ); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); } catch (...) { EngineScope scope(engine.get()); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to post message to plugin {}", getEngineData(engine)->pluginName ); - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); } } } @@ -199,18 +199,18 @@ ModuleMessage::sendTo(std::shared_ptr engine, MessageType type, st return ModuleMessageResult(msgId, {engine}); } catch (const Exception& e) { EngineScope scope(engine.get()); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to post message to plugin {}", getEngineData(engine)->pluginName ); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); } catch (...) { EngineScope scope(engine.get()); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to post message to plugin {}", getEngineData(engine)->pluginName ); - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); } return ModuleMessageResult(msgId, {}); } @@ -230,18 +230,18 @@ ModuleMessage::sendToRandom(std::string toModuleType, MessageType type, std::str return ModuleMessageResult(msgId, {engine}); } catch (const Exception& e) { EngineScope scope(engine.get()); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to post message to plugin {}", getEngineData(engine)->pluginName ); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); } catch (...) { EngineScope scope(engine.get()); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to post message to plugin {}", getEngineData(engine)->pluginName ); - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); } } } @@ -260,17 +260,17 @@ bool ModuleMessage::sendResult(MessageType typ, std::string dat, int64_t delay) return true; } catch (const Exception& e) { EngineScope scope(engine); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to post message to plugin {}", getEngineData(engine)->pluginName ); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); } catch (...) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to post message to plugin {}", getEngineData(engine)->pluginName ); - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); } return false; } @@ -339,23 +339,23 @@ void MessageSystemLoopOnce() { } } catch (const Exception& e) { EngineScope scope(engine.get()); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Error occurred in Engine Message Loop!" ); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); + lse::LegacyScriptEngine::getLogger().error( "In Plugin: " + getEngineOwnData()->pluginName ); } catch (...) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Error occurred in Engine Message Loop!" ); - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); } } } // messageLoopLock.unlock(); - // lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("Engine-{} Message Loop.", LLSE_BACKEND_TYPE); + // lse::LegacyScriptEngine::getLogger().debug("Engine-{} Message Loop.", LLSE_BACKEND_TYPE); } void InitMessageSystem() { diff --git a/src/legacy/engine/RemoteCall.cpp b/src/legacy/engine/RemoteCall.cpp index 0ccb4069..b69a16c1 100644 --- a/src/legacy/engine/RemoteCall.cpp +++ b/src/legacy/engine/RemoteCall.cpp @@ -19,8 +19,8 @@ void inline StringTrim(string& str) { } void RemoteSyncCallRequest(ModuleMessage& msg) { - // lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("*** Remote call request received."); - // lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("*** Current Module:{}", LLSE_BACKEND_TYPE); + // lse::LegacyScriptEngine::getLogger().debug("*** Remote call request received."); + // lse::LegacyScriptEngine::getLogger().debug("*** Current Module:{}", LLSE_BACKEND_TYPE); std::istringstream sin(msg.getData()); @@ -42,52 +42,52 @@ void RemoteSyncCallRequest(ModuleMessage& msg) { argsVector.push_back(JsonToValue(arg)); } - // lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("*** Before remote call execute"); + // lse::LegacyScriptEngine::getLogger().debug("*** Before remote call execute"); Local result = funcData->func.get().call({}, argsVector); - // lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("*** After remote call execute"); + // lse::LegacyScriptEngine::getLogger().debug("*** After remote call execute"); // Feedback - // lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("*** Before remote call result return"); + // lse::LegacyScriptEngine::getLogger().debug("*** Before remote call result return"); if (!msg.sendResult(ModuleMessage::MessageType::RemoteSyncCallReturn, ValueToJson(result))) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to post remote call result return!" ); } - // lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("*** After remote call result return"); + // lse::LegacyScriptEngine::getLogger().debug("*** After remote call result return"); } catch (const Exception& e) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Error occurred in remote engine!"); + lse::LegacyScriptEngine::getLogger().error("Error occurred in remote engine!"); if (engine) { EngineScope enter(engine); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); + lse::LegacyScriptEngine::getLogger().error( "[Error] In Plugin: " + getEngineOwnData()->pluginName ); } // Feedback if (!msg.sendResult(ModuleMessage::MessageType::RemoteSyncCallReturn, "[null]")) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to post remote call result return!" ); } } catch (const std::out_of_range&) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( string("Fail to import! Function [") + funcName + "] has not been exported!" ); // Feedback if (!msg.sendResult(ModuleMessage::MessageType::RemoteSyncCallReturn, "[null]")) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to post remote call result return!" ); } } catch (...) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Error occurred in remote engine!"); - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + lse::LegacyScriptEngine::getLogger().error("Error occurred in remote engine!"); + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); // Feedback if (!msg.sendResult(ModuleMessage::MessageType::RemoteSyncCallReturn, "[null]")) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to post remote call result return!" ); } @@ -95,8 +95,8 @@ void RemoteSyncCallRequest(ModuleMessage& msg) { } void RemoteSyncCallReturn(ModuleMessage& msg) { - // lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("*** Remote call result message received."); - // lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("*** Result: {}", msg.getData()); + // lse::LegacyScriptEngine::getLogger().debug("*** Remote call result message received."); + // lse::LegacyScriptEngine::getLogger().debug("*** Result: {}", msg.getData()); remoteResultMap[msg.getId()] = msg.getData(); OperationCount(std::to_string(msg.getId())).done(); } @@ -108,7 +108,7 @@ Local MakeRemoteCall(const string& funcName, const Arguments& args) auto data = globalShareData->exportedFuncs.find(funcName); if (data == globalShareData->exportedFuncs.end()) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Fail to import! Function [{}] has not been exported!", funcName); + lse::LegacyScriptEngine::getLogger().error("Fail to import! Function [{}] has not been exported!", funcName); return Local(); } @@ -132,7 +132,7 @@ bool LLSEExportFunc(ScriptEngine *engine, const Local &func, const str auto data = globalShareData->exportedFuncs.find(exportName); if (data == globalShareData->exportedFuncs.end()) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Exported function \"{}\" not found", exportName); + lse::LegacyScriptEngine::getLogger().error("Exported function \"{}\" not found", exportName); return ""; } auto engine = data->second.engine; @@ -184,7 +184,7 @@ Local LlClass::importFunc(const Arguments &args) #ifdef DEBUG auto startTime = clock(); auto res = MakeRemoteCall(funcName, args); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().info("MakeRemoteCall time: {}s", (clock() - startTime) / 1000.0); + lse::LegacyScriptEngine::getLogger().info("MakeRemoteCall time: {}s", (clock() - startTime) / 1000.0); return res; #endif // DEBUG return MakeRemoteCall(funcName, args); diff --git a/src/legacy/engine/TimeTaskSystem.cpp b/src/legacy/engine/TimeTaskSystem.cpp index b596f9fb..9855bd7c 100644 --- a/src/legacy/engine/TimeTaskSystem.cpp +++ b/src/legacy/engine/TimeTaskSystem.cpp @@ -26,16 +26,16 @@ std::unordered_map timeTaskMap; #define TIMETASK_CATCH(TASK_TYPE) \ catch (const Exception& e) { \ EngineScope scope(data.engine); \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Error occurred in {}", TASK_TYPE); \ - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( \ + lse::LegacyScriptEngine::getLogger().error("Error occurred in {}", TASK_TYPE); \ + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); \ + lse::LegacyScriptEngine::getLogger().error( \ "In Plugin: " + getEngineData(data.engine)->pluginName \ ); \ } \ catch (...) { \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Error occurred in {}", TASK_TYPE); \ - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); \ - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( \ + lse::LegacyScriptEngine::getLogger().error("Error occurred in {}", TASK_TYPE); \ + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); \ + lse::LegacyScriptEngine::getLogger().error( \ "In Plugin: " + getEngineData(data.engine)->pluginName \ ); \ } @@ -199,8 +199,8 @@ bool ClearTimeTask(int const& id) { timeTaskMap.erase(id); } } catch (...) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Fail in ClearTimeTask"); - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + lse::LegacyScriptEngine::getLogger().error("Fail in ClearTimeTask"); + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); } return true; } @@ -218,7 +218,7 @@ void LLSERemoveTimeTaskData(std::shared_ptr engine) { } } } catch (...) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().info("Fail in LLSERemoveTimeTaskData"); - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + lse::LegacyScriptEngine::getLogger().info("Fail in LLSERemoveTimeTaskData"); + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); } } diff --git a/src/legacy/legacyapi/db/Session.cpp b/src/legacy/legacyapi/db/Session.cpp index 563b7443..5992d8d8 100644 --- a/src/legacy/legacyapi/db/Session.cpp +++ b/src/legacy/legacyapi/db/Session.cpp @@ -29,12 +29,12 @@ ResultSet Session::query(const std::string& query) { }); IF_ENDBG { if (result.valid()) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("Session::query: Results >"); + lse::LegacyScriptEngine::getLogger().debug("Session::query: Results >"); for (auto& str : ll::string_utils::splitByPattern(result.toTableString(), "\n")) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug(str); + lse::LegacyScriptEngine::getLogger().debug(str); } } else { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + lse::LegacyScriptEngine::getLogger().debug( "Session::query: Query returned no result" ); } @@ -46,7 +46,7 @@ std::string Session::getLastError() const { throw std::runtime_error("Session::g std::weak_ptr Session::getOrSetSelf() { if (self.expired()) { - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "Session::getOrSetSelf: `self` expired, trying fetching" ); return self = getSession(this); @@ -111,7 +111,7 @@ SharedPointer Session::_Create(DBType type, const ConnParams& params) { break; case DBType::MySQL: #ifdef LSE_BACKEND_NODEJS - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Session::_Create: MySQL is disabled in NodeJS backend because its OpenSSL has conflicts with libnode" ); #else @@ -119,7 +119,7 @@ SharedPointer Session::_Create(DBType type, const ConnParams& params) { #endif break; default: - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Session::_Create: Unknown/Unsupported database type" ); } diff --git a/src/legacy/legacyapi/db/impl/mysql/Session.cpp b/src/legacy/legacyapi/db/impl/mysql/Session.cpp index 3304c805..12248492 100644 --- a/src/legacy/legacyapi/db/impl/mysql/Session.cpp +++ b/src/legacy/legacyapi/db/impl/mysql/Session.cpp @@ -8,14 +8,14 @@ namespace DB { MySQLSession::MySQLSession() { - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().info( + IF_ENDBG lse::LegacyScriptEngine::getLogger().info( "MySQLSession::MySQLSession: Constructed! this: {}", (void*)this ); conn = mysql_init(nullptr); } MySQLSession::MySQLSession(const ConnParams& params) { - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().info( + IF_ENDBG lse::LegacyScriptEngine::getLogger().info( "MySQLSession::MySQLSession: Constructed! this: {}", (void*)this ); @@ -24,7 +24,7 @@ MySQLSession::MySQLSession(const ConnParams& params) { } MySQLSession::~MySQLSession() { - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().info( + IF_ENDBG lse::LegacyScriptEngine::getLogger().info( "MySQLSession::MySQLSession: Destructor: this: {}", (void*)this ); @@ -79,7 +79,7 @@ void MySQLSession::open(const ConnParams& params) { "true", "utf8" ); - // IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("MySQLSession::open: MySQL default + // IF_ENDBG lse::LegacyScriptEngine::getLogger().debug("MySQLSession::open: MySQL default // charset name : {}", defaultCharset); mysql_options(conn, MYSQL_SET_CHARSET_NAME, charset.c_str()); auto res = mysql_real_connect( @@ -97,7 +97,7 @@ void MySQLSession::open(const ConnParams& params) { "MySQLSession::MySQLSession: Failed to open database: " + std::string(mysql_error(conn)) ); } - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "MySQLSession::open: Opened database: " + std::string(p.getHost()) + ":" + std::to_string(port) + "/" + db ); #if defined(LLDB_DEBUG_MODE) @@ -106,7 +106,7 @@ void MySQLSession::open(const ConnParams& params) { } bool MySQLSession::execute(const std::string& query) { - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "MySQLSession::execute: Executing > " + query ); auto res = mysql_query(conn, query.c_str()); @@ -114,7 +114,7 @@ bool MySQLSession::execute(const std::string& query) { } bool MySQLSession::relogin(const std::string& user, const std::string& password, const std::string& db) { - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "MySQLSession::change: Changing user to{} and database to {} ", user, db @@ -124,7 +124,7 @@ bool MySQLSession::relogin(const std::string& user, const std::string& password, } Session& MySQLSession::query(const std::string& query, std::function callback) { - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "MySQLSession::query: Querying > " + query ); auto res = mysql_query(conn, query.c_str()); @@ -140,7 +140,7 @@ Session& MySQLSession::query(const std::string& query, std::function, std::size_t> AllocateBuffer(const MYSQL_FIELD if (len) { auto buffer = std::shared_ptr(new char[len]); #if defined(LLDB_DEBUG_MODE) - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("AllocateBuffer: Allocated! Buffer size: + lse::LegacyScriptEngine::getLogger().debug("AllocateBuffer: Allocated! Buffer size: {}", len); #endif return std::make_pair(buffer, len); @@ -235,7 +235,7 @@ Any ReceiverToAny(const Receiver& rec) { // case MYSQL_TYPE_GEOMETRY: case MYSQL_TYPE_JSON: #if defined(LLDB_DEBUG_MODE) - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("ReceiverToAny: string: length: {}, buffer + lse::LegacyScriptEngine::getLogger().debug("ReceiverToAny: string: length: {}, buffer {}", rec.length, rec.buffer.get()); #endif return Any(std::string(rec.buffer.get())); @@ -244,7 +244,7 @@ Any ReceiverToAny(const Receiver& rec) { case MYSQL_TYPE_MEDIUM_BLOB: case MYSQL_TYPE_LONG_BLOB: #if defined(LLDB_DEBUG_MODE) - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("ReceiverToAny: blob: length: {}, buffer + lse::LegacyScriptEngine::getLogger().debug("ReceiverToAny: blob: length: {}, buffer {}", rec.length, rec.buffer.get()); #endif // Unknown bug: rec.length is 0 @@ -252,7 +252,7 @@ Any ReceiverToAny(const Receiver& rec) { case MYSQL_TYPE_DECIMAL: case MYSQL_TYPE_NEWDECIMAL: // TODO: Decimal - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("MySQL_Decimal: {}", + lse::LegacyScriptEngine::getLogger().debug("MySQL_Decimal: {}", std::string(rec.buffer.get(), rec.length)); return Any(); default: throw std::runtime_error("ReceiverToAny: Unsupported MySQL data type: " + std::to_string(rec.field.type)); @@ -278,7 +278,7 @@ int MySQLStmt::getNextParamIndex() { result++; } } - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "MySQLStmt::getNextParamIndex: The next param index is {}", result + 1 ); @@ -293,7 +293,7 @@ void MySQLStmt::bindResult() { ); } if (!metadata) { - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "MySQLStmt::bindResult: No result metadata" ); return; @@ -306,7 +306,7 @@ void MySQLStmt::bindResult() { // later mysql_stmt_store_result(stmt); auto cnt = mysql_num_fields(metadata); - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "MySQLStmt::bindResult: mysql_num_fields : {} ", cnt ); @@ -334,7 +334,7 @@ void MySQLStmt::bindResult() { rec.field = field; // Save the field resultHeader->add(field.name); // Add the field name to the header - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "MySQLStmt::bindResult: Bind result {} (type {}) at index {}", field.name, (int)field.type, @@ -413,7 +413,7 @@ Stmt& MySQLStmt::bind(const Any& value, int index) { params[index].buffer_length = sz; params[index].is_null = 0; params[index].length = (unsigned long*)¶m.length; - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "MySQLStmt::bind: Bound string param at {}: {}", index, param.buffer.get() @@ -508,10 +508,10 @@ Row MySQLStmt::_Fetch() { if (fetched) { throw std::runtime_error("MySQLStmt::_Fetch: No more rows"); } - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("MySQLStmt::_Fetch: Fetching row..."); + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug("MySQLStmt::_Fetch: Fetching row..."); Row row(resultHeader); IF_ENDBG - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + lse::LegacyScriptEngine::getLogger().debug( "MySQLStmt::_Fetch: RowHeader size {}", row.header->size() ); @@ -523,7 +523,7 @@ Row MySQLStmt::_Fetch() { col.length = length; auto v = ReceiverToAny(col); row.push_back(v); - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "MySQLStmt::_Fetch: Fetched column `{}`, type {}, value {}", col.field.name, Any::type2str(v.type), @@ -612,15 +612,15 @@ SharedPointer MySQLStmt::create(const std::weak_ptr& session, con auto query = sql; auto params = ParseStmtParams(query); if (raw->debugOutput && !params.empty()) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + lse::LegacyScriptEngine::getLogger().debug( "MySQLStmt::create: Parsed named parameters in query: " ); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + lse::LegacyScriptEngine::getLogger().debug( "MySQLStmt::create: - SQL without named parameters: {}", query ); for (auto& [k, v] : params) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("MySQLStmt::create: - {}: {}", k, v); + lse::LegacyScriptEngine::getLogger().debug("MySQLStmt::create: - {}: {}", k, v); } } auto res = mysql_stmt_prepare(stmt, query.c_str(), query.size()); @@ -632,7 +632,7 @@ SharedPointer MySQLStmt::create(const std::weak_ptr& session, con result->paramIndexes = params; result->setDebugOutput(raw->debugOutput); if (raw->debugOutput) - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("MySQLStmt::create: Prepared > " + query); + lse::LegacyScriptEngine::getLogger().debug("MySQLStmt::create: Prepared > " + query); auto shared = SharedPointer(result); result->self = shared; return shared; diff --git a/src/legacy/legacyapi/db/impl/sqlite/Session.cpp b/src/legacy/legacyapi/db/impl/sqlite/Session.cpp index c752bef4..c0075685 100644 --- a/src/legacy/legacyapi/db/impl/sqlite/Session.cpp +++ b/src/legacy/legacyapi/db/impl/sqlite/Session.cpp @@ -8,13 +8,13 @@ namespace DB { SQLiteSession::SQLiteSession() { - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "SQLiteSession: Constructed! this: {}", (void*)this ); } SQLiteSession::SQLiteSession(const ConnParams& params) { - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "SQLiteSession: Constructed! this: {}", (void*)this ); @@ -22,7 +22,7 @@ SQLiteSession::SQLiteSession(const ConnParams& params) { } SQLiteSession::~SQLiteSession() { - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "SQLiteSession::~SQLiteSession: Destructor: this: {}", (void*)this ); @@ -73,13 +73,13 @@ void SQLiteSession::open(const ConnParams& params) { if (res != SQLITE_OK) { throw std::runtime_error("SQLiteSession::open: Failed to open database: " + std::string(sqlite3_errmsg(conn))); } - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "SQLiteSession::open: Opened database: " + std::string(path) ); } bool SQLiteSession::execute(const std::string& query) { - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "SQLiteSession::execute: Executing > " + query ); auto res = sqlite3_exec(conn, query.c_str(), nullptr, nullptr, nullptr); @@ -87,7 +87,7 @@ bool SQLiteSession::execute(const std::string& query) { } Session& SQLiteSession::query(const std::string& query, std::function callback) { - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "SQLiteSession::query: Querying > " + query ); auto stmt = prepare(query); @@ -125,7 +125,7 @@ void SQLiteSession::close() { ); } conn = nullptr; - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "SQLiteSession::close: Closed database" ); } diff --git a/src/legacy/legacyapi/db/impl/sqlite/Stmt.cpp b/src/legacy/legacyapi/db/impl/sqlite/Stmt.cpp index 9b9b9468..7ba23158 100644 --- a/src/legacy/legacyapi/db/impl/sqlite/Stmt.cpp +++ b/src/legacy/legacyapi/db/impl/sqlite/Stmt.cpp @@ -12,7 +12,7 @@ namespace DB { SQLiteStmt::SQLiteStmt(sqlite3_stmt* stmt, const std::weak_ptr parent, bool autoExecute) : Stmt(parent, autoExecute), stmt(stmt) { - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "SQLiteStmt::SQLiteStmt: Constructed! this: {}", (void*)this ); @@ -27,7 +27,7 @@ int SQLiteStmt::getNextParamIndex() { result++; } } - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "SQLiteStmt::getNextParamIndex: The next param index is {}", result + 1 ); @@ -39,7 +39,7 @@ void SQLiteStmt::fetchResultHeader() { int colCnt = sqlite3_column_count(stmt); for (int i = 0; i < colCnt; i++) { auto name = sqlite3_column_name(stmt, i); - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "SQLiteStmt::fetchResultHeader: Column Name[{}]: {}", i, name @@ -49,7 +49,7 @@ void SQLiteStmt::fetchResultHeader() { } SQLiteStmt::~SQLiteStmt() { - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "SQLiteStmt::~SQLiteStmt: Destructor: this: {}", (void*)this ); @@ -138,7 +138,7 @@ Stmt& SQLiteStmt::bind(const Any& value, const std::string& name) { // second is the key! throw std::invalid_argument("SQLiteStmt::bind: There isn't any statement parameter named `" + name + "`!"); } - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "SQLiteStmt::bind: Parameter `{}` is at index {}", name, index @@ -167,11 +167,11 @@ bool SQLiteStmt::step() { if (!resultHeader || resultHeader->empty()) { fetchResultHeader(); } - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("SQLiteStmt::step: Successfully"); + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug("SQLiteStmt::step: Successfully"); stepped = true; return true; } else if (res == SQLITE_DONE) { - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "SQLiteStmt::step: The statment is done" ); stepped = false; @@ -204,7 +204,7 @@ Row SQLiteStmt::_Fetch() { break; case SQLITE_TEXT: { std::string text(reinterpret_cast(sqlite3_column_text(stmt, i))); - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "SQLiteStmt::_Fetch: Fetched TEXT type column: {} {}", i, text @@ -222,7 +222,7 @@ Row SQLiteStmt::_Fetch() { for (auto& byte : arr) { out += ll::string_utils::intToHexStr(byte, true, true, false) + ' '; } - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug(out); + lse::LegacyScriptEngine::getLogger().debug(out); } row.push_back(arr); break; @@ -242,7 +242,7 @@ Stmt& SQLiteStmt::reset() { if (res != SQLITE_OK) { throw std::runtime_error("SQLiteStmt::reexec: Failed to reset"); } - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "SQLiteStmt::reexec: Reset successfully" ); resultHeader.reset(); @@ -265,14 +265,14 @@ Stmt& SQLiteStmt::clear() { if (res != SQLITE_OK) { throw std::runtime_error("SQLiteStmt::clear: Failed to reset"); } - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "SQLiteStmt::clear: Reset successfully" ); res = sqlite3_clear_bindings(stmt); if (res != SQLITE_OK) { throw std::runtime_error("SQLiteStmt::clear: Failed to clear bindings"); } - IF_ENDBG lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + IF_ENDBG lse::LegacyScriptEngine::getLogger().debug( "SQLiteStmt::clear: Cleared bindings successfully" ); boundParamsCount = 0; @@ -332,7 +332,7 @@ SQLiteStmt::create(const std::weak_ptr& session, const std::string& sql result->parent = session; result->setDebugOutput(raw->debugOutput); if (raw->debugOutput) - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("SQLiteStmt::create: Prepared > " + sql); + lse::LegacyScriptEngine::getLogger().debug("SQLiteStmt::create: Prepared > " + sql); auto shared = SharedPointer(result); result->self = shared; return shared; diff --git a/src/legacy/main/BuiltinCommands.cpp b/src/legacy/main/BuiltinCommands.cpp index 021cecb0..e6deb5fe 100644 --- a/src/legacy/main/BuiltinCommands.cpp +++ b/src/legacy/main/BuiltinCommands.cpp @@ -29,7 +29,7 @@ bool ProcessDebugEngine(const std::string& cmd) { #endif if (InConsoleDebugMode) { EngineScope enter(DebugEngine.get()); - auto& logger = lse::LegacyScriptEngine::getInstance().getSelf().getLogger(); + auto& logger = lse::LegacyScriptEngine::getLogger(); try { if (cmd == "stop" || cmd == LLSE_DEBUG_CMD) { return true; @@ -64,7 +64,7 @@ void RegisterDebugCommand() { ); command.overload().optional("eval").execute( [](CommandOrigin const&, CommandOutput& output, EngineDebugCommand const& param) { - auto& logger = lse::LegacyScriptEngine::getInstance().getSelf().getLogger(); + auto& logger = lse::LegacyScriptEngine::getLogger(); if (!param.eval.mText.empty()) { EngineScope enter(DebugEngine.get()); try { diff --git a/src/legacy/main/NodeJsHelper.cpp b/src/legacy/main/NodeJsHelper.cpp index 45639f07..e77a3bf1 100644 --- a/src/legacy/main/NodeJsHelper.cpp +++ b/src/legacy/main/NodeJsHelper.cpp @@ -98,7 +98,7 @@ LL_STATIC_HOOK( if (!(hAddon && hLibNode)) return hAddon; auto res = PatchDelayImport(hAddon, hLibNode); if (res) return hAddon; - res.error().log(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + res.error().log(lse::LegacyScriptEngine::getLogger()); } } return hAddon; @@ -130,11 +130,11 @@ bool initNodeJs() { node::ProcessInitializationFlags::kNoInitializeNodeV8Platform} ); if (result->exit_code() != 0) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Failed to initialize node! NodeJs plugins won't be loaded" ); for (const std::string& error : result->errors()) - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error(error); + lse::LegacyScriptEngine::getLogger().error(error); return false; } args = result->args(); @@ -173,7 +173,7 @@ std::shared_ptr newEngine() { if (!setup) { for (const std::string& err : errors) - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "CommonEnvironmentSetup Error: {}", err.c_str() ); @@ -192,7 +192,7 @@ std::shared_ptr newEngine() { ScriptEngine::Deleter() ); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + lse::LegacyScriptEngine::getLogger().debug( "Initialize ScriptEngine for node.js [{}]", (void*)engine.get() ); @@ -204,11 +204,11 @@ std::shared_ptr newEngine() { isolate, [](void* arg) { static_cast(arg)->destroy(); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug( + lse::LegacyScriptEngine::getLogger().debug( "Destroy ScriptEngine for node.js [{}]", arg ); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("Destroy EnvironmentCleanupHook"); + lse::LegacyScriptEngine::getLogger().debug("Destroy EnvironmentCleanupHook"); }, engine.get() ); @@ -304,7 +304,7 @@ bool loadPluginCode( // Set exit handler node::SetProcessExitHandler(env, [](node::Environment* env_, int exit_code) { auto engine = getEngine(env_); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().log( + lse::LegacyScriptEngine::getLogger().log( exit_code == 0 ? ll::io::LogLevel::Debug : ll::io::LogLevel::Error, "NodeJs plugin {} exited with code {}.", getEngineData(engine)->pluginName, @@ -317,7 +317,7 @@ bool loadPluginCode( MaybeLocal loadenv_ret = node::LoadEnvironment(env, compiler); bool loadFailed = loadenv_ret.IsEmpty(); - auto& logger = lse::LegacyScriptEngine::getInstance().getSelf().getLogger(); + auto& logger = lse::LegacyScriptEngine::getLogger(); if (!loadFailed) { v8::Local errorMsg = loadenv_ret.ToLocalChecked(); @@ -365,7 +365,7 @@ bool loadPluginCode( } if ((ll::getGamingStatus() != ll::GamingStatus::Running)) { uv_stop(eventLoop); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().debug("Destroy ServerStopping"); + lse::LegacyScriptEngine::getLogger().debug("Destroy ServerStopping"); } } } @@ -406,8 +406,8 @@ bool stopEngine(node::Environment* env) { return true; } catch (...) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Fail to stop engine {}", (void*)env); - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + lse::LegacyScriptEngine::getLogger().error("Fail to stop engine {}", (void*)env); + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); return false; } } @@ -551,7 +551,7 @@ int executeNpmCommand(std::vector npmArgs, std::string workingDir) if (!setup) { for (const std::string& err : errors) - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "CommonEnvironmentSetup Error: {}", err.c_str() ); @@ -609,10 +609,10 @@ int executeNpmCommand(std::vector npmArgs, std::string workingDir) throw std::runtime_error("Failed at LoadEnvironment"); exit_code = node::SpinEventLoop(env).FromMaybe(exit_code); } catch (...) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to execute NPM command. Error occurs" ); - ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); } node::Stop(env); } diff --git a/src/legacy/main/PythonHelper.cpp b/src/legacy/main/PythonHelper.cpp index cbfa50cd..a9edde87 100644 --- a/src/legacy/main/PythonHelper.cpp +++ b/src/legacy/main/PythonHelper.cpp @@ -69,7 +69,7 @@ bool loadPluginCode( engine->loadFile(String::newString(entryScriptPath)); } catch (const Exception& e1) { // Fail - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Fail in Loading Script Plugin!"); + lse::LegacyScriptEngine::getLogger().error("Fail in Loading Script Plugin!"); throw e1; } return true; @@ -160,7 +160,7 @@ static PyObject* getPyGlobalDict() { } bool processPythonDebugEngine(const std::string& cmd) { - auto& logger = lse::LegacyScriptEngine::getInstance().getSelf().getLogger(); + auto& logger = lse::LegacyScriptEngine::getLogger(); if (cmd == LLSE_DEBUG_CMD) { if (InConsoleDebugMode) { // EndDebug diff --git a/src/legacy/utils/IniHelper.cpp b/src/legacy/utils/IniHelper.cpp index 9f4937e7..c147162b 100644 --- a/src/legacy/utils/IniHelper.cpp +++ b/src/legacy/utils/IniHelper.cpp @@ -22,8 +22,8 @@ std::unique_ptr SimpleIni::create(const std::string& path, const std: root->SetUnicode(true); auto res = root->LoadFile(path.c_str()); if (res < 0) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Failed in loading ini file"); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error("Failed in loading ini file"); + lse::LegacyScriptEngine::getLogger().error( std::string("Error Code:") + std::to_string((int)res) ); return nullptr; diff --git a/src/legacy/utils/JsonHelper.h b/src/legacy/utils/JsonHelper.h index 8a9fa7be..f3abe37c 100644 --- a/src/legacy/utils/JsonHelper.h +++ b/src/legacy/utils/JsonHelper.h @@ -29,8 +29,8 @@ inline ordered_json CreateJson(const std::string& path, const std::string& defCo std::filesystem::create_directories(dirPath); } } else { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("Fail in create json file!"); - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error("invalid path"); + lse::LegacyScriptEngine::getLogger().error("Fail in create json file!"); + lse::LegacyScriptEngine::getLogger().error("invalid path"); jsonConf = ordered_json::object(); } @@ -38,10 +38,10 @@ inline ordered_json CreateJson(const std::string& path, const std::string& defCo try { jsonConf = ordered_json::parse(defContent, nullptr, true, allowComment); } catch (std::exception& e) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to parse default json content!" ); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); jsonConf = ordered_json::object(); } } else { @@ -60,10 +60,10 @@ inline ordered_json CreateJson(const std::string& path, const std::string& defCo try { jsonConf = ordered_json::parse(*jsonTexts, nullptr, true, allowComment); } catch (std::exception& e) { - lse::LegacyScriptEngine::getInstance().getSelf().getLogger().error( + lse::LegacyScriptEngine::getLogger().error( "Fail to parse json content in file!" ); - ll::error_utils::printException(e, lse::LegacyScriptEngine::getInstance().getSelf().getLogger()); + ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); jsonConf = ordered_json::object(); } } diff --git a/src/lse/Entry.h b/src/lse/Entry.h index d03f7b1d..32ddbd0e 100644 --- a/src/lse/Entry.h +++ b/src/lse/Entry.h @@ -10,6 +10,8 @@ class LegacyScriptEngine { public: static LegacyScriptEngine& getInstance(); + static inline ll::io::Logger& getLogger() { return getInstance().getSelf().getLogger(); } + LegacyScriptEngine() : mSelf(*ll::mod::NativeMod::current()) {} [[nodiscard]] ll::mod::NativeMod& getSelf() const { return mSelf; } diff --git a/src/lse/PluginManager.cpp b/src/lse/PluginManager.cpp index 27c9cbd1..4b4b166c 100644 --- a/src/lse/PluginManager.cpp +++ b/src/lse/PluginManager.cpp @@ -65,7 +65,7 @@ PluginManager::~PluginManager() = default; ll::Expected<> PluginManager::load(ll::mod::Manifest manifest) { #ifdef LSE_BACKEND_PYTHON - auto& logger = lse::LegacyScriptEngine::getInstance().getSelf().getLogger(); + auto& logger = lse::LegacyScriptEngine::getLogger(); std::filesystem::path dirPath = ll::mod::getModsRoot() / manifest.name; // Plugin path std::string entryPath = PythonHelper::findEntryScript(ll::string_utils::u8str2str(dirPath.u8string())); // Plugin entry @@ -100,7 +100,7 @@ ll::Expected<> PluginManager::load(ll::mod::Manifest manifest) { } #endif #ifdef LSE_BACKEND_NODEJS - auto& logger = lse::LegacyScriptEngine::getInstance().getSelf().getLogger(); + auto& logger = lse::LegacyScriptEngine::getLogger(); std::filesystem::path dirPath = ll::mod::getModsRoot() / manifest.name; // Plugin path // std::string entryPath = NodeJsHelper::findEntryScript(dirPath.string()); // Plugin entry // if (entryPath.empty()) return false; From 473a355740dbabb79f21cf85a7f2329d74879220 Mon Sep 17 00:00:00 2001 From: ShrBox Date: Sun, 18 Jan 2026 22:51:26 +0800 Subject: [PATCH 12/27] fix: add server thread check for events --- src/legacy/api/EventAPI.cpp | 403 ++++++++++++++++++-------------- src/lse/api/Thread.cpp | 11 + src/lse/api/Thread.h | 12 + src/lse/events/BlockEvents.cpp | 231 ++++++++++-------- src/lse/events/EntityEvents.cpp | 275 ++++++++++++---------- src/lse/events/OtherEvents.cpp | 31 +-- src/lse/events/PlayerEvents.cpp | 322 ++++++++++++++----------- 7 files changed, 735 insertions(+), 550 deletions(-) create mode 100644 src/lse/api/Thread.cpp create mode 100644 src/lse/api/Thread.h diff --git a/src/legacy/api/EventAPI.cpp b/src/legacy/api/EventAPI.cpp index fe2ff3d1..b87741bb 100644 --- a/src/legacy/api/EventAPI.cpp +++ b/src/legacy/api/EventAPI.cpp @@ -41,6 +41,7 @@ #include "ll/api/service/Bedrock.h" #include "ll/api/thread/ServerThreadExecutor.h" #include "lse/Entry.h" +#include "lse/api/Thread.h" #include "lse/events/BlockEvents.h" #include "lse/events/EntityEvents.h" #include "lse/events/OtherEvents.h" @@ -64,6 +65,8 @@ #include #include +using lse::api::thread::checkClientIsServerThread; + //////////////////// Listeners //////////////////// // 监听器表 @@ -102,9 +105,7 @@ LLSEAddEventListener(ScriptEngine* engine, const string& eventName, const Local< return {listener}; } catch (...) { lse::LegacyScriptEngine::getLogger().error("Event {} not found!"_tr(eventName)); - lse::LegacyScriptEngine::getLogger().error( - "In Plugin: " + getEngineData(engine)->pluginName - ); + lse::LegacyScriptEngine::getLogger().error("In Plugin: " + getEngineData(engine)->pluginName); return std::nullopt; } } @@ -157,8 +158,10 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onJoin: bus.emplaceListener([](PlayerJoinEvent& ev) { IF_LISTENED(EVENT_TYPES::onJoin) { - if (!CallEvent(EVENT_TYPES::onJoin, PlayerClass::newPlayer(&ev.self()))) { - ev.cancel(); + if (checkClientIsServerThread()) { + if (!CallEvent(EVENT_TYPES::onJoin, PlayerClass::newPlayer(&ev.self()))) { + ev.cancel(); + } } } IF_LISTENED_END(EVENT_TYPES::onJoin); @@ -168,8 +171,10 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onPreJoin: bus.emplaceListener([](PlayerConnectEvent& ev) { IF_LISTENED(EVENT_TYPES::onPreJoin) { - if (!CallEvent(EVENT_TYPES::onPreJoin, PlayerClass::newPlayer(&ev.self()))) { - ev.cancel(); + if (checkClientIsServerThread()) { + if (!CallEvent(EVENT_TYPES::onPreJoin, PlayerClass::newPlayer(&ev.self()))) { + ev.cancel(); + } } } IF_LISTENED_END(EVENT_TYPES::onPreJoin); @@ -179,7 +184,9 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onLeft: bus.emplaceListener([](PlayerDisconnectEvent& ev) { IF_LISTENED(EVENT_TYPES::onLeft) { - CallEvent(EVENT_TYPES::onLeft, PlayerClass::newPlayer(&ev.self())); // Not cancellable + if (checkClientIsServerThread()) { + CallEvent(EVENT_TYPES::onLeft, PlayerClass::newPlayer(&ev.self())); // Not cancellable + } } IF_LISTENED_END(EVENT_TYPES::onLeft); }); @@ -188,12 +195,14 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onChat: bus.emplaceListener([](PlayerChatEvent& ev) { IF_LISTENED(EVENT_TYPES::onChat) { - if (!CallEvent( - EVENT_TYPES::onChat, - PlayerClass::newPlayer(&ev.self()), - String::newString(ev.message()) - )) { - ev.cancel(); + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onChat, + PlayerClass::newPlayer(&ev.self()), + String::newString(ev.message()) + )) { + ev.cancel(); + } } } IF_LISTENED_END(EVENT_TYPES::onChat); @@ -207,7 +216,9 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onPlayerSwing: bus.emplaceListener([](PlayerSwingEvent& ev) { IF_LISTENED(EVENT_TYPES::onPlayerSwing) { - CallEvent(EVENT_TYPES::onPlayerSwing, PlayerClass::newPlayer(&ev.self())); // Not cancellable + if (checkClientIsServerThread()) { + CallEvent(EVENT_TYPES::onPlayerSwing, PlayerClass::newPlayer(&ev.self())); // Not cancellable + } } IF_LISTENED_END(EVENT_TYPES::onPlayerSwing); }); @@ -216,12 +227,14 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onAttackEntity: bus.emplaceListener([](PlayerAttackEvent& ev) { IF_LISTENED(EVENT_TYPES::onAttackEntity) { - if (!CallEvent( - EVENT_TYPES::onAttackEntity, - PlayerClass::newPlayer(&ev.self()), - EntityClass::newEntity(&ev.target()) - )) { - ev.cancel(); + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onAttackEntity, + PlayerClass::newPlayer(&ev.self()), + EntityClass::newEntity(&ev.target()) + )) { + ev.cancel(); + } } } IF_LISTENED_END(EVENT_TYPES::onAttackEntity); @@ -236,12 +249,14 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onPlayerDie: bus.emplaceListener([](ll::event::PlayerDieEvent& ev) { IF_LISTENED(EVENT_TYPES::onPlayerDie) { - Actor* source = ev.self().getDimension().fetchEntity(ev.source().getEntityUniqueID(), false); - CallEvent( - EVENT_TYPES::onPlayerDie, - PlayerClass::newPlayer(&ev.self()), - (source ? EntityClass::newEntity(source) : Local()) - ); // Not cancellable + if (checkClientIsServerThread()) { + Actor* source = ev.self().getDimension().fetchEntity(ev.source().getEntityUniqueID(), false); + CallEvent( + EVENT_TYPES::onPlayerDie, + PlayerClass::newPlayer(&ev.self()), + (source ? EntityClass::newEntity(source) : Local()) + ); // Not cancellable + } } IF_LISTENED_END(EVENT_TYPES::onPlayerDie); }); @@ -250,7 +265,9 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onRespawn: bus.emplaceListener([](ll::event::PlayerRespawnEvent& ev) { IF_LISTENED(EVENT_TYPES::onRespawn) { - CallEvent(EVENT_TYPES::onRespawn, PlayerClass::newPlayer(&ev.self())); // Not cancellable + if (checkClientIsServerThread()) { + CallEvent(EVENT_TYPES::onRespawn, PlayerClass::newPlayer(&ev.self())); // Not cancellable + } } IF_LISTENED_END(EVENT_TYPES::onRespawn) }); @@ -263,12 +280,14 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onDestroyBlock: bus.emplaceListener([](PlayerDestroyBlockEvent& ev) { IF_LISTENED(EVENT_TYPES::onDestroyBlock) { - if (!CallEvent( - EVENT_TYPES::onDestroyBlock, - PlayerClass::newPlayer(&ev.self()), - BlockClass::newBlock(ev.pos(), ev.self().getDimensionId().id) - )) { - ev.cancel(); + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onDestroyBlock, + PlayerClass::newPlayer(&ev.self()), + BlockClass::newBlock(ev.pos(), ev.self().getDimensionId().id) + )) { + ev.cancel(); + } } } IF_LISTENED_END(EVENT_TYPES::onDestroyBlock); @@ -278,36 +297,38 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onPlaceBlock: bus.emplaceListener([](PlayerPlacingBlockEvent& ev) { IF_LISTENED(EVENT_TYPES::onPlaceBlock) { - BlockPos truePos = ev.pos(); - switch (ev.face()) { - case 0: - --truePos.y; - break; - case 1: - ++truePos.y; - break; - case 2: - --truePos.z; - break; - case 3: - ++truePos.z; - break; - case 4: - --truePos.x; - break; - case 5: - ++truePos.x; - break; - } - auto block = ev.self().getCarriedItem().mBlock; - if (!CallEvent( - EVENT_TYPES::onPlaceBlock, - PlayerClass::newPlayer(&ev.self()), - block ? BlockClass::newBlock(*block, truePos, ev.self().getDimensionId().id) - : BlockClass::newBlock(truePos, ev.self().getDimensionId().id), - Number::newNumber((schar)ev.face()) - )) { - ev.cancel(); + if (checkClientIsServerThread()) { + BlockPos truePos = ev.pos(); + switch (ev.face()) { + case 0: + --truePos.y; + break; + case 1: + ++truePos.y; + break; + case 2: + --truePos.z; + break; + case 3: + ++truePos.z; + break; + case 4: + --truePos.x; + break; + case 5: + ++truePos.x; + break; + } + auto block = ev.self().getCarriedItem().mBlock; + if (!CallEvent( + EVENT_TYPES::onPlaceBlock, + PlayerClass::newPlayer(&ev.self()), + block ? BlockClass::newBlock(*block, truePos, ev.self().getDimensionId().id) + : BlockClass::newBlock(truePos, ev.self().getDimensionId().id), + Number::newNumber((schar)ev.face()) + )) { + ev.cancel(); + } } } IF_LISTENED_END(EVENT_TYPES::onPlaceBlock); @@ -317,11 +338,13 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::afterPlaceBlock: bus.emplaceListener([](PlayerPlacedBlockEvent& ev) { IF_LISTENED(EVENT_TYPES::afterPlaceBlock) { - CallEvent( - EVENT_TYPES::afterPlaceBlock, - PlayerClass::newPlayer(&ev.self()), - BlockClass::newBlock(ev.pos(), ev.self().getDimensionId().id) - ); // Not cancellable + if (checkClientIsServerThread()) { + CallEvent( + EVENT_TYPES::afterPlaceBlock, + PlayerClass::newPlayer(&ev.self()), + BlockClass::newBlock(ev.pos(), ev.self().getDimensionId().id) + ); // Not cancellable + } } IF_LISTENED_END(EVENT_TYPES::afterPlaceBlock); }); @@ -329,7 +352,9 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onJump: bus.emplaceListener([](PlayerJumpEvent& ev) { IF_LISTENED(EVENT_TYPES::onJump) { - CallEvent(EVENT_TYPES::onJump, PlayerClass::newPlayer(&ev.self())); // Not cancellable + if (checkClientIsServerThread()) { + CallEvent(EVENT_TYPES::onJump, PlayerClass::newPlayer(&ev.self())); // Not cancellable + } } IF_LISTENED_END(EVENT_TYPES::onJump); }); @@ -342,13 +367,15 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onTakeItem: bus.emplaceListener([](PlayerPickUpItemEvent& ev) { IF_LISTENED(EVENT_TYPES::onTakeItem) { - if (!CallEvent( - EVENT_TYPES::onTakeItem, - PlayerClass::newPlayer(&ev.self()), - EntityClass::newEntity(&ev.itemActor()), - ItemClass::newItem(&ev.itemActor().item()) - )) { - ev.cancel(); + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onTakeItem, + PlayerClass::newPlayer(&ev.self()), + EntityClass::newEntity(&ev.itemActor()), + ItemClass::newItem(&ev.itemActor().item()) + )) { + ev.cancel(); + } } } IF_LISTENED_END(EVENT_TYPES::onTakeItem); @@ -370,12 +397,14 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onUseItem: bus.emplaceListener([](PlayerUseItemEvent& ev) { IF_LISTENED(EVENT_TYPES::onUseItem) { - if (!CallEvent( - EVENT_TYPES::onUseItem, - PlayerClass::newPlayer(&ev.self()), - ItemClass::newItem(&ev.item()) - )) { - ev.cancel(); + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onUseItem, + PlayerClass::newPlayer(&ev.self()), + ItemClass::newItem(&ev.item()) + )) { + ev.cancel(); + } } } IF_LISTENED_END(EVENT_TYPES::onUseItem); @@ -385,16 +414,18 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onUseItemOn: bus.emplaceListener([](PlayerInteractBlockEvent& ev) { IF_LISTENED(EVENT_TYPES::onUseItemOn) { - if (!CallEvent( - EVENT_TYPES::onUseItemOn, - PlayerClass::newPlayer(&ev.self()), - ItemClass::newItem(&ev.item()), - ev.block() ? BlockClass::newBlock(ev.block(), ev.blockPos(), ev.self().getDimensionId().id) - : BlockClass::newBlock(ev.blockPos(), ev.self().getDimensionId().id), - Number::newNumber((schar)ev.face()), - FloatPos::newPos(ev.clickPos(), ev.self().getDimensionId().id) - )) { - ev.cancel(); + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onUseItemOn, + PlayerClass::newPlayer(&ev.self()), + ItemClass::newItem(&ev.item()), + ev.block() ? BlockClass::newBlock(ev.block(), ev.blockPos(), ev.self().getDimensionId().id) + : BlockClass::newBlock(ev.blockPos(), ev.self().getDimensionId().id), + Number::newNumber((schar)ev.face()), + FloatPos::newPos(ev.clickPos(), ev.self().getDimensionId().id) + )) { + ev.cancel(); + } } } IF_LISTENED_END(EVENT_TYPES::onUseItemOn); @@ -419,21 +450,25 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onChangeSprinting: bus.emplaceListener([](PlayerSprintingEvent& ev) { IF_LISTENED(EVENT_TYPES::onChangeSprinting) { - CallEvent( - EVENT_TYPES::onChangeSprinting, - PlayerClass::newPlayer(&ev.self()), - Boolean::newBoolean(true) - ); // Not cancellable + if (checkClientIsServerThread()) { + CallEvent( + EVENT_TYPES::onChangeSprinting, + PlayerClass::newPlayer(&ev.self()), + Boolean::newBoolean(true) + ); // Not cancellable + } } IF_LISTENED_END(EVENT_TYPES::onChangeSprinting); }); bus.emplaceListener([](PlayerSprintedEvent& ev) { IF_LISTENED(EVENT_TYPES::onChangeSprinting) { - CallEvent( - EVENT_TYPES::onChangeSprinting, - PlayerClass::newPlayer(&ev.self()), - Boolean::newBoolean(false) - ); // Not cancellable + if (checkClientIsServerThread()) { + CallEvent( + EVENT_TYPES::onChangeSprinting, + PlayerClass::newPlayer(&ev.self()), + Boolean::newBoolean(false) + ); // Not cancellable + } } IF_LISTENED_END(EVENT_TYPES::onChangeSprinting); }); @@ -442,16 +477,28 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onSneak: bus.emplaceListener([](PlayerSneakingEvent& ev) { IF_LISTENED(EVENT_TYPES::onSneak) { - if (!CallEvent(EVENT_TYPES::onSneak, PlayerClass::newPlayer(&ev.self()), Boolean::newBoolean(true))) { - ev.cancel(); + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onSneak, + PlayerClass::newPlayer(&ev.self()), + Boolean::newBoolean(true) + )) { + ev.cancel(); + } } } IF_LISTENED_END(EVENT_TYPES::onSneak); }); bus.emplaceListener([](PlayerSneakedEvent& ev) { IF_LISTENED(EVENT_TYPES::onSneak) { - if (!CallEvent(EVENT_TYPES::onSneak, PlayerClass::newPlayer(&ev.self()), Boolean::newBoolean(false))) { - ev.cancel(); + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onSneak, + PlayerClass::newPlayer(&ev.self()), + Boolean::newBoolean(false) + )) { + ev.cancel(); + } } } IF_LISTENED_END(EVENT_TYPES::onSneak); @@ -469,16 +516,18 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onEat: bus.emplaceListener([](PlayerUseItemEvent& ev) { IF_LISTENED(EVENT_TYPES::onEat) { - if (ev.item().getItem()->isFood() || ev.item().isPotionItem() - || ev.item().getTypeName() == VanillaItemNames::MilkBucket().getString()) { - auto attribute = ev.self().getAttribute(Player::HUNGER()); - if (attribute.mCurrentMaxValue > attribute.mCurrentValue) { - if (!CallEvent( - EVENT_TYPES::onEat, - PlayerClass::newPlayer(&ev.self()), - ItemClass::newItem(&ev.item()) - )) { - ev.cancel(); + if (checkClientIsServerThread()) { + if (ev.item().getItem()->isFood() || ev.item().isPotionItem() + || ev.item().getTypeName() == VanillaItemNames::MilkBucket().getString()) { + auto attribute = ev.self().getAttribute(Player::HUNGER()); + if (attribute.mCurrentMaxValue > attribute.mCurrentValue) { + if (!CallEvent( + EVENT_TYPES::onEat, + PlayerClass::newPlayer(&ev.self()), + ItemClass::newItem(&ev.item()) + )) { + ev.cancel(); + } } } } @@ -551,20 +600,22 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onMobDie: bus.emplaceListener([](MobDieEvent& ev) { IF_LISTENED(EVENT_TYPES::onMobDie) { - Actor* source = nullptr; - if (ev.source().isEntitySource()) { - source = ll::service::getLevel()->fetchEntity(ev.source().getDamagingEntityUniqueID(), false); - if (source) { - if (ev.source().isChildEntitySource()) source = source->getOwner(); + if (checkClientIsServerThread()) { + Actor* source = nullptr; + if (ev.source().isEntitySource()) { + source = ll::service::getLevel()->fetchEntity(ev.source().getDamagingEntityUniqueID(), false); + if (source) { + if (ev.source().isChildEntitySource()) source = source->getOwner(); + } } - } - CallEvent( - EVENT_TYPES::onMobDie, - EntityClass::newEntity(&ev.self()), - (source ? EntityClass::newEntity(source) : Local()), - Number::newNumber((int)ev.source().mCause) - ); // Not cancellable + CallEvent( + EVENT_TYPES::onMobDie, + EntityClass::newEntity(&ev.self()), + (source ? EntityClass::newEntity(source) : Local()), + Number::newNumber((int)ev.source().mCause) + ); // Not cancellable + } } IF_LISTENED_END(EVENT_TYPES::onMobDie); }); @@ -601,12 +652,14 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onBlockInteracted: bus.emplaceListener([](PlayerInteractBlockEvent& ev) { IF_LISTENED(EVENT_TYPES::onBlockInteracted) { - if (!CallEvent( - EVENT_TYPES::onBlockInteracted, - PlayerClass::newPlayer(&ev.self()), - BlockClass::newBlock(ev.blockPos(), ev.self().getDimensionId().id) - )) { - ev.cancel(); + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onBlockInteracted, + PlayerClass::newPlayer(&ev.self()), + BlockClass::newBlock(ev.blockPos(), ev.self().getDimensionId().id) + )) { + ev.cancel(); + } } } IF_LISTENED_END(EVENT_TYPES::onBlockInteracted); @@ -634,11 +687,13 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onFireSpread: bus.emplaceListener([](FireSpreadEvent& ev) { IF_LISTENED(EVENT_TYPES::onFireSpread) { - if (!CallEvent( - EVENT_TYPES::onFireSpread, - IntPos::newPos(ev.pos(), ev.blockSource().getDimensionId()) - )) { - ev.cancel(); + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onFireSpread, + IntPos::newPos(ev.pos(), ev.blockSource().getDimensionId()) + )) { + ev.cancel(); + } } } IF_LISTENED_END(EVENT_TYPES::onFireSpread); @@ -648,11 +703,13 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onBlockChanged: bus.emplaceListener([](BlockChangedEvent& ev) { IF_LISTENED(EVENT_TYPES::onBlockChanged) { - CallEvent( - EVENT_TYPES::onBlockChanged, - BlockClass::newBlock(ev.previousBlock(), ev.pos(), ev.blockSource()), - BlockClass::newBlock(ev.newBlock(), ev.pos(), ev.blockSource()) - ); // Not cancellable + if (checkClientIsServerThread()) { + CallEvent( + EVENT_TYPES::onBlockChanged, + BlockClass::newBlock(ev.previousBlock(), ev.pos(), ev.blockSource()), + BlockClass::newBlock(ev.newBlock(), ev.pos(), ev.blockSource()) + ); // Not cancellable + } } IF_LISTENED_END(EVENT_TYPES::onBlockChanged); }); @@ -668,11 +725,13 @@ void EnableEventListener(int eventId) { ); bus.emplaceListener([](SpawningMobEvent& ev) { IF_LISTENED(EVENT_TYPES::onMobSpawn) { - CallEvent( - EVENT_TYPES::onMobSpawn, - String::newString(ev.identifier().mFullName), - FloatPos::newPos(ev.pos(), ev.blockSource().getDimensionId()) - ); // Not cancellable + if (checkClientIsServerThread()) { + CallEvent( + EVENT_TYPES::onMobSpawn, + String::newString(ev.identifier().mFullName), + FloatPos::newPos(ev.pos(), ev.blockSource().getDimensionId()) + ); // Not cancellable + } } IF_LISTENED_END(EVENT_TYPES::onMobSpawn); }); @@ -681,12 +740,14 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onMobTrySpawn: bus.emplaceListener([](SpawningMobEvent& ev) { IF_LISTENED(EVENT_TYPES::onMobTrySpawn) { - if (!CallEvent( - EVENT_TYPES::onMobTrySpawn, - String::newString(ev.identifier().mFullName), - FloatPos::newPos(ev.pos(), ev.blockSource().getDimensionId()) - )) { - ev.cancel(); + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onMobTrySpawn, + String::newString(ev.identifier().mFullName), + FloatPos::newPos(ev.pos(), ev.blockSource().getDimensionId()) + )) { + ev.cancel(); + } } } IF_LISTENED_END(EVENT_TYPES::onMobTrySpawn); @@ -696,11 +757,13 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onMobSpawned: bus.emplaceListener([](SpawnedMobEvent& ev) { IF_LISTENED(EVENT_TYPES::onMobSpawned) { - CallEvent( - EVENT_TYPES::onMobSpawned, - EntityClass::newEntity(ev.mob().has_value() ? ev.mob().as_ptr() : nullptr), - FloatPos::newPos(ev.pos(), ev.blockSource().getDimensionId()) - ); // Not cancellable + if (checkClientIsServerThread()) { + CallEvent( + EVENT_TYPES::onMobSpawned, + EntityClass::newEntity(ev.mob().has_value() ? ev.mob().as_ptr() : nullptr), + FloatPos::newPos(ev.pos(), ev.blockSource().getDimensionId()) + ); // Not cancellable + } } IF_LISTENED_END(EVENT_TYPES::onMobSpawned); }); @@ -709,12 +772,14 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onExperienceAdd: bus.emplaceListener([](PlayerAddExperienceEvent& ev) { IF_LISTENED(EVENT_TYPES::onExperienceAdd) { - if (!CallEvent( - EVENT_TYPES::onExperienceAdd, - PlayerClass::newPlayer(&ev.self()), - Number::newNumber(ev.experience()) - )) { - ev.cancel(); + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onExperienceAdd, + PlayerClass::newPlayer(&ev.self()), + Number::newNumber(ev.experience()) + )) { + ev.cancel(); + } } } IF_LISTENED_END(EVENT_TYPES::onExperienceAdd); @@ -898,9 +963,7 @@ void InitBasicEventListeners() { } } } catch (...) { - lse::LegacyScriptEngine::getLogger().error( - "Error occurred in Engine Message Loop!" - ); + lse::LegacyScriptEngine::getLogger().error("Error occurred in Engine Message Loop!"); ll::error_utils::printCurrentException(lse::LegacyScriptEngine::getLogger()); } #endif diff --git a/src/lse/api/Thread.cpp b/src/lse/api/Thread.cpp new file mode 100644 index 00000000..b9955734 --- /dev/null +++ b/src/lse/api/Thread.cpp @@ -0,0 +1,11 @@ +#include "lse/api/Thread.h" + +#include "ll/api/service/Bedrock.h" +#include "mc/server/ServerInstance.h" + +namespace lse::api::thread { +bool isServerThread() { + auto instance = ll::service::getServerInstance(); + return instance && std::this_thread::get_id() == instance->mServerInstanceThread->get_id(); +} +} // namespace lse::api::thread diff --git a/src/lse/api/Thread.h b/src/lse/api/Thread.h new file mode 100644 index 00000000..91a5357a --- /dev/null +++ b/src/lse/api/Thread.h @@ -0,0 +1,12 @@ +#pragma once + +namespace lse::api::thread { +bool isServerThread(); +inline bool checkClientIsServerThread() { +#ifdef LL_PLAT_C + return isServerThread(); +#else + return true; +#endif +} +} // namespace lse::api::thread diff --git a/src/lse/events/BlockEvents.cpp b/src/lse/events/BlockEvents.cpp index b5e34ed9..7d65abf9 100644 --- a/src/lse/events/BlockEvents.cpp +++ b/src/lse/events/BlockEvents.cpp @@ -7,6 +7,7 @@ #include "ll/api/memory/Hook.h" #include "ll/api/memory/Memory.h" #include "ll/api/service/Bedrock.h" +#include "lse/api/Thread.h" #include "lse/api/helper/BlockHelper.h" #include "mc/legacy/ActorUniqueID.h" #include "mc/scripting/modules/minecraft/events/ScriptBlockGlobalEventListener.h" @@ -52,6 +53,8 @@ #include "mc/world/level/material/Material.h" namespace lse::events::block { +using api::thread::checkClientIsServerThread; + LL_TYPE_INSTANCE_HOOK( ContainerChangeHook, HookPriority::Normal, @@ -63,20 +66,22 @@ LL_TYPE_INSTANCE_HOOK( ItemStack const& newItem ) { IF_LISTENED(EVENT_TYPES::onContainerChange) { - if (*reinterpret_cast(this) != LevelContainerModel::$vftable()) - return origin(slotNumber, oldItem, newItem); + if (checkClientIsServerThread()) { + if (*reinterpret_cast(this) != LevelContainerModel::$vftable()) + return origin(slotNumber, oldItem, newItem); - // Player::hasOpenContainer() - if (mPlayer.mContainerManager) { - if (!CallEvent( - EVENT_TYPES::onContainerChange, - PlayerClass::newPlayer(&mPlayer), - BlockClass::newBlock(mBlockPos, mPlayer.getDimensionId().id), - Number::newNumber(slotNumber + this->_getContainerOffset()), - ItemClass::newItem(&const_cast(oldItem)), - ItemClass::newItem(&const_cast(newItem)) - )) { - return; + // Player::hasOpenContainer() + if (mPlayer.mContainerManager) { + if (!CallEvent( + EVENT_TYPES::onContainerChange, + PlayerClass::newPlayer(&mPlayer), + BlockClass::newBlock(mBlockPos, mPlayer.getDimensionId().id), + Number::newNumber(slotNumber + this->_getContainerOffset()), + ItemClass::newItem(&const_cast(oldItem)), + ItemClass::newItem(&const_cast(newItem)) + )) { + return; + } } } } @@ -94,13 +99,15 @@ LL_TYPE_INSTANCE_HOOK( ::SharedTypes::Legacy::EquipmentSlot slot ) { IF_LISTENED(EVENT_TYPES::onChangeArmorStand) { - if (!CallEvent( - EVENT_TYPES::onChangeArmorStand, - EntityClass::newEntity(this), - PlayerClass::newPlayer(&player), - Number::newNumber((int)slot) - )) { - return false; + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onChangeArmorStand, + EntityClass::newEntity(this), + PlayerClass::newPlayer(&player), + Number::newNumber((int)slot) + )) { + return false; + } } } IF_LISTENED_END(EVENT_TYPES::onChangeArmorStand); @@ -118,12 +125,14 @@ LL_TYPE_INSTANCE_HOOK( Actor& entity ) { IF_LISTENED(EVENT_TYPES::onStepOnPressurePlate) { - if (!CallEvent( - EVENT_TYPES::onStepOnPressurePlate, - EntityClass::newEntity(&entity), - BlockClass::newBlock(pos, region.getDimensionId()) - )) { - return false; + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onStepOnPressurePlate, + EntityClass::newEntity(&entity), + BlockClass::newBlock(pos, region.getDimensionId()) + )) { + return false; + } } } IF_LISTENED_END(EVENT_TYPES::onStepOnPressurePlate); @@ -142,12 +151,14 @@ LL_TYPE_INSTANCE_HOOK( float fallDistance ) { IF_LISTENED(EVENT_TYPES::onFarmLandDecay) { - if (!CallEvent( - EVENT_TYPES::onFarmLandDecay, - IntPos::newPos(pos, region.getDimensionId()), - EntityClass::newEntity(actor) - )) { - return; + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onFarmLandDecay, + IntPos::newPos(pos, region.getDimensionId()), + EntityClass::newEntity(actor) + )) { + return; + } } } IF_LISTENED_END(EVENT_TYPES::onFarmLandDecay); @@ -166,21 +177,23 @@ LL_TYPE_INSTANCE_HOOK( uchar pistonMoveFacing ) { IF_LISTENED(EVENT_TYPES::onPistonTryPush) { - if (region.getBlock(curPos).isAir()) { - return origin(region, curPos, curBranchFacing, pistonMoveFacing); - } - if (!CallEvent( - EVENT_TYPES::onPistonTryPush, - IntPos::newPos(this->mPosition, region.getDimensionId()), - BlockClass::newBlock(curPos, region.getDimensionId()) - )) { - return false; + if (checkClientIsServerThread()) { + if (region.getBlock(curPos).isAir()) { + return origin(region, curPos, curBranchFacing, pistonMoveFacing); + } + if (!CallEvent( + EVENT_TYPES::onPistonTryPush, + IntPos::newPos(this->mPosition, region.getDimensionId()), + BlockClass::newBlock(curPos, region.getDimensionId()) + )) { + return false; + } } } IF_LISTENED_END(EVENT_TYPES::onPistonTryPush); bool shouldPush = origin(region, curPos, curBranchFacing, pistonMoveFacing); IF_LISTENED(EVENT_TYPES::onPistonPush) { - if (shouldPush) { + if (checkClientIsServerThread() && shouldPush) { CallEvent( // Not cancellable EVENT_TYPES::onPistonPush, IntPos::newPos(this->mPosition, region.getDimensionId()), @@ -194,10 +207,29 @@ LL_TYPE_INSTANCE_HOOK( LL_TYPE_INSTANCE_HOOK(ExplodeHook, HookPriority::Normal, Explosion, &Explosion::explode, bool, ::IRandom& random) { IF_LISTENED(EVENT_TYPES::onEntityExplode) { - if (mSourceID->rawID != ActorUniqueID::INVALID_ID().rawID) { + if (checkClientIsServerThread()) { + if (mSourceID->rawID != ActorUniqueID::INVALID_ID().rawID) { + if (!CallEvent( + EVENT_TYPES::onEntityExplode, + EntityClass::newEntity(ll::service::getLevel()->fetchEntity(mSourceID, false)), + FloatPos::newPos(mPos, mRegion.getDimensionId()), + Number::newNumber(mRadius), + Number::newNumber(mMaxResistance), + Boolean::newBoolean(mBreaking), + Boolean::newBoolean(mFire) + )) { + return false; + } + } + } + } + IF_LISTENED_END(EVENT_TYPES::onEntityExplode); + + IF_LISTENED(EVENT_TYPES::onBlockExplode) { + if (checkClientIsServerThread()) { if (!CallEvent( - EVENT_TYPES::onEntityExplode, - EntityClass::newEntity(ll::service::getLevel()->fetchEntity(mSourceID, false)), + EVENT_TYPES::onBlockExplode, + BlockClass::newBlock(*mPos, mRegion.getDimensionId()), FloatPos::newPos(mPos, mRegion.getDimensionId()), Number::newNumber(mRadius), Number::newNumber(mMaxResistance), @@ -208,21 +240,6 @@ LL_TYPE_INSTANCE_HOOK(ExplodeHook, HookPriority::Normal, Explosion, &Explosion:: } } } - IF_LISTENED_END(EVENT_TYPES::onEntityExplode); - - IF_LISTENED(EVENT_TYPES::onBlockExplode) { - if (!CallEvent( - EVENT_TYPES::onBlockExplode, - BlockClass::newBlock(*mPos, mRegion.getDimensionId()), - FloatPos::newPos(mPos, mRegion.getDimensionId()), - Number::newNumber(mRadius), - Number::newNumber(mMaxResistance), - Boolean::newBoolean(mBreaking), - Boolean::newBoolean(mFire) - )) { - return false; - } - } IF_LISTENED_END(EVENT_TYPES::onBlockExplode); return origin(random); } @@ -239,12 +256,14 @@ LL_TYPE_STATIC_HOOK( Level& level ) { IF_LISTENED(EVENT_TYPES::onRespawnAnchorExplode) { - if (!CallEvent( - EVENT_TYPES::onRespawnAnchorExplode, - IntPos::newPos(pos, region.getDimensionId()), - PlayerClass::newPlayer(&player) - )) { - return; + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onRespawnAnchorExplode, + IntPos::newPos(pos, region.getDimensionId()), + PlayerClass::newPlayer(&player) + )) { + return; + } } } IF_LISTENED_END(EVENT_TYPES::onRespawnAnchorExplode); @@ -263,14 +282,16 @@ LL_TYPE_INSTANCE_HOOK( Actor* source ) { IF_LISTENED(EVENT_TYPES::onBlockExploded) { - if (destroyedBlock.isAir()) { - return origin(dimension, blockPos, destroyedBlock, source); + if (checkClientIsServerThread()) { + if (destroyedBlock.isAir()) { + return origin(dimension, blockPos, destroyedBlock, source); + } + CallEvent( + EVENT_TYPES::onBlockExploded, + BlockClass::newBlock(destroyedBlock, blockPos, dimension.getDimensionId()), + EntityClass::newEntity(source) + ); } - CallEvent( - EVENT_TYPES::onBlockExploded, - BlockClass::newBlock(destroyedBlock, blockPos, dimension.getDimensionId()), - EntityClass::newEntity(source) - ); } IF_LISTENED_END(EVENT_TYPES::onBlockExploded); return origin(dimension, blockPos, destroyedBlock, source); @@ -302,8 +323,10 @@ inline bool RedstoneUpdateEvent(BlockSource& region, BlockPos const& pos, int& s bool isFirstTime \ ) { \ IF_LISTENED(EVENT_TYPES::onRedStoneUpdate) { \ - if (!RedstoneUpdateEvent(region, pos, strength, isFirstTime)) { \ - return; \ + if (checkClientIsServerThread()) { \ + if (!RedstoneUpdateEvent(region, pos, strength, isFirstTime)) { \ + return; \ + } \ } \ } \ IF_LISTENED_END(EVENT_TYPES::onRedStoneUpdate); \ @@ -373,9 +396,7 @@ LL_TYPE_INSTANCE_HOOK( uchar flowFromDirection ) { IF_LISTENED(EVENT_TYPES::onLiquidFlow) { - auto ins = ll::service::getServerInstance(); - if (ins && std::this_thread::get_id() == ins->mServerInstanceThread->get_id() - && liquidBlockCanSpreadTo(*this, region, pos, flowFromPos, flowFromDirection)) { + if (checkClientIsServerThread() && liquidBlockCanSpreadTo(*this, region, pos, flowFromPos, flowFromDirection)) { if (!CallEvent( EVENT_TYPES::onLiquidFlow, region.isInstaticking(pos) ? Local() : BlockClass::newBlock(pos, region.getDimensionId()), @@ -400,23 +421,25 @@ LL_TYPE_INSTANCE_HOOK( bool& markForSaving ) { IF_LISTENED(EVENT_TYPES::onCmdBlockExecute) { - if (commandOrigin.getOriginType() == CommandOriginType::MinecartCommandBlock) { - if (!CallEvent( - EVENT_TYPES::onCmdBlockExecute, - String::newString(this->mCommand), - FloatPos::newPos(commandOrigin.getEntity()->getPosition(), region.getDimensionId()), - Boolean::newBoolean(true) - )) { - return false; - } - } else { - if (!CallEvent( - EVENT_TYPES::onCmdBlockExecute, - String::newString(this->mCommand), - FloatPos::newPos(commandOrigin.getBlockPosition(), region.getDimensionId()), - Boolean::newBoolean(false) - )) { - return false; + if (checkClientIsServerThread()) { + if (commandOrigin.getOriginType() == CommandOriginType::MinecartCommandBlock) { + if (!CallEvent( + EVENT_TYPES::onCmdBlockExecute, + String::newString(this->mCommand), + FloatPos::newPos(commandOrigin.getEntity()->getPosition(), region.getDimensionId()), + Boolean::newBoolean(true) + )) { + return false; + } + } else { + if (!CallEvent( + EVENT_TYPES::onCmdBlockExecute, + String::newString(this->mCommand), + FloatPos::newPos(commandOrigin.getBlockPosition(), region.getDimensionId()), + Boolean::newBoolean(false) + )) { + return false; + } } } } @@ -438,8 +461,10 @@ LL_TYPE_INSTANCE_HOOK( Container& toContainer, Vec3 const& pos ) { - hopperStatus = HopperStatus::PullIn; - hopperPos = pos; + if (checkClientIsServerThread()) { + hopperStatus = HopperStatus::PullIn; + hopperPos = pos; + } return origin(region, toContainer, pos); } @@ -454,8 +479,10 @@ LL_TYPE_INSTANCE_HOOK( Vec3 const& position, int attachedFace ) { - hopperStatus = HopperStatus::PullOut; - hopperPos = position; + if (checkClientIsServerThread()) { + hopperStatus = HopperStatus::PullOut; + hopperPos = position; + } return origin(region, fromContainer, position, attachedFace); } @@ -473,7 +500,7 @@ LL_TYPE_INSTANCE_HOOK( int itemCount ) { IF_LISTENED(EVENT_TYPES::onHopperSearchItem) { - if (hopperStatus == HopperStatus::PullIn) { + if (checkClientIsServerThread() && hopperStatus == HopperStatus::PullIn) { if (!CallEvent( EVENT_TYPES::onHopperSearchItem, FloatPos::newPos(hopperPos, region.getDimensionId()), @@ -486,7 +513,7 @@ LL_TYPE_INSTANCE_HOOK( } IF_LISTENED_END(EVENT_TYPES::onHopperSearchItem); IF_LISTENED(EVENT_TYPES::onHopperPushOut) { - if (hopperStatus == HopperStatus::PullOut) { + if (checkClientIsServerThread() && hopperStatus == HopperStatus::PullOut) { if (!CallEvent( EVENT_TYPES::onHopperPushOut, FloatPos::newPos(hopperPos, region.getDimensionId()), @@ -543,4 +570,4 @@ void HopperEvent(bool pullIn) { hopper::HopperPushOutHook::hook(); } } -} // namespace lse::events::block \ No newline at end of file +} // namespace lse::events::block diff --git a/src/lse/events/EntityEvents.cpp b/src/lse/events/EntityEvents.cpp index ba3629fb..b79f903f 100644 --- a/src/lse/events/EntityEvents.cpp +++ b/src/lse/events/EntityEvents.cpp @@ -7,6 +7,7 @@ #include "ll/api/memory/Memory.h" #include "ll/api/service/Bedrock.h" #include "ll/api/service/GamingStatus.h" +#include "lse/api/Thread.h" #include "lse/api/helper/BlockHelper.h" #include "mc/common/Globals.h" #include "mc/deps/shared_types/legacy/actor/ActorDamageCause.h" @@ -37,6 +38,8 @@ #include "mc/world/phys/HitResult.h" namespace lse::events::entity { +using api::thread::checkClientIsServerThread; + LL_TYPE_INSTANCE_HOOK( ProjectileSpawnHook1, HookPriority::Normal, @@ -50,25 +53,29 @@ LL_TYPE_INSTANCE_HOOK( Vec3 const& direction ) { IF_LISTENED(EVENT_TYPES::onSpawnProjectile) { - static auto& tridentName = EntityCanonicalName(ActorType::Trident); - if (id.mCanonicalName.get() != tridentName) { - if (!CallEvent( - EVENT_TYPES::onSpawnProjectile, - EntityClass::newEntity(spawner), - String::newString(id.mCanonicalName->getString()) - )) { - return nullptr; + if (checkClientIsServerThread()) { + static auto& tridentName = EntityCanonicalName(ActorType::Trident); + if (id.mCanonicalName.get() != tridentName) { + if (!CallEvent( + EVENT_TYPES::onSpawnProjectile, + EntityClass::newEntity(spawner), + String::newString(id.mCanonicalName->getString()) + )) { + return nullptr; + } } } } IF_LISTENED_END(EVENT_TYPES::onSpawnProjectile); Actor* projectile = origin(region, id, spawner, position, direction); IF_LISTENED(EVENT_TYPES::onProjectileCreated) { - CallEvent( // Not nancellable + if (checkClientIsServerThread()) { + CallEvent( // Not nancellable EVENT_TYPES::onProjectileCreated, EntityClass::newEntity(spawner), EntityClass::newEntity(projectile) ); + } } IF_LISTENED_END(EVENT_TYPES::onProjectileCreated); return projectile; @@ -84,12 +91,14 @@ LL_TYPE_INSTANCE_HOOK( Player& player ) { IF_LISTENED(EVENT_TYPES::onSpawnProjectile) { - if (!CallEvent( - EVENT_TYPES::onSpawnProjectile, - EntityClass::newEntity(&player), - String::newString(projectileInstance.getTypeName()) - )) { - return; + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onSpawnProjectile, + EntityClass::newEntity(&player), + String::newString(projectileInstance.getTypeName()) + )) { + return; + } } } IF_LISTENED_END(EVENT_TYPES::onSpawnProjectile); @@ -107,12 +116,14 @@ LL_TYPE_INSTANCE_HOOK( int durationLeft ) { IF_LISTENED(EVENT_TYPES::onSpawnProjectile) { - if (!CallEvent( - EVENT_TYPES::onSpawnProjectile, - EntityClass::newEntity(player), - String::newString(VanillaActorRendererId::trident().getString()) - )) { - return; + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onSpawnProjectile, + EntityClass::newEntity(player), + String::newString(VanillaActorRendererId::trident().getString()) + )) { + return; + } } } IF_LISTENED_END(EVENT_TYPES::onSpawnProjectile); @@ -121,8 +132,10 @@ LL_TYPE_INSTANCE_HOOK( LL_TYPE_INSTANCE_HOOK(ActorRideHook, HookPriority::Normal, Actor, &Actor::$canAddPassenger, bool, Actor& passenger) { IF_LISTENED(EVENT_TYPES::onRide) { - if (!CallEvent(EVENT_TYPES::onRide, EntityClass::newEntity(&passenger), EntityClass::newEntity(this))) { - return false; + if (checkClientIsServerThread()) { + if (!CallEvent(EVENT_TYPES::onRide, EntityClass::newEntity(&passenger), EntityClass::newEntity(this))) { + return false; + } } } IF_LISTENED_END(EVENT_TYPES::onRide); @@ -142,13 +155,15 @@ LL_TYPE_INSTANCE_HOOK( WitherBoss::WitherAttackType type ) { IF_LISTENED(EVENT_TYPES::onWitherBossDestroy) { - if (!CallEvent( - EVENT_TYPES::onWitherBossDestroy, - EntityClass::newEntity(this), - IntPos::newPos(bb.min, region.getDimensionId()), - IntPos::newPos(bb.max, region.getDimensionId()) - )) { - return; + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onWitherBossDestroy, + EntityClass::newEntity(this), + IntPos::newPos(bb.min, region.getDimensionId()), + IntPos::newPos(bb.max, region.getDimensionId()) + )) { + return; + } } } IF_LISTENED_END(EVENT_TYPES::onWitherBossDestroy); @@ -165,7 +180,7 @@ LL_TYPE_INSTANCE_HOOK( HitResult const& res ) { IF_LISTENED(EVENT_TYPES::onProjectileHitEntity) { - if (res.getEntity()) { + if (checkClientIsServerThread() && res.getEntity()) { if (!CallEvent( EVENT_TYPES::onProjectileHitEntity, EntityClass::newEntity(res.getEntity()), @@ -189,15 +204,17 @@ LL_TYPE_INSTANCE_HOOK( ::HitResult const& res ) { IF_LISTENED(EVENT_TYPES::onProjectileHitBlock) { - auto& region = owner.getDimensionBlockSourceConst(); - auto& block = region.getBlock(res.mBlock); - if (res.mType == HitResultType::Tile && res.mBlock != BlockPos::ZERO() && !block.isAir()) { - if (!CallEvent( - EVENT_TYPES::onProjectileHitBlock, - BlockClass::newBlock(block, res.mBlock, region), - EntityClass::newEntity(&owner) - )) { - return; + if (checkClientIsServerThread()) { + auto& region = owner.getDimensionBlockSourceConst(); + auto& block = region.getBlock(res.mBlock); + if (res.mType == HitResultType::Tile && res.mBlock != BlockPos::ZERO() && !block.isAir()) { + if (!CallEvent( + EVENT_TYPES::onProjectileHitBlock, + BlockClass::newBlock(block, res.mBlock, region), + EntityClass::newEntity(&owner) + )) { + return; + } } } } @@ -217,24 +234,26 @@ LL_TYPE_INSTANCE_HOOK( bool ignite ) { IF_LISTENED(EVENT_TYPES::onMobHurt) { - // LeviLamina's ActorHurtEvent can't handle fire hurt, so we just hook Mob::$_hurt. - Actor* damageSource = nullptr; - if (source.isEntitySource()) { - if (source.isChildEntitySource()) { - damageSource = ll::service::getLevel()->fetchEntity(source.getEntityUniqueID(), false); - } else { - damageSource = ll::service::getLevel()->fetchEntity(source.getDamagingEntityUniqueID(), false); + if (checkClientIsServerThread()) { + // LeviLamina's ActorHurtEvent can't handle fire hurt, so we just hook Mob::$_hurt. + Actor* damageSource = nullptr; + if (source.isEntitySource()) { + if (source.isChildEntitySource()) { + damageSource = ll::service::getLevel()->fetchEntity(source.getEntityUniqueID(), false); + } else { + damageSource = ll::service::getLevel()->fetchEntity(source.getDamagingEntityUniqueID(), false); + } } - } - if (!CallEvent( - EVENT_TYPES::onMobHurt, - EntityClass::newEntity(this), - damageSource ? EntityClass::newEntity(damageSource) : Local(), - Number::newNumber(damage < 0.0f ? -damage : damage), - Number::newNumber((int)source.mCause) - )) { - return false; + if (!CallEvent( + EVENT_TYPES::onMobHurt, + EntityClass::newEntity(this), + damageSource ? EntityClass::newEntity(damageSource) : Local(), + Number::newNumber(damage < 0.0f ? -damage : damage), + Number::newNumber((int)source.mCause) + )) { + return false; + } } } IF_LISTENED_END(EVENT_TYPES::onMobHurt) @@ -251,27 +270,29 @@ LL_TYPE_INSTANCE_HOOK( float damage ) { IF_LISTENED(EVENT_TYPES::onMobHurt) { - // Mob is still hurt after hook Mob::$hurtEffects, and all hurt events are handled by this function, but we just - // need magic damage. - if (source.mCause == SharedTypes::Legacy::ActorDamageCause::Magic - || source.mCause == SharedTypes::Legacy::ActorDamageCause::Wither) { - Actor* damageSource = nullptr; - if (source.isEntitySource()) { - if (source.isChildEntitySource()) { - damageSource = ll::service::getLevel()->fetchEntity(source.getEntityUniqueID(), false); - } else { - damageSource = ll::service::getLevel()->fetchEntity(source.getDamagingEntityUniqueID(), false); + if (checkClientIsServerThread()) { + // Mob is still hurt after hook Mob::$hurtEffects, and all hurt events are handled by this function, but we + // just need magic damage. + if (source.mCause == SharedTypes::Legacy::ActorDamageCause::Magic + || source.mCause == SharedTypes::Legacy::ActorDamageCause::Wither) { + Actor* damageSource = nullptr; + if (source.isEntitySource()) { + if (source.isChildEntitySource()) { + damageSource = ll::service::getLevel()->fetchEntity(source.getEntityUniqueID(), false); + } else { + damageSource = ll::service::getLevel()->fetchEntity(source.getDamagingEntityUniqueID(), false); + } } - } - if (!CallEvent( - EVENT_TYPES::onMobHurt, - EntityClass::newEntity(this), - damageSource ? EntityClass::newEntity(damageSource) : Local(), - Number::newNumber(damage < 0.0f ? -damage : damage), - Number::newNumber((int)source.mCause) - )) { - return 0.0f; + if (!CallEvent( + EVENT_TYPES::onMobHurt, + EntityClass::newEntity(this), + damageSource ? EntityClass::newEntity(damageSource) : Local(), + Number::newNumber(damage < 0.0f ? -damage : damage), + Number::newNumber((int)source.mCause) + )) { + return 0.0f; + } } } } @@ -291,24 +312,26 @@ LL_TYPE_INSTANCE_HOOK( ::std::string const& sceneName ) { IF_LISTENED(EVENT_TYPES::onNpcCmd) { - auto& action = - owner.getEntityContext().tryGetComponent()->mActionsContainer->mActions->at(actionIndex); - if (std::holds_alternative(action)) { - auto& commands = std::get(action).commands; - std::string command; - for (auto& cmd : commands.get()) { - command += cmd.rawCommand.get() + ";"; - } - if (!commands->empty()) { - command.pop_back(); - } - if (!CallEvent( - EVENT_TYPES::onNpcCmd, - EntityClass::newEntity(&owner), - PlayerClass::newPlayer(&sourcePlayer), - String::newString(command) - )) { - return; + if (checkClientIsServerThread()) { + auto& action = + owner.getEntityContext().tryGetComponent()->mActionsContainer->mActions->at(actionIndex); + if (std::holds_alternative(action)) { + auto& commands = std::get(action).commands; + std::string command; + for (auto& cmd : commands.get()) { + command += cmd.rawCommand.get() + ";"; + } + if (!commands->empty()) { + command.pop_back(); + } + if (!CallEvent( + EVENT_TYPES::onNpcCmd, + EntityClass::newEntity(&owner), + PlayerClass::newPlayer(&sourcePlayer), + String::newString(command) + )) { + return; + } } } } @@ -325,7 +348,7 @@ LL_TYPE_INSTANCE_HOOK( MobEffectInstance& effect ) { IF_LISTENED(EVENT_TYPES::onEffectUpdated) { - if (isPlayer()) { + if (checkClientIsServerThread() && isPlayer()) { if (!CallEvent( EVENT_TYPES::onEffectUpdated, PlayerClass::newPlayer(reinterpret_cast(this)), @@ -354,11 +377,13 @@ LL_TYPE_INSTANCE_HOOK( ::Level const& level ) { IF_LISTENED(EVENT_TYPES::onEntityTransformation) { - CallEvent( - EVENT_TYPES::onEntityTransformation, - String::newString(std::to_string(originalActor.getOrCreateUniqueID().rawID)), - EntityClass::newEntity(&transformed) - ); + if (checkClientIsServerThread()) { + CallEvent( + EVENT_TYPES::onEntityTransformation, + String::newString(std::to_string(originalActor.getOrCreateUniqueID().rawID)), + EntityClass::newEntity(&transformed) + ); + } } IF_LISTENED_END(EVENT_TYPES::onEntityTransformation); @@ -373,31 +398,37 @@ LL_TYPE_INSTANCE_HOOK( CoordinatorResult, EventRef> const& event ) { - bool canceled = event.get().visit([&](auto&& arg) { - if constexpr (std::is_same_v, Details::ValueOrRef>) { - IF_LISTENED(EVENT_TYPES::onEndermanTakeBlock) { - auto& griefingEvent = arg.value(); - auto entity = griefingEvent.mActorContext->tryUnwrap(); - if (entity && entity->isType(ActorType::EnderMan)) { - if (!CallEvent( - EVENT_TYPES::onEndermanTakeBlock, - EntityClass::newEntity(entity.as_ptr()), - BlockClass::newBlock( - *griefingEvent.mBlock, - BlockPos(griefingEvent.mPos), - entity->getDimensionId().id - ), - IntPos::newPos(BlockPos(griefingEvent.mPos), entity->getDimensionId().id) - )) { - return true; + + IF_LISTENED(EVENT_TYPES::onEndermanTakeBlock) { + if (checkClientIsServerThread()) { + bool canceled = event.get().visit([&](auto&& arg) { + if constexpr (std::is_same_v< + std::decay_t, + Details::ValueOrRef>) { + auto& griefingEvent = arg.value(); + auto entity = griefingEvent.mActorContext->tryUnwrap(); + if (entity && entity->isType(ActorType::EnderMan)) { + if (!CallEvent( + EVENT_TYPES::onEndermanTakeBlock, + EntityClass::newEntity(entity.as_ptr()), + BlockClass::newBlock( + *griefingEvent.mBlock, + BlockPos(griefingEvent.mPos), + entity->getDimensionId().id + ), + IntPos::newPos(BlockPos(griefingEvent.mPos), entity->getDimensionId().id) + )) { + return true; + } } } - } - IF_LISTENED_END(EVENT_TYPES::onEndermanTakeBlock); + return false; + }); + if (canceled) return CoordinatorResult::Cancel; } - return false; - }); - if (canceled) return CoordinatorResult::Cancel; + } + IF_LISTENED_END(EVENT_TYPES::onEndermanTakeBlock); + return origin(event); } @@ -419,4 +450,4 @@ void NpcCommandEvent() { NpcCommandHook::hook(); } void EndermanTakeBlockEvent() { EndermanTakeBlockHook::hook(); } void EffectUpdateEvent() { EffectUpdateHook::hook(); } void TransformationEvent() { TransformationHook::hook(); } -} // namespace lse::events::entity \ No newline at end of file +} // namespace lse::events::entity diff --git a/src/lse/events/OtherEvents.cpp b/src/lse/events/OtherEvents.cpp index 2e83c0ff..83e6e0a1 100644 --- a/src/lse/events/OtherEvents.cpp +++ b/src/lse/events/OtherEvents.cpp @@ -2,11 +2,10 @@ #include "legacy/api/PlayerAPI.h" #include "ll/api/memory/Hook.h" #include "ll/api/service/Bedrock.h" -#include "mc/legacy/ActorRuntimeID.h" +#include "lse/api/Thread.h" #include "mc/legacy/ActorUniqueID.h" #include "mc/world/scores/IdentityDefinition.h" #include "mc/world/scores/Objective.h" -#include "mc/world/scores/PlayerScoreboardId.h" #include "mc/world/scores/ScoreInfo.h" #include "mc/world/scores/ScoreboardId.h" #include "mc/world/scores/ServerScoreboard.h" @@ -22,18 +21,20 @@ LL_TYPE_INSTANCE_HOOK( Objective const& obj ) { IF_LISTENED(EVENT_TYPES::onScoreChanged) { - auto& idRef = id.mIdentityDef; - if (idRef && idRef->mIdentityType == IdentityDefinition::Type::Player) { - if (!CallEvent( - EVENT_TYPES::onScoreChanged, - PlayerClass::newPlayer( - ll::service::getLevel()->getPlayer(ActorUniqueID(idRef->mPlayerId->mActorUniqueId)) - ), - Number::newNumber(obj.getPlayerScore(id).mValue), - String::newString(obj.mName), - String::newString(obj.mDisplayName) - )) { - return; + if (api::thread::checkClientIsServerThread()) { + auto& idRef = id.mIdentityDef; + if (idRef && idRef->mIdentityType == IdentityDefinition::Type::Player) { + if (!CallEvent( + EVENT_TYPES::onScoreChanged, + PlayerClass::newPlayer( + ll::service::getLevel()->getPlayer(ActorUniqueID(idRef->mPlayerId->mActorUniqueId)) + ), + Number::newNumber(obj.getPlayerScore(id).mValue), + String::newString(obj.mName), + String::newString(obj.mDisplayName) + )) { + return; + } } } } @@ -42,4 +43,4 @@ LL_TYPE_INSTANCE_HOOK( } void ScoreChangedEvent() { ScoreChangedHook::hook(); } -} // namespace lse::events::other \ No newline at end of file +} // namespace lse::events::other diff --git a/src/lse/events/PlayerEvents.cpp b/src/lse/events/PlayerEvents.cpp index 40589cc6..80bc5c8f 100644 --- a/src/lse/events/PlayerEvents.cpp +++ b/src/lse/events/PlayerEvents.cpp @@ -7,6 +7,7 @@ #include "ll/api/memory/Hook.h" #include "ll/api/memory/Memory.h" #include "ll/api/service/Bedrock.h" +#include "lse/api/Thread.h" #include "mc/deps/ecs/WeakEntityRef.h" #include "mc/network/ServerPlayerBlockUseHandler.h" #include "mc/server/ServerInstance.h" @@ -51,6 +52,8 @@ #include "mc/world/phys/HitResult.h" namespace lse::events::player { +using api::thread::checkClientIsServerThread; + LL_TYPE_INSTANCE_HOOK( DropItemHook1, HookPriority::Normal, @@ -61,12 +64,14 @@ LL_TYPE_INSTANCE_HOOK( bool randomly ) { IF_LISTENED(EVENT_TYPES::onDropItem) { - if (!CallEvent( - EVENT_TYPES::onDropItem, - PlayerClass::newPlayer(this), - ItemClass::newItem(&const_cast(item)) - )) { - return false; + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onDropItem, + PlayerClass::newPlayer(this), + ItemClass::newItem(&const_cast(item)) + )) { + return false; + } } } IF_LISTENED_END(EVENT_TYPES::onDropItem); @@ -82,8 +87,9 @@ LL_TYPE_INSTANCE_HOOK( Player& player, bool isSenderAuthority ) { - if (mType == ComplexInventoryTransaction::Type::NormalTransaction) { - IF_LISTENED(EVENT_TYPES::onDropItem) { + + IF_LISTENED(EVENT_TYPES::onDropItem) { + if (checkClientIsServerThread() && mType == ComplexInventoryTransaction::Type::NormalTransaction) { InventorySource source{ InventorySourceType::ContainerInventory, ContainerID::Inventory, @@ -102,8 +108,8 @@ LL_TYPE_INSTANCE_HOOK( } } } - IF_LISTENED_END(EVENT_TYPES::onDropItem); } + IF_LISTENED_END(EVENT_TYPES::onDropItem); return origin(player, isSenderAuthority); } @@ -116,14 +122,16 @@ LL_TYPE_INSTANCE_HOOK( struct PlayerOpenContainerEvent const& playerOpenContainerEvent ) { IF_LISTENED(EVENT_TYPES::onOpenContainer) { - Actor* actor = static_cast((void*)&playerOpenContainerEvent)->tryUnwrap(); - if (actor && actor->isType(ActorType::Player)) { - if (!CallEvent( - EVENT_TYPES::onOpenContainer, - PlayerClass::newPlayer(static_cast(actor)), - BlockClass::newBlock(playerOpenContainerEvent.mBlockPos, actor->getDimensionId().id) - )) { - return EventResult::StopProcessing; + if (checkClientIsServerThread()) { + Actor* actor = static_cast((void*)&playerOpenContainerEvent)->tryUnwrap(); + if (actor && actor->isType(ActorType::Player)) { + if (!CallEvent( + EVENT_TYPES::onOpenContainer, + PlayerClass::newPlayer(static_cast(actor)), + BlockClass::newBlock(playerOpenContainerEvent.mBlockPos, actor->getDimensionId().id) + )) { + return EventResult::StopProcessing; + } } } } @@ -140,7 +148,7 @@ LL_TYPE_INSTANCE_HOOK( Actor& actor ) { IF_LISTENED(EVENT_TYPES::onCloseContainer) { - if (actor.isPlayer()) { + if (checkClientIsServerThread() && actor.isPlayer()) { Player& player = static_cast(actor); if (!CallEvent( EVENT_TYPES::onCloseContainer, @@ -164,7 +172,7 @@ LL_TYPE_INSTANCE_HOOK( Actor& actor ) { IF_LISTENED(EVENT_TYPES::onCloseContainer) { - if (actor.isPlayer()) { + if (checkClientIsServerThread() && actor.isPlayer()) { Player& player = static_cast(actor); if (!CallEvent( EVENT_TYPES::onCloseContainer, @@ -192,14 +200,16 @@ LL_TYPE_INSTANCE_HOOK( bool forceBalanced ) { IF_LISTENED(EVENT_TYPES::onInventoryChange) { - if (!CallEvent( - EVENT_TYPES::onInventoryChange, - PlayerClass::newPlayer(this), - slot, - ItemClass::newItem(&const_cast(oldItem)), - ItemClass::newItem(&const_cast(newItem)) - )) { - return; + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onInventoryChange, + PlayerClass::newPlayer(this), + slot, + ItemClass::newItem(&const_cast(oldItem)), + ItemClass::newItem(&const_cast(newItem)) + )) { + return; + } } } IF_LISTENED_END(EVENT_TYPES::onInventoryChange); @@ -215,31 +225,33 @@ LL_STATIC_HOOK( const BlockPos& pos, int face ) { - bool isCancelled = false; - IF_LISTENED(EVENT_TYPES::onAttackBlock) { - ItemStack const& item = player.getSelectedItem(); - if (!CallEvent( - EVENT_TYPES::onAttackBlock, - PlayerClass::newPlayer(&player), - BlockClass::newBlock(pos, player.getDimensionId().id), - !item.isNull() ? ItemClass::newItem(&const_cast(item)) : Local() - )) { - isCancelled = true; + if (checkClientIsServerThread()) { + bool isCancelled = false; + IF_LISTENED(EVENT_TYPES::onAttackBlock) { + ItemStack const& item = player.getSelectedItem(); + if (!CallEvent( + EVENT_TYPES::onAttackBlock, + PlayerClass::newPlayer(&player), + BlockClass::newBlock(pos, player.getDimensionId().id), + !item.isNull() ? ItemClass::newItem(&const_cast(item)) : Local() + )) { + isCancelled = true; + } } - } - IF_LISTENED_END(EVENT_TYPES::onAttackBlock); - IF_LISTENED(EVENT_TYPES::onStartDestroyBlock) { - if (!CallEvent( - EVENT_TYPES::onStartDestroyBlock, - PlayerClass::newPlayer(&player), - BlockClass::newBlock(pos, player.getDimensionId().id) - )) { - isCancelled = true; + IF_LISTENED_END(EVENT_TYPES::onAttackBlock); + IF_LISTENED(EVENT_TYPES::onStartDestroyBlock) { + if (!CallEvent( + EVENT_TYPES::onStartDestroyBlock, + PlayerClass::newPlayer(&player), + BlockClass::newBlock(pos, player.getDimensionId().id) + )) { + isCancelled = true; + } + } + IF_LISTENED_END(EVENT_TYPES::onStartDestroyBlock) + if (isCancelled) { + return; } - } - IF_LISTENED_END(EVENT_TYPES::onStartDestroyBlock) - if (isCancelled) { - return; } return origin(player, pos, face); } @@ -253,13 +265,15 @@ LL_TYPE_INSTANCE_HOOK( BlockEvents::BlockPlayerInteractEvent& eventData ) { IF_LISTENED(EVENT_TYPES::onUseFrameBlock) { - Player& player = eventData.mPlayer; - if (!CallEvent( - EVENT_TYPES::onUseFrameBlock, - PlayerClass::newPlayer(&player), - BlockClass::newBlock(eventData.mPos, player.getDimensionId().id) - )) { - return; + if (checkClientIsServerThread()) { + Player& player = eventData.mPlayer; + if (!CallEvent( + EVENT_TYPES::onUseFrameBlock, + PlayerClass::newPlayer(&player), + BlockClass::newBlock(eventData.mPos, player.getDimensionId().id) + )) { + return; + } } } IF_LISTENED_END(EVENT_TYPES::onUseFrameBlock); @@ -276,12 +290,14 @@ LL_TYPE_INSTANCE_HOOK( BlockPos const& pos ) { IF_LISTENED(EVENT_TYPES::onUseFrameBlock) { - if (!CallEvent( - EVENT_TYPES::onUseFrameBlock, - PlayerClass::newPlayer(player), - BlockClass::newBlock(pos, player->getDimensionId().id) - )) { - return false; + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onUseFrameBlock, + PlayerClass::newPlayer(player), + BlockClass::newBlock(pos, player->getDimensionId().id) + )) { + return false; + } } } IF_LISTENED_END(EVENT_TYPES::onUseFrameBlock); @@ -289,8 +305,8 @@ LL_TYPE_INSTANCE_HOOK( } LL_TYPE_INSTANCE_HOOK(EatHook, HookPriority::Normal, Player, &Player::completeUsingItem, void) { - if (std::this_thread::get_id() == ll::service::getServerInstance()->mServerInstanceThread->get_id()) { - IF_LISTENED(EVENT_TYPES::onAte) { + IF_LISTENED(EVENT_TYPES::onAte) { + if (checkClientIsServerThread()) { const std::set item_names{"minecraft:potion", "minecraft:milk_bucket", "minecraft:medicine"}; auto checked = mItemInUse->mItem->getItem()->isFood() || item_names.contains(mItemInUse->mItem->getTypeName()); @@ -304,8 +320,8 @@ LL_TYPE_INSTANCE_HOOK(EatHook, HookPriority::Normal, Player, &Player::completeUs else origin(); return; } - IF_LISTENED_END(EVENT_TYPES::onAte); } + IF_LISTENED_END(EVENT_TYPES::onAte); origin(); } @@ -319,12 +335,14 @@ LL_TYPE_INSTANCE_HOOK( ChangeDimensionRequest&& changeRequest ) { IF_LISTENED(EVENT_TYPES::onChangeDim) { - if (!CallEvent( - EVENT_TYPES::onChangeDim, - PlayerClass::newPlayer(&player), - Number::newNumber(changeRequest.mToDimensionId->id) - )) { - return; + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onChangeDim, + PlayerClass::newPlayer(&player), + Number::newNumber(changeRequest.mToDimensionId->id) + )) { + return; + } } } IF_LISTENED_END(EVENT_TYPES::onChangeDim); @@ -340,8 +358,10 @@ LL_TYPE_INSTANCE_HOOK( ContainerScreenContext const& screenContext ) { IF_LISTENED(EVENT_TYPES::onOpenContainerScreen) { - if (!CallEvent(EVENT_TYPES::onOpenContainerScreen, PlayerClass::newPlayer(&mPlayer))) { - return; + if (checkClientIsServerThread()) { + if (!CallEvent(EVENT_TYPES::onOpenContainerScreen, PlayerClass::newPlayer(&mPlayer))) { + return; + } } } IF_LISTENED_END(EVENT_TYPES::onOpenContainerScreen); @@ -360,12 +380,14 @@ LL_TYPE_STATIC_HOOK( class Level& level ) { IF_LISTENED(EVENT_TYPES::onUseRespawnAnchor) { - if (!CallEvent( - EVENT_TYPES::onUseRespawnAnchor, - PlayerClass::newPlayer(&player), - IntPos::newPos(pos, region.getDimensionId()) - )) { - return false; + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onUseRespawnAnchor, + PlayerClass::newPlayer(&player), + IntPos::newPos(pos, region.getDimensionId()) + )) { + return false; + } } } IF_LISTENED_END(EVENT_TYPES::onUseRespawnAnchor); @@ -381,12 +403,14 @@ LL_TYPE_INSTANCE_HOOK( BlockPos const& pos ) { IF_LISTENED(EVENT_TYPES::onBedEnter) { - if (!CallEvent( - EVENT_TYPES::onBedEnter, - PlayerClass::newPlayer(this), - IntPos::newPos(pos, this->getDimensionId().id) - )) { - return BedSleepingResult::Ok; + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onBedEnter, + PlayerClass::newPlayer(this), + IntPos::newPos(pos, this->getDimensionId().id) + )) { + return BedSleepingResult::Ok; + } } } IF_LISTENED_END(EVENT_TYPES::onBedEnter); @@ -394,8 +418,10 @@ LL_TYPE_INSTANCE_HOOK( } LL_TYPE_INSTANCE_HOOK(OpenInventoryHook, HookPriority::Normal, ServerPlayer, &ServerPlayer::$openInventory, void, ) { IF_LISTENED(EVENT_TYPES::onOpenInventory) { - if (!CallEvent(EVENT_TYPES::onOpenInventory, PlayerClass::newPlayer(this))) { - return; + if (checkClientIsServerThread()) { + if (!CallEvent(EVENT_TYPES::onOpenInventory, PlayerClass::newPlayer(this))) { + return; + } } } IF_LISTENED_END(EVENT_TYPES::onOpenInventory); @@ -412,14 +438,17 @@ LL_TYPE_INSTANCE_HOOK( float inSpeed ) { IF_LISTENED(EVENT_TYPES::onPlayerPullFishingHook) { - if (!CallEvent( - EVENT_TYPES::onPlayerPullFishingHook, - PlayerClass::newPlayer(this->getPlayerOwner()), - EntityClass::newEntity(&inEntity), - inEntity.isType(ActorType::ItemEntity) ? ItemClass::newItem(&static_cast(inEntity).item()) - : Local() - )) { - return; + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onPlayerPullFishingHook, + PlayerClass::newPlayer(this->getPlayerOwner()), + EntityClass::newEntity(&inEntity), + inEntity.isType(ActorType::ItemEntity) + ? ItemClass::newItem(&static_cast(inEntity).item()) + : Local() + )) { + return; + } } } IF_LISTENED_END(EVENT_TYPES::onPlayerPullFishingHook); @@ -440,15 +469,17 @@ LL_TYPE_INSTANCE_HOOK( uchar face ) { IF_LISTENED(EVENT_TYPES::onUseBucketPlace) { - if (!CallEvent( - EVENT_TYPES::onUseBucketPlace, - PlayerClass::newPlayer(static_cast(placer)), - ItemClass::newItem(&const_cast(instance)), - BlockClass::newBlock(contents, pos, region), - Number::newNumber(face), - FloatPos::newPos(pos, region.getDimensionId()) - )) { - return false; + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onUseBucketPlace, + PlayerClass::newPlayer(static_cast(placer)), + ItemClass::newItem(&const_cast(instance)), + BlockClass::newBlock(contents, pos, region), + Number::newNumber(face), + FloatPos::newPos(pos, region.getDimensionId()) + )) { + return false; + } } } IF_LISTENED_END(EVENT_TYPES::onUseBucketPlace); @@ -466,15 +497,17 @@ LL_TYPE_INSTANCE_HOOK( BlockPos const& pos ) { IF_LISTENED(EVENT_TYPES::onUseBucketTake) { - if (!CallEvent( - EVENT_TYPES::onUseBucketTake, - PlayerClass::newPlayer(&static_cast(entity)), - ItemClass::newItem(&item), - BlockClass::newBlock(pos, entity.getDimensionId().id), - Number::newNumber(-1), - FloatPos::newPos(pos, entity.getDimensionId().id) - )) { - return false; + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onUseBucketTake, + PlayerClass::newPlayer(&static_cast(entity)), + ItemClass::newItem(&item), + BlockClass::newBlock(pos, entity.getDimensionId().id), + Number::newNumber(-1), + FloatPos::newPos(pos, entity.getDimensionId().id) + )) { + return false; + } } } IF_LISTENED_END(EVENT_TYPES::onUseBucketTake); @@ -492,15 +525,17 @@ LL_TYPE_INSTANCE_HOOK( BlockPos const& pos ) { IF_LISTENED(EVENT_TYPES::onUseBucketTake) { - if (!CallEvent( - EVENT_TYPES::onUseBucketTake, - PlayerClass::newPlayer(&static_cast(entity)), - ItemClass::newItem(&item), - BlockClass::newBlock(pos, entity.getDimensionId().id), - Number::newNumber(-1), - FloatPos::newPos(pos, entity.getDimensionId().id) - )) { - return false; + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onUseBucketTake, + PlayerClass::newPlayer(&static_cast(entity)), + ItemClass::newItem(&item), + BlockClass::newBlock(pos, entity.getDimensionId().id), + Number::newNumber(-1), + FloatPos::newPos(pos, entity.getDimensionId().id) + )) { + return false; + } } } IF_LISTENED_END(EVENT_TYPES::onUseBucketTake); @@ -509,8 +544,10 @@ LL_TYPE_INSTANCE_HOOK( LL_TYPE_INSTANCE_HOOK(ConsumeTotemHook, HookPriority::Normal, Player, &Player::$consumeTotem, bool) { IF_LISTENED(EVENT_TYPES::onConsumeTotem) { - if (!CallEvent(EVENT_TYPES::onConsumeTotem, PlayerClass::newPlayer(this))) { - return false; + if (checkClientIsServerThread()) { + if (!CallEvent(EVENT_TYPES::onConsumeTotem, PlayerClass::newPlayer(this))) { + return false; + } } } IF_LISTENED_END(EVENT_TYPES::onConsumeTotem); @@ -526,8 +563,9 @@ LL_TYPE_INSTANCE_HOOK( SharedTypes::Legacy::ArmorSlot const armorSlot, ItemStack const& item ) { - if (isPlayer()) { - IF_LISTENED(EVENT_TYPES::onSetArmor) { + + IF_LISTENED(EVENT_TYPES::onSetArmor) { + if (checkClientIsServerThread() && isPlayer()) { if (!CallEvent( EVENT_TYPES::onSetArmor, PlayerClass::newPlayer(reinterpret_cast(this)), @@ -537,8 +575,8 @@ LL_TYPE_INSTANCE_HOOK( return; } } - IF_LISTENED_END(EVENT_TYPES::onSetArmor); } + IF_LISTENED_END(EVENT_TYPES::onSetArmor); origin(armorSlot, item); } @@ -552,13 +590,15 @@ LL_TYPE_INSTANCE_HOOK( Vec3 const& location ) { IF_LISTENED(EVENT_TYPES::onPlayerInteractEntity) { - if (!CallEvent( - EVENT_TYPES::onPlayerInteractEntity, - PlayerClass::newPlayer(this), - EntityClass::newEntity(&actor), - FloatPos::newPos(location, getDimensionId().id) - )) { - return false; + if (checkClientIsServerThread()) { + if (!CallEvent( + EVENT_TYPES::onPlayerInteractEntity, + PlayerClass::newPlayer(this), + EntityClass::newEntity(&actor), + FloatPos::newPos(location, getDimensionId().id) + )) { + return false; + } } } IF_LISTENED_END(EVENT_TYPES::onPlayerInteractEntity) @@ -573,8 +613,8 @@ LL_TYPE_INSTANCE_HOOK( void, ::MobEffectInstance const& effect ) { - if (isPlayer()) { - IF_LISTENED(EVENT_TYPES::onEffectAdded) { + IF_LISTENED(EVENT_TYPES::onEffectAdded) { + if (checkClientIsServerThread() && isPlayer()) { if (!CallEvent( EVENT_TYPES::onEffectAdded, PlayerClass::newPlayer(reinterpret_cast(this)), @@ -585,8 +625,8 @@ LL_TYPE_INSTANCE_HOOK( return; } } - IF_LISTENED_END(EVENT_TYPES::onEffectAdded); } + IF_LISTENED_END(EVENT_TYPES::onEffectAdded); origin(effect); } @@ -598,8 +638,8 @@ LL_TYPE_INSTANCE_HOOK( void, ::MobEffectInstance& effect ) { - if (isPlayer()) { - IF_LISTENED(EVENT_TYPES::onEffectRemoved) { + IF_LISTENED(EVENT_TYPES::onEffectRemoved) { + if (checkClientIsServerThread() && isPlayer()) { if (!CallEvent( EVENT_TYPES::onEffectRemoved, PlayerClass::newPlayer(reinterpret_cast(this)), @@ -608,8 +648,8 @@ LL_TYPE_INSTANCE_HOOK( return; } } - IF_LISTENED_END(EVENT_TYPES::onEffectRemoved); } + IF_LISTENED_END(EVENT_TYPES::onEffectRemoved); origin(effect); } From af522454e53b7db3affdcb40f9e439df22943193 Mon Sep 17 00:00:00 2001 From: ShrBox Date: Sun, 18 Jan 2026 23:06:04 +0800 Subject: [PATCH 13/27] refactor: use output.success instead of logger.info for tests --- src/tests/LSETests/PlayerTests.js | 136 +++++++++++++++--------------- src/tests/LSETests/main.js | 6 +- 2 files changed, 71 insertions(+), 71 deletions(-) diff --git a/src/tests/LSETests/PlayerTests.js b/src/tests/LSETests/PlayerTests.js index 41fdb739..c0d577c2 100644 --- a/src/tests/LSETests/PlayerTests.js +++ b/src/tests/LSETests/PlayerTests.js @@ -1,83 +1,83 @@ -export function TestPlayer(players) { +export function TestPlayer(output, players) { for (let player of players) { - GetFromViewVector(player) - PrintPlayerAttributes(player) + GetFromViewVector(output, player) + PrintPlayerAttributes(output, player) } } -function GetFromViewVector(player) { +function GetFromViewVector(output, player) { let en = player.getEntityFromViewVector(5.25); if (en) { - logger.info(`Entity looking at: ${en.name}`); - logBlock(player.getBlockFromViewVector(true, false, player.distanceTo(en), false)); + output.success(`Entity looking at: ${en.name}`); + logBlock(output, player.getBlockFromViewVector(true, false, player.distanceTo(en), false)); } else { - logger.info(`No entity looking at found`); - logBlock(player.getBlockFromViewVector(true, false, 5.25, false)); + output.success(`No entity looking at found`); + logBlock(output, player.getBlockFromViewVector(true, false, 5.25, false)); } - function logBlock(bl) { + function logBlock(output, bl) { if (bl) { - logger.info(`Block looking at: ${bl.name} ${bl.pos}`); + output.success(`Block looking at: ${bl.name} ${bl.pos}`); } else { - logger.info(`No Block looking at found`); + output.success(`No Block looking at found`); } } } -function PrintPlayerAttributes(player) { - logger.info(`Name: ${player.name}`); - logger.info(`Position: ${player.pos}`); - logger.info(`Feet Position: ${player.feetPos}`); - logger.info(`Block Position: ${player.blockPos}`); - logger.info(`Last Death Position: ${player.lastDeathPos}`); - logger.info(`Real Name: ${player.realName}`); - logger.info(`XUID: ${player.xuid}`); - logger.info(`UUID: ${player.uuid}`); - logger.info(`Permission Level: ${player.permLevel}`); - logger.info(`Game Mode: ${player.gameMode}`); - logger.info(`Can Sleep: ${player.canSleep}`); - logger.info(`Can Fly: ${player.canFly}`); - logger.info(`Can Be Seen On Map: ${player.canBeSeenOnMap}`); - logger.info(`Can Freeze: ${player.canFreeze}`); - logger.info(`Can See Daylight: ${player.canSeeDaylight}`); - logger.info(`Can Show Name Tag: ${player.canShowNameTag}`); - logger.info(`Can Start Sleep In Bed: ${player.canStartSleepInBed}`); - logger.info(`Can Pickup Items: ${player.canPickupItems}`); - logger.info(`Max Health: ${player.maxHealth}`); - logger.info(`Health: ${player.health}`); - logger.info(`In Air: ${player.inAir}`); - logger.info(`In Water: ${player.inWater}`); - logger.info(`In Lava: ${player.inLava}`); - logger.info(`In Rain: ${player.inRain}`); - logger.info(`In Snow: ${player.inSnow}`); - logger.info(`In Wall: ${player.inWall}`); - logger.info(`In Water Or Rain: ${player.inWaterOrRain}`); - logger.info(`In World: ${player.inWorld}`); - logger.info(`In Clouds: ${player.inClouds}`); - logger.info(`Speed: ${player.speed}`); - logger.info(`Direction: ${player.direction}`); - logger.info(`Unique ID: ${player.uniqueId}`); - logger.info(`Language Code: ${player.langCode}`); - logger.info(`Is Loading: ${player.isLoading}`); - logger.info(`Is Invisible: ${player.isInvisible}`); - logger.info(`Is Inside Portal: ${player.isInsidePortal}`); - logger.info(`Is Hurt: ${player.isHurt}`); - logger.info(`Is Trusting: ${player.isTrusting}`); - logger.info(`Is Touching Damage Block: ${player.isTouchingDamageBlock}`); - logger.info(`Is Hungry: ${player.isHungry}`); - logger.info(`Is On Fire: ${player.isOnFire}`); - logger.info(`Is On Ground: ${player.isOnGround}`); - logger.info(`Is On Hot Block: ${player.isOnHotBlock}`); - logger.info(`Is Trading: ${player.isTrading}`); - logger.info(`Is Adventure: ${player.isAdventure}`); - logger.info(`Is Gliding: ${player.isGliding}`); - logger.info(`Is Survival: ${player.isSurvival}`); - logger.info(`Is Spectator: ${player.isSpectator}`); - logger.info(`Is Riding: ${player.isRiding}`); - logger.info(`Is Dancing: ${player.isDancing}`); - logger.info(`Is Creative: ${player.isCreative}`); - logger.info(`Is Flying: ${player.isFlying}`); - logger.info(`Is Sleeping: ${player.isSleeping}`); - logger.info(`Is Moving: ${player.isMoving}`); - logger.info(`Is Sneaking: ${player.isSneaking}`); -} \ No newline at end of file +function PrintPlayerAttributes(output, player) { + output.success(`Name: ${player.name}`); + output.success(`Position: ${player.pos}`); + output.success(`Feet Position: ${player.feetPos}`); + output.success(`Block Position: ${player.blockPos}`); + output.success(`Last Death Position: ${player.lastDeathPos}`); + output.success(`Real Name: ${player.realName}`); + output.success(`XUID: ${player.xuid}`); + output.success(`UUID: ${player.uuid}`); + output.success(`Permission Level: ${player.permLevel}`); + output.success(`Game Mode: ${player.gameMode}`); + output.success(`Can Sleep: ${player.canSleep}`); + output.success(`Can Fly: ${player.canFly}`); + output.success(`Can Be Seen On Map: ${player.canBeSeenOnMap}`); + output.success(`Can Freeze: ${player.canFreeze}`); + output.success(`Can See Daylight: ${player.canSeeDaylight}`); + output.success(`Can Show Name Tag: ${player.canShowNameTag}`); + output.success(`Can Start Sleep In Bed: ${player.canStartSleepInBed}`); + output.success(`Can Pickup Items: ${player.canPickupItems}`); + output.success(`Max Health: ${player.maxHealth}`); + output.success(`Health: ${player.health}`); + output.success(`In Air: ${player.inAir}`); + output.success(`In Water: ${player.inWater}`); + output.success(`In Lava: ${player.inLava}`); + output.success(`In Rain: ${player.inRain}`); + output.success(`In Snow: ${player.inSnow}`); + output.success(`In Wall: ${player.inWall}`); + output.success(`In Water Or Rain: ${player.inWaterOrRain}`); + output.success(`In World: ${player.inWorld}`); + output.success(`In Clouds: ${player.inClouds}`); + output.success(`Speed: ${player.speed}`); + output.success(`Direction: ${player.direction}`); + output.success(`Unique ID: ${player.uniqueId}`); + output.success(`Language Code: ${player.langCode}`); + output.success(`Is Loading: ${player.isLoading}`); + output.success(`Is Invisible: ${player.isInvisible}`); + output.success(`Is Inside Portal: ${player.isInsidePortal}`); + output.success(`Is Hurt: ${player.isHurt}`); + output.success(`Is Trusting: ${player.isTrusting}`); + output.success(`Is Touching Damage Block: ${player.isTouchingDamageBlock}`); + output.success(`Is Hungry: ${player.isHungry}`); + output.success(`Is On Fire: ${player.isOnFire}`); + output.success(`Is On Ground: ${player.isOnGround}`); + output.success(`Is On Hot Block: ${player.isOnHotBlock}`); + output.success(`Is Trading: ${player.isTrading}`); + output.success(`Is Adventure: ${player.isAdventure}`); + output.success(`Is Gliding: ${player.isGliding}`); + output.success(`Is Survival: ${player.isSurvival}`); + output.success(`Is Spectator: ${player.isSpectator}`); + output.success(`Is Riding: ${player.isRiding}`); + output.success(`Is Dancing: ${player.isDancing}`); + output.success(`Is Creative: ${player.isCreative}`); + output.success(`Is Flying: ${player.isFlying}`); + output.success(`Is Sleeping: ${player.isSleeping}`); + output.success(`Is Moving: ${player.isMoving}`); + output.success(`Is Sneaking: ${player.isSneaking}`); +} diff --git a/src/tests/LSETests/main.js b/src/tests/LSETests/main.js index 7bb3c40a..29bb39ab 100644 --- a/src/tests/LSETests/main.js +++ b/src/tests/LSETests/main.js @@ -5,7 +5,7 @@ import {TestPlayer} from './plugins/LSETests/PlayerTests.js'; RegisterEvents(); mc.listen('onServerStarted', () => { - let cmd = mc.newCommand('lsetests', "LegacyScriptEngine tests", PermType.Console); + let cmd = mc.newCommand('lsetests', "LegacyScriptEngine tests", PermType.GameMasters); cmd.setEnum('testOption', ['logger', 'events', 'player']); cmd.mandatory('testOption', ParamType.Enum, 'testOption'); cmd.optional('player', ParamType.Player); @@ -18,10 +18,10 @@ mc.listen('onServerStarted', () => { case 'events': const notTriggeredEvents = events.filter(event => !triggeredEvents.has(event)); - logger.info(`Events not triggered: ${notTriggeredEvents.join(', ')}`); + output.success(`Events not triggered: ${notTriggeredEvents.join(', ')}`); break; case 'player': - TestPlayer(results.player); + TestPlayer(output, results.player); break; default: logger.error(`Invalid test option ${results.testOption}`); From 838ca02c7c118248399f87c2a7eabeb1e5424119 Mon Sep 17 00:00:00 2001 From: ShrBox Date: Mon, 19 Jan 2026 14:43:53 +0800 Subject: [PATCH 14/27] fix: fix client command registration --- src-client/lse/PluginManager.cpp | 302 ++++++++++++++++++++++ src-client/lse/PluginManager.h | 22 ++ {src => src-server}/lse/PluginManager.cpp | 24 +- {src => src-server}/lse/PluginManager.h | 1 - src/lse/Entry.cpp | 8 +- src/lse/Entry.h | 6 +- src/lse/Plugin.cpp | 4 +- src/lse/Plugin.h | 2 +- src/lse/PluginMigration.cpp | 4 +- src/lse/PluginMigration.h | 2 +- xmake.lua | 4 + 11 files changed, 349 insertions(+), 30 deletions(-) create mode 100644 src-client/lse/PluginManager.cpp create mode 100644 src-client/lse/PluginManager.h rename {src => src-server}/lse/PluginManager.cpp (96%) rename {src => src-server}/lse/PluginManager.h (93%) diff --git a/src-client/lse/PluginManager.cpp b/src-client/lse/PluginManager.cpp new file mode 100644 index 00000000..3ddbd8ae --- /dev/null +++ b/src-client/lse/PluginManager.cpp @@ -0,0 +1,302 @@ +#include "lse/PluginManager.h" + +#include "legacy/engine/EngineManager.h" +#include "legacy/engine/EngineOwnData.h" +#include "ll/api/io/FileUtils.h" // IWYU pragma: keep +#include "ll/api/mod/Mod.h" +#include "ll/api/mod/ModManager.h" +#include "ll/api/service/GamingStatus.h" +#include "ll/api/utils/ErrorUtils.h" +#include "ll/api/utils/StringUtils.h" +#include "lse/Entry.h" +#include "lse/Plugin.h" + +#include +#include +#include +#include + +#ifdef LSE_BACKEND_LUA + +constexpr auto BaseLibFileName = "BaseLib.lua"; +constexpr auto PluginManagerName = "lse-lua"; + +#endif + +#ifdef LSE_BACKEND_QUICKJS + +constexpr auto BaseLibFileName = "BaseLib.js"; +constexpr auto PluginManagerName = "lse-quickjs"; + +#endif + +#ifdef LSE_BACKEND_PYTHON + +#include "legacy/main/PythonHelper.h" +constexpr auto BaseLibFileName = "BaseLib.py"; +constexpr auto PluginManagerName = "lse-python"; + +#endif + +#ifdef LSE_BACKEND_NODEJS + +#include "legacy/main/NodeJsHelper.h" +constexpr auto PluginManagerName = "lse-nodejs"; + +#endif + +// Do not use legacy headers directly, otherwise there will be tons of errors. +void BindAPIs(std::shared_ptr engine); +void LLSERemoveTimeTaskData(std::shared_ptr engine); +bool LLSERemoveAllEventListeners(std::shared_ptr engine); +bool LLSERemoveCmdRegister(std::shared_ptr engine); +bool LLSERemoveCmdCallback(std::shared_ptr engine); +bool LLSERemoveAllExportedFuncs(std::shared_ptr engine); +bool LLSECallEventsOnHotLoad(std::shared_ptr engine); +bool LLSECallEventsOnUnload(std::shared_ptr engine); + +namespace lse { + +PluginManager::PluginManager() : ll::mod::ModManager(PluginManagerName) {} +PluginManager::~PluginManager() = default; + +ll::Expected<> PluginManager::load(ll::mod::Manifest manifest) { + if (hasMod(manifest.name)) { + return ll::makeStringError("Plugin has already loaded"); + } + + auto plugin = std::make_shared(manifest); + + return plugin->onLoad().transform([&, this] { addMod(manifest.name, plugin); }); +} + +ll::Expected<> PluginManager::enable(std::string_view name) { +#ifdef LSE_BACKEND_PYTHON + auto& logger = lse::LegacyScriptEngine::getLogger(); + std::filesystem::path dirPath = ll::mod::getModsRoot() / manifest.name; // Plugin path + std::string entryPath = + PythonHelper::findEntryScript(ll::string_utils::u8str2str(dirPath.u8string())); // Plugin entry + // if (entryPath.empty()) return false; + // std::string pluginName = PythonHelper::getPluginPackageName(dirPath.string()); // Plugin name + + // Run "pip install" if needed + auto realPackageInstallDir = (std::filesystem::path(dirPath) / "site-packages").make_preferred(); + if (!std::filesystem::exists(realPackageInstallDir)) { + std::string dependTmpFilePath = + PythonHelper::getPluginPackDependencyFilePath(ll::string_utils::u8str2str(dirPath.u8string())); + if (!dependTmpFilePath.empty()) { + int exitCode = 0; + logger.info( + "Executing \"pip install\" for plugin {name}..."_tr( + fmt::arg("name", ll::string_utils::u8str2str(dirPath.filename().u8string())) + ) + ); + + if ((exitCode = PythonHelper::executePipCommand( + "pip install -r \"" + dependTmpFilePath + "\" -t \"" + + ll::string_utils::u8str2str(realPackageInstallDir.u8string()) + "\" --disable-pip-version-check " + )) + == 0) { + logger.info("Pip finished successfully."_tr()); + } else logger.error("Error occurred. Exit code: {code}"_tr(fmt::arg("code", exitCode))); + + // remove temp dependency file after installation + std::error_code ec; + std::filesystem::remove(std::filesystem::path(dependTmpFilePath), ec); + } + } +#endif +#ifdef LSE_BACKEND_NODEJS + auto& logger = lse::LegacyScriptEngine::getLogger(); + std::filesystem::path dirPath = ll::mod::getModsRoot() / manifest.name; // Plugin path + // std::string entryPath = NodeJsHelper::findEntryScript(dirPath.string()); // Plugin entry + // if (entryPath.empty()) return false; + // std::string pluginName = NodeJsHelper::getPluginPackageName(dirPath.string()); // Plugin name + + // Run "npm install" if needed + if (NodeJsHelper::doesPluginPackHasDependency(ll::string_utils::u8str2str(dirPath.u8string())) + && !std::filesystem::exists(std::filesystem::path(dirPath) / "node_modules")) { + int exitCode = 0; + logger.info( + "Executing \"npm install\" for plugin {name}..."_tr( + fmt::arg("name", ll::string_utils::u8str2str(dirPath.filename().u8string())) + ) + ); + if ((exitCode = NodeJsHelper::executeNpmCommand( + {"install", "--omit=dev", "--no-fund"}, + ll::string_utils::u8str2str(dirPath.u8string()) + )) + != 0) { + logger.error("Error occurred. Exit code: {code}"_tr(fmt::arg("code", exitCode))); + } + } +#endif + auto plugin = std::static_pointer_cast(getMod(name)); + if (!plugin) { + return ll::makeStringError("Plugin {0} not found"_tr(name)); + } + auto manifest = plugin->getManifest(); + + auto scriptEngine = EngineManager::newEngine(manifest.name); + + try { + EngineScope engineScope(scriptEngine.get()); + + // Init plugin logger + getEngineOwnData()->logger = ll::io::LoggerRegistry::getInstance().getOrCreate(manifest.name); + +#ifdef LSE_BACKEND_PYTHON + scriptEngine->eval("import sys as _llse_py_sys_module"); + std::error_code ec; + + // add plugin-own site-packages to sys.path + std::string pluginSitePackageFormatted = ll::string_utils::u8str2str( + std::filesystem::canonical(realPackageInstallDir.make_preferred(), ec).u8string() + ); + if (!ec) { + scriptEngine->eval("_llse_py_sys_module.path.insert(0, r'" + pluginSitePackageFormatted + "')"); + } + // add plugin source dir to sys.path + std::string sourceDirFormatted = + ll::string_utils::u8str2str(std::filesystem::canonical(dirPath.make_preferred()).u8string()); + scriptEngine->eval("_llse_py_sys_module.path.insert(0, r'" + sourceDirFormatted + "')"); + + // set __file__ and __name__ + std::string entryPathFormatted = ll::string_utils::u8str2str( + std::filesystem::canonical(std::filesystem::path(entryPath).make_preferred()).u8string() + ); + scriptEngine->set("__file__", entryPathFormatted); + // engine->set("__name__", String::newString("__main__")); +#endif + + BindAPIs(scriptEngine); + +#ifndef LSE_BACKEND_NODEJS // NodeJs backend load depends code in another place + auto& self = LegacyScriptEngine::getInstance().getSelf(); + // Load BaseLib. + auto baseLibPath = self.getModDir() / "baselib" / BaseLibFileName; + auto baseLibContent = ll::file_utils::readFile(baseLibPath); + if (!baseLibContent) { + return ll::makeStringError("Failed to read BaseLib at {0}"_tr(baseLibPath.string())); + } + scriptEngine->eval(baseLibContent.value()); +#endif + // Load the plugin entry. + auto entryPath = plugin->getModDir() / manifest.entry; + getEngineOwnData()->plugin = plugin; +#ifdef LSE_BACKEND_PYTHON + if (!PythonHelper::loadPluginCode( + scriptEngine, + ll::string_utils::u8str2str(entryPath.u8string()), + ll::string_utils::u8str2str(dirPath.u8string()) + )) { + return ll::makeStringError("Failed to load plugin code"_tr()); + } +#endif +#ifdef LSE_BACKEND_NODEJS + if (!NodeJsHelper::loadPluginCode( + scriptEngine, + ll::string_utils::u8str2str(entryPath.u8string()), + ll::string_utils::u8str2str(dirPath.u8string()), + NodeJsHelper::isESModulesSystem(ll::string_utils::u8str2str(dirPath.u8string())) + )) { + return ll::makeStringError("Failed to load plugin code"_tr()); + } +#endif +#if (defined LSE_BACKEND_QUICKJS) || (defined LSE_BACKEND_LUA) + // Try loadFile + try { + scriptEngine->loadFile(entryPath.u8string()); + } catch (const Exception&) { + // loadFile failed, try eval + auto pluginEntryContent = ll::file_utils::readFile(entryPath); + if (!pluginEntryContent) { + return ll::makeStringError("Failed to read plugin entry at {0}"_tr(entryPath.string())); + } + scriptEngine->eval(pluginEntryContent.value(), entryPath.u8string()); + } +#endif + if (ll::getGamingStatus() == ll::GamingStatus::Running) { // Is hot load + LLSECallEventsOnHotLoad(scriptEngine); + } + ExitEngineScope exit; + + if (auto res = plugin->onEnable(); !res) { + return res; + } + + return {}; + } catch (const Exception& e) { + if (scriptEngine) { + auto error = [&] { + EngineScope engineScope(scriptEngine.get()); + return ll::makeStringError( + "Failed to enable plugin {0}: {1}\n{2}"_tr(manifest.name, e.message(), e.stacktrace()) + ); + }(); + +#ifndef LSE_BACKEND_NODEJS + LLSERemoveTimeTaskData(scriptEngine); +#endif + LLSERemoveAllEventListeners(scriptEngine); + LLSERemoveCmdRegister(scriptEngine); + LLSERemoveCmdCallback(scriptEngine); + LLSERemoveAllExportedFuncs(scriptEngine); + + EngineOwnData::clearEngineObjects(scriptEngine); + EngineManager::unregisterEngine(scriptEngine); +#ifdef LSE_BACKEND_NODEJS + NodeJsHelper::stopEngine(scriptEngine); +#endif + return error; + } else { + return ll::makeStringError("Failed to enable plugin {0}: {1}"_tr(manifest.name, "ScriptEngine is nullptr")); + } + } +} + +ll::Expected<> PluginManager::disable(std::string_view name) { + try { + auto scriptEngine = EngineManager::getEngine(std::string(name)); + + if (!scriptEngine) { + return ll::makeStringError("Plugin {0} not found"_tr(name)); + } + + { + EngineScope scope(scriptEngine.get()); + LLSECallEventsOnUnload(scriptEngine); +#ifndef LSE_BACKEND_NODEJS + LLSERemoveTimeTaskData(scriptEngine); +#endif + LLSERemoveAllEventListeners(scriptEngine); + LLSERemoveCmdRegister(scriptEngine); + LLSERemoveCmdCallback(scriptEngine); + LLSERemoveAllExportedFuncs(scriptEngine); + EngineOwnData::clearEngineObjects(scriptEngine); + } + EngineManager::unregisterEngine(scriptEngine); +#ifdef LSE_BACKEND_NODEJS + NodeJsHelper::stopEngine(scriptEngine); +#endif + + if (auto res = std::static_pointer_cast(getMod(name))->onDisable(); !res) { + return res; + } + return {}; + } catch (const Exception&) { + return ll::makeStringError("Failed to disable plugin {0}: {1}"_tr(name, "Unknown script exception")); + } catch (const std::exception& e) { + return ll::makeStringError("Failed to disable plugin {0}: {1}"_tr(name, e.what())); + } +} + +ll::Expected<> PluginManager::unload(std::string_view name) { + if (auto res = std::static_pointer_cast(getMod(name))->onUnload(); !res) { + return res; + } + eraseMod(name); + return {}; +} + +} // namespace lse diff --git a/src-client/lse/PluginManager.h b/src-client/lse/PluginManager.h new file mode 100644 index 00000000..9ea8d567 --- /dev/null +++ b/src-client/lse/PluginManager.h @@ -0,0 +1,22 @@ +#pragma once +#include "ll/api/Expected.h" +#include "ll/api/mod/Manifest.h" +#include "ll/api/mod/ModManager.h" + +#include + +namespace lse { + +class PluginManager final : public ll::mod::ModManager { +public: + PluginManager(); + ~PluginManager() override; + +private: + ll::Expected<> load(ll::mod::Manifest manifest) override; + ll::Expected<> unload(std::string_view name) override; + ll::Expected<> enable(std::string_view name) override; + ll::Expected<> disable(std::string_view name) override; +}; + +} // namespace lse diff --git a/src/lse/PluginManager.cpp b/src-server/lse/PluginManager.cpp similarity index 96% rename from src/lse/PluginManager.cpp rename to src-server/lse/PluginManager.cpp index 4b4b166c..c6b86b3f 100644 --- a/src/lse/PluginManager.cpp +++ b/src-server/lse/PluginManager.cpp @@ -1,22 +1,18 @@ -#include "PluginManager.h" +#include "lse/PluginManager.h" -#include "Entry.h" -#include "Plugin.h" #include "legacy/engine/EngineManager.h" #include "legacy/engine/EngineOwnData.h" -#include "ll/api/chrono/GameChrono.h" -#include "ll/api/coro/CoroTask.h" #include "ll/api/io/FileUtils.h" // IWYU pragma: keep #include "ll/api/mod/Mod.h" #include "ll/api/mod/ModManager.h" #include "ll/api/service/GamingStatus.h" -#include "ll/api/thread/ServerThreadExecutor.h" #include "ll/api/utils/StringUtils.h" +#include "lse/Entry.h" +#include "lse/Plugin.h" #include #include #include -#include #include #ifdef LSE_BACKEND_LUA @@ -212,7 +208,7 @@ ll::Expected<> PluginManager::load(ll::mod::Manifest manifest) { LLSECallEventsOnHotLoad(scriptEngine); } ExitEngineScope exit; - plugin->onLoad([](ll::mod::Mod&) { return true; }); + plugin->onDisable([this](ll::mod::Mod& self) { if (ll::getGamingStatus() == ll::GamingStatus::Stopping) { unload(self.getName()); @@ -271,16 +267,14 @@ ll::Expected<> PluginManager::unload(std::string_view name) { EngineOwnData::clearEngineObjects(scriptEngine); } EngineManager::unregisterEngine(scriptEngine); - - if (auto plugin = std::static_pointer_cast(getMod(name))) { - plugin->onUnload(); - } - - eraseMod(name); - #ifdef LSE_BACKEND_NODEJS NodeJsHelper::stopEngine(scriptEngine); #endif + + if (auto res = std::static_pointer_cast(getMod(name))->onUnload(); !res) { + return res; + } + eraseMod(name); return {}; } catch (const Exception&) { return ll::makeStringError("Failed to unload plugin {0}: {1}"_tr(name, "Unknown script exception")); diff --git a/src/lse/PluginManager.h b/src-server/lse/PluginManager.h similarity index 93% rename from src/lse/PluginManager.h rename to src-server/lse/PluginManager.h index 7651b477..67a0949b 100644 --- a/src/lse/PluginManager.h +++ b/src-server/lse/PluginManager.h @@ -1,6 +1,5 @@ #pragma once #include "ll/api/Expected.h" -#include "ll/api/base/Macro.h" #include "ll/api/mod/Manifest.h" #include "ll/api/mod/ModManager.h" diff --git a/src/lse/Entry.cpp b/src/lse/Entry.cpp index 2287c01c..ffcbb936 100644 --- a/src/lse/Entry.cpp +++ b/src/lse/Entry.cpp @@ -1,7 +1,5 @@ -#include "Entry.h" +#include "lse/Entry.h" -#include "PluginManager.h" -#include "PluginMigration.h" #include "legacy/engine/EngineManager.h" #include "legacy/engine/EngineOwnData.h" #include "legacy/main/EconomicSystem.h" @@ -13,6 +11,8 @@ #include "ll/api/mod/RegisterHelper.h" #include "ll/api/service/PlayerInfo.h" #include "ll/api/utils/ErrorUtils.h" +#include "lse/PluginManager.h" +#include "lse/PluginMigration.h" #include #include @@ -125,8 +125,6 @@ bool LegacyScriptEngine::load() { } } -bool LegacyScriptEngine::disable() { return true; } - Config const& LegacyScriptEngine::getConfig() { return config; } PluginManager& LegacyScriptEngine::getManager() { diff --git a/src/lse/Entry.h b/src/lse/Entry.h index 32ddbd0e..a398d048 100644 --- a/src/lse/Entry.h +++ b/src/lse/Entry.h @@ -1,7 +1,7 @@ #pragma once -#include "Config.h" -#include "PluginManager.h" +#include "lse/Config.h" +#include "lse/PluginManager.h" #include "ll/api/mod/NativeMod.h" namespace lse { @@ -24,7 +24,7 @@ class LegacyScriptEngine { bool enable(); - bool disable(); + // bool disable(); // bool unload(); diff --git a/src/lse/Plugin.cpp b/src/lse/Plugin.cpp index a3482f57..b7ce8d93 100644 --- a/src/lse/Plugin.cpp +++ b/src/lse/Plugin.cpp @@ -1,6 +1,6 @@ -#include "Plugin.h" +#include "lse/Plugin.h" -#include "Entry.h" +#include "lse/Entry.h" #include "legacy/engine/EngineOwnData.h" #include "ll/api/mod/Manifest.h" #include "ll/api/mod/Mod.h" diff --git a/src/lse/Plugin.h b/src/lse/Plugin.h index 77886d4c..9d0daf96 100644 --- a/src/lse/Plugin.h +++ b/src/lse/Plugin.h @@ -1,9 +1,9 @@ #pragma once -#include "PluginManager.h" #include "ll/api/command/runtime/ParamKind.h" #include "ll/api/mod/Manifest.h" #include "ll/api/mod/Mod.h" +#include "lse/PluginManager.h" namespace lse { diff --git a/src/lse/PluginMigration.cpp b/src/lse/PluginMigration.cpp index e1087122..2ab2b51e 100644 --- a/src/lse/PluginMigration.cpp +++ b/src/lse/PluginMigration.cpp @@ -1,10 +1,10 @@ -#include "PluginMigration.h" +#include "lse/PluginMigration.h" -#include "Entry.h" #include "ll/api/i18n/I18n.h" #include "ll/api/mod/Manifest.h" #include "ll/api/mod/Mod.h" #include "ll/api/reflection/Serialization.h" +#include "lse/Entry.h" #include #include diff --git a/src/lse/PluginMigration.h b/src/lse/PluginMigration.h index 66de0146..163f16bc 100644 --- a/src/lse/PluginMigration.h +++ b/src/lse/PluginMigration.h @@ -1,6 +1,6 @@ #pragma once -#include "PluginManager.h" +#include "lse/PluginManager.h" namespace lse { diff --git a/xmake.lua b/xmake.lua index 2e79284e..c37786a7 100644 --- a/xmake.lua +++ b/xmake.lua @@ -124,8 +124,12 @@ target("LegacyScriptEngine") ) if is_config("target_type", "server") then add_defines("LL_PLAT_S") + add_files("src-server/**.cpp") + add_includedirs("src-server") else add_defines("LL_PLAT_C") + add_files("src-client/**.cpp") + add_includedirs("src-client") end if has_config("publish") then add_defines("LSE_VERSION_PUBLISH") From df874e18fb25ab1ab09ce6679a46a21dee1f1e8d Mon Sep 17 00:00:00 2001 From: ShrBox Date: Mon, 19 Jan 2026 15:19:46 +0800 Subject: [PATCH 15/27] refactor: rename Plugin to ScriptPlugin fix: fix onLeft crash on client fix: fix registerCommands not clear when disable on client --- src-client/lse/PluginManager.cpp | 15 +++++++++------ src-server/lse/PluginManager.cpp | 6 +++--- src/legacy/api/EventAPI.cpp | 4 +++- src/legacy/engine/EngineOwnData.h | 4 ++-- src/lse/Entry.cpp | 2 +- src/lse/Entry.h | 4 ---- src/lse/{Plugin.cpp => ScriptPlugin.cpp} | 11 +++++------ src/lse/{Plugin.h => ScriptPlugin.h} | 6 +++--- 8 files changed, 26 insertions(+), 26 deletions(-) rename src/lse/{Plugin.cpp => ScriptPlugin.cpp} (54%) rename src/lse/{Plugin.h => ScriptPlugin.h} (84%) diff --git a/src-client/lse/PluginManager.cpp b/src-client/lse/PluginManager.cpp index 3ddbd8ae..bb0a9c48 100644 --- a/src-client/lse/PluginManager.cpp +++ b/src-client/lse/PluginManager.cpp @@ -9,7 +9,7 @@ #include "ll/api/utils/ErrorUtils.h" #include "ll/api/utils/StringUtils.h" #include "lse/Entry.h" -#include "lse/Plugin.h" +#include "lse/ScriptPlugin.h" #include #include @@ -65,7 +65,7 @@ ll::Expected<> PluginManager::load(ll::mod::Manifest manifest) { return ll::makeStringError("Plugin has already loaded"); } - auto plugin = std::make_shared(manifest); + auto plugin = std::make_shared(manifest); return plugin->onLoad().transform([&, this] { addMod(manifest.name, plugin); }); } @@ -131,7 +131,7 @@ ll::Expected<> PluginManager::enable(std::string_view name) { } } #endif - auto plugin = std::static_pointer_cast(getMod(name)); + auto plugin = std::static_pointer_cast(getMod(name)); if (!plugin) { return ll::makeStringError("Plugin {0} not found"_tr(name)); } @@ -280,8 +280,11 @@ ll::Expected<> PluginManager::disable(std::string_view name) { NodeJsHelper::stopEngine(scriptEngine); #endif - if (auto res = std::static_pointer_cast(getMod(name))->onDisable(); !res) { - return res; + if (auto plugin = std::static_pointer_cast(getMod(name))) { + plugin->registeredCommands.clear(); + if (auto res = plugin->onDisable(); !res) { + return res; + } } return {}; } catch (const Exception&) { @@ -292,7 +295,7 @@ ll::Expected<> PluginManager::disable(std::string_view name) { } ll::Expected<> PluginManager::unload(std::string_view name) { - if (auto res = std::static_pointer_cast(getMod(name))->onUnload(); !res) { + if (auto res = std::static_pointer_cast(getMod(name))->onUnload(); !res) { return res; } eraseMod(name); diff --git a/src-server/lse/PluginManager.cpp b/src-server/lse/PluginManager.cpp index c6b86b3f..ddd7e971 100644 --- a/src-server/lse/PluginManager.cpp +++ b/src-server/lse/PluginManager.cpp @@ -8,7 +8,7 @@ #include "ll/api/service/GamingStatus.h" #include "ll/api/utils/StringUtils.h" #include "lse/Entry.h" -#include "lse/Plugin.h" +#include "lse/ScriptPlugin.h" #include #include @@ -125,7 +125,7 @@ ll::Expected<> PluginManager::load(ll::mod::Manifest manifest) { } auto scriptEngine = EngineManager::newEngine(manifest.name); - auto plugin = std::make_shared(manifest); + auto plugin = std::make_shared(manifest); try { EngineScope engineScope(scriptEngine.get()); @@ -271,7 +271,7 @@ ll::Expected<> PluginManager::unload(std::string_view name) { NodeJsHelper::stopEngine(scriptEngine); #endif - if (auto res = std::static_pointer_cast(getMod(name))->onUnload(); !res) { + if (auto res = std::static_pointer_cast(getMod(name))->onUnload(); !res) { return res; } eraseMod(name); diff --git a/src/legacy/api/EventAPI.cpp b/src/legacy/api/EventAPI.cpp index b87741bb..7f74678c 100644 --- a/src/legacy/api/EventAPI.cpp +++ b/src/legacy/api/EventAPI.cpp @@ -54,6 +54,8 @@ #include "mc/world/item/VanillaItemNames.h" #include "mc/world/level/dimension/Dimension.h" +#include + #ifdef LSE_BACKEND_NODEJS #include "legacy/main/NodeJsHelper.h" #endif @@ -184,7 +186,7 @@ void EnableEventListener(int eventId) { case EVENT_TYPES::onLeft: bus.emplaceListener([](PlayerDisconnectEvent& ev) { IF_LISTENED(EVENT_TYPES::onLeft) { - if (checkClientIsServerThread()) { + if (checkClientIsServerThread() && ll::getGamingStatus() != ll::GamingStatus::Stopping) { CallEvent(EVENT_TYPES::onLeft, PlayerClass::newPlayer(&ev.self())); // Not cancellable } } diff --git a/src/legacy/engine/EngineOwnData.h b/src/legacy/engine/EngineOwnData.h index 8ab62e10..95090c2c 100644 --- a/src/legacy/engine/EngineOwnData.h +++ b/src/legacy/engine/EngineOwnData.h @@ -1,6 +1,6 @@ #pragma once #include "legacy/main/Global.h" -#include "lse/Plugin.h" +#include "lse/ScriptPlugin.h" #include "utils/UsingScriptX.h" #include @@ -34,7 +34,7 @@ struct EngineOwnData { ll::i18n::I18n i18n; std::string defaultLocaleName; - std::shared_ptr plugin; + std::shared_ptr plugin; // Use standalone logger in EngineOwnData instead of plugin.getLogger() for allowing modify logger title. std::shared_ptr logger; diff --git a/src/lse/Entry.cpp b/src/lse/Entry.cpp index ffcbb936..5ed02424 100644 --- a/src/lse/Entry.cpp +++ b/src/lse/Entry.cpp @@ -151,7 +151,7 @@ void loadDebugEngine(const ll::mod::NativeMod& self) { // Init plugin instance for debug engine to prevent something unexpected. ll::mod::Manifest manifest; manifest.name = "DebugEngine"; - getEngineOwnData()->plugin = std::make_shared(manifest); + getEngineOwnData()->plugin = std::make_shared(manifest); // Init logger getEngineOwnData()->logger = ll::io::LoggerRegistry::getInstance().getOrCreate("DebugEngine"); diff --git a/src/lse/Entry.h b/src/lse/Entry.h index a398d048..be24e290 100644 --- a/src/lse/Entry.h +++ b/src/lse/Entry.h @@ -24,10 +24,6 @@ class LegacyScriptEngine { bool enable(); - // bool disable(); - - // bool unload(); - private: ll::mod::NativeMod& mSelf; Config config; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables) diff --git a/src/lse/Plugin.cpp b/src/lse/ScriptPlugin.cpp similarity index 54% rename from src/lse/Plugin.cpp rename to src/lse/ScriptPlugin.cpp index b7ce8d93..739ab141 100644 --- a/src/lse/Plugin.cpp +++ b/src/lse/ScriptPlugin.cpp @@ -1,17 +1,16 @@ -#include "lse/Plugin.h" - -#include "lse/Entry.h" #include "legacy/engine/EngineOwnData.h" #include "ll/api/mod/Manifest.h" #include "ll/api/mod/Mod.h" +#include "lse/Entry.h" +#include "lse/ScriptPlugin.h" namespace lse { -Plugin::Plugin(ll::mod::Manifest manifest) : ll::mod::Mod(std::move(manifest)) {} +ScriptPlugin::ScriptPlugin(ll::mod::Manifest manifest) : ll::mod::Mod(std::move(manifest)) {} -Plugin::~Plugin() { release(); } +ScriptPlugin::~ScriptPlugin() { release(); } -std::shared_ptr Plugin::current() { +std::shared_ptr ScriptPlugin::current() { return lse::LegacyScriptEngine::getInstance().getManager().getMod(getEngineOwnData()->pluginName); } } // namespace lse diff --git a/src/lse/Plugin.h b/src/lse/ScriptPlugin.h similarity index 84% rename from src/lse/Plugin.h rename to src/lse/ScriptPlugin.h index 9d0daf96..dc05b514 100644 --- a/src/lse/Plugin.h +++ b/src/lse/ScriptPlugin.h @@ -7,7 +7,7 @@ namespace lse { -class Plugin : public ll::mod::Mod { +class ScriptPlugin : public ll::mod::Mod { friend PluginManager; public: @@ -22,8 +22,8 @@ class Plugin : public ll::mod::Mod { std::unordered_map> registeredCommands; - explicit Plugin(ll::mod::Manifest manifest); - ~Plugin(); + explicit ScriptPlugin(ll::mod::Manifest manifest); + ~ScriptPlugin(); static std::shared_ptr current(); }; From fdb921a947c11c951df07d05ff84b4186346614b Mon Sep 17 00:00:00 2001 From: ShrBox Date: Mon, 19 Jan 2026 15:39:11 +0800 Subject: [PATCH 16/27] chore: solve some warn --- src/legacy/api/CommandAPI.cpp | 51 ++++++++++++++++------------------- 1 file changed, 23 insertions(+), 28 deletions(-) diff --git a/src/legacy/api/CommandAPI.cpp b/src/legacy/api/CommandAPI.cpp index dd96a3b7..f9d12d84 100644 --- a/src/legacy/api/CommandAPI.cpp +++ b/src/legacy/api/CommandAPI.cpp @@ -162,7 +162,7 @@ std::enable_if_t, T> parseEnum(Local const& value) { if (!tmp.has_value()) throw std::runtime_error("Unable to parse Enum value"); return tmp.value(); } else if (value.isNumber()) { - return (T)value.asNumber().toInt32(); + return static_cast(value.asNumber().toInt32()); } throw std::runtime_error("Unable to parse Enum value"); } @@ -198,7 +198,7 @@ Local McClass::runcmdEx(const Arguments& args) { auto command = ll::service::getMinecraft()->mCommands->compileCommand( args[0].asString().toString(), origin, - (CurrentCmdVersion)CommandVersion::CurrentVersion(), + static_cast(CommandVersion::CurrentVersion()), [&](std::string const& err) { outputStr.append(err).append("\n"); } ); Local resObj = Object::newObject(); @@ -238,13 +238,13 @@ Local McClass::newCommand(const Arguments& args) { auto desc = args[1].asString().toString(); CommandPermissionLevel permission = CommandPermissionLevel::Admin; - CommandFlag flag = {(CommandFlagValue)0x80}; + CommandFlag flag = {static_cast(0x80)}; std::string alias; if (args.size() > 2) { - permission = (CommandPermissionLevel)parseEnum(args[2]); + permission = static_cast(parseEnum(args[2])); if (args.size() > 3) { CHECK_ARG_TYPE(args[3], ValueKind::kNumber); - flag = {(CommandFlagValue)args[3].asNumber().toInt32()}; + flag = {static_cast(args[3].asNumber().toInt32())}; if (args.size() > 4) { CHECK_ARG_TYPE(args[4], ValueKind::kString); alias = args[4].asString().toString(); @@ -256,10 +256,8 @@ Local McClass::newCommand(const Arguments& args) { CommandPermissionLevel const& permission, CommandFlag const& flag, std::string const& alias) { - auto registry = ll::service::getCommandRegistry(); - if (registry) { - auto instance = registry->findCommand(name); - if (instance) { + if (auto registry = ll::service::getCommandRegistry()) { + if (registry->findCommand(name)) { lse::LegacyScriptEngine::getLogger().warn( "Runtime command {} already exists, changes will not beapplied except for setOverload!"_tr(name) ); @@ -308,7 +306,7 @@ Local CommandClass::setAlias(const Arguments& args) { std::string alias = args[0].asString().toString(); if (ll::getGamingStatus() == ll::GamingStatus::Starting) { ll::coro::keepThis([commandName(commandName), alias]() -> ll::coro::CoroTask<> { - ll::command::CommandRegistrar::getInstance(false).getOrCreateCommand(commandName).alias(alias); + CommandRegistrar::getInstance(false).getOrCreateCommand(commandName).alias(alias); co_return; }).launch(ll::thread::ServerThreadExecutor::getDefault()); return Boolean::newBoolean(true); @@ -351,7 +349,7 @@ Local CommandClass::setEnum(const Arguments& args) { void onExecute(CommandOrigin const& origin, CommandOutput& output, RuntimeCommand const& runtime) { std::string commandName = runtime.getCommandName(); - if (localShareData->commandCallbacks.find(commandName) == localShareData->commandCallbacks.end()) { + if (!localShareData->commandCallbacks.contains(commandName)) { lse::LegacyScriptEngine::getLogger().warn( "Command {} failed to execute, is the plugin unloaded?"_tr(commandName) ); @@ -365,10 +363,8 @@ void onExecute(CommandOrigin const& origin, CommandOutput& output, RuntimeComman auto* outp = new CommandOutputClass(std::make_shared(output), ori->get()); auto& registeredCommands = getEngineOwnData()->plugin->registeredCommands; - if (registeredCommands.find(commandName) == registeredCommands.end()) { - lse::LegacyScriptEngine::getLogger().warn( - "Could not find {} in registered commands."_tr(commandName) - ); + if (!registeredCommands.contains(commandName)) { + lse::LegacyScriptEngine::getLogger().warn("Could not find {} in registered commands."_tr(commandName)); return; } for (auto& info : registeredCommands[commandName]) { @@ -411,7 +407,7 @@ Local CommandClass::newParameter(const Arguments& args) { CHECK_ARG_TYPE(args[0], ValueKind::kString); try { auto name = args[0].asString().toString(); - ParamKind::Kind type = (ParamKind::Kind)parseEnum(args[1]); + ParamKind::Kind type = static_cast(parseEnum(args[1])); std::string enumName = ""; bool optional = false; std::string identifier = ""; @@ -421,7 +417,7 @@ Local CommandClass::newParameter(const Arguments& args) { if (args.size() > index && args[index].isString()) enumName = args[index++].asString().toString(); if (args.size() > index && args[index].isString()) identifier = args[index++].asString().toString(); if (args.size() > index && args[index].isNumber()) - option = (CommandParameterOption)args[index++].asNumber().toInt32(); + option = static_cast(args[index++].asNumber().toInt32()); if (index != args.size()) throw std::runtime_error("Error Argument in newParameter"); getEngineOwnData()->plugin->registeredCommands[commandName].push_back( @@ -440,7 +436,7 @@ Local CommandClass::mandatory(const Arguments& args) { CHECK_ARG_TYPE(args[0], ValueKind::kString); try { auto name = args[0].asString().toString(); - ParamKind::Kind type = (ParamKind::Kind)parseEnum(args[1]); + ParamKind::Kind type = static_cast(parseEnum(args[1])); std::string enumName = ""; std::string identifier = ""; size_t index = 2; @@ -448,7 +444,7 @@ Local CommandClass::mandatory(const Arguments& args) { if (args.size() > index && args[index].isString()) enumName = args[index++].asString().toString(); if (args.size() > index && args[index].isString()) identifier = args[index++].asString().toString(); if (args.size() > index && args[index].isNumber()) - option = (CommandParameterOption)args[index++].asNumber().toInt32(); + option = static_cast(args[index++].asNumber().toInt32()); if (index != args.size()) throw std::runtime_error("Error Argument in newParameter"); getEngineOwnData()->plugin->registeredCommands[commandName].push_back( @@ -467,7 +463,7 @@ Local CommandClass::optional(const Arguments& args) { CHECK_ARG_TYPE(args[0], ValueKind::kString); try { auto name = args[0].asString().toString(); - ParamKind::Kind type = (ParamKind::Kind)parseEnum(args[1]); + ParamKind::Kind type = static_cast(parseEnum(args[1])); std::string enumName = ""; std::string identifier = ""; size_t index = 2; @@ -475,7 +471,7 @@ Local CommandClass::optional(const Arguments& args) { if (args.size() > index && args[index].isString()) enumName = args[index++].asString().toString(); if (args.size() > index && args[index].isString()) identifier = args[index++].asString().toString(); if (args.size() > index && args[index].isNumber()) - option = (CommandParameterOption)args[index++].asNumber().toInt32(); + option = static_cast(args[index++].asNumber().toInt32()); if (index != args.size()) throw std::runtime_error("Error Argument in newParameter"); getEngineOwnData()->plugin->registeredCommands[commandName].push_back( @@ -517,7 +513,7 @@ Local CommandClass::addOverload(const Arguments& args) { ll::coro::keepThis( [paramNames, commandName(commandName), overloadFunc, e(EngineScope::currentEngine())]() -> ll::coro::CoroTask<> { - auto cmd = ll::command::CommandRegistrar::getInstance(false) + auto cmd = CommandRegistrar::getInstance(false) .getOrCreateCommand(commandName) .runtimeOverload(getEngineData(e)->plugin); for (auto& paramName : paramNames) { @@ -533,7 +529,7 @@ Local CommandClass::addOverload(const Arguments& args) { ll::coro::keepThis( [commandName(commandName), e(EngineScope::currentEngine())]() -> ll::coro::CoroTask<> { getEngineData(e)->plugin->registeredCommands[commandName].push_back({}); - auto cmd = ll::command::CommandRegistrar::getInstance(false) + auto cmd = CommandRegistrar::getInstance(false) .getOrCreateCommand(commandName) .runtimeOverload(getEngineData(e)->plugin); cmd.execute(onExecute); @@ -591,7 +587,7 @@ Local CommandClass::addOverload(const Arguments& args) { ll::coro::keepThis( [commandName(commandName), e(EngineScope::currentEngine())]() -> ll::coro::CoroTask<> { getEngineData(e)->plugin->registeredCommands[commandName].push_back({}); - auto cmd = ll::command::CommandRegistrar::getInstance(false) + auto cmd = CommandRegistrar::getInstance(false) .getOrCreateCommand(commandName) .runtimeOverload(getEngineData(e)->plugin); cmd.execute(onExecute); @@ -746,12 +742,11 @@ Local CommandClass::getSoftEnumValues(const Arguments& args) { CHECK_ARGS_COUNT(args, 1); CHECK_ARG_TYPE(args[0], ValueKind::kString); try { - auto name = args[0].asString().toString(); - auto registry = ll::service::getCommandRegistry(); - if (registry) { + auto name = args[0].asString().toString(); + if (auto registry = ll::service::getCommandRegistry()) { auto& lookup = registry->mSoftEnumLookup; auto& softEnums = registry->mSoftEnums; - if (lookup.find(name) != lookup.end()) { + if (lookup.contains(name)) { return getStringArray(softEnums[lookup[name]].mValues); } } From 0116081fba1c58203c4c3445f1f3627ea7b010fd Mon Sep 17 00:00:00 2001 From: ShrBox Date: Mon, 19 Jan 2026 16:28:10 +0800 Subject: [PATCH 17/27] refactor: replace int with CommandPermissionLevel for debugCommandLevel fix: fix NodeJs compilation chore: update CHANGELOG.md --- CHANGELOG.md | 6 +++++- src-client/lse/PluginManager.cpp | 11 +++++------ src/lse/Config.h | 6 ++++-- 3 files changed, 14 insertions(+), 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 52a9cb89..fbeeae93 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,10 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [0.17.0-rc.1] - 2026-01-19 + ### Changed - Supported LeviLamina 1.8.0-rc.2 - Added client support +- Replace int with CommandPermissionLevel for debugCommandLevel ## [0.16.7] - 2026-01-13 @@ -1111,7 +1114,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 [#332]: https://github.com/LiteLDev/LegacyScriptEngine/issues/332 [#339]: https://github.com/LiteLDev/LegacyScriptEngine/issues/339 -[Unreleased]: https://github.com/LiteLDev/LegacyScriptEngine/compare/v0.16.7...HEAD +[Unreleased]: https://github.com/LiteLDev/LegacyScriptEngine/compare/v0.17.0-rc.1...HEAD +[0.17.0-rc.1]: https://github.com/LiteLDev/LegacyScriptEngine/compare/v0.16.7...v0.17.0-rc.1 [0.16.7]: https://github.com/LiteLDev/LegacyScriptEngine/compare/v0.16.6...v0.16.7 [0.16.6]: https://github.com/LiteLDev/LegacyScriptEngine/compare/v0.16.5...v0.16.6 [0.16.5]: https://github.com/LiteLDev/LegacyScriptEngine/compare/v0.16.4...v0.16.5 diff --git a/src-client/lse/PluginManager.cpp b/src-client/lse/PluginManager.cpp index bb0a9c48..2dd9b818 100644 --- a/src-client/lse/PluginManager.cpp +++ b/src-client/lse/PluginManager.cpp @@ -71,6 +71,11 @@ ll::Expected<> PluginManager::load(ll::mod::Manifest manifest) { } ll::Expected<> PluginManager::enable(std::string_view name) { + auto plugin = std::static_pointer_cast(getMod(name)); + if (!plugin) { + return ll::makeStringError("Plugin {0} not found"_tr(name)); + } + auto manifest = plugin->getManifest(); #ifdef LSE_BACKEND_PYTHON auto& logger = lse::LegacyScriptEngine::getLogger(); std::filesystem::path dirPath = ll::mod::getModsRoot() / manifest.name; // Plugin path @@ -131,12 +136,6 @@ ll::Expected<> PluginManager::enable(std::string_view name) { } } #endif - auto plugin = std::static_pointer_cast(getMod(name)); - if (!plugin) { - return ll::makeStringError("Plugin {0} not found"_tr(name)); - } - auto manifest = plugin->getManifest(); - auto scriptEngine = EngineManager::newEngine(manifest.name); try { diff --git a/src/lse/Config.h b/src/lse/Config.h index 05f1c019..321798a7 100644 --- a/src/lse/Config.h +++ b/src/lse/Config.h @@ -2,16 +2,18 @@ #include +#include "mc/server/commands/CommandPermissionLevel.h" + namespace lse { struct Config { - int version = 2; + int version = 3; bool migratePlugins = true; #ifdef LSE_BACKEND_NODEJS // fix addons that build with node-gyp version < 11.1.0, default: true std::optional fixLegacyAddons{std::nullopt}; #endif - int debugCommandLevel = 4; + CommandPermissionLevel debugCommandLevel = CommandPermissionLevel::GameDirectors; }; } // namespace lse From d6dc4c7a8ff403144a573e23e10de30b0f89e6ac Mon Sep 17 00:00:00 2001 From: ShrBox Date: Mon, 19 Jan 2026 17:08:35 +0800 Subject: [PATCH 18/27] chore: update CHANGELOG.md & tooth.json --- CHANGELOG.md | 6 +++--- tooth.json | 14 +++++++------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index fbeeae93..8176e6c8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] -## [0.17.0-rc.1] - 2026-01-19 +## [0.17.0-rc.2] - 2026-01-19 ### Changed @@ -1114,8 +1114,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 [#332]: https://github.com/LiteLDev/LegacyScriptEngine/issues/332 [#339]: https://github.com/LiteLDev/LegacyScriptEngine/issues/339 -[Unreleased]: https://github.com/LiteLDev/LegacyScriptEngine/compare/v0.17.0-rc.1...HEAD -[0.17.0-rc.1]: https://github.com/LiteLDev/LegacyScriptEngine/compare/v0.16.7...v0.17.0-rc.1 +[Unreleased]: https://github.com/LiteLDev/LegacyScriptEngine/compare/v0.17.0-rc.2...HEAD +[0.17.0-rc.2]: https://github.com/LiteLDev/LegacyScriptEngine/compare/v0.16.7...v0.17.0-rc.2 [0.16.7]: https://github.com/LiteLDev/LegacyScriptEngine/compare/v0.16.6...v0.16.7 [0.16.6]: https://github.com/LiteLDev/LegacyScriptEngine/compare/v0.16.5...v0.16.6 [0.16.5]: https://github.com/LiteLDev/LegacyScriptEngine/compare/v0.16.4...v0.16.5 diff --git a/tooth.json b/tooth.json index cdf9eb75..dae8f7ef 100644 --- a/tooth.json +++ b/tooth.json @@ -2,7 +2,7 @@ "format_version": 3, "format_uuid": "289f771f-2c9a-4d73-9f3f-8492495a924d", "tooth": "github.com/LiteLDev/LegacyScriptEngine", - "version": "0.17.0-rc.1", + "version": "0.17.0-rc.2", "info": { "name": "LegacyScriptEngine", "description": "A plugin engine for running LLSE plugins on LeviLamina", @@ -25,8 +25,8 @@ "label": "client", "platform": "win-x64", "dependencies": { - "github.com/LiteLDev/LegacyScriptEngine#quickjs-client": "{{version}}", - "github.com/LiteLDev/LegacyScriptEngine#lua-client": "{{version}}" + "github.com/LiteLDev/LegacyScriptEngine#client_quickjs": "{{version}}", + "github.com/LiteLDev/LegacyScriptEngine#client_lua": "{{version}}" } }, { @@ -136,7 +136,7 @@ ] }, { - "label": "nodejs-client", + "label": "client_nodejs", "platform": "win-x64", "dependencies": { "github.com/LiteLDev/LegacyRemoteCall#client": "0.17.0-rc.1", @@ -173,7 +173,7 @@ ] }, { - "label": "quickjs-client", + "label": "client_quickjs", "platform": "win-x64", "dependencies": { "github.com/LiteLDev/LegacyRemoteCall#client": "0.17.0-rc.1", @@ -196,7 +196,7 @@ ] }, { - "label": "lua-client", + "label": "client_lua", "platform": "win-x64", "dependencies": { "github.com/LiteLDev/LegacyRemoteCall#client": "0.17.0-rc.1", @@ -219,7 +219,7 @@ ] }, { - "label": "python-client", + "label": "client_python", "platform": "win-x64", "dependencies": { "github.com/LiteLDev/LegacyRemoteCall#client": "0.17.0-rc.1", From d0a6a84cec8ad51790b9fa50c0691473b79001fd Mon Sep 17 00:00:00 2001 From: ShrBox Date: Mon, 19 Jan 2026 18:34:15 +0800 Subject: [PATCH 19/27] docs: add client installation guide --- README.md | 20 +------------------- README.zh.md | 19 +------------------ docs/index.md | 32 ++++++++++++++++++++++++++++---- docs/index.zh.md | 30 +++++++++++++++++++++++++++--- 4 files changed, 57 insertions(+), 44 deletions(-) diff --git a/README.md b/README.md index 57356854..4d89b82f 100644 --- a/README.md +++ b/README.md @@ -5,25 +5,7 @@ A plugin engine for running LLSE plugins on LeviLamina ## Installation -### Attention - -Before installing the Python engine, you need to -install [Python 3.12.10](https://www.python.org/downloads/release/python-31210/) first. -To install a specific engine, you can use the following command: -```shell -lip install github.com/LiteLDev/LegacyScriptEngine#lua -lip install github.com/LiteLDev/LegacyScriptEngine#quickjs -lip install github.com/LiteLDev/LegacyScriptEngine#nodejs -lip install github.com/LiteLDev/LegacyScriptEngine#python -``` -For version older than 0.10.0, you can use the following command: -```shell -lip install git.levimc.org/LiteLDev/legacy-script-engine-lua@version -lip install git.levimc.org/LiteLDev/legacy-script-engine-quickjs@version -lip install git.levimc.org/LiteLDev/legacy-script-engine-nodejs@version -lip install git.levimc.org/LiteLDev/legacy-script-engine-python@version -``` -Version numbers can be found in [releases](https://github.com/LiteLDev/LegacyScriptEngine/releases). +Please refer to https://lse.levimc.org/ ## Usage diff --git a/README.zh.md b/README.zh.md index 92d43f91..4eac42d0 100644 --- a/README.zh.md +++ b/README.zh.md @@ -5,24 +5,7 @@ ## 安装 -### 注意 - -在安装Python引擎之前,你需要先安装[Python 3.12.10](https://www.python.org/downloads/release/python-31210/) -要安装特定的引擎,您可以使用以下命令: -```shell -lip install github.com/LiteLDev/LegacyScriptEngine#lua -lip install github.com/LiteLDev/LegacyScriptEngine#quickjs -lip install github.com/LiteLDev/LegacyScriptEngine#nodejs -lip install github.com/LiteLDev/LegacyScriptEngine#python -``` -对于0.10.0之前的版本,可以使用以下命令: -```shell -lip install git.levimc.org/LiteLDev/legacy-script-engine-lua@版本 -lip install git.levimc.org/LiteLDev/legacy-script-engine-quickjs@版本 -lip install git.levimc.org/LiteLDev/legacy-script-engine-nodejs@版本 -lip install git.levimc.org/LiteLDev/legacy-script-engine-python@版本 -``` -可以在[releases](https://github.com/LiteLDev/LegacyScriptEngine/releases)中找到版本号。 +请参考 https://lse.levimc.org/zh/ ## 使用 diff --git a/docs/index.md b/docs/index.md index 0822ed76..85ae0a61 100644 --- a/docs/index.md +++ b/docs/index.md @@ -1,14 +1,20 @@ # LegacyScriptEngine -English | [简体中文](README.zh.md) A plugin engine for running LLSE plugins on LeviLamina ## Installation -### Attention +### Server + +!!! warning + Before installing the Python engine, you need to install Python first. Here is a list of LSE versions and their required Python versions. + +| LSE Version | Python Version | +|-----------------|----------------| +| >=0.16.2 | 3.12.10 | +| >=0.9.0 <0.16.2 | 3.12.8 | +| <0.9.0 | 3.10.11 | -Before installing the Python engine, you need to -install [Python 3.12.10](https://www.python.org/downloads/release/python-31210/) first. To install a specific engine, you can use the following command: ```shell lip install github.com/LiteLDev/LegacyScriptEngine#lua @@ -25,6 +31,24 @@ lip install git.levimc.org/LiteLDev/legacy-script-engine-python@version ``` Version numbers can be found in [releases](https://github.com/LiteLDev/LegacyScriptEngine/releases). +### Client + +To install a specific engine, you can use the following command: +```shell +lip install github.com/LiteLDev/LegacyScriptEngine#client_lua +lip install github.com/LiteLDev/LegacyScriptEngine#client_quickjs +lip install github.com/LiteLDev/LegacyScriptEngine#client_nodejs +lip install github.com/LiteLDev/LegacyScriptEngine#client_python +``` +To install a specific version, you can add`@version` at the end of installation command, such as: +```shell +lip install github.com/LiteLDev/LegacyScriptEngine#client_lua@0.17.0-rc.2 +lip install github.com/LiteLDev/LegacyScriptEngine#client_quickjs@0.17.0-rc.2 +lip install github.com/LiteLDev/LegacyScriptEngine#client_nodejs@0.17.0-rc.2 +lip install github.com/LiteLDev/LegacyScriptEngine#client_python@0.17.0-rc.2 +``` + + ## Usage To access plugin development API hints and scaffolding toolkits, visit the [legacy-script-engine-api](https://github.com/LiteLDev/legacy-script-engine-api) repository. diff --git a/docs/index.zh.md b/docs/index.zh.md index 75dee503..89f30678 100644 --- a/docs/index.zh.md +++ b/docs/index.zh.md @@ -1,13 +1,20 @@ # LegacyScriptEngine -[English](README.md) | 简体中文 一个用于在 LeviLamina 上运行 LLSE 插件的插件引擎 ## 安装 -### 注意 +!!! warning + 在安装Python引擎之前,你需要先安装Python。下面是一份LSE版本和需要的Python版本的列表。 + +| LSE 版本 | Python 版本 | +|-----------------|-----------| +| >=0.16.2 | 3.12.10 | +| >=0.9.0 <0.16.2 | 3.12.8 | +| <0.9.0 | 3.10.11 | + +### 服务端 -在安装Python引擎之前,你需要先安装[Python 3.12.10](https://www.python.org/downloads/release/python-31210/) 要安装特定的引擎,您可以使用以下命令: ```shell lip install github.com/LiteLDev/LegacyScriptEngine#lua @@ -24,6 +31,23 @@ lip install git.levimc.org/LiteLDev/legacy-script-engine-python@版本 ``` 可以在[releases](https://github.com/LiteLDev/LegacyScriptEngine/releases)中找到版本号。 +### 客户端 + +要安装特定的引擎,您可以使用以下命令: +```shell +lip install github.com/LiteLDev/LegacyScriptEngine#client_lua +lip install github.com/LiteLDev/LegacyScriptEngine#client_quickjs +lip install github.com/LiteLDev/LegacyScriptEngine#client_nodejs +lip install github.com/LiteLDev/LegacyScriptEngine#client_python +``` +要安装特定版本,需要在命令最后加上`@版本号`,例如: +```shell +lip install github.com/LiteLDev/LegacyScriptEngine#client_lua@0.17.0-rc.2 +lip install github.com/LiteLDev/LegacyScriptEngine#client_quickjs@0.17.0-rc.2 +lip install github.com/LiteLDev/LegacyScriptEngine#client_nodejs@0.17.0-rc.2 +lip install github.com/LiteLDev/LegacyScriptEngine#client_python@0.17.0-rc.2 +``` + ## 使用 如需获取插件开发 API 提示库和脚手架工具,请访问 [legacy-script-engine-api](https://github.com/LiteLDev/legacy-script-engine-api) 仓库 From e7a1e0de0a935cd10676ee2600380c2cb4ab9078 Mon Sep 17 00:00:00 2001 From: ShrBox Date: Mon, 19 Jan 2026 18:53:00 +0800 Subject: [PATCH 20/27] chore: update translations --- src/lang/de.json | 5 ++++- src/lang/en.json | 5 ++++- src/lang/fr.json | 5 ++++- src/lang/id.json | 5 ++++- src/lang/it.json | 5 ++++- src/lang/ja.json | 5 ++++- src/lang/ko.json | 5 ++++- src/lang/pt_BR.json | 5 ++++- src/lang/ru.json | 5 ++++- src/lang/th.json | 5 ++++- src/lang/tr.json | 5 ++++- src/lang/vi.json | 5 ++++- src/lang/zh_CN.json | 5 ++++- src/lang/zh_TW.json | 5 ++++- 14 files changed, 56 insertions(+), 14 deletions(-) diff --git a/src/lang/de.json b/src/lang/de.json index 60dac295..ad286afb 100644 --- a/src/lang/de.json +++ b/src/lang/de.json @@ -54,5 +54,8 @@ "Could not find {} in registered commands": { "": "Konnte {} in registrierten Befehlen nicht finden." }, - "Event {} not found!": "Event {} nicht gefunden!" + "Event {} not found!": "Event {} nicht gefunden!", + "Failed to enable plugin {0}: {1}\\n{2}": "Konnte Plugin {0}nicht aktivieren: {1}\\n{2}", + "Failed to enable plugin {0}: {1}": "Konnte Plugin {0}nicht aktivieren: {1}", + "Failed to disable plugin {0}: {1}": "Konnte Plugin {0}nicht deaktivieren: {1}" } diff --git a/src/lang/en.json b/src/lang/en.json index ec2992d2..86042a21 100644 --- a/src/lang/en.json +++ b/src/lang/en.json @@ -54,5 +54,8 @@ "Could not find {} in registered commands": { "": "Could not find {} in registered commands." }, - "Event {} not found!": "Event {} not found!" + "Event {} not found!": "Event {} not found!", + "Failed to enable plugin {0}: {1}\\n{2}": "Failed to enable plugin {0}: {1}\\n{2}", + "Failed to enable plugin {0}: {1}": "Failed to enable plugin {0}: {1}", + "Failed to disable plugin {0}: {1}": "Failed to disable plugin {0}: {1}" } diff --git a/src/lang/fr.json b/src/lang/fr.json index 9369f4ce..60f1e6b8 100644 --- a/src/lang/fr.json +++ b/src/lang/fr.json @@ -54,5 +54,8 @@ "Could not find {} in registered commands": { "": "Impossible de trouver {} dans les commandes enregistrées." }, - "Event {} not found!": "Événement {} introuvable !" + "Event {} not found!": "Événement {} introuvable !", + "Failed to enable plugin {0}: {1}\\n{2}": "Impossible d'activer le plugin {0}: {1}\\n{2}", + "Failed to enable plugin {0}: {1}": "Impossible d'activer le plugin {0}: {1}", + "Failed to disable plugin {0}: {1}": "Impossible de désactiver le plugin {0}: {1}" } diff --git a/src/lang/id.json b/src/lang/id.json index 749d7d98..f6c110a6 100644 --- a/src/lang/id.json +++ b/src/lang/id.json @@ -54,5 +54,8 @@ "Could not find {} in registered commands": { "": "Could not find {} in registered commands." }, - "Event {} not found!": "Event {} not found!" + "Event {} not found!": "Event {} not found!", + "Failed to enable plugin {0}: {1}\\n{2}": "Failed to enable plugin {0}: {1}\\n{2}", + "Failed to enable plugin {0}: {1}": "Failed to enable plugin {0}: {1}", + "Failed to disable plugin {0}: {1}": "Failed to disable plugin {0}: {1}" } diff --git a/src/lang/it.json b/src/lang/it.json index 16cc424e..193c9ead 100644 --- a/src/lang/it.json +++ b/src/lang/it.json @@ -54,5 +54,8 @@ "Could not find {} in registered commands": { "": "Impossibile trovare {} nei comandi registrati." }, - "Event {} not found!": "Evento {} non trovato!" + "Event {} not found!": "Evento {} non trovato!", + "Failed to enable plugin {0}: {1}\\n{2}": "Attivazione del plugin {0}non riuscita: {1}\\n{2}", + "Failed to enable plugin {0}: {1}": "Attivazione del plugin {0}non riuscita: {1}", + "Failed to disable plugin {0}: {1}": "Impossibile disabilitare il plugin {0}: {1}" } diff --git a/src/lang/ja.json b/src/lang/ja.json index 029796aa..b5dd7096 100644 --- a/src/lang/ja.json +++ b/src/lang/ja.json @@ -54,5 +54,8 @@ "Could not find {} in registered commands": { "": "登録されたコマンドで {} が見つかりませんでした。" }, - "Event {} not found!": "イベント {} が見つかりません!" + "Event {} not found!": "イベント {} が見つかりません!", + "Failed to enable plugin {0}: {1}\\n{2}": "プラグイン {0}の有効化に失敗しました: {1}\\n{2}", + "Failed to enable plugin {0}: {1}": "プラグイン {0}の有効化に失敗しました: {1}", + "Failed to disable plugin {0}: {1}": "プラグイン {0}の無効化に失敗しました: {1}" } diff --git a/src/lang/ko.json b/src/lang/ko.json index a4f541ba..8d7e58d3 100644 --- a/src/lang/ko.json +++ b/src/lang/ko.json @@ -54,5 +54,8 @@ "Could not find {} in registered commands": { "": "Could not find {} in registered commands." }, - "Event {} not found!": "Event {} not found!" + "Event {} not found!": "Event {} not found!", + "Failed to enable plugin {0}: {1}\\n{2}": "Failed to enable plugin {0}: {1}\\n{2}", + "Failed to enable plugin {0}: {1}": "Failed to enable plugin {0}: {1}", + "Failed to disable plugin {0}: {1}": "Failed to disable plugin {0}: {1}" } diff --git a/src/lang/pt_BR.json b/src/lang/pt_BR.json index 0a5216d7..ff9aff26 100644 --- a/src/lang/pt_BR.json +++ b/src/lang/pt_BR.json @@ -54,5 +54,8 @@ "Could not find {} in registered commands": { "": "Não foi possível encontrar {} nos comandos registrados." }, - "Event {} not found!": "Evento {} não encontrado!" + "Event {} not found!": "Evento {} não encontrado!", + "Failed to enable plugin {0}: {1}\\n{2}": "Falha ao ativar o plugin {0}: {1}\\n{2}", + "Failed to enable plugin {0}: {1}": "Falha ao ativar o plugin {0}: {1}", + "Failed to disable plugin {0}: {1}": "Falha ao desativar o plugin {0}: {1}" } diff --git a/src/lang/ru.json b/src/lang/ru.json index cf5fae16..02f7943f 100644 --- a/src/lang/ru.json +++ b/src/lang/ru.json @@ -54,5 +54,8 @@ "Could not find {} in registered commands": { "": "Не удалось найти {} в зарегистрированных командах." }, - "Event {} not found!": "Событие {} не найдено!" + "Event {} not found!": "Событие {} не найдено!", + "Failed to enable plugin {0}: {1}\\n{2}": "Не удалось включить плагин {0}: {1}\\n{2}", + "Failed to enable plugin {0}: {1}": "Не удалось включить плагин {0}: {1}", + "Failed to disable plugin {0}: {1}": "Не удалось отключить плагин {0}: {1}" } diff --git a/src/lang/th.json b/src/lang/th.json index a007ebf7..4b3df5b4 100644 --- a/src/lang/th.json +++ b/src/lang/th.json @@ -54,5 +54,8 @@ "Could not find {} in registered commands": { "": "Could not find {} in registered commands." }, - "Event {} not found!": "Event {} not found!" + "Event {} not found!": "Event {} not found!", + "Failed to enable plugin {0}: {1}\\n{2}": "Failed to enable plugin {0}: {1}\\n{2}", + "Failed to enable plugin {0}: {1}": "Failed to enable plugin {0}: {1}", + "Failed to disable plugin {0}: {1}": "Failed to disable plugin {0}: {1}" } diff --git a/src/lang/tr.json b/src/lang/tr.json index 7d056e34..728894be 100644 --- a/src/lang/tr.json +++ b/src/lang/tr.json @@ -54,5 +54,8 @@ "Could not find {} in registered commands": { "": "Could not find {} in registered commands." }, - "Event {} not found!": "Event {} not found!" + "Event {} not found!": "Event {} not found!", + "Failed to enable plugin {0}: {1}\\n{2}": "Failed to enable plugin {0}: {1}\\n{2}", + "Failed to enable plugin {0}: {1}": "Failed to enable plugin {0}: {1}", + "Failed to disable plugin {0}: {1}": "Failed to disable plugin {0}: {1}" } diff --git a/src/lang/vi.json b/src/lang/vi.json index dc922fc8..b0a2f62f 100644 --- a/src/lang/vi.json +++ b/src/lang/vi.json @@ -54,5 +54,8 @@ "Could not find {} in registered commands": { "": "Could not find {} in registered commands." }, - "Event {} not found!": "Event {} not found!" + "Event {} not found!": "Event {} not found!", + "Failed to enable plugin {0}: {1}\\n{2}": "Failed to enable plugin {0}: {1}\\n{2}", + "Failed to enable plugin {0}: {1}": "Failed to enable plugin {0}: {1}", + "Failed to disable plugin {0}: {1}": "Failed to disable plugin {0}: {1}" } diff --git a/src/lang/zh_CN.json b/src/lang/zh_CN.json index 28c599be..fdb834a3 100644 --- a/src/lang/zh_CN.json +++ b/src/lang/zh_CN.json @@ -54,5 +54,8 @@ "Could not find {} in registered commands": { "": "在已注册的命令中找不到 {} 。" }, - "Event {} not found!": "找不到事件 {} !" + "Event {} not found!": "找不到事件 {} !", + "Failed to enable plugin {0}: {1}\\n{2}": "启用插件 {0} 失败: {1}\\n{2}", + "Failed to enable plugin {0}: {1}": "启用插件 {0} 失败: {1}", + "Failed to disable plugin {0}: {1}": "禁用插件 {0} 失败: {1}" } diff --git a/src/lang/zh_TW.json b/src/lang/zh_TW.json index c18b5464..7e6715a0 100644 --- a/src/lang/zh_TW.json +++ b/src/lang/zh_TW.json @@ -54,5 +54,8 @@ "Could not find {} in registered commands": { "": "Could not find {} in registered commands." }, - "Event {} not found!": "Event {} not found!" + "Event {} not found!": "Event {} not found!", + "Failed to enable plugin {0}: {1}\\n{2}": "Failed to enable plugin {0}: {1}\\n{2}", + "Failed to enable plugin {0}: {1}": "Failed to enable plugin {0}: {1}", + "Failed to disable plugin {0}: {1}": "Failed to disable plugin {0}: {1}" } From 7b85aa1a0cdb106e44c0d9ac07556e17fd9e19a4 Mon Sep 17 00:00:00 2001 From: ShrBox Date: Mon, 19 Jan 2026 21:57:16 +0800 Subject: [PATCH 21/27] chore(ci): add sync_translation.yml --- .github/workflows/sync_translation.yml | 30 +++++++++++++++++++ ..._crowdin_files.py => sync_translations.py} | 0 2 files changed, 30 insertions(+) create mode 100644 .github/workflows/sync_translation.yml rename scripts/{download_crowdin_files.py => sync_translations.py} (100%) diff --git a/.github/workflows/sync_translation.yml b/.github/workflows/sync_translation.yml new file mode 100644 index 00000000..7c37842a --- /dev/null +++ b/.github/workflows/sync_translation.yml @@ -0,0 +1,30 @@ +on: + schedule: + - cron: 0 * * * * + workflow_dispatch: + +permissions: + contents: write + +jobs: + update: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - run: | + pip install crowdin-api-client + + - run: | + python scripts/sync_translations.py ${{secrets.CROWDIN_API}} + + - name: Configure git + run: | + git config user.name "github-actions[bot]" + git config user.email "github-actions[bot]@users.noreply.github.com" + + - name: Sync translations + run: | + git add . && \ + git commit -m "Sync translations from Crowdin" && \ + git push || echo "No changes to commit" diff --git a/scripts/download_crowdin_files.py b/scripts/sync_translations.py similarity index 100% rename from scripts/download_crowdin_files.py rename to scripts/sync_translations.py From 27fe32d55c62e7250f116e6356a969e203c1ee2b Mon Sep 17 00:00:00 2001 From: ShrBox Date: Mon, 19 Jan 2026 23:50:42 +0800 Subject: [PATCH 22/27] chore: update .gitignore --- .gitignore | 1 - 1 file changed, 1 deletion(-) diff --git a/.gitignore b/.gitignore index a66c74e9..6ca4a2b5 100644 --- a/.gitignore +++ b/.gitignore @@ -552,7 +552,6 @@ fabric.properties /.xmake/ /build/ /CMakeLists.txt -/cmake-build-*/ # Project specific ignores From 7b034b568d13be83b5dd2c76220d6ad74b521871 Mon Sep 17 00:00:00 2001 From: ShrBox Date: Tue, 20 Jan 2026 23:08:15 +0800 Subject: [PATCH 23/27] docs: add language auto switch docs: fix Chinese anchor --- docs/apis/DataAPI/DataBase.zh.md | 26 ++++----- docs/apis/GameAPI/Block.md | 2 +- docs/apis/GameAPI/Packet.md | 6 +- docs/apis/GameAPI/Packet.zh.md | 6 +- docs/apis/ScriptAPI/ScriptHelp.md | 2 +- docs/apis/ScriptAPI/ScriptHelp.zh.md | 2 +- docs/apis/SystemAPI/Network.zh.md | 4 +- docs/overrides/main.html | 83 ++++++++++++++++++++++++++++ mkdocs.yml | 6 +- 9 files changed, 112 insertions(+), 25 deletions(-) create mode 100644 docs/overrides/main.html diff --git a/docs/apis/DataAPI/DataBase.zh.md b/docs/apis/DataAPI/DataBase.zh.md index 66643749..1ea512b8 100644 --- a/docs/apis/DataAPI/DataBase.zh.md +++ b/docs/apis/DataAPI/DataBase.zh.md @@ -7,8 +7,8 @@ ### 📄 目录 -🔑 [KVDB 键值对数据库](#🔑-键---值对-nosql数据库) -📋 [SQL数据库](#📋-sql数据库) +🔑 [KVDB 键值对数据库](#-键---值对-nosql数据库) +📋 [SQL数据库](#-sql数据库) - 🔍 [预准备语句](#sql预准备语句) 附: 各SQL的官方文档 @@ -142,12 +142,12 @@ SQL数据库适用于使用SQL语句处理大量的关系型数据。接口底 #### 连接参数 -| 键 | 用途 | 可用数据库 | 示例 | 默认值 | -| --------- | ------------------------ | ---------- | ----------------- | ------- | -| path | 指定数据库所在路径 | `SQLite` | `plugins/test.db` | - | -| create | 数据库不存在是否自动创建 | `SQLite` | `true`/`false` | `true` | -| readonly | 以只读模式打开 | `SQLite` | `true`/`false` | `false` | -| readwrite | 以读写模式打开 | `SQLite` | `true`/`false` | `true` | +| 键 | 用途 | 可用数据库 | 示例 | 默认值 | +|-----------|--------------|----------|-------------------|---------| +| path | 指定数据库所在路径 | `SQLite` | `plugins/test.db` | - | +| create | 数据库不存在是否自动创建 | `SQLite` | `true`/`false` | `true` | +| readonly | 以只读模式打开 | `SQLite` | `true`/`false` | `false` | +| readwrite | 以读写模式打开 | `SQLite` | `true`/`false` | `true` | @@ -217,7 +217,7 @@ SQL数据库适用于使用SQL语句处理大量的关系型数据。接口底 > 预准备语句(Prepared Statement)是SQL的一个重要部分。它的实现原理是:先将含有未知参数的SQL语句(发往服务端)处理、编译,再绑定参数,最终执行并返回结果。各个SQL的预准备语句实现可能不同,其预准备语句的表示方法也可能存在差异,所以请务必仔细阅读文档(直接去阅读对应SQL的官方文档则更好)。 -预准备语句的主要作用是防止SQL注入攻击——一种很常见的、危险的攻击。如果在未经检验的情况下直接使用用户输入的数据(就像BDS一样 xD),就可能会造成免密码登录甚至数据丢失(注入执行`DROP TABLE`或`DROP DATABASE`)等严重后果。所以在处理用户输入的数据时,更推荐使用预准备语句。其次,它可以在(服务器)只编译一次语句的情况下,实现多次输入。 +> 预准备语句的主要作用是防止SQL注入攻击——一种很常见的、危险的攻击。如果在未经检验的情况下直接使用用户输入的数据(就像BDS一样 xD),就可能会造成免密码登录甚至数据丢失(注入执行`DROP TABLE`或`DROP DATABASE`)等严重后果。所以在处理用户输入的数据时,更推荐使用预准备语句。其次,它可以在(服务器)只编译一次语句的情况下,实现多次输入。 @@ -260,10 +260,10 @@ INSERT INTO table VALUES ($X, ?Y, :Z); #### 预准备语句对象 - 属性 -| 属性 | 含义 | 类型 | 另见 | -| ------------------- | ------------------------------------------------------------------------------------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------- | -| `stmt.affectedRows` | 获取该预准备语句执行后影响的行数(仅对`INSERT` `UPDATE` `DELETE` `REPLACE` 等语句生效) | `Integer` | [SQLite](https://www.sqlite.org/c3ref/changes.html) [MySQL](https://dev.mysql.com/doc/c-api/8.0/en/mysql-affected-rows.html) | -| `stmt.insertId` | 获取该`INSERT`/`UPDATE`/`REPLACE`语句执行后最后一个更改行的行号(关于行号的解释详见官方文档) | `Integer` | [SQLite](https://www.sqlite.org/c3ref/last_insert_rowid.html) [MySQL](https://dev.mysql.com/doc/c-api/8.0/en/mysql-stmt-insert-id.html) | +| 属性 | 含义 | 类型 | 另见 | +|---------------------|----------------------------------------------------------------|-----------|-----------------------------------------------------------------------------------------------------------------------------------------| +| `stmt.affectedRows` | 获取该预准备语句执行后影响的行数(仅对`INSERT` `UPDATE` `DELETE` `REPLACE` 等语句生效) | `Integer` | [SQLite](https://www.sqlite.org/c3ref/changes.html) [MySQL](https://dev.mysql.com/doc/c-api/8.0/en/mysql-affected-rows.html) | +| `stmt.insertId` | 获取该`INSERT`/`UPDATE`/`REPLACE`语句执行后最后一个更改行的行号(关于行号的解释详见官方文档) | `Integer` | [SQLite](https://www.sqlite.org/c3ref/last_insert_rowid.html) [MySQL](https://dev.mysql.com/doc/c-api/8.0/en/mysql-stmt-insert-id.html) | 这些对象属性都是只读的,无法被修改,并且只能在语句执行之后获取到 diff --git a/docs/apis/GameAPI/Block.md b/docs/apis/GameAPI/Block.md index 62050527..10ec7459 100644 --- a/docs/apis/GameAPI/Block.md +++ b/docs/apis/GameAPI/Block.md @@ -95,7 +95,7 @@ Each block object contains some member functions (member methods) that can be ex - Return value: Whether the write was successful or not. - Return value type: `Boolean` -For more usage of NBT objects, please refer to [NBT Interface Documentation](/NBT.md) +For more usage of NBT objects, please refer to [NBT Interface Documentation](../NbtAPI/NBT.md) Note: Use this api with caution, consider using mc.setBlock() instead. diff --git a/docs/apis/GameAPI/Packet.md b/docs/apis/GameAPI/Packet.md index 16401a49..fb9ab5a0 100644 --- a/docs/apis/GameAPI/Packet.md +++ b/docs/apis/GameAPI/Packet.md @@ -8,8 +8,8 @@ The documentation does not list the packet ID and its structure, please check it ## 目录 -- 🔉 [Packet Object API](#🔉-Packet-Object-api) -- 🔌 [Binary stream object API](#🔌-Binary-stream-object-api) +- 🔉 [Packet Object API](#-packet-object-api) +- 🔌 [Binary stream object API](#-binary-stream-object-api) @@ -22,7 +22,7 @@ In LLSE, 「Packet Object」 is used to get information about packets. #### Get from API Call some **return packet object** function to get to the packet object given by BDS -See [Binary Stream Objects](#🔌-binary-stream-object-api) for details +See [Binary Stream Objects](#-binary-stream-object-api) for details diff --git a/docs/apis/GameAPI/Packet.zh.md b/docs/apis/GameAPI/Packet.zh.md index b3f47618..dac8b728 100644 --- a/docs/apis/GameAPI/Packet.zh.md +++ b/docs/apis/GameAPI/Packet.zh.md @@ -8,8 +8,8 @@ ## 目录 -- 🔉 [数据包对象 API](#🔉-数据包对象-api) -- 🔌 [二进制流对象 API](#🔌-二进制流对象-api) +- 🔉 [数据包对象 API](#-数据包对象-api) +- 🔌 [二进制流对象 API](#-二进制流对象-api) @@ -22,7 +22,7 @@ #### 从API获取 调用某些**返回数据包对象**的函数,来获取到BDS给出的数据包对象 -详见 [二进制流对象](#🔌-二进制流对象-api) +详见 [二进制流对象](#-二进制流对象-api) diff --git a/docs/apis/ScriptAPI/ScriptHelp.md b/docs/apis/ScriptAPI/ScriptHelp.md index a93aed22..253fea33 100644 --- a/docs/apis/ScriptAPI/ScriptHelp.md +++ b/docs/apis/ScriptAPI/ScriptHelp.md @@ -34,7 +34,7 @@ This is an upgraded version of the above function; it supports color output. #### Show results: -![ColorLogExample](/img/ColorLog.png) +![ColorLogExample](../../img/ColorLog.png) ### Asynchronous Output diff --git a/docs/apis/ScriptAPI/ScriptHelp.zh.md b/docs/apis/ScriptAPI/ScriptHelp.zh.md index dd914fd9..57361936 100644 --- a/docs/apis/ScriptAPI/ScriptHelp.zh.md +++ b/docs/apis/ScriptAPI/ScriptHelp.zh.md @@ -33,7 +33,7 @@ #### 效果展示: -![ColorLogExample](/img/ColorLog.png) +![ColorLogExample](../../img/ColorLog.png) ### 异步输出 diff --git a/docs/apis/SystemAPI/Network.zh.md b/docs/apis/SystemAPI/Network.zh.md index 8696d880..9705b9b0 100644 --- a/docs/apis/SystemAPI/Network.zh.md +++ b/docs/apis/SystemAPI/Network.zh.md @@ -4,8 +4,8 @@ 如果有更复杂的需求,可以使用各自语言平台的网络库来完成任务 ## 目录 -- 🔌 [WebSocket 客户端对象 API](#🔌-websocket-客户端对象-api) -- 📡 [Http 服务端对象 API](#📡-http-服务端对象-api) +- 🔌 [WebSocket 客户端对象 API](#-websocket-客户端对象-api) +- 📡 [Http 服务端对象 API](#-http-服务端对象-api) - [Http 请求对象 API](#http-请求对象-api) - [Http 响应对象 API](#http-响应对象-api) diff --git a/docs/overrides/main.html b/docs/overrides/main.html new file mode 100644 index 00000000..6e87a6be --- /dev/null +++ b/docs/overrides/main.html @@ -0,0 +1,83 @@ +{% extends "base.html" %} + +{% block extrahead %} + +{% endblock %} diff --git a/mkdocs.yml b/mkdocs.yml index 92c755b8..55059496 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -62,6 +62,7 @@ nav: theme: name: material + custom_dir: docs/overrides features: - navigation.tabs - navigation.tabs.sticky @@ -88,7 +89,10 @@ markdown_extensions: - def_list - footnotes - md_in_html - - toc + - toc: + slugify: !!python/object/apply:pymdownx.slugs.slugify + kwds: + case: lower - tables - pymdownx.arithmatex - pymdownx.betterem From 13ba4727a5b760fefce0adc6a03ee045e10278bf Mon Sep 17 00:00:00 2001 From: ShrBox Date: Sun, 25 Jan 2026 16:51:21 +0800 Subject: [PATCH 24/27] feat: support LeviLamina 1.9.0 refactor: add mariadb-connector-c back to Node.js engine --- CHANGELOG.md | 9 + src/legacy/api/BlockAPI.cpp | 17 +- src/legacy/api/CommandAPI.cpp | 10 +- src/legacy/api/CommandOutputAPI.cpp | 2 +- src/legacy/api/EntityAPI.cpp | 162 ++++++++++----- src/legacy/api/EventAPI.cpp | 3 +- src/legacy/api/ItemAPI.cpp | 5 +- src/legacy/api/PlayerAPI.cpp | 266 ++++++++++++++++--------- src/legacy/api/ScoreboardAPI.cpp | 1 - src/legacy/api/SimulatedPlayerAPI.cpp | 18 +- src/legacy/legacyapi/db/Session.cpp | 8 - src/lse/api/helper/AttributeHelper.cpp | 57 +++--- src/lse/api/helper/AttributeHelper.h | 12 +- src/lse/api/helper/PlayerHelper.cpp | 28 ++- src/lse/events/BlockEvents.cpp | 101 +++++++--- src/lse/events/EntityEvents.cpp | 3 +- tooth.json | 34 ++-- xmake.lua | 29 ++- 18 files changed, 481 insertions(+), 284 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8176e6c8..ea01227a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- Added client support + +### Changed + +- Supported LeviLamina 1.9.0 +- Replace int with CommandPermissionLevel for debugCommandLevel + ## [0.17.0-rc.2] - 2026-01-19 ### Changed diff --git a/src/legacy/api/BlockAPI.cpp b/src/legacy/api/BlockAPI.cpp index f9b21434..8d54edc9 100644 --- a/src/legacy/api/BlockAPI.cpp +++ b/src/legacy/api/BlockAPI.cpp @@ -5,7 +5,6 @@ #include "api/BaseAPI.h" #include "api/BlockEntityAPI.h" #include "api/ContainerAPI.h" -#include "api/EntityAPI.h" #include "api/McAPI.h" #include "api/NbtAPI.h" #include "ll/api/service/Bedrock.h" @@ -299,7 +298,7 @@ Local BlockClass::destroyBlock(const Arguments& args) { ll::service::getLevel()->getDimension(blockPos.dim).lock()->getBlockSourceFromMainChunkSource(); return Boolean::newBoolean( ll::service::getLevel() - ->destroyBlock(bl, blockPos.getBlockPos(), args[0].asBoolean().value(), BlockChangeContext()) + ->destroyBlock(bl, blockPos.getBlockPos(), args[0].asBoolean().value(), BlockChangeContext(false)) ); } CATCH("Fail in destroyBlock!"); @@ -327,7 +326,7 @@ Local BlockClass::setNbt(const Arguments& args) { ->getDimension(blockPos.dim) .lock() ->getBlockSourceFromMainChunkSource() - .setBlock(blockPos.getBlockPos(), *bl, 3, nullptr, nullptr, BlockChangeContext()); + .setBlock(blockPos.getBlockPos(), *bl, 3, nullptr, nullptr, BlockChangeContext(false)); } preloadData(blockPos.getBlockPos(), blockPos.getDimensionId()); return Boolean::newBoolean(true); @@ -464,7 +463,11 @@ Local McClass::getBlock(const Arguments& args) { return {}; } auto& block = lc->getBlock( - ChunkBlockPos{(uchar)(pos.x & 0xf), ChunkLocalHeight{(short)pos.y - minHeight}, (uchar)(pos.z & 0xf)} + ChunkBlockPos{ + (uchar)(pos.x & 0xf), + ChunkLocalHeight{static_cast(pos.y - minHeight)}, + (uchar)(pos.z & 0xf) + } ); return BlockClass::newBlock(block, pos.getBlockPos(), pos.dim); } @@ -535,7 +538,7 @@ Local McClass::setBlock(const Arguments& args) { } BlockSource& bs = ll::service::getLevel()->getDimension(pos.dim).lock()->getBlockSourceFromMainChunkSource(); - return Boolean::newBoolean(bs.setBlock(pos.getBlockPos(), bl, 3, nullptr, nullptr, BlockChangeContext())); + return Boolean::newBoolean(bs.setBlock(pos.getBlockPos(), bl, 3, nullptr, nullptr, BlockChangeContext(false))); } else if (IsInstanceOf(block)) { // Nbt auto nbt = NbtCompoundClass::extract(block); @@ -545,7 +548,7 @@ Local McClass::setBlock(const Arguments& args) { } BlockSource& bs = ll::service::getLevel()->getDimension(pos.dim).lock()->getBlockSourceFromMainChunkSource(); - return Boolean::newBoolean(bs.setBlock(pos.getBlockPos(), bl, 3, nullptr, nullptr, BlockChangeContext())); + return Boolean::newBoolean(bs.setBlock(pos.getBlockPos(), bl, 3, nullptr, nullptr, BlockChangeContext(false))); } else { // other block object Block const* bl = BlockClass::extract(block); @@ -555,7 +558,7 @@ Local McClass::setBlock(const Arguments& args) { } BlockSource& bs = ll::service::getLevel()->getDimension(pos.dim).lock()->getBlockSourceFromMainChunkSource(); - return Boolean::newBoolean(bs.setBlock(pos.getBlockPos(), *bl, 3, nullptr, nullptr, BlockChangeContext())); + return Boolean::newBoolean(bs.setBlock(pos.getBlockPos(), *bl, 3, nullptr, nullptr, BlockChangeContext(false))); } } CATCH("Fail in SetBlock!") diff --git a/src/legacy/api/CommandAPI.cpp b/src/legacy/api/CommandAPI.cpp index f9d12d84..07b234ed 100644 --- a/src/legacy/api/CommandAPI.cpp +++ b/src/legacy/api/CommandAPI.cpp @@ -20,6 +20,7 @@ #include "ll/api/thread/ServerThreadExecutor.h" #include "magic_enum.hpp" #include "mc/_HeaderOutputPredefine.h" +#include "mc/common/SharedPtr.h" #include "mc/deps/core/utility/MCRESULT.h" #include "mc/deps/json/FastWriter.h" #include "mc/deps/json/Value.h" @@ -94,11 +95,10 @@ Local convertResult(ParamStorageType const& result, CommandOrigin const& -1 ); } else if (result.hold(ParamKind::Kind::Item)) { - return ItemClass::newItem( - std::make_unique(ll::service::getLevel()->getItemRegistry().getNameFromLegacyID( - std::get(result.value()).mId - )) - ); + if (auto itemPtr = + ll::service::getLevel()->getItemRegistry().getItem(std::get(result.value()).mId).lock()) { + return ItemClass::newItem(std::make_unique(*itemPtr)); + } } else if (result.hold(ParamKind::Kind::Actor)) { auto arr = Array::newArray(); for (auto i : std::get>(result.value()).results(origin)) { diff --git a/src/legacy/api/CommandOutputAPI.cpp b/src/legacy/api/CommandOutputAPI.cpp index 08e3a0e3..e6c010a1 100644 --- a/src/legacy/api/CommandOutputAPI.cpp +++ b/src/legacy/api/CommandOutputAPI.cpp @@ -39,7 +39,7 @@ Local CommandOutputClass::empty() { Local CommandOutputClass::getSuccessCount() { try { - return Number::newNumber(get()->mSuccessCount); + return Number::newNumber(static_cast(get()->mSuccessCount)); } CATCH("Fail in getSuccessCount!"); }; diff --git a/src/legacy/api/EntityAPI.cpp b/src/legacy/api/EntityAPI.cpp index 01b426e5..ddc6a831 100644 --- a/src/legacy/api/EntityAPI.cpp +++ b/src/legacy/api/EntityAPI.cpp @@ -12,11 +12,11 @@ #include "ll/api/service/Bedrock.h" #include "lse/api/MoreGlobal.h" #include "lse/api/helper/AttributeHelper.h" -#include "lse/api/helper/BlockHelper.h" #include "mc/deps/core/math/Vec2.h" #include "mc/deps/shared_types/legacy/actor/ActorDamageCause.h" #include "mc/deps/vanilla_components/ActorDataFlagComponent.h" #include "mc/deps/vanilla_components/StateVectorComponent.h" +#include "mc/entity/components/AttributesComponent.h" #include "mc/entity/components/InsideBlockComponent.h" #include "mc/entity/components/IsOnHotBlockFlagComponent.h" #include "mc/entity/components/TagsComponent.h" @@ -34,10 +34,9 @@ #include "mc/world/actor/Mob.h" #include "mc/world/actor/item/ItemActor.h" #include "mc/world/actor/player/Player.h" -#include "mc/world/actor/provider/ActorAttribute.h" #include "mc/world/actor/provider/ActorEquipment.h" #include "mc/world/actor/provider/SynchedActorDataAccess.h" -#include "mc/world/attribute/MutableAttributeWithContext.h" +#include "mc/world/attribute/Attribute.h" #include "mc/world/attribute/SharedAttributes.h" #include "mc/world/effect/EffectDuration.h" #include "mc/world/effect/MobEffectInstance.h" @@ -480,7 +479,7 @@ Local EntityClass::getHealth() { Actor* entity = get(); if (!entity) return Local(); - return Number::newNumber(ActorAttribute::getHealth(entity->getEntityContext())); + return Number::newNumber(entity->getHealth()); } CATCH("Fail in GetHealth!") } @@ -1017,9 +1016,16 @@ Local EntityClass::setHealth(const Arguments& args) { Actor* entity = get(); if (!entity) return Local(); - MutableAttributeWithContext attribute = entity->getMutableAttribute(SharedAttributes::HEALTH()); - AttributeHelper::setCurrentValue(attribute, args[0].asNumber().toFloat()); - return Boolean::newBoolean(true); + if (auto component = entity->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setCurrentValue( + component->mAttributes, + SharedAttributes::HEALTH(), + args[0].asNumber().toFloat() + ) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setHealth!"); } @@ -1032,10 +1038,16 @@ Local EntityClass::setAbsorption(const Arguments& args) { Actor* entity = get(); if (!entity) return Local(); - MutableAttributeWithContext attribute = entity->getMutableAttribute(SharedAttributes::ABSORPTION()); - AttributeHelper::setCurrentValue(attribute, args[0].asNumber().toFloat()); - - return Boolean::newBoolean(true); + if (auto component = entity->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setCurrentValue( + component->mAttributes, + SharedAttributes::ABSORPTION(), + args[0].asNumber().toFloat() + ) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setAbsorptionAttribute!"); } @@ -1048,10 +1060,16 @@ Local EntityClass::setAttackDamage(const Arguments& args) { Actor* entity = get(); if (!entity) return Local(); - MutableAttributeWithContext attribute = entity->getMutableAttribute(SharedAttributes::ATTACK_DAMAGE()); - AttributeHelper::setCurrentValue(attribute, args[0].asNumber().toFloat()); - - return Boolean::newBoolean(true); + if (auto component = entity->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setCurrentValue( + component->mAttributes, + SharedAttributes::ATTACK_DAMAGE(), + args[0].asNumber().toFloat() + ) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setAttackDamage!"); } @@ -1064,10 +1082,16 @@ Local EntityClass::setMaxAttackDamage(const Arguments& args) { Actor* entity = get(); if (!entity) return Local(); - MutableAttributeWithContext attribute = entity->getMutableAttribute(SharedAttributes::ATTACK_DAMAGE()); - AttributeHelper::setCurrentValue(attribute, args[0].asNumber().toFloat()); - - return Boolean::newBoolean(true); + if (auto component = entity->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setMaxValue( + component->mAttributes, + SharedAttributes::ATTACK_DAMAGE(), + args[0].asNumber().toFloat() + ) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setMaxAttackDamage!"); } @@ -1080,10 +1104,16 @@ Local EntityClass::setFollowRange(const Arguments& args) { Actor* entity = get(); if (!entity) return Local(); - MutableAttributeWithContext attribute = entity->getMutableAttribute(SharedAttributes::FOLLOW_RANGE()); - AttributeHelper::setCurrentValue(attribute, args[0].asNumber().toFloat()); - - return Boolean::newBoolean(true); + if (auto component = entity->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setCurrentValue( + component->mAttributes, + SharedAttributes::FOLLOW_RANGE(), + args[0].asNumber().toFloat() + ) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setFollowRange!"); } @@ -1096,10 +1126,16 @@ Local EntityClass::setKnockbackResistance(const Arguments& args) { Actor* entity = get(); if (!entity) return Local(); - MutableAttributeWithContext attribute = entity->getMutableAttribute(SharedAttributes::KNOCKBACK_RESISTANCE()); - AttributeHelper::setCurrentValue(attribute, args[0].asNumber().toFloat()); - - return Boolean::newBoolean(true); + if (auto component = entity->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setCurrentValue( + component->mAttributes, + SharedAttributes::KNOCKBACK_RESISTANCE(), + args[0].asNumber().toFloat() + ) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setKnockbackResistance!"); } @@ -1112,10 +1148,16 @@ Local EntityClass::setLuck(const Arguments& args) { Actor* entity = get(); if (!entity) return Local(); - MutableAttributeWithContext attribute = entity->getMutableAttribute(SharedAttributes::LUCK()); - AttributeHelper::setCurrentValue(attribute, args[0].asNumber().toFloat()); - - return Boolean::newBoolean(true); + if (auto component = entity->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setCurrentValue( + component->mAttributes, + SharedAttributes::LUCK(), + args[0].asNumber().toFloat() + ) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setLuck!"); } @@ -1128,9 +1170,15 @@ Local EntityClass::setMovementSpeed(const Arguments& args) { Actor* entity = get(); if (!entity) return Local(); - MutableAttributeWithContext attribute = entity->getMutableAttribute(SharedAttributes::MOVEMENT_SPEED()); - AttributeHelper::setCurrentValue(attribute, args[0].asNumber().toFloat()); - + if (auto component = entity->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setCurrentValue( + component->mAttributes, + SharedAttributes::MOVEMENT_SPEED(), + args[0].asNumber().toFloat() + ) + ); + } return Boolean::newBoolean(false); } CATCH("Fail in setMovementSpeed!"); @@ -1144,11 +1192,16 @@ Local EntityClass::setUnderwaterMovementSpeed(const Arguments& args) { Actor* entity = get(); if (!entity) return Local(); - MutableAttributeWithContext attribute = - entity->getMutableAttribute(SharedAttributes::UNDERWATER_MOVEMENT_SPEED()); - AttributeHelper::setCurrentValue(attribute, args[0].asNumber().toFloat()); - - return Boolean::newBoolean(true); + if (auto component = entity->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setCurrentValue( + component->mAttributes, + SharedAttributes::UNDERWATER_MOVEMENT_SPEED(), + args[0].asNumber().toFloat() + ) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setUnderwaterMovementSpeed!"); } @@ -1161,10 +1214,16 @@ Local EntityClass::setLavaMovementSpeed(const Arguments& args) { Actor* entity = get(); if (!entity) return Local(); - MutableAttributeWithContext attribute = entity->getMutableAttribute(SharedAttributes::LAVA_MOVEMENT_SPEED()); - AttributeHelper::setCurrentValue(attribute, args[0].asNumber().toFloat()); - - return Boolean::newBoolean(true); + if (auto component = entity->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setCurrentValue( + component->mAttributes, + SharedAttributes::LAVA_MOVEMENT_SPEED(), + args[0].asNumber().toFloat() + ) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setLavaMovementSpeed!"); } @@ -1177,10 +1236,16 @@ Local EntityClass::setMaxHealth(const Arguments& args) { Actor* entity = get(); if (!entity) return Local(); - MutableAttributeWithContext attribute = entity->getMutableAttribute(SharedAttributes::HEALTH()); - AttributeHelper::setMaxValue(attribute, args[0].asNumber().toFloat()); - - return Boolean::newBoolean(true); + if (auto component = entity->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setMaxValue( + component->mAttributes, + SharedAttributes::HEALTH(), + args[0].asNumber().toFloat() + ) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setMaxHealth!"); } @@ -1403,8 +1468,7 @@ Local EntityClass::getBlockFromViewVector(const Arguments& args) { } Block const& bl = actor->getDimensionBlockSource().getBlock(bp); BlockType const& legacy = bl.getBlockType(); - if (bl.isAir() - || (legacy.mProperties == BlockProperty::None && legacy.mMaterial.mType == MaterialType::Any)) { + if (bl.isAir() || (legacy.mProperties == BlockProperty::None && legacy.mMaterial.mType == MaterialType::Any)) { return Local(); } return BlockClass::newBlock(bl, bp, actor->getDimensionId()); diff --git a/src/legacy/api/EventAPI.cpp b/src/legacy/api/EventAPI.cpp index 7f74678c..e9e9a926 100644 --- a/src/legacy/api/EventAPI.cpp +++ b/src/legacy/api/EventAPI.cpp @@ -50,6 +50,7 @@ #include "mc/server/commands/CommandOriginType.h" #include "mc/world/actor/player/Player.h" #include "mc/world/attribute/AttributeInstance.h" +#include "mc/world/attribute/AttributeInstanceConstRef.h" #include "mc/world/item/Item.h" #include "mc/world/item/VanillaItemNames.h" #include "mc/world/level/dimension/Dimension.h" @@ -522,7 +523,7 @@ void EnableEventListener(int eventId) { if (ev.item().getItem()->isFood() || ev.item().isPotionItem() || ev.item().getTypeName() == VanillaItemNames::MilkBucket().getString()) { auto attribute = ev.self().getAttribute(Player::HUNGER()); - if (attribute.mCurrentMaxValue > attribute.mCurrentValue) { + if (attribute.mPtr->mCurrentMaxValue > attribute.mPtr->mCurrentValue) { if (!CallEvent( EVENT_TYPES::onEat, PlayerClass::newPlayer(&ev.self()), diff --git a/src/legacy/api/ItemAPI.cpp b/src/legacy/api/ItemAPI.cpp index 8a328895..0f52976e 100644 --- a/src/legacy/api/ItemAPI.cpp +++ b/src/legacy/api/ItemAPI.cpp @@ -7,6 +7,7 @@ #include "api/NbtAPI.h" #include "ll/api/service/Bedrock.h" #include "lse/api/helper/ItemHelper.h" +#include "mc/common/SharedPtr.h" #include "mc/safety/RedactableString.h" #include "mc/world/actor/item/ItemActor.h" #include "mc/world/item/Item.h" @@ -469,7 +470,9 @@ Local McClass::newItem(const Arguments& args) { std::string type = args[0].asString().toString(); int cnt = args[1].asNumber().toInt32(); - return ItemClass::newItem(std::make_unique(type, cnt, 0, nullptr)); + if (auto itemPtr = ll::service::getLevel()->getItemRegistry().getItem(HashedString(type)).lock()) { + return ItemClass::newItem(std::make_unique(*itemPtr)); + } } else { LOG_TOO_FEW_ARGS(__FUNCTION__); return Local(); diff --git a/src/legacy/api/PlayerAPI.cpp b/src/legacy/api/PlayerAPI.cpp index 8e0d1829..56f4c68b 100644 --- a/src/legacy/api/PlayerAPI.cpp +++ b/src/legacy/api/PlayerAPI.cpp @@ -22,20 +22,18 @@ #include "ll/api/service/Bedrock.h" #include "ll/api/service/GamingStatus.h" #include "ll/api/service/PlayerInfo.h" -#include "ll/api/service/ServerInfo.h" #include "ll/api/thread/ServerThreadExecutor.h" #include "lse/api/MoreGlobal.h" #include "lse/api/NetworkPacket.h" #include "lse/api/helper/AttributeHelper.h" -#include "lse/api/helper/BlockHelper.h" #include "lse/api/helper/PlayerHelper.h" #include "lse/api/helper/ScoreboardHelper.h" #include "main/EconomicSystem.h" #include "main/SafeGuardRecord.h" -#include "mc/certificates/WebToken.h" #include "mc/deps/core/math/Vec2.h" #include "mc/deps/core/utility/MCRESULT.h" #include "mc/entity/components/ActorRotationComponent.h" +#include "mc/entity/components/AttributesComponent.h" #include "mc/entity/components/InsideBlockComponent.h" #include "mc/entity/components/IsOnHotBlockFlagComponent.h" #include "mc/entity/components/TagsComponent.h" @@ -47,7 +45,6 @@ #include "mc/network/ConnectionRequest.h" #include "mc/network/MinecraftPacketIds.h" #include "mc/network/MinecraftPackets.h" -#include "mc/network/NetEventCallback.h" #include "mc/network/ServerNetworkHandler.h" #include "mc/network/packet/BossEventPacket.h" #include "mc/network/packet/ClientboundCloseFormPacket.h" @@ -83,10 +80,10 @@ #include "mc/world/actor/player/PermissionsHandler.h" #include "mc/world/actor/player/Player.h" #include "mc/world/actor/player/PlayerInventory.h" -#include "mc/world/actor/provider/ActorAttribute.h" #include "mc/world/actor/provider/ActorEquipment.h" #include "mc/world/actor/provider/SynchedActorDataAccess.h" -#include "mc/world/attribute/AttributeInstance.h" +#include "mc/world/attribute/Attribute.h" +#include "mc/world/attribute/AttributeInstanceConstRef.h" #include "mc/world/attribute/SharedAttributes.h" #include "mc/world/effect/EffectDuration.h" #include "mc/world/effect/MobEffectInstance.h" @@ -102,7 +99,6 @@ #include "mc/world/phys/HitResult.h" #include "mc/world/scores/IdentityDefinition.h" #include "mc/world/scores/Objective.h" -#include "mc/world/scores/ObjectiveCriteria.h" #include "mc/world/scores/PlayerScoreSetFunction.h" #include "mc/world/scores/PlayerScoreboardId.h" #include "mc/world/scores/ScoreInfo.h" @@ -110,6 +106,9 @@ #include "mc/world/scores/ScoreboardId.h" #include "mc/world/scores/ScoreboardOperationResult.h" +#include +#include + SetScorePacket::SetScorePacket() = default; //////////////////// Class Definition //////////////////// @@ -747,9 +746,8 @@ Local McClass::broadcast(const Arguments& args) { int newType = args[1].asNumber().toInt32(); if (newType >= 0 && newType <= 11) type = (TextPacketType)newType; } - TextPacket pkt = TextPacket(); - pkt.mType = type; - pkt.mMessage = args[0].asString().toString(); + TextPacket pkt; + pkt.mBody = TextPacket::MessageOnly(type, args[0].asString().toString()); pkt.sendToClients(); return Boolean::newBoolean(true); } @@ -1040,7 +1038,7 @@ Local PlayerClass::getHealth() { Player* player = get(); if (!player) return Local(); - return Number::newNumber(ActorAttribute::getHealth(player->getEntityContext())); + return Number::newNumber(player->getHealth()); } CATCH("Fail in GetHealth!") } @@ -1224,7 +1222,7 @@ Local PlayerClass::isHurt() { return Local(); } - int health = ActorAttribute::getHealth(player->getEntityContext()); + int health = player->getHealth(); if (health > 0 && health < player->getMaxHealth()) { return Boolean::newBoolean(true); } @@ -1266,8 +1264,10 @@ Local PlayerClass::isHungry() { return Local(); } - auto attribute = player->getAttribute(Player::HUNGER()); - return Boolean::newBoolean(attribute.mCurrentMaxValue > attribute.mCurrentValue); + if (auto attribute = player->getAttribute(Player::HUNGER()).mPtr) { + return Boolean::newBoolean(attribute->mCurrentMaxValue > attribute->mCurrentValue); + } + return Boolean::newBoolean(false); } CATCH("Fail in isHungry!") } @@ -1592,7 +1592,7 @@ Local PlayerClass::runcmd(const Arguments& args) { if (!player) return Local(); CommandContext context = CommandContext( args[0].asString().toString(), - std::make_unique(*get()), + std::make_unique(ll::service::getLevel(), player->getOrCreateUniqueID()), CommandVersion::CurrentVersion() ); ll::service::getMinecraft()->mCommands->executeCommand(context, false); @@ -1632,8 +1632,7 @@ Local PlayerClass::tell(const Arguments& args) { } TextPacket pkt = TextPacket(); - pkt.mType = type; - pkt.mMessage.assign(args[0].asString().toString()); + pkt.mBody = TextPacket::MessageOnly(type, args[0].asString().toString()); player->sendNetworkPacket(pkt); return Boolean::newBoolean(true); } @@ -1715,8 +1714,10 @@ Local PlayerClass::talkTo(const Arguments& args) { Player* player = get(); if (!player) return Local(); - TextPacket pkt = - TextPacket::createWhisper(player->getRealName(), args[0].asString().toString(), {}, player->getXuid(), {}); + TextPacket pkt; + pkt.mXuid = player->getXuid(); + pkt.mBody = + TextPacket::AuthorAndMessage(TextPacketType::Whisper, player->getRealName(), args[0].asString().toString()); target->sendNetworkPacket(pkt); return Boolean::newBoolean(true); } @@ -1894,7 +1895,7 @@ Local PlayerClass::getLevel(const Arguments&) { Player* player = get(); if (!player) return Local(); - return Number::newNumber(player->getAttribute(Player::LEVEL()).mCurrentValue); + return Number::newNumber(player->getAttribute(Player::LEVEL()).mPtr->mCurrentValue); } CATCH("Fail in getLevel!") } @@ -1907,7 +1908,9 @@ Local PlayerClass::setLevel(const Arguments& args) { Player* player = get(); if (!player) return Local(); - player->addLevels(args[0].asNumber().toInt32() - (int)player->getAttribute(Player::LEVEL()).mCurrentValue); + player->addLevels( + args[0].asNumber().toInt32() - (int)player->getAttribute(Player::LEVEL()).mPtr->mCurrentValue + ); return Boolean::newBoolean(true); } CATCH("Fail in setLevel!"); @@ -1962,30 +1965,39 @@ Local PlayerClass::reduceExperience(const Arguments& args) { return Local(); } - float exp = args[0].asNumber().toFloat(); - auto attribute = player->getMutableAttribute(Player::EXPERIENCE()); - auto instance = attribute.mInstance; - if (!instance) { - return Boolean::newBoolean(false); - } - int neededExp = player->getXpNeededForNextLevel(); - int currentExp = static_cast(instance->mCurrentValue * neededExp); - if (exp <= currentExp) { - AttributeHelper::setCurrentValue(attribute, static_cast(currentExp - exp) / neededExp); - return Boolean::newBoolean(true); - } - AttributeHelper::setCurrentValue(attribute, 0.0f); - size_t needExp = exp - currentExp; - int level = player->getAttribute(Player::LEVEL()).mCurrentValue; - while (level > 0) { - player->addLevels(-1); - int levelXp = player->getXpNeededForNextLevel(); - if (needExp < levelXp) { - AttributeHelper::setCurrentValue(attribute, static_cast(levelXp - needExp) / levelXp); + float exp = args[0].asNumber().toFloat(); + if (auto component = player->getEntityContext().tryGetComponent()) { + auto instance = component->mAttributes->getMutableInstance(Player::EXPERIENCE().mIDValue).mPtr; + if (!instance) { + return Boolean::newBoolean(false); + } + int neededExp = player->getXpNeededForNextLevel(); + int currentExp = static_cast(instance->mCurrentValue * neededExp); + if (exp <= currentExp) { + AttributeHelper::setCurrentValue( + component->mAttributes, + Player::EXPERIENCE(), + static_cast(currentExp - exp) / neededExp + ); return Boolean::newBoolean(true); } - needExp -= levelXp; - level = player->getAttribute(Player::LEVEL()).mCurrentValue; + AttributeHelper::setCurrentValue(component->mAttributes, Player::EXPERIENCE(), 0.0f); + size_t needExp = exp - currentExp; + int level = player->getAttribute(Player::LEVEL()).mPtr->mCurrentValue; + while (level > 0) { + player->addLevels(-1); + int levelXp = player->getXpNeededForNextLevel(); + if (needExp < levelXp) { + AttributeHelper::setCurrentValue( + component->mAttributes, + Player::EXPERIENCE(), + static_cast(levelXp - needExp) / levelXp + ); + return Boolean::newBoolean(true); + } + needExp -= levelXp; + level = player->getAttribute(Player::LEVEL()).mPtr->mCurrentValue; + } } return Boolean::newBoolean(false); } @@ -2028,7 +2040,7 @@ Local PlayerClass::getTotalExperience(const Arguments&) { } int startLevel = 0; - int endLevel = (int)player->getAttribute(Player::LEVEL()).mCurrentValue; + int endLevel = (int)player->getAttribute(Player::LEVEL()).mPtr->mCurrentValue; unsigned int totalXp = 0; for (int level = startLevel; level < endLevel; ++level) { @@ -2585,9 +2597,7 @@ Local PlayerClass::sendCustomForm(const Arguments& args) { return Number::newNumber(3); } catch (const ordered_json::exception& e) { - lse::LegacyScriptEngine::getLogger().error( - "Fail to parse Json string in sendCustomForm!" - ); + lse::LegacyScriptEngine::getLogger().error("Fail to parse Json string in sendCustomForm!"); ll::error_utils::printException(e, lse::LegacyScriptEngine::getLogger()); return {}; } @@ -2750,10 +2760,16 @@ Local PlayerClass::setHealth(const Arguments& args) { Player* player = get(); if (!player) return Local(); - auto attribute = player->getMutableAttribute(SharedAttributes::HEALTH()); - AttributeHelper::setCurrentValue(attribute, args[0].asNumber().toFloat()); - - return Boolean::newBoolean(true); + if (auto component = player->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setCurrentValue( + component->mAttributes, + SharedAttributes::HEALTH(), + args[0].asNumber().toFloat() + ) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setHealth!"); } @@ -2766,10 +2782,16 @@ Local PlayerClass::setMaxHealth(const Arguments& args) { Player* player = get(); if (!player) return Local(); - auto attribute = player->getMutableAttribute(SharedAttributes::HEALTH()); - AttributeHelper::setMaxValue(attribute, args[0].asNumber().toFloat()); - - return Boolean::newBoolean(true); + if (auto component = player->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setMaxValue( + component->mAttributes, + SharedAttributes::HEALTH(), + args[0].asNumber().toFloat() + ) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setMaxHealth!"); } @@ -2782,10 +2804,16 @@ Local PlayerClass::setAbsorption(const Arguments& args) { Player* player = get(); if (!player) return Local(); - auto attribute = player->getMutableAttribute(SharedAttributes::ABSORPTION()); - AttributeHelper::setCurrentValue(attribute, args[0].asNumber().toFloat()); - - return Boolean::newBoolean(true); + if (auto component = player->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setCurrentValue( + component->mAttributes, + SharedAttributes::ABSORPTION(), + args[0].asNumber().toFloat() + ) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setAbsorptionAttribute!"); } @@ -2798,10 +2826,16 @@ Local PlayerClass::setAttackDamage(const Arguments& args) { Player* player = get(); if (!player) return Local(); - auto attribute = player->getMutableAttribute(SharedAttributes::ATTACK_DAMAGE()); - AttributeHelper::setCurrentValue(attribute, args[0].asNumber().toFloat()); - - return Boolean::newBoolean(true); + if (auto component = player->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setCurrentValue( + component->mAttributes, + SharedAttributes::ATTACK_DAMAGE(), + args[0].asNumber().toFloat() + ) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setAttackDamage!"); } @@ -2814,10 +2848,16 @@ Local PlayerClass::setMaxAttackDamage(const Arguments& args) { Player* player = get(); if (!player) return Local(); - auto attribute = player->getMutableAttribute(SharedAttributes::ATTACK_DAMAGE()); - AttributeHelper::setMaxValue(attribute, args[0].asNumber().toFloat()); - - return Boolean::newBoolean(true); + if (auto component = player->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setMaxValue( + component->mAttributes, + SharedAttributes::ATTACK_DAMAGE(), + args[0].asNumber().toFloat() + ) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setMaxAttackDamage!"); } @@ -2830,10 +2870,16 @@ Local PlayerClass::setFollowRange(const Arguments& args) { Player* player = get(); if (!player) return Local(); - auto attribute = player->getMutableAttribute(SharedAttributes::FOLLOW_RANGE()); - AttributeHelper::setCurrentValue(attribute, args[0].asNumber().toFloat()); - - return Boolean::newBoolean(true); + if (auto component = player->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setCurrentValue( + component->mAttributes, + SharedAttributes::FOLLOW_RANGE(), + args[0].asNumber().toFloat() + ) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setFollowRange!"); } @@ -2846,10 +2892,16 @@ Local PlayerClass::setKnockbackResistance(const Arguments& args) { Player* player = get(); if (!player) return Local(); - auto attribute = player->getMutableAttribute(SharedAttributes::KNOCKBACK_RESISTANCE()); - AttributeHelper::setCurrentValue(attribute, args[0].asNumber().toFloat()); - - return Boolean::newBoolean(true); + if (auto component = player->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setCurrentValue( + component->mAttributes, + SharedAttributes::KNOCKBACK_RESISTANCE(), + args[0].asNumber().toFloat() + ) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setKnockbackResistance!"); } @@ -2862,10 +2914,16 @@ Local PlayerClass::setLuck(const Arguments& args) { Player* player = get(); if (!player) return Local(); - auto attribute = player->getMutableAttribute(SharedAttributes::LUCK()); - AttributeHelper::setCurrentValue(attribute, args[0].asNumber().toFloat()); - - return Boolean::newBoolean(true); + if (auto component = player->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setCurrentValue( + component->mAttributes, + SharedAttributes::LUCK(), + args[0].asNumber().toFloat() + ) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setLuck!"); } @@ -2878,9 +2936,15 @@ Local PlayerClass::setMovementSpeed(const Arguments& args) { Player* player = get(); if (!player) return Local(); - auto attribute = player->getMutableAttribute(SharedAttributes::MOVEMENT_SPEED()); - AttributeHelper::setCurrentValue(attribute, args[0].asNumber().toFloat()); - + if (auto component = player->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setCurrentValue( + component->mAttributes, + SharedAttributes::MOVEMENT_SPEED(), + args[0].asNumber().toFloat() + ) + ); + } return Boolean::newBoolean(false); } CATCH("Fail in setMovementSpeed!"); @@ -2894,10 +2958,16 @@ Local PlayerClass::setUnderwaterMovementSpeed(const Arguments& args) { Player* player = get(); if (!player) return Local(); - auto attribute = player->getMutableAttribute(SharedAttributes::UNDERWATER_MOVEMENT_SPEED()); - AttributeHelper::setCurrentValue(attribute, args[0].asNumber().toFloat()); - - return Boolean::newBoolean(true); + if (auto component = player->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setCurrentValue( + component->mAttributes, + SharedAttributes::UNDERWATER_MOVEMENT_SPEED(), + args[0].asNumber().toFloat() + ) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setUnderwaterMovementSpeed!"); } @@ -2910,10 +2980,16 @@ Local PlayerClass::setLavaMovementSpeed(const Arguments& args) { Player* player = get(); if (!player) return Local(); - auto attribute = player->getMutableAttribute(SharedAttributes::LAVA_MOVEMENT_SPEED()); - AttributeHelper::setCurrentValue(attribute, args[0].asNumber().toFloat()); - - return Boolean::newBoolean(true); + if (auto component = player->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setCurrentValue( + component->mAttributes, + SharedAttributes::LAVA_MOVEMENT_SPEED(), + args[0].asNumber().toFloat() + ) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setLavaMovementSpeed!"); } @@ -2926,10 +3002,12 @@ Local PlayerClass::setHungry(const Arguments& args) { Player* player = get(); if (!player) return Local(); - auto attribute = player->getMutableAttribute(Player::HUNGER()); - AttributeHelper::setCurrentValue(attribute, args[0].asNumber().toFloat()); - - return Boolean::newBoolean(true); + if (auto component = player->getEntityContext().tryGetComponent()) { + return Boolean::newBoolean( + AttributeHelper::setCurrentValue(component->mAttributes, Player::HUNGER(), args[0].asNumber().toFloat()) + ); + } + return Boolean::newBoolean(false); } CATCH("Fail in setHungry!"); } diff --git a/src/legacy/api/ScoreboardAPI.cpp b/src/legacy/api/ScoreboardAPI.cpp index d7ef451a..da8d88c8 100644 --- a/src/legacy/api/ScoreboardAPI.cpp +++ b/src/legacy/api/ScoreboardAPI.cpp @@ -4,7 +4,6 @@ #include "api/McAPI.h" #include "api/PlayerAPI.h" #include "ll/api/service/Bedrock.h" -#include "mc/world/actor/player/Player.h" #include "mc/world/scores/DisplayObjective.h" #include "mc/world/scores/Objective.h" #include "mc/world/scores/ScoreInfo.h" diff --git a/src/legacy/api/SimulatedPlayerAPI.cpp b/src/legacy/api/SimulatedPlayerAPI.cpp index 469bfdf8..b0e6b91c 100644 --- a/src/legacy/api/SimulatedPlayerAPI.cpp +++ b/src/legacy/api/SimulatedPlayerAPI.cpp @@ -9,15 +9,11 @@ #include "engine/GlobalShareData.h" #include "ll/api/service/Bedrock.h" #include "lse/api/helper/SimulatedPlayerHelper.h" -#include "mc/nbt/CompoundTag.h" #include "mc/network/ServerNetworkHandler.h" #include "mc/scripting/modules/gametest/ScriptNavigationResult.h" #include "mc/server/SimulatedPlayer.h" #include "mc/server/sim/LookDuration.h" -#include "mc/world/Container.h" -#include "mc/world/Minecraft.h" #include "mc/world/actor/Actor.h" -#include "mc/world/level/BlockSource.h" #include "mc/world/level/dimension/Dimension.h" #include @@ -91,7 +87,7 @@ Local PlayerClass::simulateAttack(const Arguments& args) { if (args.size() == 0) return Boolean::newBoolean(sp->simulateAttack()); if (auto actor = EntityClass::tryExtractActor(args[0])) { - sp->_trySwing(); + sp->swing(ActorSwingSource::Attack); return Boolean::newBoolean(sp->attack(*actor, SharedTypes::Legacy::ActorDamageCause::EntityAttack)); } @@ -389,9 +385,7 @@ Local PlayerClass::simulateLookAt(const Arguments& args) { sp->simulateLookAt(pos->getBlockPos(), lookDuration); return Boolean::newBoolean(true); } - lse::LegacyScriptEngine::getLogger().debug( - "Can't simulate look at other dimension!" - ); + lse::LegacyScriptEngine::getLogger().debug("Can't simulate look at other dimension!"); return Boolean::newBoolean(false); } else if (IsInstanceOf(args[0])) { auto pos = FloatPos::extractPos(args[0]); @@ -400,9 +394,7 @@ Local PlayerClass::simulateLookAt(const Arguments& args) { sp->simulateLookAt(pos->getVec3(), (sim::LookDuration)lookDuration); return Boolean::newBoolean(true); } - lse::LegacyScriptEngine::getLogger().debug( - "Can't simulate look at other dimension!" - ); + lse::LegacyScriptEngine::getLogger().debug("Can't simulate look at other dimension!"); return Boolean::newBoolean(false); } else if (IsInstanceOf(args[0])) { auto block = EngineScope::currentEngine()->getNativeInstance(args[0]); @@ -412,9 +404,7 @@ Local PlayerClass::simulateLookAt(const Arguments& args) { sp->simulateLookAt(pos->getBlockPos(), (sim::LookDuration)lookDuration); return Boolean::newBoolean(true); } - lse::LegacyScriptEngine::getLogger().debug( - "Can't simulate look at other dimension!" - ); + lse::LegacyScriptEngine::getLogger().debug("Can't simulate look at other dimension!"); return Boolean::newBoolean(false); } else if (auto actor = EntityClass::tryExtractActor(args[0])) { sp->simulateLookAt(*actor, (sim::LookDuration)lookDuration); diff --git a/src/legacy/legacyapi/db/Session.cpp b/src/legacy/legacyapi/db/Session.cpp index 5992d8d8..fcb73ab8 100644 --- a/src/legacy/legacyapi/db/Session.cpp +++ b/src/legacy/legacyapi/db/Session.cpp @@ -1,9 +1,7 @@ #include "legacyapi/db/Session.h" #include "lse/Entry.h" -#ifndef LSE_BACKEND_NODEJS #include "legacyapi/db/impl/mysql/Session.h" -#endif #include "legacyapi/db/impl/sqlite/Session.h" #include "ll/api/io/LoggerRegistry.h" #include "ll/api/utils/StringUtils.h" @@ -110,13 +108,7 @@ SharedPointer Session::_Create(DBType type, const ConnParams& params) { session = params.empty() ? std::make_shared() : std::make_shared(params); break; case DBType::MySQL: -#ifdef LSE_BACKEND_NODEJS - lse::LegacyScriptEngine::getLogger().error( - "Session::_Create: MySQL is disabled in NodeJS backend because its OpenSSL has conflicts with libnode" - ); -#else session = params.empty() ? std::make_shared() : std::make_shared(params); -#endif break; default: lse::LegacyScriptEngine::getLogger().error( diff --git a/src/lse/api/helper/AttributeHelper.cpp b/src/lse/api/helper/AttributeHelper.cpp index 1737057f..c4d4d3e8 100644 --- a/src/lse/api/helper/AttributeHelper.cpp +++ b/src/lse/api/helper/AttributeHelper.cpp @@ -1,39 +1,46 @@ #include "AttributeHelper.h" +#include "mc/world/attribute/Attribute.h" #include "mc/world/attribute/AttributeInstance.h" -#include "mc/world/attribute/AttributeModificationContext.h" +#include "mc/world/attribute/AttributeInstanceRef.h" #include "mc/world/attribute/BaseAttributeMap.h" namespace lse::api { -inline void AttributeHelper::setDirty(MutableAttributeWithContext& attribute) { - auto map = attribute.mContext->mAttributeMap; - if (map) { - map->_onAttributeModified(*attribute.mInstance); - } +inline void AttributeHelper::setDirty(BaseAttributeMap& map, AttributeInstance const* attribute) { + map._onAttributeModified(*attribute); } -void AttributeHelper::setCurrentValue(MutableAttributeWithContext& attribute, float value) { - auto& instance = attribute.mInstance; - instance->mCurrentValue = value; - setDirty(attribute); +bool AttributeHelper::setCurrentValue(BaseAttributeMap& map, Attribute const& attribute, float value) { + if (auto ptr = map.getMutableInstance(attribute.mIDValue).mPtr) { + ptr->mCurrentValue = value; + setDirty(map, ptr); + return true; + } + return false; } -void AttributeHelper::setMaxValue(MutableAttributeWithContext& attribute, float value) { - auto& instance = attribute.mInstance; - instance->mCurrentMaxValue = value; - instance->mDefaultMaxValue = value; - float& currentValue = instance->mCurrentValue; - currentValue = std::max(currentValue, instance->mCurrentMinValue); - setDirty(attribute); +bool AttributeHelper::setMaxValue(BaseAttributeMap& map, Attribute const& attribute, float value) { + if (auto ptr = map.getMutableInstance(attribute.mIDValue).mPtr) { + ptr->mCurrentMaxValue = value; + ptr->mDefaultMaxValue = value; + float& currentValue = ptr->mCurrentValue; + currentValue = std::max(currentValue, ptr->mCurrentMinValue); + setDirty(map, ptr); + return true; + } + return false; } -void AttributeHelper::setDefaultValue(MutableAttributeWithContext& attribute, float value) { - auto& instance = attribute.mInstance; - float& defaultValue = instance->mDefaultValue; - if (value != defaultValue) { - defaultValue = value; - instance->mCurrentValue = value; - setDirty(attribute); +bool AttributeHelper::setDefaultValue(BaseAttributeMap& map, Attribute const& attribute, float value) { + if (auto ptr = map.getMutableInstance(attribute.mIDValue).mPtr) { + float& defaultValue = ptr->mDefaultValue; + if (value != defaultValue) { + defaultValue = value; + ptr->mCurrentValue = value; + setDirty(map, ptr); + return true; + } } + return false; } -} // namespace lse::api::AttributeHelper \ No newline at end of file +} // namespace lse::api diff --git a/src/lse/api/helper/AttributeHelper.h b/src/lse/api/helper/AttributeHelper.h index 61e93e08..fe2b542d 100644 --- a/src/lse/api/helper/AttributeHelper.h +++ b/src/lse/api/helper/AttributeHelper.h @@ -1,13 +1,13 @@ #pragma once -#include "mc/world/attribute/MutableAttributeWithContext.h" +#include "mc/world/attribute/BaseAttributeMap.h" namespace lse::api { class AttributeHelper { - static void setDirty(MutableAttributeWithContext& attribute); + static void setDirty(BaseAttributeMap& map, AttributeInstance const* attribute); public: - static void setCurrentValue(MutableAttributeWithContext& attribute, float value); - static void setMaxValue(MutableAttributeWithContext& attribute, float value); - static void setDefaultValue(MutableAttributeWithContext& attribute, float value); + static bool setCurrentValue(BaseAttributeMap& map, Attribute const& attribute, float value); + static bool setMaxValue(BaseAttributeMap& map, Attribute const& attribute, float value); + static bool setDefaultValue(BaseAttributeMap& map, Attribute const& attribute, float value); }; -} // namespace lse::api \ No newline at end of file +} // namespace lse::api diff --git a/src/lse/api/helper/PlayerHelper.cpp b/src/lse/api/helper/PlayerHelper.cpp index 8101f3b9..87f5674b 100644 --- a/src/lse/api/helper/PlayerHelper.cpp +++ b/src/lse/api/helper/PlayerHelper.cpp @@ -1,17 +1,17 @@ #include "PlayerHelper.h" #include "AttributeHelper.h" +#include "mc/entity/components/AttributesComponent.h" #include "mc/world/actor/player/Player.h" #include "mc/world/attribute/AttributeInstance.h" -#include "mc/world/attribute/AttributeModificationContext.h" -#include "mc/world/attribute/MutableAttributeWithContext.h" +#include "mc/world/attribute/AttributeInstanceConstRef.h" namespace lse::api { unsigned int PlayerHelper::getPreviousLevelRequirement(Player* player) { int prevLevelReq = player->mPreviousLevelRequirement; if (player->mPlayerLevelChanged) { - int curLvl = player->getAttribute(Player::LEVEL()).mCurrentValue; + int curLvl = player->getAttribute(Player::LEVEL()).mPtr->mCurrentValue; int plus = (curLvl / 15 == 1) ? (curLvl * 4 - 38) : (curLvl * 8 - 158); prevLevelReq = (curLvl / 15) ? (curLvl + plus) : (curLvl * 2 + 7); player->mPlayerLevelChanged = false; @@ -21,16 +21,22 @@ unsigned int PlayerHelper::getPreviousLevelRequirement(Player* player) { } unsigned int PlayerHelper::getXpEarnedAtCurrentLevel(Player* player) { - unsigned int prevLevelReq = PlayerHelper::getPreviousLevelRequirement(player); - auto& attribute = player->getAttribute(Player::EXPERIENCE()); - return (unsigned int)roundf(attribute.mCurrentValue * (float)prevLevelReq); + unsigned int prevLevelReq = getPreviousLevelRequirement(player); + auto attribute = player->getAttribute(Player::EXPERIENCE()); + return static_cast(roundf(attribute.mPtr->mCurrentValue * static_cast(prevLevelReq))); } bool PlayerHelper::setXpEarnedAtCurrentLevel(Player* player, unsigned int xp) { - unsigned int prevLevelReq = PlayerHelper::getPreviousLevelRequirement(player); - auto attribute = player->getMutableAttribute(Player::EXPERIENCE()); - AttributeHelper::setCurrentValue(attribute, (float)xp / (float)prevLevelReq); - return true; + if (auto component = player->getEntityContext().tryGetComponent()) { + unsigned int prevLevelReq = getPreviousLevelRequirement(player); + AttributeHelper::setCurrentValue( + component->mAttributes, + Player::EXPERIENCE(), + static_cast(xp) / static_cast(prevLevelReq) + ); + return true; + } + return false; } -} // namespace lse::api \ No newline at end of file +} // namespace lse::api diff --git a/src/lse/events/BlockEvents.cpp b/src/lse/events/BlockEvents.cpp index 7d65abf9..86a22c3e 100644 --- a/src/lse/events/BlockEvents.cpp +++ b/src/lse/events/BlockEvents.cpp @@ -8,10 +8,8 @@ #include "ll/api/memory/Memory.h" #include "ll/api/service/Bedrock.h" #include "lse/api/Thread.h" -#include "lse/api/helper/BlockHelper.h" #include "mc/legacy/ActorUniqueID.h" #include "mc/scripting/modules/minecraft/events/ScriptBlockGlobalEventListener.h" -#include "mc/server/ServerInstance.h" #include "mc/server/commands/CommandOrigin.h" #include "mc/server/commands/CommandOriginType.h" #include "mc/world/actor/ArmorStand.h" @@ -31,7 +29,6 @@ #include "mc/world/level/block/ComparatorBlock.h" #include "mc/world/level/block/CopperBulbBlock.h" #include "mc/world/level/block/CrafterBlock.h" -#include "mc/world/level/block/DiodeBlock.h" #include "mc/world/level/block/DispenserBlock.h" #include "mc/world/level/block/DoorBlock.h" #include "mc/world/level/block/FarmBlock.h" @@ -49,6 +46,7 @@ #include "mc/world/level/block/TrapDoorBlock.h" #include "mc/world/level/block/actor/BaseCommandBlock.h" #include "mc/world/level/block/actor/PistonBlockActor.h" +#include "mc/world/level/block/block_events/BlockRedstoneUpdateEvent.h" #include "mc/world/level/dimension/Dimension.h" #include "mc/world/level/material/Material.h" @@ -310,7 +308,7 @@ inline bool RedstoneUpdateEvent(BlockSource& region, BlockPos const& pos, int& s return true; } -#define REDSTONEHOOK(BLOCK) \ +#define REDSTONE_EVNET_HOOK_OLD(BLOCK) \ LL_TYPE_INSTANCE_HOOK( \ BLOCK##Hook, \ HookPriority::Normal, \ @@ -333,28 +331,80 @@ inline bool RedstoneUpdateEvent(BlockSource& region, BlockPos const& pos, int& s origin(region, pos, strength, isFirstTime); \ } -REDSTONEHOOK(RedStoneWireBlock) -REDSTONEHOOK(DiodeBlock) -REDSTONEHOOK(RedstoneTorchBlock) -REDSTONEHOOK(ComparatorBlock) -REDSTONEHOOK(HopperBlock) -REDSTONEHOOK(CrafterBlock) -REDSTONEHOOK(CommandBlock) -REDSTONEHOOK(BaseRailBlock) -REDSTONEHOOK(PoweredRailBlock) -REDSTONEHOOK(BigDripleafBlock) -REDSTONEHOOK(CopperBulbBlock) -REDSTONEHOOK(DoorBlock) -REDSTONEHOOK(FenceGateBlock) -REDSTONEHOOK(DispenserBlock) -REDSTONEHOOK(StructureBlock) -REDSTONEHOOK(TrapDoorBlock) -REDSTONEHOOK(NoteBlock) -REDSTONEHOOK(ActivatorRailBlock) -REDSTONEHOOK(RedstoneLampBlock) -REDSTONEHOOK(TntBlock) +#define REDSTONE_EVNET_HOOK_1(BLOCK) \ + LL_TYPE_INSTANCE_HOOK( \ + BLOCK##Hook, \ + HookPriority::Normal, \ + BLOCK, \ + &BLOCK::$_onRedstoneUpdate, \ + void, \ + BlockEvents::BlockRedstoneUpdateEvent& blockEvent \ + ) { \ + IF_LISTENED(EVENT_TYPES::onRedStoneUpdate) { \ + if (checkClientIsServerThread()) { \ + if (!RedstoneUpdateEvent( \ + blockEvent.mRegion, \ + blockEvent.mPos, \ + blockEvent.mSignalLevel, \ + blockEvent.mIsFirstTime \ + )) { \ + return; \ + } \ + } \ + } \ + IF_LISTENED_END(EVENT_TYPES::onRedStoneUpdate); \ + origin(blockEvent); \ + } + +#define REDSTONE_EVNET_HOOK_2(BLOCK) \ + LL_TYPE_INSTANCE_HOOK( \ + BLOCK##Hook, \ + HookPriority::Normal, \ + BLOCK, \ + &BLOCK::_onRedstoneUpdate, \ + void, \ + BlockEvents::BlockRedstoneUpdateEvent& blockEvent \ + ) { \ + IF_LISTENED(EVENT_TYPES::onRedStoneUpdate) { \ + if (checkClientIsServerThread()) { \ + if (!RedstoneUpdateEvent( \ + blockEvent.mRegion, \ + blockEvent.mPos, \ + blockEvent.mSignalLevel, \ + blockEvent.mIsFirstTime \ + )) { \ + return; \ + } \ + } \ + } \ + IF_LISTENED_END(EVENT_TYPES::onRedStoneUpdate); \ + origin(blockEvent); \ + } + +REDSTONE_EVNET_HOOK_OLD(HopperBlock) +REDSTONE_EVNET_HOOK_OLD(CrafterBlock) +REDSTONE_EVNET_HOOK_OLD(CommandBlock) +REDSTONE_EVNET_HOOK_OLD(BigDripleafBlock) +REDSTONE_EVNET_HOOK_OLD(CopperBulbBlock) +REDSTONE_EVNET_HOOK_OLD(DoorBlock) +REDSTONE_EVNET_HOOK_OLD(FenceGateBlock) +REDSTONE_EVNET_HOOK_OLD(DispenserBlock) +REDSTONE_EVNET_HOOK_OLD(StructureBlock) +REDSTONE_EVNET_HOOK_OLD(TrapDoorBlock) +REDSTONE_EVNET_HOOK_OLD(NoteBlock) +REDSTONE_EVNET_HOOK_OLD(RedstoneLampBlock) +REDSTONE_EVNET_HOOK_OLD(TntBlock) + +REDSTONE_EVNET_HOOK_1(BaseRailBlock) +REDSTONE_EVNET_HOOK_1(PoweredRailBlock) +REDSTONE_EVNET_HOOK_1(ActivatorRailBlock) + +REDSTONE_EVNET_HOOK_2(RedStoneWireBlock) +REDSTONE_EVNET_HOOK_2(RedstoneTorchBlock) +REDSTONE_EVNET_HOOK_2(ComparatorBlock) -#undef REDSTONEHOOK +#undef REDSTONE_EVNET_HOOK_OLD +#undef REDSTONE_EVNET_HOOK } // namespace redstone @@ -541,7 +591,6 @@ void BlockExplodedEvent() { BlockExplodedHook ::hook(); } void RedstoneUpdateEvent() { redstone::RedstoneTorchBlockHook::hook(); redstone::RedStoneWireBlockHook::hook(); - redstone::DiodeBlockHook::hook(); redstone::ComparatorBlockHook::hook(); redstone::HopperBlockHook::hook(); redstone::CrafterBlockHook::hook(); diff --git a/src/lse/events/EntityEvents.cpp b/src/lse/events/EntityEvents.cpp index b79f903f..6e919cfe 100644 --- a/src/lse/events/EntityEvents.cpp +++ b/src/lse/events/EntityEvents.cpp @@ -6,7 +6,6 @@ #include "ll/api/memory/Hook.h" #include "ll/api/memory/Memory.h" #include "ll/api/service/Bedrock.h" -#include "ll/api/service/GamingStatus.h" #include "lse/api/Thread.h" #include "lse/api/helper/BlockHelper.h" #include "mc/common/Globals.h" @@ -55,7 +54,7 @@ LL_TYPE_INSTANCE_HOOK( IF_LISTENED(EVENT_TYPES::onSpawnProjectile) { if (checkClientIsServerThread()) { static auto& tridentName = EntityCanonicalName(ActorType::Trident); - if (id.mCanonicalName.get() != tridentName) { + if (id.mCanonicalName != tridentName) { if (!CallEvent( EVENT_TYPES::onSpawnProjectile, EntityClass::newEntity(spawner), diff --git a/tooth.json b/tooth.json index dae8f7ef..088276e8 100644 --- a/tooth.json +++ b/tooth.json @@ -2,7 +2,7 @@ "format_version": 3, "format_uuid": "289f771f-2c9a-4d73-9f3f-8492495a924d", "tooth": "github.com/LiteLDev/LegacyScriptEngine", - "version": "0.17.0-rc.2", + "version": "0.17.0", "info": { "name": "LegacyScriptEngine", "description": "A plugin engine for running LLSE plugins on LeviLamina", @@ -33,8 +33,8 @@ "label": "nodejs", "platform": "win-x64", "dependencies": { - "github.com/LiteLDev/LegacyRemoteCall": "0.17.0-rc.1", - "github.com/LiteLDev/LegacyMoney": "0.17.0-rc.1", + "github.com/LiteLDev/LegacyRemoteCall": "0.17.*", + "github.com/LiteLDev/LegacyMoney": "0.17.*", "git.levimc.org/ShrBox/7-zip": "24.*" }, "assets": [ @@ -70,8 +70,8 @@ "label": "quickjs", "platform": "win-x64", "dependencies": { - "github.com/LiteLDev/LegacyRemoteCall": "0.17.0-rc.1", - "github.com/LiteLDev/LegacyMoney": "0.17.0-rc.1" + "github.com/LiteLDev/LegacyRemoteCall": "0.17.*", + "github.com/LiteLDev/LegacyMoney": "0.17.*" }, "assets": [ { @@ -93,8 +93,8 @@ "label": "lua", "platform": "win-x64", "dependencies": { - "github.com/LiteLDev/LegacyRemoteCall": "0.17.0-rc.1", - "github.com/LiteLDev/LegacyMoney": "0.17.0-rc.1" + "github.com/LiteLDev/LegacyRemoteCall": "0.17.*", + "github.com/LiteLDev/LegacyMoney": "0.17.*" }, "assets": [ { @@ -116,8 +116,8 @@ "label": "python", "platform": "win-x64", "dependencies": { - "github.com/LiteLDev/LegacyRemoteCall": "0.17.0-rc.1", - "github.com/LiteLDev/LegacyMoney": "0.17.0-rc.1" + "github.com/LiteLDev/LegacyRemoteCall": "0.17.*", + "github.com/LiteLDev/LegacyMoney": "0.17.*" }, "assets": [ { @@ -139,8 +139,8 @@ "label": "client_nodejs", "platform": "win-x64", "dependencies": { - "github.com/LiteLDev/LegacyRemoteCall#client": "0.17.0-rc.1", - "github.com/LiteLDev/LegacyMoney#client": "0.17.0-rc.1", + "github.com/LiteLDev/LegacyRemoteCall#client": "0.17.*", + "github.com/LiteLDev/LegacyMoney#client": "0.17.*", "git.levimc.org/ShrBox/7-zip": "24.*" }, "assets": [ @@ -176,8 +176,8 @@ "label": "client_quickjs", "platform": "win-x64", "dependencies": { - "github.com/LiteLDev/LegacyRemoteCall#client": "0.17.0-rc.1", - "github.com/LiteLDev/LegacyMoney#client": "0.17.0-rc.1" + "github.com/LiteLDev/LegacyRemoteCall#client": "0.17.*", + "github.com/LiteLDev/LegacyMoney#client": "0.17.*" }, "assets": [ { @@ -199,8 +199,8 @@ "label": "client_lua", "platform": "win-x64", "dependencies": { - "github.com/LiteLDev/LegacyRemoteCall#client": "0.17.0-rc.1", - "github.com/LiteLDev/LegacyMoney#client": "0.17.0-rc.1" + "github.com/LiteLDev/LegacyRemoteCall#client": "0.17.*", + "github.com/LiteLDev/LegacyMoney#client": "0.17.*" }, "assets": [ { @@ -222,8 +222,8 @@ "label": "client_python", "platform": "win-x64", "dependencies": { - "github.com/LiteLDev/LegacyRemoteCall#client": "0.17.0-rc.1", - "github.com/LiteLDev/LegacyMoney#client": "0.17.0-rc.1" + "github.com/LiteLDev/LegacyRemoteCall#client": "0.17.*", + "github.com/LiteLDev/LegacyMoney#client": "0.17.*" }, "assets": [ { diff --git a/xmake.lua b/xmake.lua index c37786a7..38cde81b 100644 --- a/xmake.lua +++ b/xmake.lua @@ -3,9 +3,9 @@ add_rules("mode.debug", "mode.release") add_repositories("levimc-repo " .. (get_config("levimc_repo") or "https://github.com/LiteLDev/xmake-repo.git")) if is_config("target_type", "server") then - add_requires("levilamina 1.8.0-rc.2", {configs = {target_type = "server"}}) + add_requires("levilamina 06b1ab008c5bde2c0c2868107f963896d46bfcb5", {configs = {target_type = "server"}}) else - add_requires("levilamina 1.8.0-rc.2", {configs = {target_type = "client"}}) + add_requires("levilamina 06b1ab008c5bde2c0c2868107f963896d46bfcb5", {configs = {target_type = "client"}}) end add_requires("levibuildscript") @@ -22,29 +22,26 @@ add_requires( "ctre 3.8.1" ) +add_requires("openssl3") +add_requires("cpp-httplib 0.26.0", { configs = { ssl = true, zlib = true } }) + if is_config("backend", "lua") then - add_requires("openssl 1.1.1-w") - add_requires("mariadb-connector-c 3.3.9") - add_requires("scriptx 2026.1.10", {configs={backend="Lua"}}) + add_requires("mariadb-connector-c 3.4.8") + add_requires("scriptx 2026.1.10", { configs = { backend = "Lua" } }) elseif is_config("backend", "quickjs") then - add_requires("openssl 1.1.1-w") - add_requires("mariadb-connector-c 3.3.9") - add_requires("scriptx 2026.1.10", {configs={backend="QuickJs"}}) + add_requires("mariadb-connector-c 3.4.8") + add_requires("scriptx 2026.1.10", { configs = { backend = "QuickJs" } }) elseif is_config("backend", "python") then - add_requires("openssl 1.1.1-w") - add_requires("mariadb-connector-c 3.3.9") - add_requires("scriptx 2026.1.10", {configs={backend="Python"}}) + add_requires("mariadb-connector-c 3.4.8") + add_requires("scriptx 2026.1.10", { configs = { backend = "Python" } }) elseif is_config("backend", "nodejs") then - add_requires("scriptx 2026.1.10", {configs={backend="V8"}}) - + add_requires("mariadb-connector-c 3.4.8") + add_requires("scriptx 2026.1.10", { configs = { backend = "V8" } }) end -add_requires("openssl3") -add_requires("cpp-httplib 0.26.0", {configs = {ssl = true, zlib = true}}) - if not has_config("vs_runtime") then set_runtimes("MD") end From 50d02dea1f3b7d9fa821b47ed641853c5f6a0a4f Mon Sep 17 00:00:00 2001 From: ShrBox Date: Sun, 25 Jan 2026 17:12:21 +0800 Subject: [PATCH 25/27] fix: fix nodejs --- src/lse/api/helper/BlockHelper.cpp | 5 ++--- xmake.lua | 1 - 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/src/lse/api/helper/BlockHelper.cpp b/src/lse/api/helper/BlockHelper.cpp index 4bd28cdf..f1ba4183 100644 --- a/src/lse/api/helper/BlockHelper.cpp +++ b/src/lse/api/helper/BlockHelper.cpp @@ -5,8 +5,7 @@ namespace lse::api { bool BlockHelper::isValidHeight(WeakRef dimension, std::variant height) { - auto dim = dimension.lock(); - if (dim) { + if (auto dim = dimension.lock()) { if (std::holds_alternative(height)) { int y = std::get(height); return dim->mHeightRange->mMin <= y && dim->mHeightRange->mMax >= y; @@ -18,4 +17,4 @@ bool BlockHelper::isValidHeight(WeakRef dimension, std::variant Date: Sun, 25 Jan 2026 19:16:19 +0800 Subject: [PATCH 26/27] fix: reset DebugEngine shared pointer when unload --- src/lse/Entry.cpp | 5 +++++ src/lse/Entry.h | 4 +++- 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/src/lse/Entry.cpp b/src/lse/Entry.cpp index 5ed02424..3eafd34f 100644 --- a/src/lse/Entry.cpp +++ b/src/lse/Entry.cpp @@ -125,6 +125,11 @@ bool LegacyScriptEngine::load() { } } +bool LegacyScriptEngine::unload() { + DebugEngine.reset(); + return true; +} + Config const& LegacyScriptEngine::getConfig() { return config; } PluginManager& LegacyScriptEngine::getManager() { diff --git a/src/lse/Entry.h b/src/lse/Entry.h index be24e290..c9c4dece 100644 --- a/src/lse/Entry.h +++ b/src/lse/Entry.h @@ -1,8 +1,8 @@ #pragma once +#include "ll/api/mod/NativeMod.h" #include "lse/Config.h" #include "lse/PluginManager.h" -#include "ll/api/mod/NativeMod.h" namespace lse { @@ -24,6 +24,8 @@ class LegacyScriptEngine { bool enable(); + bool unload(); + private: ll::mod::NativeMod& mSelf; Config config; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables) From 87847af8ccc8f885c92f59642c4af77738ba1bf7 Mon Sep 17 00:00:00 2001 From: ShrBox Date: Sun, 25 Jan 2026 20:38:49 +0800 Subject: [PATCH 27/27] chore: update tooth.json & CHANGELOG.md --- CHANGELOG.md | 5 ++++- tooth.json | 10 ++++++++++ xmake.lua | 4 ++-- 3 files changed, 16 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ea01227a..f080d218 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [0.17.0] - 2026-01-25 + ### Added - Added client support @@ -1123,7 +1125,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 [#332]: https://github.com/LiteLDev/LegacyScriptEngine/issues/332 [#339]: https://github.com/LiteLDev/LegacyScriptEngine/issues/339 -[Unreleased]: https://github.com/LiteLDev/LegacyScriptEngine/compare/v0.17.0-rc.2...HEAD +[Unreleased]: https://github.com/LiteLDev/LegacyScriptEngine/compare/v0.17.0...HEAD +[0.17.0]: https://github.com/LiteLDev/LegacyScriptEngine/compare/v0.17.0-rc.2...v0.17.0 [0.17.0-rc.2]: https://github.com/LiteLDev/LegacyScriptEngine/compare/v0.16.7...v0.17.0-rc.2 [0.16.7]: https://github.com/LiteLDev/LegacyScriptEngine/compare/v0.16.6...v0.16.7 [0.16.6]: https://github.com/LiteLDev/LegacyScriptEngine/compare/v0.16.5...v0.16.6 diff --git a/tooth.json b/tooth.json index 088276e8..44537ac7 100644 --- a/tooth.json +++ b/tooth.json @@ -17,6 +17,7 @@ { "platform": "win-x64", "dependencies": { + "github.com/LiteLDev/LeviLamina": "1.9.*", "github.com/LiteLDev/LegacyScriptEngine#quickjs": "{{version}}", "github.com/LiteLDev/LegacyScriptEngine#lua": "{{version}}" } @@ -25,6 +26,7 @@ "label": "client", "platform": "win-x64", "dependencies": { + "github.com/LiteLDev/LeviLamina#client": "1.9.*", "github.com/LiteLDev/LegacyScriptEngine#client_quickjs": "{{version}}", "github.com/LiteLDev/LegacyScriptEngine#client_lua": "{{version}}" } @@ -33,6 +35,7 @@ "label": "nodejs", "platform": "win-x64", "dependencies": { + "github.com/LiteLDev/LeviLamina": "1.9.*", "github.com/LiteLDev/LegacyRemoteCall": "0.17.*", "github.com/LiteLDev/LegacyMoney": "0.17.*", "git.levimc.org/ShrBox/7-zip": "24.*" @@ -70,6 +73,7 @@ "label": "quickjs", "platform": "win-x64", "dependencies": { + "github.com/LiteLDev/LeviLamina": "1.9.*", "github.com/LiteLDev/LegacyRemoteCall": "0.17.*", "github.com/LiteLDev/LegacyMoney": "0.17.*" }, @@ -93,6 +97,7 @@ "label": "lua", "platform": "win-x64", "dependencies": { + "github.com/LiteLDev/LeviLamina": "1.9.*", "github.com/LiteLDev/LegacyRemoteCall": "0.17.*", "github.com/LiteLDev/LegacyMoney": "0.17.*" }, @@ -116,6 +121,7 @@ "label": "python", "platform": "win-x64", "dependencies": { + "github.com/LiteLDev/LeviLamina": "1.9.*", "github.com/LiteLDev/LegacyRemoteCall": "0.17.*", "github.com/LiteLDev/LegacyMoney": "0.17.*" }, @@ -139,6 +145,7 @@ "label": "client_nodejs", "platform": "win-x64", "dependencies": { + "github.com/LiteLDev/LeviLamina#client": "1.9.*", "github.com/LiteLDev/LegacyRemoteCall#client": "0.17.*", "github.com/LiteLDev/LegacyMoney#client": "0.17.*", "git.levimc.org/ShrBox/7-zip": "24.*" @@ -176,6 +183,7 @@ "label": "client_quickjs", "platform": "win-x64", "dependencies": { + "github.com/LiteLDev/LeviLamina#client": "1.9.*", "github.com/LiteLDev/LegacyRemoteCall#client": "0.17.*", "github.com/LiteLDev/LegacyMoney#client": "0.17.*" }, @@ -199,6 +207,7 @@ "label": "client_lua", "platform": "win-x64", "dependencies": { + "github.com/LiteLDev/LeviLamina#client": "1.9.*", "github.com/LiteLDev/LegacyRemoteCall#client": "0.17.*", "github.com/LiteLDev/LegacyMoney#client": "0.17.*" }, @@ -222,6 +231,7 @@ "label": "client_python", "platform": "win-x64", "dependencies": { + "github.com/LiteLDev/LeviLamina#client": "1.9.*", "github.com/LiteLDev/LegacyRemoteCall#client": "0.17.*", "github.com/LiteLDev/LegacyMoney#client": "0.17.*" }, diff --git a/xmake.lua b/xmake.lua index 1444228f..d395faff 100644 --- a/xmake.lua +++ b/xmake.lua @@ -3,9 +3,9 @@ add_rules("mode.debug", "mode.release") add_repositories("levimc-repo " .. (get_config("levimc_repo") or "https://github.com/LiteLDev/xmake-repo.git")) if is_config("target_type", "server") then - add_requires("levilamina 06b1ab008c5bde2c0c2868107f963896d46bfcb5", {configs = {target_type = "server"}}) + add_requires("levilamina 1.9.0", {configs = {target_type = "server"}}) else - add_requires("levilamina 06b1ab008c5bde2c0c2868107f963896d46bfcb5", {configs = {target_type = "client"}}) + add_requires("levilamina 1.9.0", {configs = {target_type = "client"}}) end add_requires("levibuildscript")