51 Commits

30 changed files with 1100 additions and 543 deletions
+21 -3
View File
@@ -1,5 +1,23 @@
Diagnostics: Diagnostics:
Suppress: ["-Wmicrosoft-enum-forward-reference", "-Wc++11-narrowing", "-Wc++2b-extensions", "-Wmicrosoft-cast"] Suppress:
- "-Wmicrosoft-enum-forward-reference"
- "-Wc++11-narrowing"
- "-Wc++2b-extensions"
- "-Wmicrosoft-cast"
- "-Wcxx20_deducing_this"
- "-Wundefined_internal_type"
- "-Wincomplete_member_access"
- "-Wsizeof_alignof_incomplete_or_sizeless_type"
- "-Wexplicit_spec_non_template"
- "-Wovl_no_viable_function_in_init"
CompileFlags: CompileFlags:
Add: ["-ferror-limit=0", "-D__FUNCTION__=\"dummy\"", "-D_CRT_USE_BUILTIN_OFFSETOF", "-std:c++latest"] Add:
Remove: ["/Yu_HeaderOutputPredefine.h", "/FI_HeaderOutputPredefine.h"] - "-Xclang"
- "-triple=x86_64-windows-msvc"
- "-ferror-limit=0"
- '-D__FUNCTION__="dummy"'
- "-Dnsel_CONFIG_SELECT_EXPECTED=nsel_EXPECTED_NONSTD"
- "-Xclang"
- "-std=c++23"
Remove:
- "-std"
+3 -1
View File
@@ -15,6 +15,8 @@ jobs:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- uses: xmake-io/github-action-setup-xmake@v1 - uses: xmake-io/github-action-setup-xmake@v1
with:
xmake-version: 3.0.0
- run: | - run: |
xmake repo -u xmake repo -u
@@ -25,7 +27,7 @@ jobs:
- run: | - run: |
xmake -w -y xmake -w -y
- uses: actions/upload-artifact@v3 - uses: actions/upload-artifact@v4
with: with:
name: ${{ github.event.repository.name }}-windows-x64-${{ github.sha }} name: ${{ github.event.repository.name }}-windows-x64-${{ github.sha }}
path: | path: |
+4 -2
View File
@@ -15,6 +15,8 @@ jobs:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- uses: xmake-io/github-action-setup-xmake@v1 - uses: xmake-io/github-action-setup-xmake@v1
with:
xmake-version: 3.0.0
- run: | - run: |
xmake repo -u xmake repo -u
@@ -25,7 +27,7 @@ jobs:
- run: | - run: |
xmake -w -y xmake -w -y
- uses: actions/upload-artifact@v3 - uses: actions/upload-artifact@v4
with: with:
name: ${{ github.event.repository.name }}-windows-x64-${{ github.sha }} name: ${{ github.event.repository.name }}-windows-x64-${{ github.sha }}
path: | path: |
@@ -40,7 +42,7 @@ jobs:
steps: steps:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- uses: actions/download-artifact@v3 - uses: actions/download-artifact@v4
with: with:
name: ${{ github.event.repository.name }}-windows-x64-${{ github.sha }} name: ${{ github.event.repository.name }}-windows-x64-${{ github.sha }}
path: release/ path: release/
+2
View File
@@ -6,3 +6,5 @@
/compile_commands.json /compile_commands.json
/CMakeLists.txt /CMakeLists.txt
/.vscode /.vscode
/.idea
github_mirror.lua
+111
View File
@@ -1,6 +1,117 @@
# Cleaner # Cleaner
服务器实体清理插件 服务器实体清理插件
## 配置文件
```jsonc
{
"version": 2, // 配置文件版本(勿动)
"language": "zh_CN", // 语言(目前支持zh_CN和en_US)
"Basic": { // 基础配置
"Command": "cleaner", // 清理命令
"Notice1": 20, // 提示1发送时间(剩余时间) (单位:秒)
"Notice2": 5, // 提示2发送时间(剩余时间) (单位:秒)
"ConsoleLog": true, // 是否在控制台输出清理日志
"SendBroadcast": true, // 是否发送广播
"SendToast": true // 是否发送Toast(屏幕上方)
},
"IgnoreTags": [ // 忽略的实体标签
"ignore",
"不清理"
],
"AutoCleanCount": { // 自动清理数量配置
"Enabled": true, // 是否启用
"TriggerCount": 900 // 触发清理最低数量
},
"AutoCleanTPS": { // 自动清理TPS配置
"Enabled": true, // 是否启用
"TriggerTPS": 15 // 触发清理最低TPS
},
"ItemDespawn": { // 掉落物自然刷新配置
"Enabled": true, // 是否启用
"DespawnTime": 6000, // 刷新时间(单位:tick)
"WhiteList": [ // 白名单
"minecraft:elytra"
]
},
"CleanInanimate": { // 非生物实体清理配置
"Enabled": true, // 是否启用
"Blacklist": [ // 黑名单
"minecraft:xp_orb",
"minecraft:arrow",
"minecraft:fireball",
"minecraft:small_fireball",
"minecraft:wither_skull",
"minecraft:wither_skull_dangerous",
"minecraft:dragon_fireball"
]
},
"CleanItem": { // 掉落物清理配置
"Enabled": true, // 是否启用
"ExistTicks": 0, // 安全时间(掉落物存在时间小于这个时间则不会清理) 单位:tick
"Whitelist": [ // 白名单
"minecraft:netherite_helmet",
"minecraft:netherite_sword",
"minecraft:netherite_chestplate",
"minecraft:diamond_helmet",
"minecraft:netherite_leggings",
"minecraft:undyed_shulker_box",
"minecraft:netherite_boots",
"minecraft:shulker_box",
"minecraft:elytra",
"minecraft:dragon_egg",
"minecraft:nether_star",
"minecraft:diamond_sword",
"minecraft:diamond_chestplate",
"minecraft:diamond_boots",
"minecraft:diamond_leggings",
"minecraft:diamond_hoe",
"minecraft:netherite_hoe",
"minecraft:diamond_axe",
"minecraft:netherite_axe",
"minecraft:netherite_pickaxe",
"minecraft:diamond_pickaxe"
]
},
"CleanMobs": { // 生物实体清理配置
"Enabled": true, // 是否启用
"CleanMonstors": true, // 是否清理怪物
"CleanPeacefulMobs": false, // 是否清理和平生物
"EnableAutoExclude": true, // 无用
"BlackList": [ // 黑名单
"minecraft:guardian",
"minecraft:zombie_pigman"
],
"Whitelist": [ // 白名单
"minecraft:ender_dragon",
"minecraft:shulker",
"minecraft:wither",
"minecraft:elder_guardian",
"minecraft:piglin_brute",
"minecraft:ender_pearl",
"minecraft:phantom"
]
},
"ScheduleClean": { // 定时清理配置
"Enabled": true, // 是否启用
"CleanInterval": 3600 // 清理间隔 单位:秒
},
"VoteClean": { // 投票清理配置
"Enabled": true, // 是否启用
"VoteCleanCommand": "voteclean", // 投票清理指令
"Cooldown": 120, // 投票冷却时间 单位:秒
"CheckDelay": 30, // 投票时长 单位:秒
"Percentage": 50 // 投票百分比(大于此值则清理)
},
"UnloadActorClean": { // 离线实体清理
"Enabled": false, // 是否启用
"CleanList": [ // 清理实体列表
"minecraft:iron_golem", // 铁傀儡
"minecraft:zombie_pigman" // 僵尸猪灵
]
}
}
```
# 开源许可 # 开源许可
## 源代码可用性 ## 源代码可用性
- 您可以自由地获取、使用和修改本插件的源代码,无论是个人使用还是商业目的。 - 您可以自由地获取、使用和修改本插件的源代码,无论是个人使用还是商业目的。
Submodule SDK-GMLIB deleted from cecc827900
+11 -3
View File
@@ -1,13 +1,21 @@
{ {
"name": "${pluginName}", "name": "${modName}",
"entry": "${pluginFile}", "entry": "${modFile}",
"type": "native", "type": "native",
"version": "0.11.0", "version": "0.16.1",
"author": "GroupMountain", "author": "GroupMountain",
"description": "Clean Entities", "description": "Clean Entities",
"dependencies": [ "dependencies": [
{ {
"name": "GMLIB" "name": "GMLIB"
},
{
"name": "iListenAttentively"
}
],
"optionalDependencies": [
{
"name": "ModAPI"
} }
] ]
} }
+7 -7
View File
@@ -82,16 +82,16 @@ function string_formatter(str, variables)
end) end)
end end
function pack_plugin(target,plugin_define) function pack_mod(target,mod_define)
import("lib.detect.find_file") import("lib.detect.find_file")
local manifest_path = find_file("manifest.json", os.projectdir()) local manifest_path = find_file("manifest.json", os.projectdir())
if manifest_path then if manifest_path then
local manifest = io.readfile(manifest_path) local manifest = io.readfile(manifest_path)
local bindir = path.join(os.projectdir(), "bin") local bindir = path.join(os.projectdir(), "bin")
local outputdir = path.join(bindir, plugin_define.pluginName) local outputdir = path.join(bindir, mod_define.modName)
local targetfile = path.join(outputdir, plugin_define.pluginFile) local targetfile = path.join(outputdir, mod_define.modFile)
local pdbfile = path.join(outputdir, path.basename(plugin_define.pluginFile) .. ".pdb") local pdbfile = path.join(outputdir, path.basename(mod_define.modFile) .. ".pdb")
local manifestfile = path.join(outputdir, "manifest.json") local manifestfile = path.join(outputdir, "manifest.json")
local oritargetfile = target:targetfile() local oritargetfile = target:targetfile()
local oripdbfile = path.join(path.directory(oritargetfile), path.basename(oritargetfile) .. ".pdb") local oripdbfile = path.join(path.directory(oritargetfile), path.basename(oritargetfile) .. ".pdb")
@@ -102,9 +102,9 @@ function pack_plugin(target,plugin_define)
os.cp(oripdbfile, pdbfile) os.cp(oripdbfile, pdbfile)
end end
formattedmanifest = string_formatter(manifest, plugin_define) formattedmanifest = string_formatter(manifest, mod_define)
io.writefile(manifestfile,formattedmanifest) io.writefile(manifestfile,formattedmanifest)
cprint("${bright green}[Plugin Packer]: ${reset}plugin already generated to " .. outputdir) cprint("${bright green}[Mod Packer]: ${reset}mod already generated to " .. outputdir)
else else
cprint("${bright yellow}warn: ${reset}not found manifest.json in root dir!") cprint("${bright yellow}warn: ${reset}not found manifest.json in root dir!")
end end
@@ -112,7 +112,7 @@ end
return { return {
pack_plugin = pack_plugin, pack_mod = pack_mod,
beautify_json = beautify_json, beautify_json = beautify_json,
string_formatter = string_formatter string_formatter = string_formatter
} }
+84 -86
View File
@@ -1,38 +1,43 @@
#pragma once #pragma once
#include "Global.h" #include <string>
#include <vector>
std::string defaultConfig = R"({ namespace Cleaner {
"Basic": { struct Config {
"Language": "en_US", int version = 2;
"Command": "cleaner",
"Notice1": 20, std::string language = "zh_CN";
"Notice2": 5,
"ConsoleLog": true, struct basic {
"SendBroadcast": true, std::string Command = "cleaner";
"SendToast": true int Notice1 = 20;
}, int Notice2 = 5;
"IgnoreTags": [ bool ConsoleLog = true;
"ignore", bool SendBroadcast = true;
"不清理" bool SendToast = true;
], } Basic;
"AutoCleanCount": {
"Enabled": true, std::vector<std::string> IgnoreTags = {"ignore", "不清理"};
"TriggerCount": 900
}, struct auto_clean_count {
"AutoCleanTPS": { bool Enabled = true;
"Enabled": false, int TriggerCount = 900;
"TriggerTPS": 15 } AutoCleanCount;
},
"ItemDespawn": { struct auto_clean_tps {
"Enabled": true, bool Enabled = true;
"DespawnTime": 6000, int TriggerTPS = 15;
"WhiteList": [ } AutoCleanTPS;
"minecraft:elytra"
] struct item_despawn {
}, bool Enabled = true;
"CleanInanimate": { int DespawnTime = 6000;
"Enabled": true, std::vector<std::string> WhiteList = {"minecraft:elytra"};
"Blacklist": [ } ItemDespawn;
struct Clean_Inanimate {
bool Enabled = true;
std::vector<std::string> Blacklist = {
"minecraft:xp_orb", "minecraft:xp_orb",
"minecraft:arrow", "minecraft:arrow",
"minecraft:fireball", "minecraft:fireball",
@@ -40,45 +45,30 @@ std::string defaultConfig = R"({
"minecraft:wither_skull", "minecraft:wither_skull",
"minecraft:wither_skull_dangerous", "minecraft:wither_skull_dangerous",
"minecraft:dragon_fireball" "minecraft:dragon_fireball"
] };
}, } CleanInanimate;
"CleanItem": {
"Enabled": true, struct Clean_Item {
"ExistTicks": 0, bool Enabled = true;
"Whitelist": [ int ExistTicks = 0;
"minecraft:netherite_helmet", std::vector<std::string> Whitelist = {
"minecraft:netherite_sword", "minecraft:netherite_helmet", "minecraft:netherite_sword", "minecraft:netherite_chestplate",
"minecraft:netherite_chestplate", "minecraft:diamond_helmet", "minecraft:netherite_leggings", "minecraft:undyed_shulker_box",
"minecraft:diamond_helmet", "minecraft:netherite_boots", "minecraft:shulker_box", "minecraft:elytra",
"minecraft:netherite_leggings", "minecraft:dragon_egg", "minecraft:nether_star", "minecraft:diamond_sword",
"minecraft:undyed_shulker_box", "minecraft:diamond_chestplate", "minecraft:diamond_boots", "minecraft:diamond_leggings",
"minecraft:netherite_boots", "minecraft:diamond_hoe", "minecraft:netherite_hoe", "minecraft:diamond_axe",
"minecraft:shulker_box", "minecraft:netherite_axe", "minecraft:netherite_pickaxe", "minecraft:diamond_pickaxe"
"minecraft:elytra", };
"minecraft:dragon_egg", } CleanItem;
"minecraft:nether_star",
"minecraft:diamond_sword", struct Clean_Mobs {
"minecraft:diamond_chestplate", bool Enabled = true;
"minecraft:diamond_boots", bool CleanMonstors = true;
"minecraft:diamond_leggings", bool CleanPeacefulMobs = false;
"minecraft:diamond_hoe", bool EnableAutoExclude = true;
"minecraft:netherite_hoe", std::vector<std::string> BlackList = {"minecraft:guardian", "minecraft:zombie_pigman"};
"minecraft:diamond_axe", std::vector<std::string> Whitelist = {
"minecraft:netherite_axe",
"minecraft:netherite_pickaxe",
"minecraft:diamond_pickaxe"
]
},
"CleanMobs": {
"Enabled": true,
"CleanMonstors": true,
"CleanPeacefulMobs": false,
"EnableAutoExclude": true,
"BlackList": [
"minecraft:guardian",
"minecraft:zombie_pigman"
],
"Whitelist": [
"minecraft:ender_dragon", "minecraft:ender_dragon",
"minecraft:shulker", "minecraft:shulker",
"minecraft:wither", "minecraft:wither",
@@ -86,17 +76,25 @@ std::string defaultConfig = R"({
"minecraft:piglin_brute", "minecraft:piglin_brute",
"minecraft:ender_pearl", "minecraft:ender_pearl",
"minecraft:phantom" "minecraft:phantom"
] };
}, } CleanMobs;
"ScheduleClean": {
"Enabled": true, struct Schedule_Clean {
"CleanInterval": 3600 bool Enabled = true;
}, int CleanInterval = 3600;
"VoteClean": { } ScheduleClean;
"Enabled": true,
"VoteCleanCommand": "voteclean", struct Vote_Clean {
"Cooldown": 120, bool Enabled = true;
"CheckDelay": 30, std::string VoteCleanCommand = "voteclean";
"Percentage": 50 int Cooldown = 120;
} int CheckDelay = 30;
})"; int Percentage = 50;
} VoteClean;
struct Unload_Actor_Clean {
bool Enabled = false;
std::vector<std::string> CleanList = {"minecraft:iron_golem", "minecraft:zombie_pigman"};
} UnloadActorClean;
};
} // namespace Cleaner
+27 -22
View File
@@ -1,5 +1,6 @@
#include "Cleaner.h" #include "Cleaner.h"
#include "mc/world/actor/provider/SynchedActorDataAccess.h"
#include "gmlib/mc/world/actor/Actor.h"
namespace Cleaner { namespace Cleaner {
bool isMatch(std::string& A, std::string& B) { bool isMatch(std::string& A, std::string& B) {
@@ -15,9 +16,11 @@ bool isMatch(std::string& A, std::string& B) {
return (A == B); return (A == B);
} }
bool shouldIgnore(GMLIB_Actor* ac) { bool isTrust(Actor* ac) { return SynchedActorDataAccess::getActorFlag(ac->getEntityContext(), ::ActorFlags::Trusting); }
if (ac->isMob() || ac->isItemActor()) {
if (ac->isTame() || ac->isTrusting() || ac->getNameTag() != "" || ac->hasTag("cleaner:ignore")) { bool shouldIgnore(gmlib::GMActor* ac) {
if (ac->hasCategory(::ActorCategory::Mob) || ac->hasCategory(::ActorCategory::Item)) {
if (ac->isTame() || isTrust(ac) || ac->getNameTag() != "" || ac->hasTag("cleaner:ignore")) {
return true; return true;
} }
} }
@@ -26,25 +29,26 @@ bool shouldIgnore(GMLIB_Actor* ac) {
bool ShouldClean(Actor* actor) { bool ShouldClean(Actor* actor) {
// Players // Players
auto en = (GMLIB_Actor*)actor; auto& config = Cleaner::Entry::getInstance().getConfig();
auto en = (gmlib::GMActor*)actor;
if (en->isPlayer() || shouldIgnore(en)) { if (en->isPlayer() || shouldIgnore(en)) {
return false; return false;
} }
auto type = en->getTypeName(); auto type = en->getTypeName();
for (auto& tag : ConfigFile::mIgnoreTags) { for (auto& tag : config.IgnoreTags) {
if (en->hasTag(tag)) { if (en->hasTag(tag)) {
return false; return false;
} }
} }
// Items // Items
if (en->isItemActor()) { if (en->hasCategory(::ActorCategory::Item)) {
if (Config->getValue<bool>({"CleanItem", "Enabled"}, false)) { if (config.CleanItem.Enabled) {
auto itac = (ItemActor*)en; auto itac = (ItemActor*)en;
if (itac->age() <= Config->getValue<int>({"CleanItem", "ExistTicks"}, 0)) { if (itac->age() <= config.CleanItem.ExistTicks) {
return false; return false;
} }
auto itemType = itac->item().getTypeName(); auto itemType = itac->item().getTypeName();
auto whitelist = Config->getValue<std::vector<std::string>>({"CleanItem", "Whitelist"}, {}); auto whitelist = config.CleanItem.Whitelist;
for (auto& key : whitelist) { for (auto& key : whitelist) {
if (isMatch(itemType, key)) { if (isMatch(itemType, key)) {
return false; return false;
@@ -55,25 +59,24 @@ bool ShouldClean(Actor* actor) {
return false; return false;
} }
// Mobs // Mobs
else if (en->isMob()) { else if (en->hasCategory(::ActorCategory::Mob)) {
if (Config->getValue<bool>({"CleanMobs", "Enabled"}, false)) { if (config.CleanMobs.Enabled) {
auto blacklist = Config->getValue<std::vector<std::string>>({"CleanMobs", "BlackList"}, {}); auto blacklist = config.CleanMobs.BlackList;
for (auto& key : blacklist) { for (auto& key : blacklist) {
if (isMatch(type, key)) { if (isMatch(type, key)) {
return true; return true;
} }
} }
auto whitelist = Config->getValue<std::vector<std::string>>({"CleanMobs", "Whitelist"}, {}); auto whitelist = config.CleanMobs.Whitelist;
for (auto& key : whitelist) { for (auto& key : whitelist) {
if (isMatch(type, key)) { if (isMatch(type, key)) {
return false; return false;
} }
} }
if (Config->getValue<bool>({"CleanMobs", "CleanMonstors"}, false) if (config.CleanMobs.CleanMonstors && en->hasCategory(ActorCategory::Monster)) {
&& en->hasCategory(ActorCategory::Monster)) {
return true; return true;
} }
if (Config->getValue<bool>({"CleanMobs", "CleanPeacefulMobs"}, false)) { if (config.CleanMobs.CleanPeacefulMobs) {
return true; return true;
} }
} }
@@ -81,8 +84,8 @@ bool ShouldClean(Actor* actor) {
} }
// Others // Others
else { else {
if (Config->getValue<bool>({"CleanInanimate", "Enabled"}, false)) { if (config.CleanInanimate.Enabled) {
auto blacklist = Config->getValue<std::vector<std::string>>({"CleanInanimate", "Blacklist"}, {}); auto blacklist = config.CleanInanimate.Blacklist;
for (auto& key : blacklist) { for (auto& key : blacklist) {
if (isMatch(type, key)) { if (isMatch(type, key)) {
return true; return true;
@@ -94,8 +97,9 @@ bool ShouldClean(Actor* actor) {
} }
int ExecuteClean() { int ExecuteClean() {
auto level = ll::service::getLevel();
int clean_count = 0; int clean_count = 0;
auto all_entities = GMLIB_Level::getLevel()->getAllEntities(); auto all_entities = level->getRuntimeActorList();
for (auto entity : all_entities) { for (auto entity : all_entities) {
if (ShouldClean(entity)) { if (ShouldClean(entity)) {
entity->despawn(); entity->despawn();
@@ -106,9 +110,10 @@ int ExecuteClean() {
} }
int CountEntities() { int CountEntities() {
auto level = ll::service::getLevel();
int clean_count = 0; int clean_count = 0;
auto all_entities = GMLIB_Level::getLevel()->getAllEntities(); auto all_entities = level->getRuntimeActorList();
for (auto entity : all_entities) { for (auto* entity : all_entities) {
if (ShouldClean(entity)) { if (ShouldClean(entity)) {
clean_count++; clean_count++;
} }
+80 -58
View File
@@ -1,124 +1,146 @@
#include "Cleaner.h" #include "Cleaner.h"
#include <memory>
namespace ConfigFile { #include "gmlib/mc/world/Level.h"
#include "gmlib/gm/data/TpsStatus.h"
bool mConsoleLog = true;
bool mAnnounce = true;
bool mSendToast = true;
std::vector<std::string> mIgnoreTags = {};
} // namespace ConfigFile
namespace Cleaner { namespace Cleaner {
static std::shared_ptr<ll::schedule::task::Task<ll::chrono::ServerClock>> mAutoCleanTask = nullptr; static std::shared_ptr<bool> mAutoCleanTask = std::make_shared<bool>(false);
static std::shared_ptr<ll::schedule::task::Task<ll::chrono::ServerClock>> mCleanTaskCount = nullptr; static std::shared_ptr<bool> mCleanTaskCount = std::make_shared<bool>(false);
static std::shared_ptr<ll::schedule::task::Task<ll::chrono::ServerClock>> mCleanTaskTPS = nullptr; static std::shared_ptr<bool> mCleanTaskTPS = std::make_shared<bool>(false);
ServerTimeScheduler scheduler;
bool auto_clean_triggerred = false; bool auto_clean_triggerred = false;
void CleanTask() { void CleanTask() {
auto time = Config->getValue<int>({"Basic", "Notice1"}, 20); auto& config = Cleaner::Entry::getInstance().getConfig();
auto announce_time = Config->getValue<int>({"Basic", "Notice2"}, 5); auto time = config.Basic.Notice1;
auto time_1 = std::chrono::seconds::duration(time); auto announce_time = config.Basic.Notice2;
auto time_2 = std::chrono::seconds::duration(time - announce_time); std::chrono::seconds time_1(time);
if (ConfigFile::mConsoleLog) { std::chrono::seconds time_2(time - announce_time);
logger.info(tr("cleaner.output.count1", {S(time_1.count())})); if (config.Basic.ConsoleLog) {
ll::io::LoggerRegistry::getInstance().getOrCreate("Cleaner")->info(
tr("cleaner.output.count1", {S(time_1.count())})
);
} }
if (ConfigFile::mAnnounce) { if (config.Basic.SendBroadcast) {
Helper::broadcastMessage(tr("cleaner.output.count1", {S(time_1.count())})); Helper::broadcastMessage(tr("cleaner.output.count1", {S(time_1.count())}));
} }
if (ConfigFile::mSendToast) { if (config.Basic.SendToast) {
Helper::broadcastToast(tr("cleaner.output.count2", {S(announce_time)})); Helper::broadcastToast(tr("cleaner.output.count2", {S(announce_time)}));
} }
scheduler.add<DelayTask>(time_2, [announce_time] { ll::coro::keepThis([announce_time, &config, time_2]() -> ll::coro::CoroTask<> {
if (ConfigFile::mConsoleLog) { co_await time_2;
logger.info(tr("cleaner.output.count2", {S(announce_time)})); if (config.Basic.ConsoleLog) {
ll::io::LoggerRegistry::getInstance().getOrCreate("Cleaner")->info(
tr("cleaner.output.count2", {S(announce_time)})
);
} }
if (ConfigFile::mAnnounce) { if (config.Basic.SendBroadcast) {
Helper::broadcastMessage(tr("cleaner.output.count2", {S(announce_time)})); Helper::broadcastMessage(tr("cleaner.output.count2", {S(announce_time)}));
} }
if (ConfigFile::mSendToast) { if (config.Basic.SendToast) {
Helper::broadcastToast(tr("cleaner.output.count2", {S(announce_time)})); Helper::broadcastToast(tr("cleaner.output.count2", {S(announce_time)}));
} }
}); co_return;
scheduler.add<DelayTask>(time_1, [] { }).launch(ll::thread::ServerThreadExecutor::getDefault());
ll::coro::keepThis([announce_time, &config, time_1]() -> ll::coro::CoroTask<> {
co_await time_1;
auto count = ExecuteClean(); auto count = ExecuteClean();
if (ConfigFile::mConsoleLog) { if (config.Basic.ConsoleLog) {
logger.info(tr("cleaner.output.finish", {S(count)})); ll::io::LoggerRegistry::getInstance().getOrCreate("Cleaner")->info(tr("cleaner.output.finish", {S(count)}));
} }
if (ConfigFile::mAnnounce) { if (config.Basic.SendBroadcast) {
Helper::broadcastMessage(tr("cleaner.output.finish", {S(count)})); Helper::broadcastMessage(tr("cleaner.output.finish", {S(count)}));
} }
if (ConfigFile::mSendToast) { if (config.Basic.SendToast) {
Helper::broadcastToast(tr("cleaner.output.finish", {S(count)})); Helper::broadcastToast(tr("cleaner.output.finish", {S(count)}));
} }
auto_clean_triggerred = false; auto_clean_triggerred = false;
}); co_return;
}).launch(ll::thread::ServerThreadExecutor::getDefault());
} }
void AutoCleanTask(int seconds) { void AutoCleanTask(int seconds) {
auto time = std::chrono::seconds::duration(seconds); std::chrono::seconds time(seconds);
mAutoCleanTask = scheduler.add<RepeatTask>(time, [] { CleanTask(); }); *mAutoCleanTask = true;
ll::coro::keepThis([time]() -> ll::coro::CoroTask<> {
while (true) {
co_await time;
if (*mAutoCleanTask == false) co_return;
CleanTask();
}
co_return;
}).launch(ll::thread::ServerThreadExecutor::getDefault());
} }
void CleanTaskCount(int max_entities) { void CleanTaskCount(int max_entities) {
mCleanTaskCount = scheduler.add<RepeatTask>(10s, [max_entities] { auto& config = Cleaner::Entry::getInstance().getConfig();
*mCleanTaskCount = true;
ll::coro::keepThis([max_entities, &config]() -> ll::coro::CoroTask<> {
while (true) {
co_await 10s;
if (*mCleanTaskCount == false) co_return;
auto count = CountEntities(); auto count = CountEntities();
if (auto_clean_triggerred == false) { if (auto_clean_triggerred == false) {
if (count >= max_entities) { if (count >= max_entities) {
auto_clean_triggerred = true; auto_clean_triggerred = true;
if (ConfigFile::mConsoleLog) { if (config.Basic.ConsoleLog) {
logger.warn(tr("cleaner.output.triggerAutoCleanCount", {S(count)})); ll::io::LoggerRegistry::getInstance().getOrCreate("Cleaner")->warn(
tr("cleaner.output.triggerAutoCleanCount", {S(count)})
);
} }
if (ConfigFile::mAnnounce) { if (config.Basic.SendBroadcast) {
Helper::broadcastMessage(tr("cleaner.output.triggerAutoCleanCount", {S(count)})); Helper::broadcastMessage(tr("cleaner.output.triggerAutoCleanCount", {S(count)}));
} }
if (ConfigFile::mSendToast) { if (config.Basic.SendToast) {
Helper::broadcastToast(tr("cleaner.output.triggerAutoCleanCount", {S(count)})); Helper::broadcastToast(tr("cleaner.output.triggerAutoCleanCount", {S(count)}));
} }
CleanTask(); CleanTask();
} }
} }
}); }
co_return;
}).launch(ll::thread::ServerThreadExecutor::getDefault());
} }
void CleanTaskTPS(float min_tps) { void CleanTaskTPS(float min_tps) {
mCleanTaskTPS = scheduler.add<RepeatTask>(10s, [min_tps] { auto& config = Cleaner::Entry::getInstance().getConfig();
*mCleanTaskTPS = true;
ll::coro::keepThis([min_tps, &config]() -> ll::coro::CoroTask<> {
while (true) {
co_await 10s;
if (*mCleanTaskTPS == false) co_return;
if (auto_clean_triggerred == false) { if (auto_clean_triggerred == false) {
if (GMLIB_Level::getLevel()->getServerAverageTps() <= min_tps) { if (gmlib::TpsStatus::getInstance().getLevelAverageTps() <= min_tps) {
auto_clean_triggerred = true; auto_clean_triggerred = true;
auto mspt = S(GMLIB_Level::getLevel()->getServerAverageTps()); auto mspt = S(gmlib::TpsStatus::getInstance().getLevelAverageTps());
if (ConfigFile::mConsoleLog) { if (config.Basic.ConsoleLog) {
logger.warn(tr("cleaner.output.triggerAutoCleanTps", {mspt})); ll::io::LoggerRegistry::getInstance().getOrCreate("Cleaner")->warn(
tr("cleaner.output.triggerAutoCleanTps", {mspt})
);
} }
if (ConfigFile::mAnnounce) { if (config.Basic.SendBroadcast) {
Helper::broadcastMessage(tr("cleaner.output.triggerAutoCleanTps", {mspt})); Helper::broadcastMessage(tr("cleaner.output.triggerAutoCleanTps", {mspt}));
} }
if (ConfigFile::mSendToast) { if (config.Basic.SendToast) {
Helper::broadcastToast(tr("cleaner.output.triggerAutoCleanTps", {mspt})); Helper::broadcastToast(tr("cleaner.output.triggerAutoCleanTps", {mspt}));
} }
CleanTask(); CleanTask();
} }
} }
}); }
co_return;
}).launch(ll::thread::ServerThreadExecutor::getDefault());
} }
void stopAllTasks() { void stopAllTasks() {
if (!mCleanTaskCount) { if (!mCleanTaskCount) {
mCleanTaskTPS->cancel(); *mCleanTaskTPS = false;
scheduler.remove(mCleanTaskTPS);
} }
if (mCleanTaskCount) { if (mCleanTaskCount) {
mCleanTaskCount->cancel(); *mCleanTaskCount = false;
scheduler.remove(mCleanTaskCount);
} }
if (mAutoCleanTask) { if (mAutoCleanTask) {
mAutoCleanTask->cancel(); *mAutoCleanTask = false;
scheduler.remove(mAutoCleanTask);
} }
} }
} // namespace Cleaner } // namespace Cleaner
+12 -17
View File
@@ -3,31 +3,26 @@
namespace Cleaner { namespace Cleaner {
void loadCleaner() { void loadCleaner() {
if (Config->getValue<bool>({"ScheduleClean", "Enabled"}, false)) { auto& config = Cleaner::Entry::getInstance().getConfig();
Cleaner::AutoCleanTask(Config->getValue<int>({"ScheduleClean", "CleanInterval"}, 3000)); if(config.UnloadActorClean.Enabled){
UnloadActorClean::cleanUnloadActor();
} }
if (Config->getValue<bool>({"AutoCleanCount", "Enabled"}, false)) { if (config.ScheduleClean.Enabled) {
Cleaner::CleanTaskCount(Config->getValue<int>({"AutoCleanCount", "TriggerCount"}, 900)); Cleaner::AutoCleanTask(config.ScheduleClean.CleanInterval);
} }
if (Config->getValue<bool>({"AutoCleanTPS", "Enabled"}, false)) { if (config.AutoCleanCount.Enabled) {
Cleaner::CleanTaskTPS(Config->getValue<float>({"AutoCleanTPS", "TriggerTPS"}, 15.0f)); Cleaner::CleanTaskCount(config.AutoCleanCount.TriggerCount);
}
if (config.AutoCleanTPS.Enabled) {
Cleaner::CleanTaskTPS(config.AutoCleanTPS.TriggerTPS);
} }
ConfigFile::mItemDespawnTicks = Config->getValue<int>({"ItemDespawn", "DespawnTime"}, 6000);
ConfigFile::mAnnounce = Config->getValue<bool>({"Basic", "SendBroadcast"}, true);
ConfigFile::mConsoleLog = Config->getValue<bool>({"Basic", "ConsoleLog"}, true);
ConfigFile::mSendToast = Config->getValue<bool>({"Basic", "SendToast"}, true);
ConfigFile::mIgnoreTags = Config->getValue<std::vector<std::string>>({"IgnoreTags"}, {});
} }
void unloadCleaner() { stopAllTasks(); } void unloadCleaner() { stopAllTasks(); }
void reloadCleaner() { void reloadCleaner() {
unloadCleaner(); Cleaner::Entry::getInstance().disable();
Config->reload(); Cleaner::Entry::getInstance().enable();
std::string languageCode = Config->getValue<std::string>({"Basic", "Language"}, "en_US");
Language->reloadAllLanguages();
Language->chooseLanguage(languageCode);
loadCleaner();
} }
} // namespace Cleaner } // namespace Cleaner
+10 -3
View File
@@ -1,13 +1,13 @@
#pragma once #pragma once
#include "Global.h" #include "Global.h"
using namespace ll::schedule; #include <gmlib/mc/world/actor/UnloadedActor.h>
extern void MainForm(Player* player);
using namespace ll::chrono_literals; using namespace ll::chrono_literals;
namespace Cleaner { namespace Cleaner {
extern ServerTimeScheduler scheduler;
extern int ExecuteClean(); extern int ExecuteClean();
extern int CountEntities(); extern int CountEntities();
@@ -20,6 +20,7 @@ extern void CleanTask();
extern void reloadCleaner(); extern void reloadCleaner();
extern void loadCleaner(); extern void loadCleaner();
extern void unloadCleaner(); extern void unloadCleaner();
extern bool shouldIgnore(gmlib::GMActor* ac);
extern bool isMatch(std::string& A, std::string& B); extern bool isMatch(std::string& A, std::string& B);
@@ -30,3 +31,9 @@ namespace VoteClean {
extern void voteCommandExecute(Player* pl); extern void voteCommandExecute(Player* pl);
} }
namespace UnloadActorClean {
extern void cleanUnloadActor();
}
+17 -27
View File
@@ -1,50 +1,40 @@
#include "Cleaner.h" #include "Cleaner.h"
#include "gmlib/mc/world/Level.h"
namespace ConfigFile { #include "gmlib/mc/world/actor/Player.h"
int mItemDespawnTicks = 3000;
} // namespace ConfigFile
namespace Cleaner { namespace Cleaner {
void setShouldIgnore(gmlib::GMActor* ac) { ac->addTag("cleaner:ignore"); }
void setShouldIgnore(GMLIB_Actor* ac) { ac->addTag("cleaner:ignore"); }
void ListenEvents() { void ListenEvents() {
auto& eventBus = ll::event::EventBus::getInstance(); auto& eventBus = ll::event::EventBus::getInstance();
auto& config = Cleaner::Entry::getInstance().getConfig();
// ItemSpawnEvent // ItemSpawnEvent
eventBus.emplaceListener<GMLIB::Event::EntityEvent::ItemActorSpawnAfterEvent>( eventBus.emplaceListener<ila::mc::SpawnItemActorAfterEvent>([&config](ila::mc::SpawnItemActorAfterEvent& event) {
[](GMLIB::Event::EntityEvent::ItemActorSpawnAfterEvent& event) { auto& item = event.itemActor();
auto& item = event.getItemActor(); if (event.spawner()) {
if (event.getSpawner().has_value()) { auto pl = (gmlib::GMPlayer*)event.spawner();
auto pl = (GMLIB_Player*)event.getSpawner().as_ptr();
if (pl->isPlayer() && !pl->isAlive()) { // Death Drop if (pl->isPlayer() && !pl->isAlive()) { // Death Drop
auto ac = (GMLIB_Actor*)&item; auto ac = (gmlib::GMActor*)&item;
setShouldIgnore(ac); setShouldIgnore(ac);
return; return;
} }
} }
if (Config->getValue<bool>({"ItemDespawn", "Enabled"}, true)) { if (config.ItemDespawn.Enabled) {
item.lifeTime() = ConfigFile::mItemDespawnTicks; // item.lifeTime() = config.ItemDespawn.DespawnTime;
auto list = Config->getValue<std::vector<std::string>>({"ItemDespawn", "WhiteList"}, {}); auto list = config.ItemDespawn.WhiteList;
auto type = item.item().getTypeName(); auto type = item.item().getTypeName();
for (auto& key : list) { for (auto& key : list) {
if (isMatch(type, key)) { if (isMatch(type, key)) {
return; return;
} }
} }
item.lifeTime() = ConfigFile::mItemDespawnTicks; item.lifeTime() = config.ItemDespawn.DespawnTime;
} }
} });
);
// MobTakeItemEvent // MobTakeItemEvent
eventBus.emplaceListener<GMLIB::Event::EntityEvent::MobPickupItemAfterEvent>( eventBus.emplaceListener<ila::mc::ActorPickupItemAfterEvent>([](ila::mc::ActorPickupItemAfterEvent& event) {
[](GMLIB::Event::EntityEvent::MobPickupItemAfterEvent& event) { auto mob = (gmlib::GMActor*)&event.self();
auto mob = (GMLIB_Actor*)&event.self();
setShouldIgnore(mob); setShouldIgnore(mob);
} });
);
} }
} // namespace Cleaner } // namespace Cleaner
+7 -3
View File
@@ -1,9 +1,13 @@
#include "Global.h" #include "Global.h"
#include "gmlib/mc/world/Level.h"
namespace Helper { namespace Helper {
void broadcastMessage(std::string_view msg) { GMLIB_Level::broadcast(tr("cleaner.info.prefix") + std::string(msg)); } void broadcastMessage(std::string_view msg) {
gmlib::GMLevel::getInstance()->broadcast(tr("cleaner.info.prefix") + std::string(msg));
}
void broadcastToast(std::string_view msg) { GMLIB_Level::broadcastToast(tr("cleaner.info.prefix"), msg); } void broadcastToast(std::string_view msg) {
gmlib::GMLevel::getInstance()->broadcastToast(tr("cleaner.info.prefix"), msg);
}
} // namespace Helper } // namespace Helper
+288
View File
@@ -0,0 +1,288 @@
#include "Cleaner.h"
#include "Global.h"
#include "Mod.h"
#include "ll/api/base/Containers.h"
#include "ll/api/service/Bedrock.h"
#include "mc/common/Globals.h"
#include "mc/world/level/Level.h"
#include <gmlib/mc/world/Level.h>
#include <gmlib/mc/world/actor/UnloadedActor.h>
#include <ll/api/form/CustomForm.h>
#include <ll/api/form/ModalForm.h>
#include <ll/api/form/SimpleForm.h>
#include <string>
#include <thread>
#include <vector>
#include <mutex>
using UnloadEntityMap = std::unordered_map<std::string, std::vector<gmlib::UnloadedActor>>;
struct {
std::chrono::system_clock::time_point lastUpdate{};
std::atomic_bool isUpdating{false};
UnloadEntityMap offlineEntities{};
ll::SmallDenseSet<ActorUniqueID> waitedPlayers{};
std::atomic_bool requireUpdate{false};
std::mutex offlineEntitiesMutex; // ✅ 新增
} OfflineEntity;
auto typeNameToLocString(std::string const& typeName) {
return EntityTypeToLocString(
EntityTypeFromString(typeName),
ActorTypeNamespaceRules::ReturnWithoutNamespace
);
}
auto getAllEntityTypes() {
return std::ranges::to<ll::SmallDenseSet<std::string>>(
ll::service::getLevel()->getRuntimeActorList()
| std::views::transform(&Actor::getTypeName)
);
}
auto getEntityCountByType(std::string const& typeName) {
return std::ranges::count_if(
ll::service::getLevel()->getRuntimeActorList(),
[&](const Actor* a) { return a && a->getTypeName() == typeName; }
);
}
void ConfirmForm(Player& player, bool isOnline, const std::string& TypeName, bool needCondition) {
auto fm = ll::form::ModalForm(
tr("cleaner.form.confirm.title"),
tr(isOnline&&needCondition?"cleaner.form.confirm.important"
:"cleaner.form.confirm.warning",{
tr(typeNameToLocString(TypeName)),
TypeName,
std::to_string(
isOnline
? getEntityCountByType(TypeName)
: OfflineEntity.offlineEntities[TypeName].size()
)
}),
tr("cleaner.form.confirm.confirm"),
tr("cleaner.form.confirm.cancel")
);
fm.sendTo(player, [isOnline, TypeName, needCondition](
const Player& player,
ll::form::ModalFormResult rst,
ll::form::FormCancelReason res
) {
if (res) return;
if (!rst || rst.value() != ll::form::ModalFormSelectedButton::Upper)
return;
if (isOnline) {
for (auto en : ll::service::getLevel()->getRuntimeActorList()) {
auto actor = (gmlib::GMActor*)en;
if (en->getTypeName() == TypeName &&
(!needCondition || !Cleaner::shouldIgnore(actor))) {
en->despawn();
}
}
} else {
if (!OfflineEntity.isUpdating.exchange(true)) {
std::thread([TypeName]() {
{
std::lock_guard<std::mutex> lock(
OfflineEntity.offlineEntitiesMutex
);
auto it = OfflineEntity.offlineEntities.find(TypeName);
if (it != OfflineEntity.offlineEntities.end()) {
for (auto& en : it->second) {
if (en.isValid()) en.remove();
}
OfflineEntity.offlineEntities.erase(it);
}
}
OfflineEntity.isUpdating.store(false);
}).detach();
} else {
player.sendMessage(tr(""));
}
}
});
}
void SettingCleanForm(Player& player, bool isOnline, const std::string& TypeName) {
if (!isOnline) {
ConfirmForm(player, isOnline, TypeName, false);
return;
}
auto fm = ll::form::CustomForm(tr("cleaner.form.setting.title"));
fm.appendLabel(
tr("cleaner.form.setting.content",{
tr(typeNameToLocString(TypeName)),
TypeName,
std::to_string(
isOnline
? getEntityCountByType(TypeName)
: OfflineEntity.offlineEntities[TypeName].size()
)
})
);
fm.appendToggle(
"cleanIgnoreActor",
tr("cleaner.form.setting.cleanIgnore"),
false,
tr("cleaner.form.setting.cleanIgnore.tip")
);
fm.sendTo(player, [TypeName, isOnline](
Player& player,
const ll::form::CustomFormResult& rst,
ll::form::FormCancelReason res
) {
if (!rst) return;
bool cleanIgnoreActor =
std::get<uint64>(rst->at("cleanIgnoreActor"));
ConfirmForm(player, isOnline, TypeName, !cleanIgnoreActor);
});
}
void OnlineEntityForm(Player& player) {
auto fm = ll::form::SimpleForm(tr("cleaner.form.runtime.title"), tr("cleaner.form.runtime.content"));
for (auto& entityID : getAllEntityTypes()) {
fm.appendButton(
typeNameToLocString(entityID),
[entityID](Player& player) {
SettingCleanForm(player, true, entityID);
}
);
}
fm.sendTo(player);
}
void updateUnloadEntityMap(const Player& player, bool notice = false) {
if (OfflineEntity.lastUpdate.time_since_epoch().count() == 0)
OfflineEntity.requireUpdate.store(true);
if (OfflineEntity.lastUpdate >=
std::chrono::system_clock::now() - std::chrono::minutes(10)) {
if (notice) player.sendMessage(tr("cleaner.unload.updated.warn"));
return;
}
if (!OfflineEntity.isUpdating.exchange(true) &&
OfflineEntity.requireUpdate) {
std::thread([]() {
UnloadEntityMap offlineEntityMap{};
gmlib::UnloadedActor::foreachUnloadedActor(
[&](gmlib::UnloadedActor& actor) -> bool {
offlineEntityMap[actor.getTypeName()]
.emplace_back(std::move(actor));
return true;
}
);
{
std::lock_guard<std::mutex> lock(
OfflineEntity.offlineEntitiesMutex
);
for (auto& playerID : OfflineEntity.waitedPlayers) {
if (auto pl =
ll::service::getLevel()->getPlayer(playerID))
pl->sendMessage(tr("cleaner.unload.updated.msg"));
}
OfflineEntity.offlineEntities.swap(offlineEntityMap);
}
OfflineEntity.lastUpdate = std::chrono::system_clock::now();
OfflineEntity.isUpdating.store(false);
}).detach();
} else if (notice) {
player.sendMessage(tr("cleaner.unload.update.warn"));
}
}
void OfflineEntityForm(Player& player) {
Cleaner::Entry::getInstance().getSelf().getLogger().info("preload");
updateUnloadEntityMap(player);
auto fm = ll::form::SimpleForm(tr("cleaner.form.unload.title"), tr("cleaner.form.unload.content"));
if (OfflineEntity.lastUpdate !=
std::chrono::system_clock::time_point{}) {
fm.appendLabel(
tr("cleaner.form.unload.updated",{std::format("{:%Y-%m-%d %H:%M}", OfflineEntity.lastUpdate)})
);
}
if (OfflineEntity.isUpdating.load()) {
fm.appendLabel(
tr("cleaner.form.unload.updating")
);
{
std::lock_guard<std::mutex> lock(
OfflineEntity.offlineEntitiesMutex
);
OfflineEntity.waitedPlayers.insert(
player.getOrCreateUniqueID()
);
}
fm.appendButton(tr("cleaner.form.unload.refresh"), [](Player& player) {
OfflineEntityForm(player);
});
} else {
fm.appendButton(tr("cleaner.form.unload.refresh"), [](Player& player) {
OfflineEntity.requireUpdate.store(true);
updateUnloadEntityMap(player, true);
});
}
{
std::lock_guard<std::mutex> lock(
OfflineEntity.offlineEntitiesMutex
);
for (auto& entity : OfflineEntity.offlineEntities) {
fm.appendButton(
typeNameToLocString(entity.first),
[typeName = entity.first](Player& player) {
SettingCleanForm(player, false, typeName);
}
);
}
}
fm.sendTo(player);
}
void MainForm(Player* player) {
auto fm = ll::form::SimpleForm(tr("cleaner.form.main.title"), tr("cleaner.form.main.context"));
fm.appendButton(tr("cleaner.form.main.runtime"), [](Player& player) {
OnlineEntityForm(player);
});
fm.appendButton(tr("cleaner.form.main.unload"), [](Player& player) {
OfflineEntityForm(player);
});
fm.sendTo(*player);
}
+21
View File
@@ -0,0 +1,21 @@
#include "Cleaner.h"
#include "Global.h"
#include "gmlib/mc/world/actor/UnloadedActor.h"
namespace UnloadActorClean {
void cleanUnloadActor() {
auto& config = Cleaner::Entry::getInstance().getConfig();
std::thread([config]() {
gmlib::UnloadedActor::foreachUnloadedActor(
[config](gmlib::UnloadedActor& actor) -> bool {
for (auto& actorname : config.UnloadActorClean.CleanList) {
if (actor.getTypeName() == actorname) {
actor.remove();
}
}
return true;
}
);
}).detach();
}
} // namespace UnloadActorClean
+19 -13
View File
@@ -9,8 +9,6 @@ int playerCount = 0;
std::unordered_map<mce::UUID, bool> voteList; std::unordered_map<mce::UUID, bool> voteList;
static std::shared_ptr<ll::schedule::task::Task<ll::chrono::ServerClock>> mAutoCleanTask;
int getPlayerCount() { int getPlayerCount() {
int result = 0; int result = 0;
ll::service::getLevel()->forEachPlayer([&](Player& pl) -> bool { ll::service::getLevel()->forEachPlayer([&](Player& pl) -> bool {
@@ -53,7 +51,8 @@ void sendVoteForm(Player* pl) {
} }
void checkVote() { void checkVote() {
float percentage = Config->getValue<float>({"VoteClean", "Percentage"}, 50.0f) / 100.0f; auto& config = Cleaner::Entry::getInstance().getConfig();
float percentage = config.VoteClean.Percentage / 100.0f;
int voteCount = 0; int voteCount = 0;
for (auto& key : voteList) { for (auto& key : voteList) {
if (key.second == true) { if (key.second == true) {
@@ -62,18 +61,18 @@ void checkVote() {
} }
float result = ((float)voteCount) / ((float)playerCount); float result = ((float)voteCount) / ((float)playerCount);
if (result >= percentage) { if (result >= percentage) {
if (ConfigFile::mAnnounce) { if (config.Basic.SendBroadcast) {
Helper::broadcastMessage(tr("cleaner.vote.succeed")); Helper::broadcastMessage(tr("cleaner.vote.succeed"));
} }
if (ConfigFile::mSendToast) { if (config.Basic.SendToast) {
Helper::broadcastToast(tr("cleaner.vote.succeed")); Helper::broadcastToast(tr("cleaner.vote.succeed"));
} }
Cleaner::CleanTask(); Cleaner::CleanTask();
} else { } else {
if (ConfigFile::mAnnounce) { if (config.Basic.SendBroadcast) {
Helper::broadcastMessage(tr("cleaner.vote.failed")); Helper::broadcastMessage(tr("cleaner.vote.failed"));
} }
if (ConfigFile::mSendToast) { if (config.Basic.SendToast) {
Helper::broadcastToast(tr("cleaner.vote.failed")); Helper::broadcastToast(tr("cleaner.vote.failed"));
} }
} }
@@ -82,21 +81,28 @@ void checkVote() {
} }
void voteClean(Player* pl) { void voteClean(Player* pl) {
auto& config = Cleaner::Entry::getInstance().getConfig();
voteList.clear(); voteList.clear();
canVote = false; canVote = false;
hasVote = true; hasVote = true;
playerCount = getPlayerCount(); playerCount = getPlayerCount();
if (ConfigFile::mAnnounce) { if (config.Basic.SendBroadcast) {
Helper::broadcastMessage(tr("cleaner.vote.voteMessage", {pl->getRealName()})); Helper::broadcastMessage(tr("cleaner.vote.voteMessage", {pl->getRealName()}));
} }
if (ConfigFile::mSendToast) { if (config.Basic.SendToast) {
Helper::broadcastToast(tr("cleaner.vote.voteMessage", {pl->getRealName()})); Helper::broadcastToast(tr("cleaner.vote.voteMessage", {pl->getRealName()}));
} }
sendVoteForm(pl); sendVoteForm(pl);
auto cooldown = std::chrono::seconds::duration(Config->getValue<int>({"VoteClean", "Cooldown"}, 120)); ll::coro::keepThis([&config]() -> ll::coro::CoroTask<> {
auto waitTime = std::chrono::seconds::duration(Config->getValue<int>({"VoteClean", "CheckDelay"}, 30)); co_await std::chrono::seconds(config.VoteClean.Cooldown);
Cleaner::scheduler.add<DelayTask>(cooldown, [] { canVote = false; }); canVote = true;
Cleaner::scheduler.add<DelayTask>(waitTime, [] { checkVote(); }); co_return;
}).launch(ll::thread::ServerThreadExecutor::getDefault());
ll::coro::keepThis([&config]() -> ll::coro::CoroTask<> {
co_await std::chrono::seconds(config.VoteClean.CheckDelay);
checkVote();
co_return;
}).launch(ll::thread::ServerThreadExecutor::getDefault());
} }
void confirmForm(Player* pl) { void confirmForm(Player* pl) {
+7 -17
View File
@@ -1,29 +1,19 @@
#pragma once #pragma once
#include "Plugin.h" // IWYU pragma: begin_exports
#include <include_all.h> #include "Mod.h"
#include "gmlib/include_ll.h"
#include "ila/include_all.h"
#include <regex> #include <regex>
// IWYU pragma: end_exports
#define S(x) std::to_string(x) #define S(x) std::to_string(x)
extern ll::Logger logger;
extern GMLIB::Files::JsonConfig* Config;
extern GMLIB::Files::I18n::JsonI18n* Language;
extern void RegisterCommands(); extern void RegisterCommands();
extern void initPlugin();
namespace ConfigFile {
extern int mItemDespawnTicks;
extern bool mConsoleLog;
extern bool mAnnounce;
extern bool mSendToast;
extern std::vector<std::string> mIgnoreTags;
} // namespace ConfigFile
namespace Helper { namespace Helper {
extern void broadcastMessage(std::string_view msg); extern void broadcastMessage(std::string_view msg);
extern void broadcastToast(std::string_view msg); extern void broadcastToast(std::string_view msg);
} // namespace Helper } // namespace Helper
extern std::string tr(std::string key, std::vector<std::string> data = {}); extern std::string tr(std::string const& key, std::vector<std::string> const& params = {});
-21
View File
@@ -1,21 +0,0 @@
#include "Config.h"
#include "Global.h"
#include "Language.h"
GMLIB::Files::JsonConfig* Config = nullptr;
GMLIB::Files::I18n::JsonI18n* Language = nullptr;
int commandPermissionLevel = 4;
void initPlugin() {
Config = new GMLIB::Files::JsonConfig("./plugins/Cleaner/config/config.json", defaultConfig);
Config->init();
std::string langPath = "./plugins/Cleaner/language/";
std::string languageCode = Config->getValue<std::string>({"Basic", "Language"}, "en_US");
Language = new GMLIB::Files::I18n::JsonI18n(langPath, languageCode);
Language->updateOrCreateLanguage("en_US", defaultLanguage_en_US);
Language->updateOrCreateLanguage("zh_CN", defaultLanguage_zh_CN);
Language->loadAllLanguages();
Language->chooseLanguage(languageCode);
}
std::string tr(std::string key, std::vector<std::string> data) { return Language->translate(key, data); }
+118 -70
View File
@@ -1,74 +1,122 @@
#pragma once #pragma once
#include "Global.h" #include "Global.h"
std::string defaultLanguage_en_US = R"({ std::string en_US = R"(
"cleaner.info.prefix": "§e§l[Cleaner] §r", cleaner.info.prefix=§e§l[Cleaner] §r
"cleaner.command.cleaner": "Cleaner admin command.", cleaner.command.cleaner=Cleaner admin command.
"cleaner.command.despawnSuccess": "Successfully despawned %1$s entities.", cleaner.command.despawnSuccess=Successfully despawned %1$s entities.
"cleaner.command.error.noTarget": "No targets matched the selector.", cleaner.command.error.noTarget=No targets matched the selector.
"cleaner.command.error.playerOnly": "This command can only be executed by players!", cleaner.command.error.playerOnly=This command can only be executed by players!
"cleaner.command.tps.output": "Current server real-time TPS %1$s §r, average TPS %2$s.", cleaner.command.tps.output=Current server real-time TPS %1$s §r, average TPS %2$s.
"cleaner.command.mspt.output": "Current server MSPT %1$s.", cleaner.command.mspt.output=Current server MSPT %1$s.
"cleaner.command.clean.output": "Clean task successfully initiated!", cleaner.command.clean.output=Clean task successfully initiated!
"cleaner.command.voteclean": "Initiate entity clean vote.", cleaner.command.voteclean=Initiate entity clean vote.
"cleaner.command.despawntime": "Despawn time for items set to %1$s game ticks.", cleaner.command.despawntime=Despawn time for items set to %1$s game ticks.
"cleaner.output.count1": "The system will automatically clean server entities in %1$s seconds!", cleaner.output.count1=The system will automatically clean server entities in %1$s seconds!
"cleaner.output.count2": "Attention! The system will automatically clean server entities in %1$s seconds!", cleaner.output.count2=Attention! The system will automatically clean server entities in %1$s seconds!
"cleaner.output.finish": "Cleaning complete! A total of %1$s entities have been cleaned this time.", cleaner.output.finish=Cleaning complete! A total of %1$s entities have been cleaned this time.
"cleaner.output.opClean": "Admin has enabled server entity cleaning.", cleaner.output.opClean=Admin has enabled server entity cleaning.
"cleaner.output.reload": "Cleaner plugin reloaded. Some configurations may require a server restart to take effect.", cleaner.output.reload=Cleaner mod reloaded. Some configurations may require a server restart to take effect.
"cleaner.output.triggerAutoCleanCount": "Too many server entities detected! There are %1$s cleanable entities currently on the server. Auto-clean program has been activated.", cleaner.output.triggerAutoCleanCount=Too many server entities detected! There are %1$s cleanable entities currently on the server. Auto-clean program has been activated.
"cleaner.output.triggerAutoCleanTps": "Low TPS detected! Server average TPS %1$s\nClean program has been initiated.", cleaner.output.triggerAutoCleanTps=Low TPS detected! Server average TPS %1$s\nClean program has been initiated.
"cleaner.vote.cooldown": "Vote cleaning cooldown...", cleaner.vote.cooldown=Vote cleaning cooldown...
"cleaner.vote.cancel": "Vote canceled!", cleaner.vote.cancel=Vote canceled!
"cleaner.vote.confirmNo": "Think again", cleaner.vote.confirmNo=Think again
"cleaner.vote.confirmOk": "Initiate vote", cleaner.vote.confirmOk=Initiate vote
"cleaner.vote.confirmTubtitle": "Do you want to initiate a clean vote?", cleaner.vote.confirmTubtitle=Do you want to initiate a clean vote?
"cleaner.vote.accept": "You have agreed to entity cleaning.", cleaner.vote.accept=You have agreed to entity cleaning.
"cleaner.vote.deny": "You have declined entity cleaning.", cleaner.vote.deny=You have declined entity cleaning.
"cleaner.vote.no": "Deny", cleaner.vote.no=Deny
"cleaner.vote.ok": "Agree", cleaner.vote.ok=Agree
"cleaner.vote.subtitle": "%1$s lunched a clean vote.\n\n Do you agree to clean server entities now?", cleaner.vote.subtitle=%1$s lunched a clean vote.\n\n Do you agree to clean server entities now?
"cleaner.vote.timeout": "Vote has expired!", cleaner.vote.timeout=Vote has expired!
"cleaner.vote.succeed": "Vote cleaning successful!", cleaner.vote.succeed=Vote cleaning successful!
"cleaner.vote.failed": "Vote cleaning did not passed!", cleaner.vote.failed=Vote cleaning did not passed!
"cleaner.vote.title": "Vote Cleaning", cleaner.vote.title=Vote Cleaning
"cleaner.vote.voted": "You have been voted!", cleaner.vote.voted=You have been voted!
"cleaner.vote.voteMessage": "%1$s lunched a clean vote. If you agree cleaning entities but did not received a form, please type command /voteclean to vote." cleaner.vote.voteMessage=%1$s lunched a clean vote. If you agree cleaning entities but did not received a form, please type command /voteclean to vote.
})"; cleaner.form.main.title=§e§lCleaner§r - Main Menu
cleaner.form.main.context=Select entity category to clean:
cleaner.form.main.runtime=Loaded Entities
cleaner.form.main.unload=Unloaded Entities
cleaner.form.runtime.title=§e§lCleaner§r - Loaded Entity Manager
cleaner.form.runtime.content=Select loaded entity to clean:
cleaner.form.unload.title=§e§lCleaner§r - Unloaded Entity Manager
cleaner.form.unload.content=Select unloaded entity to clean:
cleaner.form.unload.updating=§2Updating...§r\nIf your world contains many entities, this may take §b a long time (~20k entities/min)§r. You can close this panel first; you'll be notified when the update finishes.
cleaner.form.unload.updated=Last updated: §b%1$s§r\n§eData may be out of sync. Click "Refresh" to update. Max 1 refresh per 10 minutes.\n§c§lWarning: Cleaning unloaded entities will force-remove ALL of them, including named, tamed, and ignored ones. Proceed with caution.
cleaner.form.unload.refresh=Refresh
cleaner.unload.updated.msg=§e§lUnloaded entity list§r has finished loading
cleaner.unload.update.warn=§g§lUnloaded entity list is already updating, cannot trigger again§r
cleaner.unload.updated.warn=§g§lUnloaded entity list refresh too frequent (max once per 10 min)§r
cleaner.form.setting.title=§e§lCleaner§r - Clean Options
cleaner.form.setting.content=Deleting entities\n§b%1$s (%2$s)\n§eTotal: %3$s
cleaner.form.setting.cleanIgnore=Force Clean All Entities
cleaner.form.setting.cleanIgnore.tip=§c§lDangerous: §r§gThis will clean ALL entities including named, tamed, and config-ignored ones
cleaner.form.confirm.title=Confirmation
cleaner.form.confirm.warning=§c§lConfirm dangerous operation:§r\nConfirm §c§lforce §rdeletion of\n§b%1$s (%2$s)\n§eTotal: %3$s ?
cleaner.form.confirm.important=§u§lConfirm operation:§r\nConfirm deletion of\n§b%1$s (%2$s)\n§eTotal: %3$s ? This will force-remove ALL including named, tamed, config-ignored, etc. Proceed with caution.
cleaner.form.confirm.confirm=Confirm
cleaner.form.confirm.cancel=Cancel
cleaner.confirm.unload.warn=Form is updating, deletion temporarily unavailable
)";
std::string defaultLanguage_zh_CN = R"({ std::string zh_CN = R"(
"cleaner.toast.title": "§e§lCleaner", cleaner.info.prefix=§e§l[Cleaner] §r
"cleaner.command.cleaner": "Cleaner管理员命令", cleaner.command.cleaner=Cleaner管理员命令
"cleaner.command.despawnSuccess": "已成功清除了 %1$s 个实体", cleaner.command.despawnSuccess= %1$s
"cleaner.command.error.noTarget": "没有与选择器匹配的目标", cleaner.command.error.noTarget=
"cleaner.command.error.playerOnly": "该命令只能由玩家执行!", cleaner.command.error.playerOnly=
"cleaner.command.tps.output": "当前服务器实时TPS %1$s §r,平均TPS %2$s", cleaner.command.tps.output=TPS %1$s §rTPS %2$s
"cleaner.command.mspt.output": "当前服务器实MSPT %1$s", cleaner.command.mspt.output=MSPT %1$s
"cleaner.command.clean.output": "已成功启动清理任务!", cleaner.command.clean.output=
"cleaner.command.voteclean": "发起实体清理投票。", cleaner.command.voteclean=
"cleaner.command.despawntime" : "已成功将物品消失时间设置为 %1$s 游戏刻", cleaner.command.despawntime= %1$s
"cleaner.output.count1": "系统将在 %1$s 秒后自动清理服务器实体!", cleaner.output.count1= %1$s
"cleaner.output.count2": "请注意!系统将在 %1$s 秒后自动清理服务器实体!", cleaner.output.count2= %1$s
"cleaner.output.finish": "清理完成!本次总共清理了 %1$s 个实体。", cleaner.output.finish= %1$s
"cleaner.output.opClean": "管理员启用了服务器实体清理。", cleaner.output.opClean=
"cleaner.output.reload": "已重载Cleaner插件,部分配置可能需要重启服务器才能生效。", cleaner.output.reload=Cleaner插件
"cleaner.output.triggerAutoCleanCount": "检测到服务器实体过多!!当前服务器存在 %1$s 个可清理实体,已启动自动清理程序。", cleaner.output.triggerAutoCleanCount= %1$s
"cleaner.output.triggerAutoCleanTps": "当前服务器TPS过低!!服务器平均TPS %1$s\n系统已启动清理程序", cleaner.output.triggerAutoCleanTps=TPS过低TPS %1$s\n系统已启动清理程序
"cleaner.vote.cooldown": "投票清理正在冷却...", cleaner.vote.cooldown=...
"cleaner.vote.cancel": "投票已取消!", cleaner.vote.cancel=
"cleaner.vote.confirmNo": "我再想想", cleaner.vote.confirmNo=
"cleaner.vote.confirmOk": "发起投票", cleaner.vote.confirmOk=
"cleaner.vote.confirmTubtitle": "你是否要发起投票清理?", cleaner.vote.confirmTubtitle=
"cleaner.vote.accept": "你已同意实体清理。", cleaner.vote.accept=
"cleaner.vote.deny": "你已拒绝实体清理。", cleaner.vote.deny=
"cleaner.vote.no": "拒绝", cleaner.vote.no=
"cleaner.vote.ok": "同意", cleaner.vote.ok=
"cleaner.vote.subtitle": "%1$s 发起了服务器实体清理投票!\n\n你是否同意现在清理服务器实体", cleaner.vote.subtitle=%1$s \n\n你是否同意现在清理服务器实体
"cleaner.vote.timeout": "投票已过期!", cleaner.vote.timeout=
"cleaner.vote.succeed": "投票清理成功!", cleaner.vote.succeed=
"cleaner.vote.failed": "投票清理未通过。", cleaner.vote.failed=
"cleaner.vote.title": "投票清理", cleaner.vote.title=
"cleaner.vote.voted": "你已经投过票了!", cleaner.vote.voted=
"cleaner.vote.voteMessage": "%1$s 发起了服务器实体清理投票!如果同意清理但是未收到表单,请输入命令 /voteclean 投票。拒绝清理请忽略此信息。" cleaner.vote.voteMessage=%1$s /voteclean
})"; cleaner.form.main.title=§e§lCleaner§r
cleaner.form.main.context=:
cleaner.form.main.runtime=
cleaner.form.main.unload=
cleaner.form.runtime.title=§e§lCleaner§r-
cleaner.form.runtime.content=:
cleaner.form.unload.title=§e§lCleaner-
cleaner.form.unload.content=:
cleaner.form.unload.updating=§2...§r\n如果您存档中有较多实体§b较长时间(2w个生物/)§r,
cleaner.form.unload.updated=:§b %1$s \n§e数据有时不同步10\n§c§l注意, , , ,
cleaner.form.unload.refresh=
cleaner.unload.updated.msg=§e§l离线生物列表§r已完成加载
cleaner.unload.update.warn=§g§l离线生物列表正在更新§r
cleaner.unload.updated.warn=§g§l离线生物列表更新过频繁10
cleaner.form.setting.title=§e§lCleaner-
cleaner.form.setting.content=\n§b%1$s (%2$s)\n§e共计: %3$s
cleaner.form.setting.cleanIgnore=
cleaner.form.setting.cleanIgnore.tip=§c§l危险操作: §r§g这会清理包过有命名, ,
cleaner.form.confirm.title=
cleaner.form.confirm.warning=§c§l确认危险操作:§r\n确认§c§l强制§r删除生物\n§b%1$s (%2$s)\n§e共计: %3$s ?
cleaner.form.confirm.important=§u§l确认操作:§r\n确认删除生物\n§b%1$s (%2$s)\n§e共计: %3$s ?, , , ,
cleaner.form.confirm.confirm=
cleaner.form.confirm.cancel=
cleaner.confirm.unload.warn=,
)";
+2 -2
View File
@@ -1,5 +1,5 @@
// This file will make your plugin use LeviLamina's memory operators by default. // This file will make your mod use LeviLamina's memory operators by default.
// This improves the memory management of your plugin and is recommended to use. // This improves the memory management of your mod and is recommended to use.
// You should not modify anything in this file. // You should not modify anything in this file.
#define LL_MEMORY_OPERATORS #define LL_MEMORY_OPERATORS
+64
View File
@@ -0,0 +1,64 @@
#include "Mod.h"
#include "Features/Cleaner.h"
#include "Global.h"
#include "Language.h"
#include "ll/api/utils/ErrorUtils.h"
#include "ll/api/memory/Hook.h"
#include "mc/world/actor/Actor.h"
#include "gmlib/mc/locale/I18nAPI.h"
#include "gmlib/gm/data/TpsStatus.h"
namespace Cleaner {
Entry& Entry::getInstance() {
static Entry instance;
return instance;
}
bool Entry::load() { return true; }
bool Entry::enable() {
(void)gmlib::TpsStatus::getInstance();
mConfig.emplace();
try {
ll::config::loadConfig(*mConfig, getSelf().getConfigDir() / "config.json");
} catch (...) {
ll::error_utils::printCurrentException(getSelf().getLogger());
}
saveConfig();
gmlib::I18nAPI::updateOrCreateLanguageFile(getSelf().getLangDir(), "en_US", en_US);
gmlib::I18nAPI::updateOrCreateLanguageFile(getSelf().getLangDir(), "zh_CN", zh_CN);
gmlib::I18nAPI::loadLanguagesFromDirectory(getSelf().getLangDir());
gmlib::I18nAPI::chooseLanguage(Cleaner::Entry::getInstance().getConfig().language);
Cleaner::ListenEvents();
RegisterCommands();
Cleaner::loadCleaner();
getSelf().getLogger().info("Cleaner Loaded!");
getSelf().getLogger().info("Author: GroupMountain");
getSelf().getLogger().info("Repository: https://github.com/GroupMountain/Cleaner");
return true;
}
bool Entry::disable() {
mConfig.reset();
Cleaner::unloadCleaner();
return true;
}
bool Entry::unload() {
return true;
}
Config& Entry::getConfig() { return mConfig.value(); }
void Entry::saveConfig() { ll::config::saveConfig(*mConfig, getSelf().getConfigDir() / "config.json"); }
} // namespace Cleaner
LL_REGISTER_MOD(Cleaner::Entry, Cleaner::Entry::getInstance());
std::string tr(std::string const& key, std::vector<std::string> const& params) {
return gmlib::I18nAPI::get(key, params);
}
+39
View File
@@ -0,0 +1,39 @@
#pragma once
#include "Config.h"
#include <ll/api/mod/NativeMod.h>
namespace Cleaner {
class Entry {
public:
static Entry& getInstance();
Entry() : mSelf(*ll::mod::NativeMod::current()) {}
[[nodiscard]] ll::mod::NativeMod& getSelf() const { return mSelf; }
/// @return True if the mod is loaded successfully.
bool load();
/// @return True if the mod is enabled successfully.
bool enable();
/// @return True if the mod is disabled successfully.
bool disable();
// TODO: Implement this method if you need to unload the mod.
// /// @return True if the mod is unloaded successfully.
bool unload();
Config& getConfig();
void saveConfig();
private:
ll::mod::NativeMod& mSelf;
std::optional<Config> mConfig;
};
} // namespace Cleaner
-30
View File
@@ -1,30 +0,0 @@
#include "Features/Cleaner.h"
#include "Global.h"
ll::Logger logger("Cleaner");
namespace plugin {
Plugin::Plugin(ll::plugin::NativePlugin& self) : mSelf(self) {
// Code for loading the plugin goes here.
initPlugin();
}
bool Plugin::enable() {
Cleaner::ListenEvents();
RegisterCommands();
Cleaner::loadCleaner();
logger.info("Cleaner Loaded!");
logger.info("Author: GroupMountain");
logger.info("Repository: https://github.com/GroupMountain/Cleaner");
return true;
}
bool Plugin::disable() {
// Code for disabling the plugin goes here.
Cleaner::unloadCleaner();
logger.info("Cleaner Disabled!");
return true;
}
} // namespace plugin
-28
View File
@@ -1,28 +0,0 @@
#pragma once
#include <ll/api/plugin/NativePlugin.h>
namespace plugin {
class Plugin {
public:
explicit Plugin(ll::plugin::NativePlugin& self);
Plugin(Plugin&&) = delete;
Plugin(const Plugin&) = delete;
Plugin& operator=(Plugin&&) = delete;
Plugin& operator=(const Plugin&) = delete;
~Plugin() = default;
/// @return True if the plugin is enabled successfully.
bool enable();
/// @return True if the plugin is disabled successfully.
bool disable();
private:
ll::plugin::NativePlugin& mSelf;
};
} // namespace plugin
+46 -31
View File
@@ -1,46 +1,54 @@
#include "Features/Cleaner.h" #include "Features/Cleaner.h"
#include "Global.h" #include "gmlib/mc/world/Level.h"
#include "gmlib/gm/data/TpsStatus.h"
#include "mc/server/commands/CommandOutput.h"
struct CleanerParam { struct CleanerParam {
enum class Despawn { despawn } despawn; enum class Despawn { despawn } despawn;
enum class Action { tps, clean, reload, mspt } action; enum class Action { gui ,tps, clean, reload, mspt } action;
enum class DespawnTime { despawntime } despawntime; enum class DespawnTime { despawntime } despawntime;
int ticks; int ticks;
CommandSelector<Actor> entity; CommandSelector<Actor> entity;
}; };
void RegCleanerCommand() { void RegCleanerCommand() {
auto& cmd = ll::command::CommandRegistrar::getInstance().getOrCreateCommand( auto& config = Cleaner::Entry::getInstance().getConfig();
Config->getValue<std::string>({"Basic", "Command"}, "cleaner"), auto& cmd = ll::command::CommandRegistrar::getInstance(false).getOrCreateCommand(
config.Basic.Command,
tr("cleaner.command.cleaner"), tr("cleaner.command.cleaner"),
CommandPermissionLevel::GameDirectors CommandPermissionLevel::GameDirectors
); );
cmd.overload<CleanerParam>() cmd.overload<CleanerParam>().required("despawn").required("entity").execute(
.required("despawn") [&](CommandOrigin const& origin, CommandOutput& output, CleanerParam const& param) {
.required("entity")
.execute<[&](CommandOrigin const& origin, CommandOutput& output, CleanerParam const& param) {
auto ens = param.entity.results(origin); auto ens = param.entity.results(origin);
if (ens.empty()) { if (ens.empty()) {
return output.error(tr("cleaner.command.error.noTarget")); return output.error(tr("cleaner.command.error.noTarget"));
} }
for (auto en : ens) { for (auto en : ens) {
/*NO NEED
*Tip: Player don't exit through normal logic when despawn player
*That may cause other plugins crash,causing Levilamina crash
*if (en->hasCategory(ActorCategory::Player)) {
auto pl=(Player*)en;
pl->disconnect("You've been despawn by Cleaner");
continue;
}*/
en->despawn(); en->despawn();
} }
return output.success(tr("cleaner.command.despawnSuccess", {S(ens.size())})); return output.success(tr("cleaner.command.despawnSuccess", {S(ens.size())}));
}>(); }
cmd.overload<CleanerParam>() );
.required("action") cmd.overload<CleanerParam>().required("action").execute(
.execute<[&](CommandOrigin const& origin, CommandOutput& output, CleanerParam const& param) { [&](CommandOrigin const& origin, CommandOutput& output, CleanerParam const& param) {
switch (param.action) { switch (param.action) {
case CleanerParam::Action::clean: { case CleanerParam::Action::clean: {
Cleaner::CleanTask(); Cleaner::CleanTask();
if (ConfigFile::mConsoleLog) { if (Cleaner::Entry::getInstance().getConfig().Basic.ConsoleLog) {
logger.info(tr("cleaner.output.opClean")); ll::io::LoggerRegistry::getInstance().getOrCreate("Cleaner")->info(tr("cleaner.output.opClean"));
} }
if (ConfigFile::mAnnounce) { if (Cleaner::Entry::getInstance().getConfig().Basic.SendBroadcast) {
Helper::broadcastMessage(tr("cleaner.output.opClean")); Helper::broadcastMessage(tr("cleaner.output.opClean"));
} }
if (ConfigFile::mSendToast) { if (Cleaner::Entry::getInstance().getConfig().Basic.SendToast) {
Helper::broadcastToast(tr("cleaner.output.opClean")); Helper::broadcastToast(tr("cleaner.output.opClean"));
} }
return output.success(tr("cleaner.command.clean.output")); return output.success(tr("cleaner.command.clean.output"));
@@ -48,47 +56,54 @@ void RegCleanerCommand() {
case CleanerParam::Action::tps: { case CleanerParam::Action::tps: {
return output.success( return output.success(
tr("cleaner.command.tps.output", tr("cleaner.command.tps.output",
{S(GMLIB_Level::getLevel()->getServerCurrentTps()), {S(gmlib::GMLevel::getInstance()->getServerCurrentTps()),
S(GMLIB_Level::getLevel()->getServerAverageTps())}) S(gmlib::TpsStatus::getInstance().getLevelAverageTps())})
); );
} }
case CleanerParam::Action::mspt: { case CleanerParam::Action::mspt: {
return output.success(tr("cleaner.command.mspt.output", {S(GMLIB_Level::getLevel()->getServerMspt())})); return output.success(
tr("cleaner.command.mspt.output", {S(gmlib::GMLevel::getInstance()->getServerMspt())})
);
} }
case CleanerParam::Action::reload: { case CleanerParam::Action::reload: {
Cleaner::reloadCleaner(); Cleaner::reloadCleaner();
return output.success(tr("cleaner.output.reload")); return output.success(tr("cleaner.output.reload"));
} }
case CleanerParam::Action::gui:
if (origin.getOriginType()==CommandOriginType::Player)
MainForm((Player*)origin.getEntity());
break;
} }
}>(); }
);
cmd.overload<CleanerParam>() cmd.overload<CleanerParam>()
.required("despawntime") .required("despawntime")
.required("ticks") .required("ticks")
.execute<[&](CommandOrigin const& origin, CommandOutput& output, CleanerParam const& param) { .execute([&](CommandOrigin const& origin, CommandOutput& output, CleanerParam const& param) {
ConfigFile::mItemDespawnTicks = param.ticks; Cleaner::Entry::getInstance().getConfig().ItemDespawn.DespawnTime = param.ticks;
Config->setValue({"ItemDespawn", "DespawnTime"}, ConfigFile::mItemDespawnTicks); Cleaner::Entry::getInstance().saveConfig();
return output.success(tr("cleaner.command.despawntime", {S(ConfigFile::mItemDespawnTicks)})); return output.success(tr("cleaner.command.despawntime", {S(param.ticks)}));
}>(); });
}; };
void RegVoteCommand() { void RegVoteCommand() {
auto& cmd = ll::command::CommandRegistrar::getInstance().getOrCreateCommand( auto& cmd = ll::command::CommandRegistrar::getInstance(false).getOrCreateCommand(
Config->getValue<std::string>({"VoteClean", "VoteCleanCommand"}, "voteclean"), Cleaner::Entry::getInstance().getConfig().VoteClean.VoteCleanCommand,
tr("cleaner.command.voteclean"), tr("cleaner.command.voteclean"),
CommandPermissionLevel::Any CommandPermissionLevel::Any
); );
cmd.overload().execute<[&](CommandOrigin const& origin, CommandOutput& output) { cmd.overload().execute([&](CommandOrigin const& origin, CommandOutput& output) {
if (origin.getOriginType() == CommandOriginType::Player) { if (origin.getOriginType() == CommandOriginType::Player) {
auto pl = (Player*)origin.getEntity(); auto pl = (Player*)origin.getEntity();
return VoteClean::voteCommandExecute(pl); return VoteClean::voteCommandExecute(pl);
} }
return output.error(tr("cleaner.command.error.playerOnly")); return output.error(tr("cleaner.command.error.playerOnly"));
}>(); });
} }
void RegisterCommands() { void RegisterCommands() {
RegCleanerCommand(); RegCleanerCommand();
if (Config->getValue<bool>({"VoteClean", "Enabled"}, false)) { if (Cleaner::Entry::getInstance().getConfig().VoteClean.Enabled) {
RegVoteCommand(); RegVoteCommand();
} }
} }
-32
View File
@@ -1,32 +0,0 @@
#include <memory>
#include <ll/api/plugin/NativePlugin.h>
#include "Plugin.h"
namespace plugin {
// The global plugin instance.
std::unique_ptr<Plugin> plugin = nullptr;
extern "C" {
_declspec(dllexport) bool ll_plugin_load(ll::plugin::NativePlugin& self) {
plugin = std::make_unique<plugin::Plugin>(self);
return true;
}
/// @warning Unloading the plugin may cause a crash if the plugin has not released all of its
/// resources. If you are unsure, keep this function commented out.
// _declspec(dllexport) bool ll_plugin_unload(ll::plugin::Plugin&) {
// plugin.reset();
//
// return true;
// }
_declspec(dllexport) bool ll_plugin_enable(ll::plugin::NativePlugin&) { return plugin->enable(); }
_declspec(dllexport) bool ll_plugin_disable(ll::plugin::NativePlugin&) { return plugin->disable(); }
}
} // namespace plugin
+39 -13
View File
@@ -1,28 +1,54 @@
{ {
"format_version": 2, "format_version": 3,
"format_uuid": "289f771f-2c9a-4d73-9f3f-8492495a924d",
"tooth": "github.com/GroupMountain/Cleaner", "tooth": "github.com/GroupMountain/Cleaner",
"version": "0.11.0", "version": "0.16.1",
"info": { "info": {
"name": "Cleaner", "name": "Cleaner",
"description": "A Powerful Entities Cleaning up Plugin for BDS", "description": "A Powerful Entities Cleaning up Mod for BDS",
"author": "GroupMountain",
"source": "github.com/GroupMountain/Cleaner",
"tags": [ "tags": [
"levilamina", "levilamina",
"cleaner", "cleaner",
"gmlib" "gmlib"
] ],
"avatar_url": ""
}, },
"asset_url": "https://github.com/GroupMountain/Cleaner/releases/download/v0.11.0/Cleaner-windows-x64.zip", "variants": [
"dependencies": {
"github.com/GroupMountain/GMLIB": ">=0.10.0"
},
"files": {
"place": [
{ {
"src": "Cleaner/*", "label": "",
"platform": "win-x64",
"dependencies": {
"github.com/GroupMountain/GMLIB-Release": ">=1.9.0",
"github.com/GroupMountain/ModAPI-Release": ">=0.4.0",
"github.com/MiracleForest/iListenAttentively-Release": ">=0.11.0"
},
"assets": [
{
"type": "zip",
"urls": [
"https://github.com/GroupMountain/Cleaner/releases/download/v{{version}}/Cleaner-windows-x64.zip"
],
"placements": [
{
"type": "dir",
"src": "Cleaner/",
"dest": "plugins/Cleaner" "dest": "plugins/Cleaner"
} }
] ]
} }
],
"preserve_files": [],
"remove_files": [],
"scripts": {
"pre_install": [],
"install": [],
"post_install": [],
"pre_pack": [],
"post_pack": [],
"pre_uninstall": [],
"uninstall": [],
"post_uninstall": []
}
}
]
} }
+23 -15
View File
@@ -1,15 +1,20 @@
add_rules("mode.debug", "mode.release", "mode.releasedbg") add_rules("mode.debug", "mode.release", "mode.releasedbg")
add_repositories("liteldev-repo https://github.com/LiteLDev/xmake-repo.git") add_repositories("liteldev-repo https://github.com/LiteLDev/xmake-repo.git")
add_repositories("groupmountain-repo https://github.com/GroupMountain/xmake-repo.git")
add_repositories("miracleforest https://github.com/MiracleForest/xmake-repo")
if not has_config("vs_runtime") then if not has_config("vs_runtime") then
set_runtimes("MD") set_runtimes("MD")
end end
-- Option 1: Use the latest version of LeviLamina released on GitHub. -- Option 1: Use the latest version of LeviLamina released on GitHub.
add_requires("levilamina") add_requires("levilamina 26.10.5", {configs = {target_type = "server"}})
add_requires("levibuildscript")
add_requires("gmlib 26.10.0")
add_requires("ilistenattentively 0.12.0")
target("Cleaner") -- Change this to your plugin name. target("Cleaner") -- Change this to your mod name.
add_cxflags( add_cxflags(
"/EHa", "/EHa",
"/utf-8" "/utf-8"
@@ -17,30 +22,33 @@ target("Cleaner") -- Change this to your plugin name.
add_files( add_files(
"src/**.cpp" "src/**.cpp"
) )
add_links(
"SDK-GMLIB/Lib/GMLIB"
)
add_includedirs( add_includedirs(
"SDK-GMLIB",
"src" "src"
) )
add_packages( add_packages(
"levilamina" "levilamina",
"gmlib",
"ilistenattentively"
) )
add_shflags( add_defines(
"/DELAYLOAD:bedrock_server.dll" "NOMINMAX",
"UNICODE",
"_HAS_CXX23=1"
) )
add_defines("LL_PLAT_S") --TODO: check client compatibility
add_rules("@levibuildscript/linkrule")
set_exceptions("none") set_exceptions("none")
set_kind("shared") set_kind("shared")
set_languages("cxx23") set_languages("cxx20")
set_symbols("debug")
after_build(function (target) after_build(function (target)
local plugin_packer = import("scripts.after_build") local mod_packer = import("scripts.after_build")
local plugin_define = { local mod_define = {
pluginName = target:name(), modName = target:name(),
pluginFile = path.filename(target:targetfile()), modFile = path.filename(target:targetfile()),
} }
plugin_packer.pack_plugin(target,plugin_define) mod_packer.pack_mod(target,mod_define)
end) end)