Compare commits

...

21 Commits

14 changed files with 717 additions and 539 deletions
+12 -5
View File
@@ -7,23 +7,30 @@ jobs:
build: build:
runs-on: windows-latest runs-on: windows-latest
steps: steps:
- name: Checkout repository - uses: actions/checkout@v6
uses: actions/checkout@v2
- uses: xmake-io/github-action-setup-xmake@v1 - uses: xmake-io/github-action-setup-xmake@v1
# with:
# xmake-version: branch@master
- uses: actions/cache@v5
with: with:
xmake-version: 3.0.0 path: |
~/AppData/Local/.xmake
key: xmake-${{ hashFiles('xmake.lua') }}
restore-keys: |
xmake-
- run: | - run: |
xmake repo -u xmake repo -u
- run: | - run: |
xmake f -a x64 -m release -p windows -v -y xmake f -a x64 -m release -p windows -y
- run: | - run: |
xmake -w -y xmake -w -y
- uses: actions/upload-artifact@v4 - uses: actions/upload-artifact@v7
with: with:
name: ${{ github.event.repository.name }}-windows-x64-${{ github.sha }} name: ${{ github.event.repository.name }}-windows-x64-${{ github.sha }}
path: | path: |
+16 -8
View File
@@ -7,23 +7,31 @@ jobs:
build: build:
runs-on: windows-latest runs-on: windows-latest
steps: steps:
- name: Checkout repository - uses: actions/checkout@v6
uses: actions/checkout@v2
- uses: xmake-io/github-action-setup-xmake@v1 - uses: xmake-io/github-action-setup-xmake@v1
# with:
# xmake-version: branch@master
- uses: actions/cache@v5
with: with:
xmake-version: 3.0.0 path: |
~/AppData/Local/.xmake
key: xmake-${{ hashFiles('xmake.lua') }}
restore-keys: |
xmake-
- run: | - run: |
xmake repo -u xmake repo -u
- run: | - run: |
xmake f -a x64 -m release -p windows -v -y xmake f -a x64 -m release -p windows -y
- run: | - run: |
xmake -w -y xmake -w -y
- uses: actions/upload-artifact@v4 - uses: actions/upload-artifact@v7
with: with:
name: ${{ github.event.repository.name }}-windows-x64-${{ github.sha }} name: ${{ github.event.repository.name }}-windows-x64-${{ github.sha }}
path: | path: |
@@ -37,10 +45,10 @@ jobs:
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
- name: Checkout code - name: Checkout code
uses: actions/checkout@v4 uses: actions/checkout@v6
- name: Download Mod - name: Download Mod
uses: actions/download-artifact@v4 uses: actions/download-artifact@v7
with: with:
name: ${{ github.event.repository.name }}-windows-x64-${{ github.sha }} name: ${{ github.event.repository.name }}-windows-x64-${{ github.sha }}
path: artifact path: artifact
@@ -55,7 +63,7 @@ jobs:
working-directory: artifact working-directory: artifact
- name: Create GitHub Release - name: Create GitHub Release
uses: softprops/action-gh-release@v1 uses: softprops/action-gh-release@v3
with: with:
files: | files: |
${{ github.event.repository.name }}-windows-x64.zip ${{ github.event.repository.name }}-windows-x64.zip
+19 -16
View File
@@ -1,11 +1,13 @@
/**
* @returns {string}
*/
const getPluginName = () => { const getPluginName = () => {
// quickjs if (getPluginName.PluginNameCache) return getPluginName.PluginNameCache;
try {
throw new Error("getPluginName"); return getPluginName.PluginNameCache = (() => {
} catch (error) { if (ll.getCurrentPluginInfo) return ll.getCurrentPluginInfo().name;
const error = new Error("getPluginName");
switch (ll.scriptEngineVersion) {
case "QuickJS": {
if (!error.stack) break;
const /** @type {string} */ line = error.stack.trim().split("\n").pop().trim(); const /** @type {string} */ line = error.stack.trim().split("\n").pop().trim();
if (line.includes("<anonymous>")) { if (line.includes("<anonymous>")) {
return line.slice( return line.slice(
@@ -19,33 +21,34 @@ const getPluginName = () => {
line.indexOf("\\") line.indexOf("\\")
); );
} }
break;
} }
case "V8 12.4.254.21-node.21": {
// nodejs
try { try {
const path = require('path'); const selfFileName = require('path').basename(__filename);
const selfFileName = path.basename(__filename);
const pluginDirectory = Object.entries( const pluginDirectory = Object.entries(
require('module')._pathCache require('module')._pathCache
).find( ).find(
([key, _]) => ([key, _]) => key.includes(selfFileName)
key.includes(selfFileName)
)[0].split("\u0000")[1]; )[0].split("\u0000")[1];
const directories = pluginDirectory.split("\\"); const directories = pluginDirectory.split("\\");
const pluginName = directories[directories.findIndex(value => value === "plugins") + 1].trim(); const pluginName = directories[directories.findIndex(value => value === "plugins") + 1].trim();
if (pluginName) return pluginName; if (pluginName) return pluginName;
} catch { } } catch { }
try {
throw new Error("getPluginName"); if (!error.stack) break;
} catch (error) {
const /** @type {string} */ line = error.stack.trim().split("\n").pop().trim(); const /** @type {string} */ line = error.stack.trim().split("\n").pop().trim();
if (line.includes(".js") && /:\d+:\d+$/.test(line)) { if (line.includes(".js") && /:\d+:\d+$/.test(line)) {
const directories = line.split("\\"); const directories = line.split("\\");
const pluginName = directories[directories.findIndex(value => value === "plugins") + 1].trim(); const pluginName = directories[directories.findIndex(value => value === "plugins") + 1].trim();
if (pluginName) return pluginName; if (pluginName) return pluginName;
} }
break;
}
default: break;
} }
return "Unknown"; return "Unknown";
})();
}; };
module.exports = { module.exports = {
+196 -167
View File
@@ -183,19 +183,34 @@ export class Minecraft {
pos: IntPos pos: IntPos
): void; ): void;
/** 启用教育版内容 */ /**
* @deprecated 已删
* 启用教育版内容
*/
static setEducationFeatureEnabled(): void; static setEducationFeatureEnabled(): void;
/** 注册Ability命令 */ /**
* @deprecated 已删
* 注册Ability命令
*/
static registerAbilityCommand(): void; static registerAbilityCommand(): void;
/** 启用Xbox成就 */ /**
* @deprecated 已删
* 启用Xbox成就
*/
static setEnableAchievement(): void; static setEnableAchievement(): void;
/** 信任所有玩家皮肤 */ /**
* @deprecated 已删
* 信任所有玩家皮肤
*/
static setForceTrustSkins(): void; static setForceTrustSkins(): void;
/** 启用资源包双端共存 */ /**
* @deprecated 已删
* 启用资源包双端共存
*/
static enableCoResourcePack(): void; static enableCoResourcePack(): void;
/** 获取存档名称 */ /** 获取存档名称 */
@@ -206,13 +221,19 @@ export class Minecraft {
name: string name: string
): boolean; ): boolean;
/** 设置假种子 */ /**
* @deprecated 已删
* 设置假种子
*/
static setFakeSeed( static setFakeSeed(
/** 要设置的假种子 */ /** 要设置的假种子 */
seed: number | undefined seed: number | undefined
): void; ): void;
/** 启用错误方块清理 */ /**
* @deprecated 已删
* 启用错误方块清理
*/
static setUnknownBlockCleaner(): void; static setUnknownBlockCleaner(): void;
/** 强制生成实体 */ /** 强制生成实体 */
@@ -309,7 +330,10 @@ export class Minecraft {
/** 移除所有虚假列表玩家 */ /** 移除所有虚假列表玩家 */
static removeAllFakeLists(): boolean; static removeAllFakeLists(): boolean;
/** 启用I18n修复 */ /**
* @deprecated 已删
* 启用I18n修复
*/
static setFixI18nEnabled(): void; static setFixI18nEnabled(): void;
/** 保存NBT至文件 */ /** 保存NBT至文件 */
@@ -359,7 +383,7 @@ export class Minecraft {
): string; ): string;
/** 通过附魔ID获取附魔命名空间ID */ /** 通过附魔ID获取附魔命名空间ID */
static getMaxPlayers( static getEnchantTypeNameFromId(
/** 附魔ID */ /** 附魔ID */
id: number id: number
): string | null; ): string | null;
@@ -367,6 +391,14 @@ export class Minecraft {
/** 获取最大玩家数 */ /** 获取最大玩家数 */
static getMaxPlayers(): number; static getMaxPlayers(): number;
/** 设置最大玩家数 */
static setMaxPlayers(
/** 最大玩家数 */
count: number,
/** 是否忽略原版限制 */
ignoreVanillaLimit?: boolean
): void;
/** 玩家是否拥有NBT */ /** 玩家是否拥有NBT */
static hasPlayerNbt( static hasPlayerNbt(
/** 玩家的uuid */ /** 玩家的uuid */
@@ -1046,12 +1078,12 @@ export class UserCache {
/** 获取玩家信息 */ /** 获取玩家信息 */
static getPlayerInfo( static getPlayerInfo(
/** 玩家名 或 xuid 或 uuid */ /** 玩家名 或 xuid 或 uuid 或 serverId 或 uniqueId */
playerIdentifier: string playerIdentifier: string
): { Xuid: String, Uuid: string, Name: string } | null; ): { Xuid: string, Uuid: string, Name: string, ServerId: string, ActorUniqueID: string } | null;
/** 获取所有玩家信息 */ /** 获取所有玩家信息 */
static getAllPlayerInfo(): { Xuid: String; Uuid: string; Name: string; }[] static getAllPlayerInfo(): { Xuid: string, Uuid: string, Name: string, ServerId: string, ActorUniqueID: string }[]
} }
type PacketDataItem = ( type PacketDataItem = (
@@ -1349,161 +1381,158 @@ export class GMLIB_BinaryStream {
export enum ActorType { export enum ActorType {
Undefined = 1, Undefined = 1,
TypeMask = 0b11111111, TypeMask = 255,
None = 0, Mob = 256,
Mob = 1 << 8, PathfinderMob = 768,
PathfinderMob = 1 << 9 | Mob, Monster = 2816,
UnknownType = 1 << 10, Animal = 4864,
Monster = 1 << 11 | PathfinderMob, TamableAnimal = 21248,
Animal = 1 << 12 | PathfinderMob, Ambient = 33024,
WaterAnimal = 1 << 13 | PathfinderMob, UndeadMob = 68352,
TamableAnimal = 1 << 14 | Animal, ZombieMonster = 199424,
Ambient = 1 << 15 | Mob, Arthropod = 264960,
UndeadMob = 1 << 16 | Monster, Minecart = 524288,
ZombieMonster = 1 << 17 | UndeadMob, SkeletonMonster = 1116928,
Arthropod = 1 << 18 | Monster, EquineAnimal = 2118400,
Minecart = 1 << 19, Projectile = 4194304,
SkeletonMonster = 1 << 20 | UndeadMob, AbstractArrow = 8388608,
EquineAnimal = 1 << 21 | TamableAnimal, WaterAnimal = 8960,
Projectile = 1 << 22, VillagerBase = 16777984,
AbstractArrow = 1 << 23, Chicken = 4874,
VillagerBase = 1 << 24 | PathfinderMob, Cow = 4875,
Pig = 4876,
Chicken = 10 | Animal, Sheep = 4877,
Cow = 11 | Animal, Wolf = 21262,
Pig = 12 | Animal, Villager = 16777999,
Sheep = 13 | Animal, MushroomCow = 4880,
Wolf = 14 | TamableAnimal, Squid = 8977,
Villager = 15 | VillagerBase, Rabbit = 4882,
MushroomCow = 16 | Animal, Bat = 33043,
Squid = 17 | WaterAnimal, IronGolem = 788,
Rabbit = 18 | Animal, SnowGolem = 789,
Bat = 19 | Ambient, Ocelot = 21270,
IronGolem = 20 | PathfinderMob, Horse = 2118423,
SnowGolem = 21 | PathfinderMob, PolarBear = 4892,
Ocelot = 22 | TamableAnimal, Llama = 4893,
Horse = 23 | EquineAnimal, Parrot = 21278,
Donkey = 24 | EquineAnimal, Dolphin = 8991,
Mule = 25 | EquineAnimal, Donkey = 2118424,
SkeletonHorse = 26 | EquineAnimal | UndeadMob, Mule = 2118425,
ZombieHorse = 27 | EquineAnimal | UndeadMob, SkeletonHorse = 2186010,
PolarBear = 28 | Animal, ZombieHorse = 2186011,
Llama = 29 | Animal, Zombie = 199456,
Parrot = 30 | TamableAnimal, Creeper = 2849,
Dolphin = 31 | WaterAnimal, Skeleton = 1116962,
Zombie = 32 | ZombieMonster, Spider = 264995,
Creeper = 33 | Monster, PigZombie = 68388,
Skeleton = 34 | SkeletonMonster, Slime = 2853,
Spider = 35 | Arthropod, EnderMan = 2854,
PigZombie = 36 | UndeadMob, Silverfish = 264999,
Slime = 37 | Monster, CaveSpider = 265000,
EnderMan = 38 | Monster, Ghast = 2857,
Silverfish = 39 | Arthropod, LavaSlime = 2858,
CaveSpider = 40 | Arthropod, Blaze = 2859,
Ghast = 41 | Monster, ZombieVillager = 199468,
LavaSlime = 42 | Monster, Witch = 2861,
Blaze = 43 | Monster, Stray = 1116974,
ZombieVillager = 44 | ZombieMonster, Husk = 199471,
Witch = 45 | Monster, WitherSkeleton = 1116976,
Stray = 46 | SkeletonMonster, Guardian = 2865,
Husk = 47 | ZombieMonster, ElderGuardian = 2866,
WitherSkeleton = 48 | SkeletonMonster, Npc = 307,
Guardian = 49 | Monster, WitherBoss = 68404,
ElderGuardian = 50 | Monster, Dragon = 2869,
Npc = 51 | Mob, Shulker = 2870,
WitherBoss = 52 | UndeadMob, Endermite = 265015,
Dragon = 53 | Monster, Agent = 312,
Shulker = 54 | Monster, Vindicator = 2873,
Endermite = 55 | Arthropod, Phantom = 68410,
Agent = 56 | Mob, IllagerBeast = 2875,
Vindicator = 57 | Monster, ArmorStand = 317,
Phantom = 58 | UndeadMob, TripodCamera = 318,
IllagerBeast = 59 | Monster, Player = 319,
UNUSED60 = 60, ItemEntity = 64,
ArmorStand = 61 | Mob, PrimedTnt = 65,
TripodCamera = 62 | Mob, FallingBlock = 66,
Player = 63 | Mob, MovingBlock = 67,
ItemEntity = 64 | None, ExperiencePotion = 4194372,
PrimedTnt = 65 | None, Experience = 69,
FallingBlock = 66 | None, EyeOfEnder = 70,
MovingBlock = 67 | None, EnderCrystal = 71,
ExperiencePotion = 68 | Projectile, FireworksRocket = 72,
Experience = 69 | None, Trident = 12582985,
EyeOfEnder = 70 | None, Turtle = 4938,
EnderCrystal = 71 | None, Cat = 21323,
FireworksRocket = 72 | None, ShulkerBullet = 4194380,
Trident = 73 | Projectile | AbstractArrow, FishingHook = 77,
Turtle = 74 | Animal, Chalkboard = 78,
Cat = 75 | TamableAnimal, DragonFireball = 4194383,
ShulkerBullet = 76 | Projectile, Arrow = 12582992,
FishingHook = 77 | None, Snowball = 4194385,
Chalkboard = 78 | None, ThrownEgg = 4194386,
DragonFireball = 79 | Projectile, Painting = 83,
Arrow = 80 | Projectile | AbstractArrow, LargeFireball = 4194389,
Snowball = 81 | Projectile, ThrownPotion = 4194390,
ThrownEgg = 82 | Projectile, Enderpearl = 4194391,
Painting = 83 | None, LeashKnot = 88,
MinecartRideable = 84 | Minecart, WitherSkull = 4194393,
LargeFireball = 85 | Projectile, BoatRideable = 90,
ThrownPotion = 86 | Projectile, WitherSkullDangerous = 4194395,
Enderpearl = 87 | Projectile, LightningBolt = 93,
LeashKnot = 88 | None, SmallFireball = 4194398,
WitherSkull = 89 | Projectile, AreaEffectCloud = 95,
BoatRideable = 90 | None, LingeringPotion = 4194405,
WitherSkullDangerous = 91 | Projectile, LlamaSpit = 4194406,
UNUSED92 = 92, EvocationFang = 4194407,
LightningBolt = 93 | None, EvocationIllager = 2920,
SmallFireball = 94 | Projectile, Vex = 2921,
AreaEffectCloud = 95 | None, MinecartRideable = 524372,
MinecartHopper = 96 | Minecart, MinecartHopper = 524384,
MinecartTNT = 97 | Minecart, MinecartTNT = 524385,
MinecartChest = 98 | Minecart, MinecartChest = 524386,
MinecartFurnace = 99 | Minecart, MinecartFurnace = 524387,
MinecartCommandBlock = 100 | Minecart, MinecartCommandBlock = 524388,
LingeringPotion = 101 | Projectile, IceBomb = 4194410,
LlamaSpit = 102 | Projectile, Balloon = 107,
EvocationFang = 103 | Projectile, Pufferfish = 9068,
EvocationIllager = 104 | Monster, Salmon = 9069,
Vex = 105 | Monster, Drowned = 199534,
IceBomb = 106 | Projectile, Tropicalfish = 9071,
Balloon = 107 | None, Fish = 9072,
Pufferfish = 108 | WaterAnimal, Panda = 4977,
Salmon = 109 | WaterAnimal, Pillager = 2930,
Drowned = 110 | ZombieMonster, VillagerV2 = 16778099,
Tropicalfish = 111 | WaterAnimal, ZombieVillagerV2 = 199540,
Fish = 112 | WaterAnimal, Shield = 117,
Panda = 113 | Animal, WanderingTrader = 886,
Pillager = 114 | Monster, Lectern = 119,
VillagerV2 = 115 | VillagerBase, ElderGuardianGhost = 2936,
ZombieVillagerV2 = 116 | ZombieMonster, Fox = 4985,
Shield = 117 | None, Bee = 378,
WanderingTrader = 118 | PathfinderMob, Piglin = 379,
Lectern = 119 | None, Hoglin = 4988,
ElderGuardianGhost = 120 | Monster, Strider = 4989,
Fox = 121 | Animal, Zoglin = 68478,
Bee = 122 | Mob, PiglinBrute = 383,
Piglin = 123 | Mob, Goat = 4992,
Hoglin = 124 | Animal, GlowSquid = 9089,
Strider = 125 | Animal, Axolotl = 4994,
Zoglin = 126 | UndeadMob, Warden = 2947,
PiglinBrute = 127 | Mob, Frog = 4996,
Goat = 128 | Animal, Tadpole = 9093,
GlowSquid = 129 | WaterAnimal, Allay = 390,
Axolotl = 130 | Animal, ChestBoatRideable = 218,
Warden = 131 | Monster, TraderLlama = 5021,
Frog = 132 | Animal, Camel = 5002,
Tadpole = 133 | WaterAnimal, Sniffer = 5003,
Allay = 134 | Mob, Breeze = 2956,
ChestBoatRideable = 136 | BoatRideable, BreezeWindChargeProjectile = 4194445,
TraderLlama = 137 | Llama, Armadillo = 5006,
Camel = 138 | Animal, WindChargeProjectile = 4194447,
Sniffer = 139 | Animal, Bogged = 1117072,
Breeze = 140 | Monster, OminousItemSpawner = 145,
BreezeWindChargeProjectile = 141 | Projectile, Creaking = 2962,
Armadillo = 142 | Animal, HappyGhast = 5011,
WindChargeProjectile = 143 | Projectile,
Bogged = 144 | SkeletonMonster,
OminousItemSpawner = 145
} }
interface Player { interface Player {
+178 -166
View File
@@ -216,16 +216,18 @@ const GMLIB_API = {
getXuidByName: ll.imports("GMLIB_API", "getXuidByName"), getXuidByName: ll.imports("GMLIB_API", "getXuidByName"),
/** 根据名字获取uuid @type {function(string):string} */ /** 根据名字获取uuid @type {function(string):string} */
getUuidByName: ll.imports("GMLIB_API", "getUuidByName"), getUuidByName: ll.imports("GMLIB_API", "getUuidByName"),
/** 获取所有已记录的玩家信息 @type {function():Array.<{"Uuid":string,"Xuid":string,"Name":string}>} */ /** 根据信息获取玩家信息 @type {function():{"Uuid":string,"Xuid":string,"Name":string,"ServerId":string,"ActorUniqueID":string}} */
getPlayerInfo: ll.imports("GMLIB_API", "getPlayerInfo"),
/** 获取所有已记录的玩家信息 @type {function():Array.<{"Uuid":string,"Xuid":string,"Name":string,"ServerId":string,"ActorUniqueID":string}>} */
getAllPlayerInfo: ll.imports("GMLIB_API", "getAllPlayerInfo"), getAllPlayerInfo: ll.imports("GMLIB_API", "getAllPlayerInfo"),
/** 获取方块RuntimeId @type {function(string,number):number} */ /** 获取方块RuntimeId @type {function(string,number):number} */
getBlockRuntimeId: ll.imports("GMLIB_API", "getBlockRuntimeId"), getBlockRuntimeId: ll.imports("GMLIB_API", "getBlockRuntimeId"),
/** 添加虚假列表玩家 @type {function(string,string):boolean} */ /** 添加虚假列表玩家 @type {function(string,string):boolean} */
addFakeList: ll.imports("GMLIB_API", "addFakeList"), addFakeList: ll.imports("GMLib_ServerAPI", "addFakeList"),
/** 删除虚假列表玩家 @type {function(string):boolean} */ /** 删除虚假列表玩家 @type {function(string):boolean} */
removeFakeList: ll.imports("GMLIB_API", "removeFakeList"), removeFakeList: ll.imports("GMLib_ServerAPI", "removeFakeList"),
/** 删除所有虚假列表玩家 @type {function():void} */ /** 删除所有虚假列表玩家 @type {function():void} */
removeAllFakeLists: ll.imports("GMLIB_API", "removeAllFakeList"), removeAllFakeLists: ll.imports("GMLib_ServerAPI", "removeAllFakeList"),
/** 启用I18n修复 @type {function():void} */ /** 启用I18n修复 @type {function():void} */
setFixI18nEnabled: ll.imports("GMLib_ModAPI", "setFixI18nEnabled"), setFixI18nEnabled: ll.imports("GMLib_ModAPI", "setFixI18nEnabled"),
/** 获取方块翻译键名 @type {function(Block):string} */ /** 获取方块翻译键名 @type {function(Block):string} */
@@ -280,6 +282,8 @@ const GMLIB_API = {
getEnchantTypeNameFromId: ll.imports("GMLIB_API", "getEnchantTypeNameFromId"), getEnchantTypeNameFromId: ll.imports("GMLIB_API", "getEnchantTypeNameFromId"),
/** 获取最大玩家数 @type {function():number} */ /** 获取最大玩家数 @type {function():number} */
getMaxPlayers: ll.imports("GMLib_ServerAPI", "getMaxPlayers"), getMaxPlayers: ll.imports("GMLib_ServerAPI", "getMaxPlayers"),
/** 获取最大玩家数 @type {function(number,boolean):void} */
setMaxPlayers: ll.imports("GMLib_ServerAPI", "setMaxPlayers"),
/** 丢出玩家背包内物品 @type {function(Player,Item,boolean):boolean} */ /** 丢出玩家背包内物品 @type {function(Player,Item,boolean):boolean} */
dropPlayerItem: ll.imports("GMLIB_API", "dropPlayerItem"), dropPlayerItem: ll.imports("GMLIB_API", "dropPlayerItem"),
/** 获取玩家的RuntimeId @type {function(Player):number} */ /** 获取玩家的RuntimeId @type {function(Player):number} */
@@ -324,7 +328,7 @@ const GMLIB_API = {
getItemCategoryName: ll.imports("GMLIB_API", "getItemCategoryName"), getItemCategoryName: ll.imports("GMLIB_API", "getItemCategoryName"),
/** 获取物品的命名 @type {function(Item):string} */ /** 获取物品的命名 @type {function(Item):string} */
getItemCustomName: ll.imports("GMLIB_API", "getItemCustomName"), getItemCustomName: ll.imports("GMLIB_API", "getItemCustomName"),
/** 获取物品BUFF效果名称 @type {function(Item):string} */ /** 获取物品BUFF效果名称 @type {function(Item,boolean):string} */
getItemEffecName: ll.imports("GMLIB_API", "getItemEffecName"), getItemEffecName: ll.imports("GMLIB_API", "getItemEffecName"),
/** 物品是否为食物 @type {function(Item):boolean} */ /** 物品是否为食物 @type {function(Item):boolean} */
itemIsFood: ll.imports("GMLIB_API", "itemIsFood"), itemIsFood: ll.imports("GMLIB_API", "itemIsFood"),
@@ -1113,6 +1117,15 @@ class Minecraft {
return GMLIB_API.getMaxPlayers(); return GMLIB_API.getMaxPlayers();
} }
/**
* 设置最大玩家数量
* @param {number} count 最大玩家数量
* @param {boolean} [ignoreVanillaLimit=false] 是否忽略原版限制
*/
static setMaxPlayers(count, ignoreVanillaLimit = false) {
return GMLIB_API.setMaxPlayers(count, ignoreVanillaLimit);
}
/** /**
* 玩家是否拥有NBT * 玩家是否拥有NBT
* @param {string} uuid 玩家的uuid * @param {string} uuid 玩家的uuid
@@ -2096,16 +2109,17 @@ class UserCache {
/** /**
* 获取玩家信息 * 获取玩家信息
* @param {string} playerIdentifier 玩家的 xuid 或 uuid 或 名称 * @param {string} playerIdentifier 玩家的 xuid 或 uuid 或 realName 或 serverId 或 uniqueId
* @returns {{Xuid: String, Uuid: string, Name: string}?} 玩家信息 * @returns {{Xuid: string, Uuid: string, Name: string, ServerId: string, ActorUniqueID: string}?} 玩家信息
*/ */
static getPlayerInfo(playerIdentifier) { static getPlayerInfo(playerIdentifier) {
return GMLIB_API.getAllPlayerInfo().find(Info => Object.keys(Info).some(InfoKey => Info[InfoKey] === playerIdentifier)); const result = GMLIB_API.getPlayerInfo(playerIdentifier)
return Object.keys(result).length === 0 ? null : result;
} }
/** /**
* 获取所有玩家信息 * 获取所有玩家信息
* @returns {Array.<{Xuid: String, Uuid: string, Name: string}>} 包含所有玩家信息的数组 * @returns {Array.<{Xuid: string, Uuid: string, Name: string, ServerId: string, ActorUniqueID: string}>} 包含所有玩家信息的数组
*/ */
static getAllPlayerInfo() { static getAllPlayerInfo() {
return GMLIB_API.getAllPlayerInfo(); return GMLIB_API.getAllPlayerInfo();
@@ -2990,10 +3004,11 @@ LLSE_Item.prototype.getCustomName =
LLSE_Item.prototype.getEffecName = LLSE_Item.prototype.getEffecName =
/** /**
* 获取物品的BUFF效果名称 * 获取物品的BUFF效果名称
* @param {boolean} playerIsCreative 玩家是否为创造模式
* @returns {string} * @returns {string}
*/ */
function () { function (playerIsCreative = false) {
return GMLIB_API.getItemEffecName(this); return GMLIB_API.getItemEffecName(this, playerIsCreative);
}; };
LLSE_Item.prototype.isFood = LLSE_Item.prototype.isFood =
@@ -3119,7 +3134,7 @@ LLSE_Entity.prototype.getAllEffectsInfo =
* @returns {{Id: number, Amplifier: number, Duration: number, DurationEasy: number, DurationNormal: number, DurationHard: number, Ambient: boolean, ShowParticles: boolean}[]} * @returns {{Id: number, Amplifier: number, Duration: number, DurationEasy: number, DurationNormal: number, DurationHard: number, Ambient: boolean, ShowParticles: boolean}[]}
*/ */
function () { function () {
return this.getAllEffects().map(effectId => this.getEffectInfo(effectId)); return this.getAllEffects().map(effectId => this.getEffectInfo(effectId)).filter(effectId => effectId);
}; };
LLSE_Entity.prototype.isType = LLSE_Entity.prototype.isType =
@@ -3153,161 +3168,158 @@ LLSE_Entity.prototype.getEntityTypeId =
const ActorType = Object.freeze({ const ActorType = Object.freeze({
Undefined: 1, Undefined: 1,
TypeMask: 0b11111111, TypeMask: 255,
None: 0, Mob: 256,
Mob: 1 << 8, PathfinderMob: 768,
PathfinderMob: 1 << 9 | this.Mob, Monster: 2816,
UnknownType: 1 << 10, Animal: 4864,
Monster: 1 << 11 | this.PathfinderMob, TamableAnimal: 21248,
Animal: 1 << 12 | this.PathfinderMob, Ambient: 33024,
WaterAnimal: 1 << 13 | this.PathfinderMob, UndeadMob: 68352,
TamableAnimal: 1 << 14 | this.Animal, ZombieMonster: 199424,
Ambient: 1 << 15 | this.Mob, Arthropod: 264960,
UndeadMob: 1 << 16 | this.Monster, Minecart: 524288,
ZombieMonster: 1 << 17 | this.UndeadMob, SkeletonMonster: 1116928,
Arthropod: 1 << 18 | this.Monster, EquineAnimal: 2118400,
Minecart: 1 << 19, Projectile: 4194304,
SkeletonMonster: 1 << 20 | this.UndeadMob, AbstractArrow: 8388608,
EquineAnimal: 1 << 21 | this.TamableAnimal, WaterAnimal: 8960,
Projectile: 1 << 22, VillagerBase: 16777984,
AbstractArrow: 1 << 23, Chicken: 4874,
VillagerBase: 1 << 24 | this.PathfinderMob, Cow: 4875,
Pig: 4876,
Chicken: 10 | this.Animal, Sheep: 4877,
Cow: 11 | this.Animal, Wolf: 21262,
Pig: 12 | this.Animal, Villager: 16777999,
Sheep: 13 | this.Animal, MushroomCow: 4880,
Wolf: 14 | this.TamableAnimal, Squid: 8977,
Villager: 15 | this.VillagerBase, Rabbit: 4882,
MushroomCow: 16 | this.Animal, Bat: 33043,
Squid: 17 | this.WaterAnimal, IronGolem: 788,
Rabbit: 18 | this.Animal, SnowGolem: 789,
Bat: 19 | this.Ambient, Ocelot: 21270,
IronGolem: 20 | this.PathfinderMob, Horse: 2118423,
SnowGolem: 21 | this.PathfinderMob, PolarBear: 4892,
Ocelot: 22 | this.TamableAnimal, Llama: 4893,
Horse: 23 | this.EquineAnimal, Parrot: 21278,
Donkey: 24 | this.EquineAnimal, Dolphin: 8991,
Mule: 25 | this.EquineAnimal, Donkey: 2118424,
SkeletonHorse: 26 | this.EquineAnimal | this.UndeadMob, Mule: 2118425,
ZombieHorse: 27 | this.EquineAnimal | this.UndeadMob, SkeletonHorse: 2186010,
PolarBear: 28 | this.Animal, ZombieHorse: 2186011,
Llama: 29 | this.Animal, Zombie: 199456,
Parrot: 30 | this.TamableAnimal, Creeper: 2849,
Dolphin: 31 | this.WaterAnimal, Skeleton: 1116962,
Zombie: 32 | this.ZombieMonster, Spider: 264995,
Creeper: 33 | this.Monster, PigZombie: 68388,
Skeleton: 34 | this.SkeletonMonster, Slime: 2853,
Spider: 35 | this.Arthropod, EnderMan: 2854,
PigZombie: 36 | this.UndeadMob, Silverfish: 264999,
Slime: 37 | this.Monster, CaveSpider: 265000,
EnderMan: 38 | this.Monster, Ghast: 2857,
Silverfish: 39 | this.Arthropod, LavaSlime: 2858,
CaveSpider: 40 | this.Arthropod, Blaze: 2859,
Ghast: 41 | this.Monster, ZombieVillager: 199468,
LavaSlime: 42 | this.Monster, Witch: 2861,
Blaze: 43 | this.Monster, Stray: 1116974,
ZombieVillager: 44 | this.ZombieMonster, Husk: 199471,
Witch: 45 | this.Monster, WitherSkeleton: 1116976,
Stray: 46 | this.SkeletonMonster, Guardian: 2865,
Husk: 47 | this.ZombieMonster, ElderGuardian: 2866,
WitherSkeleton: 48 | this.SkeletonMonster, Npc: 307,
Guardian: 49 | this.Monster, WitherBoss: 68404,
ElderGuardian: 50 | this.Monster, Dragon: 2869,
Npc: 51 | this.Mob, Shulker: 2870,
WitherBoss: 52 | this.UndeadMob, Endermite: 265015,
Dragon: 53 | this.Monster, Agent: 312,
Shulker: 54 | this.Monster, Vindicator: 2873,
Endermite: 55 | this.Arthropod, Phantom: 68410,
Agent: 56 | this.Mob, IllagerBeast: 2875,
Vindicator: 57 | this.Monster, ArmorStand: 317,
Phantom: 58 | this.UndeadMob, TripodCamera: 318,
IllagerBeast: 59 | this.Monster, Player: 319,
UNUSED60: 60, ItemEntity: 64,
ArmorStand: 61 | this.Mob, PrimedTnt: 65,
TripodCamera: 62 | this.Mob, FallingBlock: 66,
Player: 63 | this.Mob, MovingBlock: 67,
ItemEntity: 64 | this.None, ExperiencePotion: 4194372,
PrimedTnt: 65 | this.None, Experience: 69,
FallingBlock: 66 | this.None, EyeOfEnder: 70,
MovingBlock: 67 | this.None, EnderCrystal: 71,
ExperiencePotion: 68 | this.Projectile, FireworksRocket: 72,
Experience: 69 | this.None, Trident: 12582985,
EyeOfEnder: 70 | this.None, Turtle: 4938,
EnderCrystal: 71 | this.None, Cat: 21323,
FireworksRocket: 72 | this.None, ShulkerBullet: 4194380,
Trident: 73 | this.Projectile | this.AbstractArrow, FishingHook: 77,
Turtle: 74 | this.Animal, Chalkboard: 78,
Cat: 75 | this.TamableAnimal, DragonFireball: 4194383,
ShulkerBullet: 76 | this.Projectile, Arrow: 12582992,
FishingHook: 77 | this.None, Snowball: 4194385,
Chalkboard: 78 | this.None, ThrownEgg: 4194386,
DragonFireball: 79 | this.Projectile, Painting: 83,
Arrow: 80 | this.Projectile | this.AbstractArrow, LargeFireball: 4194389,
Snowball: 81 | this.Projectile, ThrownPotion: 4194390,
ThrownEgg: 82 | this.Projectile, Enderpearl: 4194391,
Painting: 83 | this.None, LeashKnot: 88,
MinecartRideable: 84 | this.Minecart, WitherSkull: 4194393,
LargeFireball: 85 | this.Projectile, BoatRideable: 90,
ThrownPotion: 86 | this.Projectile, WitherSkullDangerous: 4194395,
Enderpearl: 87 | this.Projectile, LightningBolt: 93,
LeashKnot: 88 | this.None, SmallFireball: 4194398,
WitherSkull: 89 | this.Projectile, AreaEffectCloud: 95,
BoatRideable: 90 | this.None, LingeringPotion: 4194405,
WitherSkullDangerous: 91 | this.Projectile, LlamaSpit: 4194406,
UNUSED92: 92, EvocationFang: 4194407,
LightningBolt: 93 | this.None, EvocationIllager: 2920,
SmallFireball: 94 | this.Projectile, Vex: 2921,
AreaEffectCloud: 95 | this.None, MinecartRideable: 524372,
MinecartHopper: 96 | this.Minecart, MinecartHopper: 524384,
MinecartTNT: 97 | this.Minecart, MinecartTNT: 524385,
MinecartChest: 98 | this.Minecart, MinecartChest: 524386,
MinecartFurnace: 99 | this.Minecart, MinecartFurnace: 524387,
MinecartCommandBlock: 100 | this.Minecart, MinecartCommandBlock: 524388,
LingeringPotion: 101 | this.Projectile, IceBomb: 4194410,
LlamaSpit: 102 | this.Projectile, Balloon: 107,
EvocationFang: 103 | this.Projectile, Pufferfish: 9068,
EvocationIllager: 104 | this.Monster, Salmon: 9069,
Vex: 105 | this.Monster, Drowned: 199534,
IceBomb: 106 | this.Projectile, Tropicalfish: 9071,
Balloon: 107 | this.None, Fish: 9072,
Pufferfish: 108 | this.WaterAnimal, Panda: 4977,
Salmon: 109 | this.WaterAnimal, Pillager: 2930,
Drowned: 110 | this.ZombieMonster, VillagerV2: 16778099,
Tropicalfish: 111 | this.WaterAnimal, ZombieVillagerV2: 199540,
Fish: 112 | this.WaterAnimal, Shield: 117,
Panda: 113 | this.Animal, WanderingTrader: 886,
Pillager: 114 | this.Monster, Lectern: 119,
VillagerV2: 115 | this.VillagerBase, ElderGuardianGhost: 2936,
ZombieVillagerV2: 116 | this.ZombieMonster, Fox: 4985,
Shield: 117 | this.None, Bee: 378,
WanderingTrader: 118 | this.PathfinderMob, Piglin: 379,
Lectern: 119 | this.None, Hoglin: 4988,
ElderGuardianGhost: 120 | this.Monster, Strider: 4989,
Fox: 121 | this.Animal, Zoglin: 68478,
Bee: 122 | this.Mob, PiglinBrute: 383,
Piglin: 123 | this.Mob, Goat: 4992,
Hoglin: 124 | this.Animal, GlowSquid: 9089,
Strider: 125 | this.Animal, Axolotl: 4994,
Zoglin: 126 | this.UndeadMob, Warden: 2947,
PiglinBrute: 127 | this.Mob, Frog: 4996,
Goat: 128 | this.Animal, Tadpole: 9093,
GlowSquid: 129 | this.WaterAnimal, Allay: 390,
Axolotl: 130 | this.Animal, ChestBoatRideable: 218,
Warden: 131 | this.Monster, TraderLlama: 5021,
Frog: 132 | this.Animal, Camel: 5002,
Tadpole: 133 | this.WaterAnimal, Sniffer: 5003,
Allay: 134 | this.Mob, Breeze: 2956,
ChestBoatRideable: 136 | this.BoatRideable, BreezeWindChargeProjectile: 4194445,
TraderLlama: 137 | this.Llama, Armadillo: 5006,
Camel: 138 | this.Animal, WindChargeProjectile: 4194447,
Sniffer: 139 | this.Animal, Bogged: 1117072,
Breeze: 140 | this.Monster,
BreezeWindChargeProjectile: 141 | this.Projectile,
Armadillo: 142 | this.Animal,
WindChargeProjectile: 143 | this.Projectile,
Bogged: 144 | this.SkeletonMonster,
OminousItemSpawner: 145, OminousItemSpawner: 145,
Creaking: 2962,
HappyGhast: 5011,
}); });
module.exports = { module.exports = {
+19 -13
View File
@@ -1,10 +1,15 @@
/// <reference path='d:/dts/dts/helperlib/src/index.d.ts'/> /// <reference path='d:/dts/dts/helperlib/src/index.d.ts'/>
const getPluginName = () => { const getPluginName = () => {
// quickjs if (getPluginName.PluginNameCache) return getPluginName.PluginNameCache;
try {
throw new Error("getPluginName"); return getPluginName.PluginNameCache = (() => {
} catch (error) { if (ll.getCurrentPluginInfo) return ll.getCurrentPluginInfo().name;
const error = new Error("getPluginName");
switch (ll.scriptEngineVersion) {
case "QuickJS": {
if (!error.stack) break;
const /** @type {string} */ line = error.stack.trim().split("\n").pop().trim(); const /** @type {string} */ line = error.stack.trim().split("\n").pop().trim();
if (line.includes("<anonymous>")) { if (line.includes("<anonymous>")) {
return line.slice( return line.slice(
@@ -18,33 +23,34 @@ const getPluginName = () => {
line.indexOf("\\") line.indexOf("\\")
); );
} }
break;
} }
case "V8 12.4.254.21-node.21": {
// nodejs
try { try {
const path = require('path'); const selfFileName = require('path').basename(__filename);
const selfFileName = path.basename(__filename);
const pluginDirectory = Object.entries( const pluginDirectory = Object.entries(
require('module')._pathCache require('module')._pathCache
).find( ).find(
([key, _]) => ([key, _]) => key.includes(selfFileName)
key.includes(selfFileName)
)[0].split("\u0000")[1]; )[0].split("\u0000")[1];
const directories = pluginDirectory.split("\\"); const directories = pluginDirectory.split("\\");
const pluginName = directories[directories.findIndex(value => value === "plugins") + 1].trim(); const pluginName = directories[directories.findIndex(value => value === "plugins") + 1].trim();
if (pluginName) return pluginName; if (pluginName) return pluginName;
} catch { } } catch { }
try {
throw new Error("getPluginName"); if (!error.stack) break;
} catch (error) {
const /** @type {string} */ line = error.stack.trim().split("\n").pop().trim(); const /** @type {string} */ line = error.stack.trim().split("\n").pop().trim();
if (line.includes(".js") && /:\d+:\d+$/.test(line)) { if (line.includes(".js") && /:\d+:\d+$/.test(line)) {
const directories = line.split("\\"); const directories = line.split("\\");
const pluginName = directories[directories.findIndex(value => value === "plugins") + 1].trim(); const pluginName = directories[directories.findIndex(value => value === "plugins") + 1].trim();
if (pluginName) return pluginName; if (pluginName) return pluginName;
} }
break;
}
default: break;
} }
return "Unknown"; return "Unknown";
})();
}; };
module.exports = { module.exports = {
+3
View File
@@ -14,6 +14,9 @@
}, },
{ {
"name": "iListenAttentively" "name": "iListenAttentively"
},
{
"name": "ModAPI"
} }
] ]
} }
+104 -51
View File
@@ -1,4 +1,5 @@
#include "Global.h" #include "Global.h"
#include "gmlib/mc/world/actor/Player.h"
#include "mc/platform/UUID.h" #include "mc/platform/UUID.h"
#include <regex> #include <regex>
@@ -11,7 +12,7 @@ void Export_Compatibility_API() {
return CustomRecipeRegistry::getInstance().unregisterRecipe(id, true); return CustomRecipeRegistry::getInstance().unregisterRecipe(id, true);
}); });
RemoteCall::exportAs("GMLIB_API", "setCustomPackPath", [](std::string const& path) -> void { RemoteCall::exportAs("GMLIB_API", "setCustomPackPath", [](std::string const& path) -> void {
AddonsLoader::addCustomPackPath(path); AddonsLoader::getInstance().addCustomPackPath(path);
}); });
RemoteCall::exportAs("GMLIB_API", "getServerMspt", []() -> double { RemoteCall::exportAs("GMLIB_API", "getServerMspt", []() -> double {
return GMLevel::getInstance().transform( return GMLevel::getInstance().transform(
@@ -19,14 +20,10 @@ void Export_Compatibility_API() {
).value_or(0.0); ).value_or(0.0);
}); });
RemoteCall::exportAs("GMLIB_API", "getServerCurrentTps", []() -> float { RemoteCall::exportAs("GMLIB_API", "getServerCurrentTps", []() -> float {
return GMLevel::getInstance().transform( return TpsStatus::getInstance().getLevelCurrentTps();
[](GMLevel& level) -> float { return level.getServerCurrentTps(); }
).value_or(0.0);
}); });
RemoteCall::exportAs("GMLIB_API", "getServerAverageTps", []() -> double { RemoteCall::exportAs("GMLIB_API", "getServerAverageTps", []() -> double {
return GMLevel::getInstance().transform( return TpsStatus::getInstance().getLevelAverageTps();
[](GMLevel& level) -> double { return level.getServerAverageTps(); }
).value_or(0.0);
}); });
RemoteCall::exportAs("GMLIB_API", "getAllPlayerUuids", []() -> std::vector<std::string> { RemoteCall::exportAs("GMLIB_API", "getAllPlayerUuids", []() -> std::vector<std::string> {
std::vector<std::string> result; std::vector<std::string> result;
@@ -45,7 +42,8 @@ void Export_Compatibility_API() {
"GMLIB_API", "GMLIB_API",
"setPlayerNbt", "setPlayerNbt",
[](std::string const& uuid, CompoundTag* nbt, bool forceCreate) -> bool { [](std::string const& uuid, CompoundTag* nbt, bool forceCreate) -> bool {
if (auto player = OfflinePlayer::fromUuid(mce::UUID::fromString(uuid))) return player->setNbt(*nbt); auto player = OfflinePlayer::fromUuid(mce::UUID::fromString(uuid));
if (player&&player->hasNbt()) return player->setNbt(*nbt);
return forceCreate ? OfflinePlayer::createNewPlayerNbt(mce::UUID::fromString(uuid), *nbt).has_value() return forceCreate ? OfflinePlayer::createNewPlayerNbt(mce::UUID::fromString(uuid), *nbt).has_value()
: false; : false;
} }
@@ -444,13 +442,28 @@ void Export_Compatibility_API() {
return ll::service::getLevel()->fetchEntity(parseScriptUniqueID(uniqueId), false); return ll::service::getLevel()->fetchEntity(parseScriptUniqueID(uniqueId), false);
}); });
RemoteCall::exportAs("GMLIB_API", "getWorldSpawn", []() -> std::pair<BlockPos, int> { RemoteCall::exportAs("GMLIB_API", "getWorldSpawn", []() -> std::pair<BlockPos, int> {
return {GMLevel::getInstance()->getLevelData().getSpawnPos(), 0}; constexpr static HashedString SPAWN_POS{"spawnPos"};
auto& levelData = GMLevel::getInstance()->getLevelData();
if (auto it = levelData.mValues->find(SPAWN_POS); it != levelData.mValues->end()) {
if (auto value = std::get_if<BlockPos>(&it->second.mValue.get()); value) {
return {*value, 0};
}
}
if (auto it = levelData.mOverrides->find(SPAWN_POS); it != levelData.mOverrides->end()) {
if (auto value = std::get_if<BlockPos>(&it->second.mValue.get()); value) {
return {*value, 0};
}
}
return {BlockPos::ZERO(), 1};
}); });
RemoteCall::exportAs("GMLIB_API", "setWorldSpawn", [](std::pair<BlockPos, int> pos) -> bool { RemoteCall::exportAs("GMLIB_API", "setWorldSpawn", [](std::pair<BlockPos, int> pos) -> bool {
if (pos.second != 0) return false; if (pos.second != 0) return false;
GMLevel::getInstance()->getLevelData().setSpawnPos(pos.first); GMLevel::getInstance()->getLevelData().setSpawnPos(pos.first);
auto pkt = SetSpawnPositionPacket(); auto pkt = SetSpawnPositionPacket();
pkt.mSpawnBlockPos = NetworkBlockPosition(pos.first); pkt.mSpawnBlockPos = pos.first;
pkt.mDimensionType = 0; pkt.mDimensionType = 0;
pkt.mSpawnPosType = SpawnPositionType::WorldSpawn; pkt.mSpawnPosType = SpawnPositionType::WorldSpawn;
pkt.sendToClients(); pkt.sendToClients();
@@ -483,7 +496,7 @@ void Export_Compatibility_API() {
return ""; return "";
}); });
RemoteCall::exportAs("GMLIB_API", "getXuidByName", [](std::string const& name) -> std::string { RemoteCall::exportAs("GMLIB_API", "getXuidByName", [](std::string const& name) -> std::string {
if (auto uce = UserCache::getInstance()->from(name, UserCache::QueryType::Name)) { if (auto uce = UserCache::getInstance()->from(name, UserCache::Name)) {
return uce->mXuid; return uce->mXuid;
} }
return ""; return "";
@@ -495,34 +508,63 @@ void Export_Compatibility_API() {
return ""; return "";
}); });
RemoteCall::exportAs("GMLIB_API", "getNameByXuid", [](std::string const& xuid) -> std::string { RemoteCall::exportAs("GMLIB_API", "getNameByXuid", [](std::string const& xuid) -> std::string {
if (auto uce = UserCache::getInstance()->from(xuid, UserCache::QueryType::Xuid)) { if (auto uce = UserCache::getInstance()->from(xuid, UserCache::Xuid)) {
return uce->mName; return uce->mName;
} }
return ""; return "";
}); });
RemoteCall::exportAs("GMLIB_API", "getUuidByXuid", [](std::string const& xuid) -> std::string { RemoteCall::exportAs("GMLIB_API", "getUuidByXuid", [](std::string const& xuid) -> std::string {
if (auto uce = UserCache::getInstance()->from(xuid, UserCache::QueryType::Xuid)) { if (auto uce = UserCache::getInstance()->from(xuid, UserCache::Xuid)) {
return uce->mUuid.asString(); return uce->mUuid.asString();
} }
return ""; return "";
}); });
RemoteCall::exportAs("GMLIB_API", "getUuidByName", [](std::string const& name) -> std::string { RemoteCall::exportAs("GMLIB_API", "getUuidByName", [](std::string const& name) -> std::string {
if (auto uce = UserCache::getInstance()->from(name, UserCache::QueryType::Name)) { if (auto uce = UserCache::getInstance()->from(name, UserCache::Name)) {
return uce->mUuid.asString(); return uce->mUuid.asString();
} }
return ""; return "";
}); });
RemoteCall::exportAs(
"GMLIB_API",
"getPlayerInfo",
[](std::string const& info) -> std::unordered_map<std::string, std::string> {
// TODO: 下个GMLIB更新直接改成from(info, UserCache::QueryType::All)
std::unordered_map<std::string, std::string> result;
if (auto uce = UserCache::getInstance()->from(mce::UUID::fromString(info))) {
ll::reflection::forEachMember(*uce, [&](std::string_view name, auto&& member) {
result[std::string{name.substr(1)}] = fmt::to_string(member);
});
return result;
}
if (auto uniqeuId = ll::string_utils::svtoll(info); uniqeuId) {
if (auto uce = UserCache::getInstance()->from(ActorUniqueID{*uniqeuId})) {
ll::reflection::forEachMember(*uce, [&](std::string_view name, auto&& member) {
result[std::string{name.substr(1)}] = fmt::to_string(member);
});
return result;
}
}
if (auto uce = UserCache::getInstance()->from(info, UserCache::Default)) {
ll::reflection::forEachMember(*uce, [&](std::string_view name, auto&& member) {
result[std::string{name.substr(1)}] = fmt::to_string(member);
});
return result;
}
return result;
}
);
RemoteCall::exportAs( RemoteCall::exportAs(
"GMLIB_API", "GMLIB_API",
"getAllPlayerInfo", "getAllPlayerInfo",
[]() -> std::vector<std::unordered_map<std::string, std::string>> { []() -> std::vector<std::unordered_map<std::string, std::string>> {
std::vector<std::unordered_map<std::string, std::string>> result; std::vector<std::unordered_map<std::string, std::string>> result;
for (auto entry : UserCache::getInstance()->entries()) { for (auto& entry : UserCache::getInstance()->entries()) {
result.push_back({ std::unordered_map<std::string, std::string> item;
{"Name", entry.mName }, ll::reflection::forEachMember(entry, [&](std::string_view name, auto&& member) {
{"Xuid", entry.mXuid }, item[std::string{name.substr(1)}] = fmt::to_string(member);
{"Uuid", entry.mUuid.asString()}
}); });
result.emplace_back(std::move(item));
} }
return result; return result;
} }
@@ -533,7 +575,7 @@ void Export_Compatibility_API() {
.value_or(0); .value_or(0);
}); });
RemoteCall::exportAs("GMLIB_API", "getBlockTranslateKey", [](Block const* block) -> std::string { RemoteCall::exportAs("GMLIB_API", "getBlockTranslateKey", [](Block const* block) -> std::string {
return block->getLegacyBlock().mDescriptionId.get() + ".name"; return block->mBlockType->mDescriptionId.get() + ".name";
}); });
RemoteCall::exportAs("GMLIB_API", "getItemTranslateKey", [](ItemStack* item) -> std::string { RemoteCall::exportAs("GMLIB_API", "getItemTranslateKey", [](ItemStack* item) -> std::string {
return item->getDescriptionId(); return item->getDescriptionId();
@@ -572,8 +614,8 @@ void Export_Compatibility_API() {
} }
); );
RemoteCall::exportAs("GMLIB_API", "itemCanDestroyBlock", [](ItemStack const* item, Block const* block) -> bool { RemoteCall::exportAs("GMLIB_API", "itemCanDestroyBlock", [](ItemStack const* item, Block const* block) -> bool {
return std::ranges::any_of(item->mCanDestroy, [block](BlockLegacy const* blockLegacy) { return std::ranges::any_of(item->mCanDestroy, [block](BlockType const* blockLegacy) {
return block->getTypeName() == blockLegacy->getTypeName(); return blockLegacy && block->getTypeName() == blockLegacy->getTypeName();
}); });
}); });
RemoteCall::exportAs("GMLIB_API", "itemCanDestroyInCreative", [](ItemStack const* item) -> bool { RemoteCall::exportAs("GMLIB_API", "itemCanDestroyInCreative", [](ItemStack const* item) -> bool {
@@ -583,16 +625,19 @@ void Export_Compatibility_API() {
return false; return false;
}); });
RemoteCall::exportAs("GMLIB_API", "itemCanDestroySpecial", [](ItemStack const* item, Block const* block) -> bool { RemoteCall::exportAs("GMLIB_API", "itemCanDestroySpecial", [](ItemStack const* item, Block const* block) -> bool {
return item->getItem()->canDestroySpecial(*block); if (auto itemDef = item->getItem(); itemDef) {
return itemDef->canDestroySpecial(*block);
}
return false;
}); });
RemoteCall::exportAs("GMLIB_API", "blockCanDropWithAnyTool", [](Block const* block) -> bool { RemoteCall::exportAs("GMLIB_API", "blockCanDropWithAnyTool", [](Block const* block) -> bool {
return !block->getLegacyBlock().mRequiresCorrectToolForDrops; return !block->mBlockType->mRequiresCorrectToolForDrops;
}); });
RemoteCall::exportAs( RemoteCall::exportAs(
"GMLIB_API", "GMLIB_API",
"blockPlayerWillDestroy", "blockPlayerWillDestroy",
[](Block const* block, Player* player, std::pair<BlockPos, int> pos) -> bool { [](Block const* block, Player* player, std::pair<BlockPos, int> pos) -> bool {
return block->getLegacyBlock().playerWillDestroy(*player, pos.first, *block); return block->mBlockType->playerWillDestroy(*player, pos.first, *block);
} }
); );
RemoteCall::exportAs("GMLIB_API", "playerAttack", [](Player* player, Actor* entity) -> bool { RemoteCall::exportAs("GMLIB_API", "playerAttack", [](Player* player, Actor* entity) -> bool {
@@ -628,21 +673,21 @@ void Export_Compatibility_API() {
result.push_back({ result.push_back({
{"Name", gameRule.mName }, {"Name", gameRule.mName },
{"Type", "Bool" }, {"Type", "Bool" },
{"Value", std::to_string(gameRule.mValue->boolVal)} {"Value", std::to_string(std::get<bool>(*gameRule.mValue))}
}); });
break; break;
case GameRule::Type::Float: case GameRule::Type::Float:
result.push_back({ result.push_back({
{"Name", gameRule.mName }, {"Name", gameRule.mName },
{"Type", "Float" }, {"Type", "Float" },
{"Value", std::to_string(gameRule.mValue->floatVal)} {"Value", std::to_string(std::get<float>(*gameRule.mValue))}
}); });
break; break;
case GameRule::Type::Int: case GameRule::Type::Int:
result.push_back({ result.push_back({
{"Name", gameRule.mName }, {"Name", gameRule.mName },
{"Type", "Int" }, {"Type", "Int" },
{"Value", std::to_string(gameRule.mValue->intVal)} {"Value", std::to_string(std::get<int>(*gameRule.mValue))}
}); });
break; break;
case GameRule::Type::Invalid: case GameRule::Type::Invalid:
@@ -670,7 +715,7 @@ void Export_Compatibility_API() {
); );
} }
); );
RemoteCall::exportAs("GMLIB_API", "removeEnchants", [](ItemStack* item) -> void { item->removeEnchants(); }); RemoteCall::exportAs("GMLIB_API", "removeEnchants", [](ItemStack* item) -> void { (void)item->removeEnchants(); });
RemoteCall::exportAs("GMLIB_API", "hasEnchant", [](ItemStack* item, std::string const& typeName) -> bool { RemoteCall::exportAs("GMLIB_API", "hasEnchant", [](ItemStack* item, std::string const& typeName) -> bool {
return EnchantUtils::hasEnchant(Enchant::mEnchantNameToType()[HashedString(typeName)], *item); return EnchantUtils::hasEnchant(Enchant::mEnchantNameToType()[HashedString(typeName)], *item);
}); });
@@ -699,7 +744,7 @@ void Export_Compatibility_API() {
return entity->getNameTag(); return entity->getNameTag();
}); });
RemoteCall::exportAs("GMLIB_API", "ItemisUnbreakable", [](ItemStack const* item) -> bool { RemoteCall::exportAs("GMLIB_API", "ItemisUnbreakable", [](ItemStack const* item) -> bool {
return ((GMItemStack*)item)->isUnbreakable(); return ((GMItemStack*)item)->getUnbreakable();
}); });
RemoteCall::exportAs("GMLIB_API", "setItemUnbreakable", [](ItemStack const* item, bool value) -> void { RemoteCall::exportAs("GMLIB_API", "setItemUnbreakable", [](ItemStack const* item, bool value) -> void {
((GMItemStack*)item)->setUnbreakable(value); ((GMItemStack*)item)->setUnbreakable(value);
@@ -710,10 +755,10 @@ void Export_Compatibility_API() {
RemoteCall::exportAs("GMLIB_API", "setItemShouldKeepOnDeath", [](ItemStack const* item, bool value) -> void { RemoteCall::exportAs("GMLIB_API", "setItemShouldKeepOnDeath", [](ItemStack const* item, bool value) -> void {
auto nbt = ((GMItemStack*)item)->getNbt(); auto nbt = ((GMItemStack*)item)->getNbt();
if (value) { if (value) {
(*nbt)["tags"]["minecraft:keep_on_death"] = true; (*nbt)["tag"]["minecraft:keep_on_death"] = true;
} else { } else {
if (nbt->contains("tags") && (*nbt)["tags"].contains("minecraft:keep_on_death")) { if (nbt->contains("tag") && (*nbt)["tag"].contains("minecraft:keep_on_death")) {
(*nbt)["tags"].get<CompoundTag>().erase("minecraft:keep_on_death"); (*nbt)["tag"].get<CompoundTag>().erase("minecraft:keep_on_death");
} }
} }
((GMItemStack*)item)->setNbt(*nbt); ((GMItemStack*)item)->setNbt(*nbt);
@@ -741,9 +786,9 @@ void Export_Compatibility_API() {
"GMLIB_API", "GMLIB_API",
"setItemCanDestroy", "setItemCanDestroy",
[](ItemStack const* item, std::vector<std::string> blocks) -> void { [](ItemStack const* item, std::vector<std::string> blocks) -> void {
std::vector<const BlockLegacy*> data; std::vector<const BlockType*> data;
for (auto& name : blocks) { for (auto& name : blocks) {
if (auto block = BlockLegacy::tryGetFromRegistry(name)) { if (auto block = BlockType::tryGetFromRegistry(name)) {
data.push_back(block.as_ptr()); data.push_back(block.as_ptr());
} }
} }
@@ -761,9 +806,9 @@ void Export_Compatibility_API() {
"GMLIB_API", "GMLIB_API",
"setItemCanPlaceOn", "setItemCanPlaceOn",
[](ItemStack const* item, std::vector<std::string> blocks) -> void { [](ItemStack const* item, std::vector<std::string> blocks) -> void {
std::vector<const BlockLegacy*> data; std::vector<const BlockType*> data;
for (auto& name : blocks) { for (auto& name : blocks) {
if (auto block = BlockLegacy::tryGetFromRegistry(name)) { if (auto block = BlockType::tryGetFromRegistry(name)) {
data.push_back(block.as_ptr()); data.push_back(block.as_ptr());
} }
} }
@@ -771,7 +816,7 @@ void Export_Compatibility_API() {
} }
); );
RemoteCall::exportAs("GMLIB_API", "getPlayerHungry", [](Player* player) -> float { RemoteCall::exportAs("GMLIB_API", "getPlayerHungry", [](Player* player) -> float {
return player->getMutableAttribute(Player::HUNGER()).mInstance->mCurrentValue; return player->getAttribute(Player::HUNGER()).mPtr->mCurrentValue;
}); });
RemoteCall::exportAs("GMLIB_API", "getPlayerArmorCoverPercentage", [](Player* player) -> float { RemoteCall::exportAs("GMLIB_API", "getPlayerArmorCoverPercentage", [](Player* player) -> float {
return player->getArmorCoverPercentage(); return player->getArmorCoverPercentage();
@@ -791,9 +836,9 @@ void Export_Compatibility_API() {
RemoteCall::exportAs("GMLIB_API", "getItemCustomName", [](ItemStack const* item) -> std::string { RemoteCall::exportAs("GMLIB_API", "getItemCustomName", [](ItemStack const* item) -> std::string {
return item->getCustomName(); return item->getCustomName();
}); });
RemoteCall::exportAs("GMLIB_API", "getItemEffecName", [](ItemStack const* item) -> std::string { RemoteCall::exportAs("GMLIB_API", "getItemEffecName", [](ItemStack const* item, bool playerIsCreative) -> std::string {
if (auto item2 = item->mItem) { if (auto item2 = item->mItem) {
return item2->buildEffectDescriptionName(*item); return item2->buildEffectDescriptionName(*item, playerIsCreative);
} }
return ""; return "";
}); });
@@ -833,36 +878,39 @@ void Export_Compatibility_API() {
RemoteCall::exportAs("GMLIB_API", "getPlayerDestroyBlockProgress", [](Player* player, Block const* block) -> float { RemoteCall::exportAs("GMLIB_API", "getPlayerDestroyBlockProgress", [](Player* player, Block const* block) -> float {
return player->getDestroyProgress(*block); return player->getDestroyProgress(*block);
}); });
static constexpr size_t effectMaxCount = 36;
RemoteCall::exportAs("GMLIB_API", "getEntityEffectVisible", [](Actor* entity, int effectId) -> bool { RemoteCall::exportAs("GMLIB_API", "getEntityEffectVisible", [](Actor* entity, int effectId) -> bool {
if (effectId < 0 || !MobEffect::mMobEffects()[effectId]) return false; if (effectId <= 0 || effectId > effectMaxCount || !MobEffect::mMobEffects()[effectId]) return false;
if (auto effect = entity->getEffect(*MobEffect::mMobEffects()[effectId])) { if (auto effect = entity->getEffect(*MobEffect::mMobEffects()[effectId])) {
return effect->mEffectVisible; return effect->mEffectVisible;
} }
return 0; return false;
}); });
RemoteCall::exportAs("GMLIB_API", "getEntityEffectDuration", [](Actor* entity, int effectId) -> int { RemoteCall::exportAs("GMLIB_API", "getEntityEffectDuration", [](Actor* entity, int effectId) -> int {
if (effectId < 0 || !MobEffect::mMobEffects()[effectId]) return false; if (effectId <= 0 || effectId > effectMaxCount|| !MobEffect::mMobEffects()[effectId]) return false;
if (auto effect = entity->getEffect(*MobEffect::mMobEffects()[effectId])) { if (auto effect = entity->getEffect(*MobEffect::mMobEffects()[effectId])) {
return effect->mDuration->mValue; return effect->mDuration->mValue;
} }
return 0; return 0;
}); });
RemoteCall::exportAs("GMLIB_API", "getEntityEffectDurationEasy", [](Actor* entity, int effectId) -> int { RemoteCall::exportAs("GMLIB_API", "getEntityEffectDurationEasy", [](Actor* entity, int effectId) -> int {
if (effectId < 0 || !MobEffect::mMobEffects()[effectId]) return false; if (effectId <= 0 || effectId > effectMaxCount || !MobEffect::mMobEffects()[effectId]) return false;
if (auto effect = entity->getEffect(*MobEffect::mMobEffects()[effectId])) { if (auto effect = entity->getEffect(*MobEffect::mMobEffects()[effectId])) {
return effect->mDurationEasy->transform([](auto&& duration) -> int { return duration.mValue; }).value_or(0); return effect->mDurationEasy->transform([](auto&& duration) -> int { return duration.mValue; }).value_or(0);
} }
return 0; return 0;
}); });
RemoteCall::exportAs("GMLIB_API", "getEntityEffectDurationHard", [](Actor* entity, int effectId) -> int { RemoteCall::exportAs("GMLIB_API", "getEntityEffectDurationHard", [](Actor* entity, int effectId) -> int {
if (effectId < 0 || !MobEffect::mMobEffects()[effectId]) return false; if (effectId <= 0 || effectId > effectMaxCount || !MobEffect::mMobEffects()[effectId]) return false;
if (auto effect = entity->getEffect(*MobEffect::mMobEffects()[effectId])) { if (auto effect = entity->getEffect(*MobEffect::mMobEffects()[effectId])) {
return effect->mDurationHard->transform([](auto&& duration) -> int { return duration.mValue; }).value_or(0); return effect->mDurationHard->transform([](auto&& duration) -> int { return duration.mValue; }).value_or(0);
} }
return 0; return 0;
}); });
RemoteCall::exportAs("GMLIB_API", "getEntityEffectDurationNormal", [](Actor* entity, int effectId) -> int { RemoteCall::exportAs("GMLIB_API", "getEntityEffectDurationNormal", [](Actor* entity, int effectId) -> int {
if (effectId < 0 || !MobEffect::mMobEffects()[effectId]) return false; if (effectId <= 0 || effectId > effectMaxCount|| !MobEffect::mMobEffects()[effectId]) return false;
if (auto effect = entity->getEffect(*MobEffect::mMobEffects()[effectId])) { if (auto effect = entity->getEffect(*MobEffect::mMobEffects()[effectId])) {
return effect->mDurationNormal->transform( return effect->mDurationNormal->transform(
[](auto&& duration) -> int { return duration.mValue; } [](auto&& duration) -> int { return duration.mValue; }
@@ -871,21 +919,23 @@ void Export_Compatibility_API() {
return 0; return 0;
}); });
RemoteCall::exportAs("GMLIB_API", "getEntityEffectAmplifier", [](Actor* entity, int effectId) -> int { RemoteCall::exportAs("GMLIB_API", "getEntityEffectAmplifier", [](Actor* entity, int effectId) -> int {
if (effectId < 0 || !MobEffect::mMobEffects()[effectId]) return false; if (effectId <= 0 || effectId > effectMaxCount || !MobEffect::mMobEffects()[effectId]) return false;
if (auto effect = entity->getEffect(*MobEffect::mMobEffects()[effectId])) { if (auto effect = entity->getEffect(*MobEffect::mMobEffects()[effectId])) {
return effect->mAmplifier; return effect->mAmplifier;
} }
return 0; return 0;
}); });
RemoteCall::exportAs("GMLIB_API", "getEntityEffectAmbient", [](Actor* entity, int effectId) -> bool { RemoteCall::exportAs("GMLIB_API", "getEntityEffectAmbient", [](Actor* entity, int effectId) -> bool {
if (effectId < 0 || !MobEffect::mMobEffects()[effectId]) return false; if (effectId <= 0 || effectId > effectMaxCount || !MobEffect::mMobEffects()[effectId]) return false;
if (auto effect = entity->getEffect(*MobEffect::mMobEffects()[effectId])) { if (auto effect = entity->getEffect(*MobEffect::mMobEffects()[effectId])) {
return effect->mAmbient; return effect->mAmbient;
} }
return 0; return false;
}); });
RemoteCall::exportAs("GMLIB_API", "entityHasEffect", [](Actor* entity, int effectId) -> bool { RemoteCall::exportAs("GMLIB_API", "entityHasEffect", [](Actor* entity, int effectId) -> bool {
return effectId > 0x24 ? false : entity->hasEffect(*MobEffect::mMobEffects()[effectId]); return effectId <= 0 || effectId > effectMaxCount || !MobEffect::mMobEffects()[effectId]
? false
: entity->hasEffect(*MobEffect::mMobEffects()[effectId]);
}); });
RemoteCall::exportAs("GMLIB_API", "getGameDifficulty", []() -> int { RemoteCall::exportAs("GMLIB_API", "getGameDifficulty", []() -> int {
return ll::service::getLevel().transform( return ll::service::getLevel().transform(
@@ -963,7 +1013,10 @@ void Export_Compatibility_API() {
return entity->isType((ActorType)type); return entity->isType((ActorType)type);
}); });
RemoteCall::exportAs("GMLIB_API", "entityHasType", [](Actor* entity, int type) -> bool { RemoteCall::exportAs("GMLIB_API", "entityHasType", [](Actor* entity, int type) -> bool {
return entity->hasType((ActorType)type); if (auto component = entity->mEntityContext->tryGetComponent<ActorTypeComponent>(); component) {
return (type & std::to_underlying(component->mType)) == type;
}
return false;
}); });
RemoteCall::exportAs("GMLIB_API", "getEntityTypeId", [](Actor* entity) -> int { RemoteCall::exportAs("GMLIB_API", "getEntityTypeId", [](Actor* entity) -> int {
return (int)entity->getEntityTypeId(); return (int)entity->getEntityTypeId();
+3 -2
View File
@@ -216,10 +216,11 @@ void Export_Event_API() {
); );
} }
case doHash("gmlib::EndermanTakeBlockBeforeEvent"): { case doHash("gmlib::EndermanTakeBlockBeforeEvent"): {
REGISTER_EVENT_LISTEN(ila::mc::EndermanTakeBlockBeforeEvent, REGISTER_EVENT_LISTEN(ila::mc::MobTakeBlockBeforeEvent,
(Actor * mob, bool isCancelled), (Actor * mob, bool isCancelled),
(&event.self(), event.isCancelled()), (&event.self(), event.isCancelled()),
event.setCancelled(result);); event.setCancelled(result);
, if (!event.self().isType(ActorType::EnderMan)) return;);
} }
case doHash("gmlib::DragonRespawnBeforeEvent"): { case doHash("gmlib::DragonRespawnBeforeEvent"): {
REGISTER_EVENT_LISTEN(ila::mc::DragonRespawnBeforeEvent, REGISTER_EVENT_LISTEN(ila::mc::DragonRespawnBeforeEvent,
+32 -5
View File
@@ -1,17 +1,28 @@
#pragma once #pragma once
// clang-format off // clang-format off
#define GMLIB_GLOBAL_USING #pragma warning(push)
#include <gmlib/GlobalUsing.h> #pragma warning(disable : 4996)
#include <gmlib/include_all.h> #pragma include_alias("mc/world/item/HumanoidArmorItem.h", "modapi/item/types/mc/HumanoidArmorItem.h")
#include <gmlib/include_ll.h>
#include <gmlib/include_lib.h>
#include <gmlib/include_mc.h>
#include <ila/include_all.h> #include <ila/include_all.h>
#include <modapi/addons/AddonsLoader.h>
#include <modapi/recipe/CustomRecipeRegistry.h>
#include <modapi/item/CustomItemRegistry.h>
#include <RemoteCallAPI.h> #include <RemoteCallAPI.h>
using namespace gmlib::mod; using namespace gmlib;
using namespace gmlib::ui;
using namespace gmlib::i18n;
using namespace gmlib::memory;
using namespace modapi;
#pragma warning(pop)
// clang-format on // clang-format on
#define PLUGIN_NAME fmt::format(fg(fmt::color::light_green), "GMLIB-LRCA") #define PLUGIN_NAME fmt::format(fg(fmt::color::light_green), "GMLIB-LRCA")
#define LIB_VERSION_MAJOR 1 #define LIB_VERSION_MAJOR 1
#define LIB_VERSION_MINOR 0 #define LIB_VERSION_MINOR 8
#define LIB_VERSION_PATCH 0 #define LIB_VERSION_PATCH 0
#define LIB_VERSION_PRERELEASE std::nullopt #define LIB_VERSION_PRERELEASE std::nullopt
@@ -30,3 +41,19 @@ extern void Export_BinaryStream_API();
extern ll::thread::ThreadPoolExecutor const& getThreadPoolExecutor(); extern ll::thread::ThreadPoolExecutor const& getThreadPoolExecutor();
extern ll::io::Logger& getLogger(); extern ll::io::Logger& getLogger();
// extern void Export_Form_API(); // extern void Export_Form_API();
template <>
struct fmt::formatter<ActorUniqueID> : fmt::formatter<int64> {
template <class FormatContext>
auto format(ActorUniqueID const& t, FormatContext& ctx) const {
return formatter<int64>::format(t.rawID, ctx);
}
};
template <>
struct fmt::formatter<mce::UUID> : fmt::formatter<std::string> {
template <class FormatContext>
auto format(mce::UUID const& t, FormatContext& ctx) const {
return formatter<std::string>::format(t.asString(), ctx);
}
};
+5
View File
@@ -79,4 +79,9 @@ void Export_Legacy_GMLib_ServerAPI() {
[](GMLevel& level) -> int { return level.getMaxPlayerCount(); } [](GMLevel& level) -> int { return level.getMaxPlayerCount(); }
).value_or(0); ).value_or(0);
}); });
RemoteCall::exportAs("GMLib_ServerAPI", "setMaxPlayers", [&](int count, bool ignoreVanillaLimit) {
if (auto level = GMLevel::getInstance(); level) {
level->setMaxPlayerCount(count, ignoreVanillaLimit);
}
});
} }
+39 -27
View File
@@ -2,10 +2,12 @@
#include <regex> #include <regex>
namespace PAPIRemoteCall { namespace PAPIRemoteCall {
std::string GetValue(std::string const& from) { return PlaceholderAPI::getValue(from, std::nullopt).value_or(""); } std::string GetValue(std::string const& from) {
return PlaceholderAPI::getInstance().getValue(from, std::nullopt).value_or("");
}
std::string GetValueWithPlayer(std::string const& key, Player* player) { std::string GetValueWithPlayer(std::string const& key, Player* player) {
return PlaceholderAPI::getValue(key, (GMActor*)player).value_or(""); return PlaceholderAPI::getInstance().getValue(key, (GMActor*)player).value_or("");
} }
void registerPlayerPlaceholder( void registerPlayerPlaceholder(
@@ -15,15 +17,15 @@ void registerPlayerPlaceholder(
) { ) {
if (!RemoteCall::hasFunc(PluginName, FuncName)) return; if (!RemoteCall::hasFunc(PluginName, FuncName)) return;
auto func = [=]() -> void { auto func = [=]() -> void {
PlaceholderAPI::unregisterPlaceholder(PAPIName); PlaceholderAPI::getInstance().unregisterPlaceholder(PAPIName);
std::weak_ptr mod = ll::mod::ModManagerRegistry::getInstance().getMod(PluginName); std::weak_ptr mod = ll::mod::ModManagerRegistry::getInstance().getMod(PluginName);
if (mod.expired()) return; if (mod.expired()) return;
PlaceholderAPI::registerPlaceholder( PlaceholderAPI::getInstance().registerPlaceholder(
PAPIName, PAPIName,
[Call = RemoteCall::importAs<std::string(Player * pl, std::unordered_map<std::string, std::string>)>( [Call = RemoteCall::importAs<std::string(Player * pl, std::unordered_map<std::string, std::string>)>(
PluginName, PluginName,
FuncName FuncName
)](optional_ref<Actor> actor, ll::StringMap<std::string> const& params, auto&&... )](optional_ref<Actor> actor, ll::SmallStringMap<std::string> const& params, auto&&...
) -> std::optional<std::string> { ) -> std::optional<std::string> {
if (actor.has_value() && ((Actor*)actor.as_ptr())->isPlayer()) { if (actor.has_value() && ((Actor*)actor.as_ptr())->isPlayer()) {
std::unordered_map<std::string, std::string> paramMap; std::unordered_map<std::string, std::string> paramMap;
@@ -34,6 +36,7 @@ void registerPlayerPlaceholder(
} }
return std::nullopt; return std::nullopt;
}, },
false,
mod mod
); );
}; };
@@ -51,21 +54,22 @@ void registerServerPlaceholder(
) { ) {
if (!RemoteCall::hasFunc(PluginName, FuncName)) return; if (!RemoteCall::hasFunc(PluginName, FuncName)) return;
auto func = [=]() -> void { auto func = [=]() -> void {
PlaceholderAPI::unregisterPlaceholder(PAPIName); PlaceholderAPI::getInstance().unregisterPlaceholder(PAPIName);
std::weak_ptr mod = ll::mod::ModManagerRegistry::getInstance().getMod(PluginName); std::weak_ptr mod = ll::mod::ModManagerRegistry::getInstance().getMod(PluginName);
if (mod.expired()) return; if (mod.expired()) return;
PlaceholderAPI::registerPlaceholder( PlaceholderAPI::getInstance().registerPlaceholder(
PAPIName, PAPIName,
[Call = RemoteCall::importAs<std::string(std::unordered_map<std::string, std::string>)>( [Call = RemoteCall::importAs<std::string(std::unordered_map<std::string, std::string>)>(
PluginName, PluginName,
FuncName FuncName
)](auto, ll::StringMap<std::string> const& params, auto&&...) -> std::optional<std::string> { )](auto, ll::SmallStringMap<std::string> const& params, auto&&...) -> std::optional<std::string> {
std::unordered_map<std::string, std::string> paramMap; std::unordered_map<std::string, std::string> paramMap;
for (auto& [key, val] : params) { for (auto& [key, val] : params) {
paramMap[key] = val; paramMap[key] = val;
} }
return Call(paramMap); return Call(paramMap);
}, },
false,
mod mod
); );
}; };
@@ -84,13 +88,14 @@ void registerStaticPlaceholder(
) { ) {
if (!RemoteCall::hasFunc(PluginName, FuncName)) return; if (!RemoteCall::hasFunc(PluginName, FuncName)) return;
auto func = [=]() -> void { auto func = [=]() -> void {
PlaceholderAPI::unregisterPlaceholder(PAPIName); PlaceholderAPI::getInstance().unregisterPlaceholder(PAPIName);
std::weak_ptr mod = ll::mod::ModManagerRegistry::getInstance().getMod(PluginName); std::weak_ptr mod = ll::mod::ModManagerRegistry::getInstance().getMod(PluginName);
if (mod.expired()) return; if (mod.expired()) return;
PlaceholderAPI::registerPlaceholder( PlaceholderAPI::getInstance().registerPlaceholder(
PAPIName, PAPIName,
[Call = RemoteCall::importAs<std::string()>(PluginName, FuncName)](auto&&...) [Call = RemoteCall::importAs<std::string()>(PluginName, FuncName)](auto&&...
-> std::optional<std::string> { return Call(); }, ) -> std::optional<std::string> { return Call(); },
false,
mod mod
); );
}; };
@@ -102,16 +107,18 @@ void registerStaticPlaceholder(
} }
std::string translateStringWithPlayer(std::string const& str, Player* pl) { std::string translateStringWithPlayer(std::string const& str, Player* pl) {
return PlaceholderAPI::translate(str, (GMActor*)pl); return PlaceholderAPI::getInstance().translate(str, (GMActor*)pl);
} }
std::string translateString(std::string const& str) { return PlaceholderAPI::translate(str, std::nullopt); } std::string translateString(std::string const& str) {
return PlaceholderAPI::getInstance().translate(str, std::nullopt);
}
bool unRegisterPlaceholder(std::string const& str) { return PlaceholderAPI::unregisterPlaceholder(str); } bool unRegisterPlaceholder(std::string const& str) { return PlaceholderAPI::getInstance().unregisterPlaceholder(str); }
std::vector<std::string> getAllPAPI() { std::vector<std::string> getAllPAPI() {
std::vector<std::string> result; std::vector<std::string> result;
for (auto& papi : PlaceholderAPI::getAllPlaceholderData()) { for (auto& papi : PlaceholderAPI::getInstance().getAllPlaceholderData()) {
result.push_back(papi.first); result.push_back(papi.first);
} }
return result; return result;
@@ -121,23 +128,23 @@ std::vector<std::string> getAllPAPI() {
namespace NewPapiRemoteCall { namespace NewPapiRemoteCall {
std::string translate(std::string const& value, std::string const& language) { std::string translate(std::string const& value, std::string const& language) {
return PlaceholderAPI::translate(value, std::nullopt, language); return PlaceholderAPI::getInstance().translate(value, std::nullopt, language);
} }
std::string translateFromActor(std::string const& value, Actor* actor, std::string const& language) { std::string translateFromActor(std::string const& value, Actor* actor, std::string const& language) {
return PlaceholderAPI::translate(value, (GMActor*)actor, language); return PlaceholderAPI::getInstance().translate(value, (GMActor*)actor, language);
} }
void registerPlaceholder(std::string const& placeholder, std::string const& funcName, std::string const& pluginName) { void registerPlaceholder(std::string const& placeholder, std::string const& funcName, std::string const& pluginName) {
if (!RemoteCall::hasFunc(pluginName, funcName)) return; if (!RemoteCall::hasFunc(pluginName, funcName)) return;
auto func = [=]() -> void { auto func = [=]() -> void {
if (std::weak_ptr mod = ll::mod::ModManagerRegistry::getInstance().getMod(pluginName); !mod.expired()) { if (std::weak_ptr mod = ll::mod::ModManagerRegistry::getInstance().getMod(pluginName); !mod.expired()) {
PlaceholderAPI::unregisterPlaceholder(placeholder); PlaceholderAPI::getInstance().unregisterPlaceholder(placeholder);
PlaceholderAPI::registerPlaceholder( PlaceholderAPI::getInstance().registerPlaceholder(
placeholder, placeholder,
[Call = RemoteCall::importAs< [Call = RemoteCall::importAs<
std::string(Actor*, std::unordered_map<std::string, std::string>, std::string)>( std::string(Actor*, std::unordered_map<std::string, std::string>, std::string)>(
pluginName, pluginName,
funcName funcName
)](optional_ref<Actor> actor, ll::StringMap<std::string> const& params, std::string const& language )](optional_ref<Actor> actor, ll::SmallStringMap<std::string> const& params, std::string const& language
) -> std::optional<std::string> { ) -> std::optional<std::string> {
std::unordered_map<std::string, std::string> paramMap; std::unordered_map<std::string, std::string> paramMap;
for (auto& [key, val] : params) { for (auto& [key, val] : params) {
@@ -146,6 +153,7 @@ void registerPlaceholder(std::string const& placeholder, std::string const& func
auto result = Call((Actor*)actor.as_ptr(), paramMap, language); auto result = Call((Actor*)actor.as_ptr(), paramMap, language);
return result == "<std::nullopt>" ? std::nullopt : std::optional(result); return result == "<std::nullopt>" ? std::nullopt : std::optional(result);
}, },
false,
mod mod
); );
} }
@@ -157,23 +165,25 @@ void registerPlaceholder(std::string const& placeholder, std::string const& func
} }
} }
bool unregisterPlaceholder(std::string const& placeholder) { bool unregisterPlaceholder(std::string const& placeholder) {
return PlaceholderAPI::unregisterPlaceholder(placeholder); return PlaceholderAPI::getInstance().unregisterPlaceholder(placeholder);
} }
bool unregisterPlaceholderFromModName(std::string const& pluginName) { bool unregisterPlaceholderFromModName(std::string const& pluginName) {
std::weak_ptr plugin = ll::mod::ModManagerRegistry::getInstance().getMod(pluginName); std::weak_ptr plugin = ll::mod::ModManagerRegistry::getInstance().getMod(pluginName);
if (plugin.expired()) return false; if (plugin.expired()) return false;
return PlaceholderAPI::unregisterPlaceholder(plugin); return PlaceholderAPI::getInstance().unregisterPlaceholder(plugin);
} }
std::string getValue( std::string getValue(
std::string const& placeholder, std::string const& placeholder,
std::unordered_map<std::string, std::string> params, std::unordered_map<std::string, std::string> params,
std::string const& language std::string const& language
) { ) {
ll::StringMap<std::string> paramMap; ll::SmallStringMap<std::string> paramMap;
for (auto& [key, val] : params) { for (auto& [key, val] : params) {
paramMap[key] = val; paramMap[key] = val;
} }
return PlaceholderAPI::getValue(placeholder, std::nullopt, paramMap, language).value_or("<std::nullopt>"); return PlaceholderAPI::getInstance()
.getValue(placeholder, std::nullopt, paramMap, language)
.value_or("<std::nullopt>");
} }
std::string getValueFromActor( std::string getValueFromActor(
std::string const& placeholder, std::string const& placeholder,
@@ -181,11 +191,13 @@ std::string getValueFromActor(
std::unordered_map<std::string, std::string> params, std::unordered_map<std::string, std::string> params,
std::string const& language std::string const& language
) { ) {
ll::StringMap<std::string> paramMap; ll::SmallStringMap<std::string> paramMap;
for (auto& [key, val] : params) { for (auto& [key, val] : params) {
paramMap[key] = val; paramMap[key] = val;
} }
return PlaceholderAPI::getValue(placeholder, (GMActor*)actor, paramMap, language).value_or("<std::nullopt>"); return PlaceholderAPI::getInstance()
.getValue(placeholder, (GMActor*)actor, paramMap, language)
.value_or("<std::nullopt>");
} }
} // namespace NewPapiRemoteCall } // namespace NewPapiRemoteCall
+5 -4
View File
@@ -2,7 +2,7 @@
"format_version": 3, "format_version": 3,
"format_uuid": "289f771f-2c9a-4d73-9f3f-8492495a924d", "format_uuid": "289f771f-2c9a-4d73-9f3f-8492495a924d",
"tooth": "github.com/GroupMountain/GMLIB-LegacyRemoteCallApi", "tooth": "github.com/GroupMountain/GMLIB-LegacyRemoteCallApi",
"version": "1.4.0", "version": "1.10.0",
"info": { "info": {
"name": "GMLIB-LegacyRemoteCallApi", "name": "GMLIB-LegacyRemoteCallApi",
"description": "Legacy RemoteCall API for GMLIB", "description": "Legacy RemoteCall API for GMLIB",
@@ -19,9 +19,10 @@
{ {
"platform": "win-x64", "platform": "win-x64",
"dependencies": { "dependencies": {
"github.com/LiteLDev/LeviLamina": ">=1.3.0", "github.com/LiteLDev/LeviLamina": ">=26.10.0",
"github.com/GroupMountain/GMLIB-Release": ">=1.3.0-rc.1", "github.com/GroupMountain/GMLIB-Release": ">=26.10.0",
"github.com/MiracleForest/iListenAttentively-Release": ">=0.6.0" "github.com/GroupMountain/ModAPI-Release": ">=26.10.0",
"github.com/MiracleForest/iListenAttentively-Release": ">=0.12.0"
}, },
"assets": [ "assets": [
{ {
+16 -5
View File
@@ -8,11 +8,18 @@ if not has_config("vs_runtime") then
set_runtimes("MD") set_runtimes("MD")
end end
add_requires("levilamina 1.4.1", {configs = {target_type = "server"}}) add_requires("levilamina 26.10.5", {configs = {target_type = "server"}})
add_requires("legacyremotecall") add_requires("legacyremotecall")
add_requires("levibuildscript") add_requires("levibuildscript 0.6.0")
add_requires("ilistenattentively 0.7.0") add_requires("ilistenattentively 0.12.0")
add_requires("gmlib 1.4.0") add_requires("gmlib 26.10.0")
add_requires("modapi 26.10.0")
rule("package_envs")
before_link(function (target)
os.addenvs(target:pkgenvs())
end)
rule_end()
target("GMLIB-LegacyRemoteCallApi") target("GMLIB-LegacyRemoteCallApi")
add_cxflags( add_cxflags(
@@ -25,6 +32,7 @@ target("GMLIB-LegacyRemoteCallApi")
"UNICODE", "UNICODE",
"_HAS_CXX23=1" "_HAS_CXX23=1"
) )
add_defines("LL_PLAT_S") --TODO: check client compatibility
add_files( add_files(
"src/**.cpp" "src/**.cpp"
) )
@@ -34,9 +42,12 @@ target("GMLIB-LegacyRemoteCallApi")
add_packages( add_packages(
"levilamina", "levilamina",
"legacyremotecall", "legacyremotecall",
"levibuildscript",
"ilistenattentively", "ilistenattentively",
"gmlib" "gmlib",
"modapi"
) )
add_rules("package_envs")
add_rules("@levibuildscript/linkrule") add_rules("@levibuildscript/linkrule")
add_rules("@levibuildscript/modpacker") add_rules("@levibuildscript/modpacker")
set_exceptions("none") set_exceptions("none")