Compare commits

..

178 Commits

31 changed files with 8100 additions and 1240 deletions
+4 -12
View File
@@ -9,12 +9,10 @@ jobs:
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v2 uses: actions/checkout@v2
with:
submodules: recursive
- 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,14 +23,8 @@ 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: |
bin/DLL/ bin/
- uses: actions/upload-artifact@v3
with:
name: PDB
path: |
bin/PDB/
+10 -27
View File
@@ -9,12 +9,10 @@ jobs:
steps: steps:
- name: Checkout repository - name: Checkout repository
uses: actions/checkout@v2 uses: actions/checkout@v2
with:
submodules: recursive
- 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,17 +23,11 @@ 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: |
bin/DLL/ bin/
- uses: actions/upload-artifact@v3
with:
name: PDB
path: |
bin/PDB/
upload-to-release: upload-to-release:
needs: needs:
@@ -47,32 +39,23 @@ jobs:
- name: Checkout code - name: Checkout code
uses: actions/checkout@v4 uses: actions/checkout@v4
- name: Download Plugin - name: Download Mod
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/Plugin/ path: artifact
- name: Download PDB
uses: actions/download-artifact@v3
with:
name: PDB
path: release/PDB/
- name: Copy additional files - name: Copy additional files
run: | run: |
cp LICENSE README.md release/Plugin/ cp -v LICENSE README.md artifact/
- name: Archive release - name: Archive release
run: | run: |
cd release/Plugin
zip -r ../${{ github.event.repository.name }}-windows-x64.zip * zip -r ../${{ github.event.repository.name }}-windows-x64.zip *
cd .. working-directory: artifact
- name: Create GitHub Release - name: Create GitHub Release
id: create_release
uses: softprops/action-gh-release@v1 uses: softprops/action-gh-release@v1
with: with:
files: | files: |
release/${{ github.event.repository.name }}-windows-x64.zip ${{ github.event.repository.name }}-windows-x64.zip
release/PDB/${{ github.event.repository.name }}.pdb
+1
View File
@@ -15,3 +15,4 @@ build/
/.xmake /.xmake
/CMakeLists.txt /CMakeLists.txt
/bin /bin
.cache/clangd/index
-3
View File
@@ -1,3 +0,0 @@
[submodule "SDK-GMLIB"]
path = SDK-GMLIB
url = https://github.com/GroupMountain/SDK-GMLIB.git
+2 -3
View File
@@ -5,6 +5,5 @@ Legacy RemoteCall API for GMLIB. Only for legacy LSE plugin compatibility.
- 本模块是 `GMLIB``Legacy RemoteCall API` 模块,是为LL2的LLSE插件的兼容性保留。 - 本模块是 `GMLIB``Legacy RemoteCall API` 模块,是为LL2的LLSE插件的兼容性保留。
- 通过本模块,可以使LSE插件调用 `GMLIB` 内部的API。 - 通过本模块,可以使LSE插件调用 `GMLIB` 内部的API。
# 注意事项 # 开发文档
- 本模块仅为兼容性保留模块,仅保留过去的接口以保留兼容性。 - https://groupmountain.github.io/Documentation/
- 本模块不会提供 `GMLIB` 在迁移到 `LeviLamina` 后新开发的接口。
Submodule SDK-GMLIB deleted from 7206bf0c10
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 67 KiB

+72
View File
@@ -0,0 +1,72 @@
export class PAPI {
/** 注册一个玩家PAPI变量 */
static registerPlayerPlaceholder(
/** PAPI调用函数 */
func: (
/** 玩家对象 */
player: Player,
/** 变量参数 */
param: null | object.<string, string>
) => string,
/** 插件名字 */
pluginsName: string,
/** PAPI变量 */
PAPIName: string
): void;
/** 注册一个服务器PAPI变量 */
static registerServerPlaceholder(
/** PAPI调用函数 */
func: (
/** 变量参数 */
param: null | object.<string, string>
) => string,
/** 插件名字 */
pluginsName: string,
/** PAPI变量 */
PAPIName: string
): void;
/** 注册一个静态PAPI变量 */
static registerStaticPlaceholder(
/** PAPI调用函数 */
func: () => string,
/** 插件名字 */
pluginsName: string,
/** PAPI变量 */
PAPIName: string,
/** 更新时间 */
UpdateInterval: number
): void;
/** 获取一个服务器变量的值 */
static getValue(
/** PAPI名 */
key: string
): string;
/** 获取一个玩家变量的值 */
static getValueByPlayer(
/** PAPI名 */
key: string,
/** 玩家对象 */
pl: Player
): string;
/** 翻译带PAPI变量的字符串 */
static translateString(
/** 要翻译的字符串 */
str: string,
/** 玩家对象 */
pl: Player | undefined
): string;
/** 注销一个PAPI变量 */
static unRegisterPlaceholder(
/** PAPI名 */
str: string
): boolean;
/** 获取所有已注册的PAPI变量 */
static getAllPAPI(): string[];
}
+73 -19
View File
@@ -1,47 +1,92 @@
const PlaceholderAPI = { const PlaceholderAPI = {
getValueAPI: ll.import("BEPlaceholderAPI", "GetValue"), /** 获取一个服务器变量的值 @type {function(string):string} */
getValueByPlayerAPI: ll.import("BEPlaceholderAPI", "GetValueWithPlayer"), getValueAPI: ll.imports("BEPlaceholderAPI", "GetValue"),
registerPlayerPlaceholderAPI: ll.import("BEPlaceholderAPI", "registerPlayerPlaceholder"), /** 获取一个玩家变量的值 @type {function(string,Player):string} */
registerServerPlaceholderAPI: ll.import("BEPlaceholderAPI", "registerServerPlaceholder"), getValueByPlayerAPI: ll.imports("BEPlaceholderAPI", "GetValueWithPlayer"),
registerStaticPlaceholderAPI: ll.import("BEPlaceholderAPI", "registerStaticPlaceholder"), /** 注册一个玩家变量 @type {function(string,string,string):boolean} */
translateStringAPI: ll.import("BEPlaceholderAPI", "translateString"), registerPlayerPlaceholderAPI: ll.imports("BEPlaceholderAPI", "registerPlayerPlaceholder"),
translateStringWithPlayerAPI: ll.import("BEPlaceholderAPI", "translateStringWithPlayer"), /** 注册一个服务器变量 @type {function(string,string,string):boolean} */
unRegisterPlaceholderAPI: ll.import("BEPlaceholderAPI", "unRegisterPlaceholder"), registerServerPlaceholderAPI: ll.imports("BEPlaceholderAPI", "registerServerPlaceholder"),
getAllPAPI: ll.import("BEPlaceholderAPI", "getAllPAPI") /** 注册一个静态变量 @type {function(string,string,string,number):boolean} */
} registerStaticPlaceholderAPI: ll.imports("BEPlaceholderAPI", "registerStaticPlaceholder"),
/** 翻译包含PAPI服务器变量的字符串 @type {function(string):string} */
Function.prototype.getName = function () { translateStringAPI: ll.imports("BEPlaceholderAPI", "translateString"),
return this.name || this.toString().match(/function\s*([^(]*)\(/)[1] /** 翻译包含PAPI玩家变量的字符串 @type {function(string,Player):string} */
translateStringWithPlayerAPI: ll.imports("BEPlaceholderAPI", "translateStringWithPlayer"),
/** 注销PAPI变量 @type {function(string):boolean} */
unRegisterPlaceholderAPI: ll.imports("BEPlaceholderAPI", "unRegisterPlaceholder"),
/** 获取所有已注册的PAPI变量 @type {function():Array.<string>} */
getAllPAPI: ll.imports("BEPlaceholderAPI", "getAllPAPI")
} }
/** PAPI变量类 */
class PAPI { class PAPI {
constructor() { constructor() {
throw new Error("Static class cannot be instantiated"); throw new Error("Static class cannot be instantiated");
} }
/**
* 注册一个玩家PAPI变量
* @param {function} func 变量调用的函数
* @param {string} PluginName 插件名字
* @param {string} PAPIName PAPI变量名
* @returns {boolean} 是否注册成功
*/
static registerPlayerPlaceholder(func, PluginName, PAPIName) { static registerPlayerPlaceholder(func, PluginName, PAPIName) {
ll.export(func, PluginName, func.getName()); ll.export(func, PluginName, `Placeholder_${PAPIName}`);
return PlaceholderAPI.registerPlayerPlaceholderAPI(PluginName, func.getName(), PAPIName); PlaceholderAPI.registerPlayerPlaceholderAPI(PluginName, `Placeholder_${PAPIName}`, PAPIName);
} }
/**
* 注册一个服务器PAPI变量
* @param {function} func 变量调用的函数
* @param {string} PluginName 插件名字
* @param {string} PAPIName PAPI变量名
* @returns {boolean} 是否注册成功
*/
static registerServerPlaceholder(func, PluginName, PAPIName) { static registerServerPlaceholder(func, PluginName, PAPIName) {
ll.export(func, PluginName, func.getName()); ll.export(func, PluginName, `Placeholder_${PAPIName}`);
return PlaceholderAPI.registerServerPlaceholderAPI(PluginName, func.getName(), PAPIName); PlaceholderAPI.registerServerPlaceholderAPI(PluginName, `Placeholder_${PAPIName}`, PAPIName);
} }
/**
* 注册一个静态PAPI变量
* @param {function} func 变量调用的函数
* @param {string} PluginName 插件名字
* @param {string} PAPIName PAPI变量名
* @param {number} [UpdateInterval=50] 更新间隔
* @returns {boolean} 是否注册成功
*/
static registerStaticPlaceholder(func, PluginName, PAPIName, UpdateInterval = 50) { static registerStaticPlaceholder(func, PluginName, PAPIName, UpdateInterval = 50) {
ll.export(func, PluginName, func.getName()); ll.export(func, PluginName, `Placeholder_${PAPIName}`);
return PlaceholderAPI.registerStaticPlaceholderAPI(PluginName, func.getName(), PAPIName, UpdateInterval); PlaceholderAPI.registerStaticPlaceholderAPI(PluginName, `Placeholder_${PAPIName}`, PAPIName, UpdateInterval);
} }
/**
* 获取一个服务器变量的值
* @param {string} key PAPI变量名
* @returns {string} 值
*/
static getValue(key) { static getValue(key) {
return PlaceholderAPI.getValueAPI(key); return PlaceholderAPI.getValueAPI(key);
} }
/**
* 获取一个玩家变量的值
* @param {string} key PAPI变量名
* @param {Player} pl 玩家对象
* @returns {string} 值
*/
static getValueByPlayer(key, pl) { static getValueByPlayer(key, pl) {
return PlaceholderAPI.getValueByPlayerAPI(key, pl); return PlaceholderAPI.getValueByPlayerAPI(key, pl);
} }
/**
* 翻译带PAPI变量的字符串
* @param {string} str 字符串
* @param {Player} pl 玩家对象
* @returns {string} 翻译结果
*/
static translateString(str, pl = null) { static translateString(str, pl = null) {
if (pl) { if (pl) {
return PlaceholderAPI.translateStringWithPlayerAPI(str, pl); return PlaceholderAPI.translateStringWithPlayerAPI(str, pl);
@@ -49,10 +94,19 @@ class PAPI {
return PlaceholderAPI.translateStringAPI(str); return PlaceholderAPI.translateStringAPI(str);
} }
/**
* 注销一个PAPI变量
* @param {string} str PAPI变量名
* @returns {boolean} 是否注销成功
*/
static unRegisterPlaceholder(str) { static unRegisterPlaceholder(str) {
return PlaceholderAPI.unRegisterPlaceholderAPI(str); return PlaceholderAPI.unRegisterPlaceholderAPI(str);
} }
/**
* 获取所有已注册的PAPI变量
* @returns {Array.<string>} 已注册的PAPI变量数组
*/
static getAllPAPI() { static getAllPAPI() {
return PlaceholderAPI.getAllPAPI(); return PlaceholderAPI.getAllPAPI();
} }
+894
View File
@@ -0,0 +1,894 @@
export namespace Event {
/** 事件优先级 */
export enum EventPriority {
/** 最高 */
Highest = 0,
/** 高 */
High = 100,
/** 正常(推荐) */
Normal = 200,
/** 低 */
Low = 300,
/** 最低 */
Lowest = 400
}
/** 获取所有事件订阅 */
export function getListener(): Record<string, number[]>;
/** 获取事件订阅列表 */
export function getListener(
/** 事件名 */
eventName:
"ll::ServerStoppingEvent"
| "gmlib::ClientLoginAfterEvent"
| "gmlib::WeatherUpdateBeforeEvent"
| "gmlib::MobPickupItemBeforeEvent"
| "gmlib::ItemActorSpawnBeforeEvent"
| "gmlib::ItemActorSpawnAfterEvent"
| "gmlib::ActorChangeDimensionBeforeEvent"
| "gmlib::PlayerStopSleepBeforeEvent"
| "gmlib::DeathMessageAfterEvent"
| "gmlib::MobHurtAfterEvent"
| "gmlib::EndermanTakeBlockBeforeEvent"
| "gmlib::ActorChangeDimensionAfterEvent"
| "gmlib::DragonRespawnBeforeEvent"
| "gmlib::ProjectileCreateBeforeEvent"
| "gmlib::ProjectileCreateAfterEvent"
| "gmlib::SpawnWanderingTraderBeforeEvent"
| "gmlib::HandleRequestActionBeforeEvent"
| "gmlib::ContainerClosePacketSendAfterEvent"
): number[];
/** 订阅事件是否存在 */
export function hasListener(
/** 事件ID */
eventId: number
): boolean;
/** 取消事件订阅 */
export function removeListener(
/** 事件ID */
eventId: number
): boolean;
/** 获取订阅事件优先级 */
export function getListenerPriority(
/** 事件ID */
eventId: number
): EventPriority | undefined;
/** 设置事件异常处理回调 */
export function setErrorHanlerCallback(
/** 回调 */
callback: (
/** 错误 */
error: Error,
/** 事件名 */
eventName: string,
/** 事件ID */
eventId: number,
/** 插件名 */
pluginName: string
) => void
): boolean;
/** 监听事件(兼容旧版) */
export function listen(
/** 事件名 */
eventName: "onServerStopping"
| "onClientLogin"
| "onWeatherChange"
| "onMobPick"
| "onItemTrySpawn"
| "onItemSpawned"
| "onEntityTryChangeDim"
| "onLeaveBed"
| "onDeathMessage"
| "onMobHurted"
| "onEndermanTake"
| "onEntityChangeDim"
| "onDragonRespawn"
| "onProjectileTryCreate"
| "onProjectileCreate"
| "onSpawnWanderingTrader"
| "onHandleRequestAction"
| "onSendContainerClosePacket",
/** 回调 */
callback: Function
): boolean;
/** 订阅事件 */
export function emplaceListener(
/** 事件名 */
eventName: string,
/** 回调 */
callback: (event: {
/** 事件参数 */
params: any[],
/** 拦截事件 */
cancel: () => void,
/** 设置拦截状态 */
setCancelled: (
/** 是否拦截 */
value: boolean
) => void,
/** 是否被拦截 */
isCancelled: () => boolean,
/** 获取事件ID */
getId: () => number,
/** 获取事件类型 */
getEventType: () => string
}) => void,
/** 优先级 */
priority?: Event.EventPriority,
/** 插件名 */
pluginName?: string
): number;
/** 订阅事件(服务器关闭事件) */
export function emplaceListener(
/** 事件名 */
eventName: "ll::ServerStoppingEvent",
/** 回调 */
callback: (event: {
/** 事件参数 */
params: {},
/** 获取事件ID */
getId: () => number,
/** 获取事件类型 */
getEventType: () => string
}) => void,
/** 优先级 */
priority?: Event.EventPriority,
/** 插件名 */
pluginName?: string
): number;
/** 订阅事件(客户端登录后事件) */
export function emplaceListener(
/** 事件名 */
eventName: "gmlib::ClientLoginAfterEvent",
/** 回调 */
callback: (event: {
/** 事件参数 */
params: {
/** 玩家名 */
0: string,
/** 玩家uuid */
1: string,
/** 玩家服务端xuid */
2: string,
/** 玩家客户端xuid */
3: string,
},
/** 拦截事件 */
cancel: () => void,
/** 设置拦截状态 */
setCancelled: (
/** 是否拦截 */
value: boolean
) => void,
/** 是否被拦截 */
isCancelled: () => boolean,
/** 获取事件ID */
getId: () => number,
/** 获取事件类型 */
getEventType: () => string
}) => void,
/** 优先级 */
priority?: Event.EventPriority,
/** 插件名 */
pluginName?: string
): number;
/** 订阅事件(天气更新前事件) */
export function emplaceListener(
/** 事件名 */
eventName: "gmlib::WeatherUpdateBeforeEvent",
/** 回调 */
callback: (event: {
/** 事件参数 */
params: {
/** 雨天等级 */
0: number,
/** 雨天时间(tick) */
1: number,
/** 暴雨等级 */
2: number,
/** 暴雨时间(tick) */
3: number,
},
/** 拦截事件 */
cancel: () => void,
/** 设置拦截状态 */
setCancelled: (
/** 是否拦截 */
value: boolean
) => void,
/** 是否被拦截 */
isCancelled: () => boolean,
/** 获取事件ID */
getId: () => number,
/** 获取事件类型 */
getEventType: () => string
}) => void,
/** 优先级 */
priority?: Event.EventPriority,
/** 插件名 */
pluginName?: string
): number;
/** 订阅事件(天气更新后事件) */
export function emplaceListener(
/** 事件名 */
eventName: "gmlib::WeatherUpdateAfterEvent",
/** 回调 */
callback: (event: {
/** 事件参数 */
params: {
/** 雨天等级 */
0: number,
/** 雨天时间(tick) */
1: number,
/** 暴雨等级 */
2: number,
/** 暴雨时间(tick) */
3: number,
},
/** 获取事件ID */
getId: () => number,
/** 获取事件类型 */
getEventType: () => string
}) => void,
/** 优先级 */
priority?: Event.EventPriority,
/** 插件名 */
pluginName?: string
): number;
/** 订阅事件(实体捡起物品前事件) */
export function emplaceListener(
/** 事件名 */
eventName: "gmlib::MobPickupItemBeforeEvent",
/** 回调 */
callback: (event: {
/** 事件参数 */
params: {
/** 捡起物品的实体 */
0: Entity,
/** 掉落物 */
1: Entity
},
/** 拦截事件 */
cancel: () => void,
/** 设置拦截状态 */
setCancelled: (
/** 是否拦截 */
value: boolean
) => void,
/** 是否被拦截 */
isCancelled: () => boolean,
/** 获取事件ID */
getId: () => number,
/** 获取事件类型 */
getEventType: () => string
}) => void,
/** 优先级 */
priority?: Event.EventPriority,
/** 插件名 */
pluginName?: string
): number;
/** 订阅事件(实体捡起物品后事件) */
export function emplaceListener(
/** 事件名 */
eventName: "gmlib::MobPickupItemAfterEvent",
/** 回调 */
callback: (event: {
/** 事件参数 */
params: {
/** 捡起物品的实体 */
0: Entity,
/** 掉落物 */
1: Entity
},
/** 获取事件ID */
getId: () => number,
/** 获取事件类型 */
getEventType: () => string
}) => void,
/** 优先级 */
priority?: Event.EventPriority,
/** 插件名 */
pluginName?: string
): number;
/** 订阅事件(掉落物生成前事件) */
export function emplaceListener(
/** 事件名 */
eventName: "gmlib::ItemActorSpawnBeforeEvent",
/** 回调 */
callback: (event: {
/** 事件参数 */
params: {
/** 物品 */
0: Item,
/** 生成坐标坐标 */
1: FloatPos,
/** 生成此物品主人的uniqueId (-1为不存在) */
2: number
},
/** 拦截事件 */
cancel: () => void,
/** 设置拦截状态 */
setCancelled: (
/** 是否拦截 */
value: boolean
) => void,
/** 是否被拦截 */
isCancelled: () => boolean,
/** 获取事件ID */
getId: () => number,
/** 获取事件类型 */
getEventType: () => string
}) => void,
/** 优先级 */
priority?: Event.EventPriority,
/** 插件名 */
pluginName?: string
): number;
/** 订阅事件(掉落物生成后事件) */
export function emplaceListener(
/** 事件名 */
eventName: "gmlib::ItemActorSpawnAfterEvent",
/** 回调 */
callback: (event: {
/** 事件参数 */
params: {
/** 物品实体对象 */
0: Entity,
/** 生成坐标坐标 */
1: FloatPos,
/** 生成此物品主人的uniqueId (-1为不存在) */
2: number
},
/** 获取事件ID */
getId: () => number,
/** 获取事件类型 */
getEventType: () => string
}) => void,
/** 优先级 */
priority?: Event.EventPriority,
/** 插件名 */
pluginName?: string
): number;
/** 订阅事件(实体切换维度前事件) */
export function emplaceListener(
/** 事件名 */
eventName: "gmlib::ActorChangeDimensionBeforeEvent",
/** 回调 */
callback: (event: {
/** 事件参数 */
params: {
/** 切换维度的实体 */
0: Entity,
/** 前往的维度ID */
1: number
},
/** 拦截事件 */
cancel: () => void,
/** 设置拦截状态 */
setCancelled: (
/** 是否拦截 */
value: boolean
) => void,
/** 是否被拦截 */
isCancelled: () => boolean,
/** 获取事件ID */
getId: () => number,
/** 获取事件类型 */
getEventType: () => string
}) => void,
/** 优先级 */
priority?: Event.EventPriority,
/** 插件名 */
pluginName?: string
): number;
/** 订阅事件(事件切换维度后事件) */
export function emplaceListener(
/** 事件名 */
eventName: "gmlib::ActorChangeDimensionAfterEvent",
/** 回调 */
callback: (event: {
/** 事件参数 */
params: {
/** 切换维度的实体 */
0: Entity,
/** 原来的维度ID */
1: number,
/** 前往的维度ID */
2: number
},
/** 获取事件ID */
getId: () => number,
/** 获取事件类型 */
getEventType: () => string
}) => void,
/** 优先级 */
priority?: Event.EventPriority,
/** 插件名 */
pluginName?: string
): number;
/** 订阅事件(玩家开始睡觉前事件) */
export function emplaceListener(
/** 事件名 */
eventName: "gmlib::PlayerStartSleepBeforeEvent",
/** 回调 */
callback: (event: {
/** 事件参数 */
params: {
/** 睡觉的玩家 */
0: Player,
/** 床的坐标 */
1: IntPos
},
/** 拦截事件 */
cancel: () => void,
/** 设置拦截状态 */
setCancelled: (
/** 是否拦截 */
value: boolean
) => void,
/** 是否被拦截 */
isCancelled: () => boolean,
/** 获取事件ID */
getId: () => number,
/** 获取事件类型 */
getEventType: () => string
}) => void,
/** 优先级 */
priority?: Event.EventPriority,
/** 插件名 */
pluginName?: string
): number;
/** 订阅事件(玩家开始睡觉后事件) */
export function emplaceListener(
/** 事件名 */
eventName: "gmlib::PlayerStartSleepAfterEvent",
/** 回调 */
callback: (event: {
/** 事件参数 */
params: {
/** 睡觉的玩家 */
0: Player,
/** 床的坐标 */
1: IntPos,
/** 睡觉的结果 */
2: number
},
/** 获取事件ID */
getId: () => number,
/** 获取事件类型 */
getEventType: () => string
}) => void,
/** 优先级 */
priority?: Event.EventPriority,
/** 插件名 */
pluginName?: string
): number;
/** 订阅事件(玩家停止睡觉前事件) */
export function emplaceListener(
/** 事件名 */
eventName: "gmlib::PlayerStopSleepBeforeEvent",
/** 回调 */
callback: (event: {
/** 事件参数 */
params: {
/** 睡觉的玩家 */
0: Player,
/** forcefulWakeUp */
1: boolean,
/** updateLevelList */
2: boolean
},
/** 拦截事件 */
cancel: () => void,
/** 设置拦截状态 */
setCancelled: (
/** 是否拦截 */
value: boolean
) => void,
/** 是否被拦截 */
isCancelled: () => boolean,
/** 获取事件ID */
getId: () => number,
/** 获取事件类型 */
getEventType: () => string
}) => void,
/** 优先级 */
priority?: Event.EventPriority,
/** 插件名 */
pluginName?: string
): number;
/** 订阅事件(玩家停止睡觉后事件) */
export function emplaceListener(
/** 事件名 */
eventName: "gmlib::PlayerStopSleepAfterEvent",
/** 回调 */
callback: (event: {
/** 事件参数 */
params: {
/** 睡觉的玩家 */
0: Player,
/** forcefulWakeUp */
1: boolean,
/** updateLevelList */
2: boolean
},
/** 获取事件ID */
getId: () => number,
/** 获取事件类型 */
getEventType: () => string
}) => void,
/** 优先级 */
priority?: Event.EventPriority,
/** 插件名 */
pluginName?: string
): number;
/** 订阅事件(生成死亡消息后事件) */
export function emplaceListener(
/** 事件名 */
eventName: "gmlib::DeathMessageAfterEvent",
/** 回调 */
callback: (event: {
/** 事件参数 */
params: {
/** 键名 */
0: string,
/** 翻译参数 */
1: string[],
/** 死亡的实体 */
2: Entity
},
/** 获取事件ID */
getId: () => number,
/** 获取事件类型 */
getEventType: () => string
}) => void,
/** 优先级 */
priority?: Event.EventPriority,
/** 插件名 */
pluginName?: string
): number;
/** 订阅事件(实体受伤后事件) */
export function emplaceListener(
/** 事件名 */
eventName: "gmlib::MobHurtAfterEvent",
/** 回调 */
callback: (event: {
/** 事件参数 */
params: {
/** 受伤的实体 */
0: Entity,
/** 伤害来源 */
1: Entity,
/** 伤害值 */
2: number,
/** 伤害类型 */
3: DamageCause
},
/** 获取事件ID */
getId: () => number,
/** 获取事件类型 */
getEventType: () => string
}) => void,
/** 优先级 */
priority?: Event.EventPriority,
/** 插件名 */
pluginName?: string
): number;
/** 订阅事件(末影人搬运方块前事件) */
export function emplaceListener(
/** 事件名 */
eventName: "gmlib::EndermanTakeBlockBeforeEvent",
/** 回调 */
callback: (event: {
/** 事件参数 */
params: {
/** 末影人实体 */
0: Entity
},
/** 拦截事件 */
cancel: () => void,
/** 设置拦截状态 */
setCancelled: (
/** 是否拦截 */
value: boolean
) => void,
/** 是否被拦截 */
isCancelled: () => boolean,
/** 获取事件ID */
getId: () => number,
/** 获取事件类型 */
getEventType: () => string
}) => void,
/** 优先级 */
priority?: Event.EventPriority,
/** 插件名 */
pluginName?: string
): number;
/** 订阅事件(末影龙复活前事件) */
export function emplaceListener(
/** 事件名 */
eventName: "gmlib::DragonRespawnBeforeEvent",
/** 回调 */
callback: (event: {
/** 事件参数 */
params: {},
/** 拦截事件 */
cancel: () => void,
/** 设置拦截状态 */
setCancelled: (
/** 是否拦截 */
value: boolean
) => void,
/** 是否被拦截 */
isCancelled: () => boolean,
/** 获取事件ID */
getId: () => number,
/** 获取事件类型 */
getEventType: () => string
}) => void,
/** 优先级 */
priority?: Event.EventPriority,
/** 插件名 */
pluginName?: string
): number;
/** 订阅事件(末影龙复活后事件) */
export function emplaceListener(
/** 事件名 */
eventName: "gmlib::DragonRespawnAfterEvent",
/** 回调 */
callback: (event: {
/** 事件参数 */
params: {
/** 末影龙实体 */
0: Entity
},
/** 获取事件ID */
getId: () => number,
/** 获取事件类型 */
getEventType: () => string
}) => void,
/** 优先级 */
priority?: Event.EventPriority,
/** 插件名 */
pluginName?: string
): number;
/** 订阅事件(投射物创建前事件) */
export function emplaceListener(
/** 事件名 */
eventName: "gmlib::ProjectileCreateBeforeEvent",
/** 回调 */
callback: (event: {
/** 事件参数 */
params: {
/** 投射物实体 */
0: Entity,
/** 创建投射物实体的uniqueId */
1: number
},
/** 拦截事件 */
cancel: () => void,
/** 设置拦截状态 */
setCancelled: (
/** 是否拦截 */
value: boolean
) => void,
/** 是否被拦截 */
isCancelled: () => boolean,
/** 获取事件ID */
getId: () => number,
/** 获取事件类型 */
getEventType: () => string
}) => void,
/** 优先级 */
priority?: Event.EventPriority,
/** 插件名 */
pluginName?: string
): number;
/** 订阅事件(投射物创建后事件) */
export function emplaceListener(
/** 事件名 */
eventName: "gmlib::ProjectileCreateAfterEvent",
/** 回调 */
callback: (event: {
/** 事件参数 */
params: {
/** 投射物实体 */
0: Entity,
/** 创建投射物实体的uniqueId */
1: number
},
/** 获取事件ID */
getId: () => number,
/** 获取事件类型 */
getEventType: () => string
}) => void,
/** 优先级 */
priority?: Event.EventPriority,
/** 插件名 */
pluginName?: string
): number;
/** 订阅事件(生成流浪商人前事件) */
export function emplaceListener(
/** 事件名 */
eventName: "gmlib::SpawnWanderingTraderBeforeEvent",
/** 回调 */
callback: (event: {
/** 事件参数 */
params: {
/** 出现的坐标 */
0: IntPos
},
/** 拦截事件 */
cancel: () => void,
/** 设置拦截状态 */
setCancelled: (
/** 是否拦截 */
value: boolean
) => void,
/** 是否被拦截 */
isCancelled: () => boolean,
/** 获取事件ID */
getId: () => number,
/** 获取事件类型 */
getEventType: () => string
}) => void,
/** 优先级 */
priority?: Event.EventPriority,
/** 插件名 */
pluginName?: string
): number;
/** 订阅事件(生成流浪商人后事件) */
export function emplaceListener(
/** 事件名 */
eventName: "gmlib::SpawnWanderingTraderAfterEvent",
/** 回调 */
callback: (event: {
/** 事件参数 */
params: {
/** 出现的坐标 */
0: IntPos
},
/** 获取事件ID */
getId: () => number,
/** 获取事件类型 */
getEventType: () => string
}) => void,
/** 优先级 */
priority?: Event.EventPriority,
/** 插件名 */
pluginName?: string
): number;
/** 订阅事件(处理物品请求前事件) */
export function emplaceListener(
/** 事件名 */
eventName: "gmlib::HandleRequestActionBeforeEvent",
/** 回调 */
callback: (event: {
/** 事件参数 */
params: {
/** 请求的玩家 */
0: Player,
/** 请求类型 */
1: string,
/** 请求数量 */
2: number,
/** 请求原容器类型 */
3: string,
/** 请求原容器槽位 */
4: number,
/** 请求前往的容器类型 */
5: string,
/** 请求前往的槽位 */
6: number
},
/** 拦截事件 */
cancel: () => void,
/** 设置拦截状态 */
setCancelled: (
/** 是否拦截 */
value: boolean
) => void,
/** 是否被拦截 */
isCancelled: () => boolean,
/** 获取事件ID */
getId: () => number,
/** 获取事件类型 */
getEventType: () => string
}) => void,
/** 优先级 */
priority?: Event.EventPriority,
/** 插件名 */
pluginName?: string
): number;
/** 订阅事件(处理物品请求后事件) */
export function emplaceListener(
/** 事件名 */
eventName: "gmlib::HandleRequestActionAfterEvent",
/** 回调 */
callback: (event: {
/** 事件参数 */
params: {
/** 请求的玩家 */
0: Player,
/** 请求类型 */
1: string,
/** 请求数量 */
2: number,
/** 请求原容器类型 */
3: string,
/** 请求原容器槽位 */
4: number,
/** 请求前往的容器类型 */
5: string,
/** 请求前往的槽位 */
6: number
},
/** 获取事件ID */
getId: () => number,
/** 获取事件类型 */
getEventType: () => string
}) => void,
/** 优先级 */
priority?: Event.EventPriority,
/** 插件名 */
pluginName?: string
): number;
/** 订阅事件(玩家关闭容器后事件) */
export function emplaceListener(
/** 事件名 */
eventName: "gmlib::ContainerClosePacketSendAfterEvent",
/** 回调 */
callback: (event: {
/** 事件参数 */
params: {
/** 关闭的玩家 */
0: Player,
/** 容器会话ID */
1: number,
/** 由服务器关闭 */
2: boolean
},
/** 获取事件ID */
getId: () => number,
/** 获取事件类型 */
getEventType: () => string
}) => void,
/** 优先级 */
priority?: Event.EventPriority,
/** 插件名 */
pluginName?: string
): number;
}
+202 -19
View File
@@ -1,29 +1,212 @@
const CallEvent = ll.import("GMLIB_API", "callCustomEvent"); const getPluginName = () => {
if (getPluginName.PluginNameCache) return getPluginName.PluginNameCache;
let NextEventId = 0; return getPluginName.PluginNameCache = (() => {
if (ll.getCurrentPluginInfo) return ll.getCurrentPluginInfo().name;
function getNextEventId() { const error = new Error("getPluginName");
NextEventId++; switch (ll.scriptEngineVersion) {
return "GMLIB_Event_" + NextEventId; case "QuickJS": {
if (!error.stack) break;
const /** @type {string} */ line = error.stack.trim().split("\n").pop().trim();
if (line.includes("<anonymous>")) {
return line.slice(
line.indexOf("(") + 1,
line.indexOf("\\")
);
} }
if (line.includes("<eval>")) {
return line.slice(
line.indexOf("/", line.indexOf("/") + 1) + 1,
line.indexOf("\\")
);
}
break;
}
case "V8 12.4.254.21-node.21": {
try {
const selfFileName = require('path').basename(__filename);
const pluginDirectory = Object.entries(
require('module')._pathCache
).find(
([key, _]) => key.includes(selfFileName)
)[0].split("\u0000")[1];
const directories = pluginDirectory.split("\\");
const pluginName = directories[directories.findIndex(value => value === "plugins") + 1].trim();
if (pluginName) return pluginName;
} catch { }
class Event { if (!error.stack) break;
constructor() { const /** @type {string} */ line = error.stack.trim().split("\n").pop().trim();
throw new Error("Static class cannot be instantiated"); if (line.includes(".js") && /:\d+:\d+$/.test(line)) {
const directories = line.split("\\");
const pluginName = directories[directories.findIndex(value => value === "plugins") + 1].trim();
if (pluginName) return pluginName;
} }
break;
static listen(event, callback) {
let eventId = getNextEventId();
ll.export(callback, event, eventId);
let result = CallEvent(event, eventId);
if (!result) {
logger.error(`Cannot listen event "${event}"!`);
logger.error(`Event "${event}" No Found!`);
}
return result;
} }
default: break;
} }
return "Unknown";
})();
};
module.exports = { module.exports = {
Event Event: {
/**
* 事件订阅记录
* 例如: {事件名: [事件ID, ...], ...}
* @type {Object.<string, number[]>}
*/
mEventData: {},
/**
* 事件异常处理回调
* @param {Error} error
* @param {string} eventName
* @param {number} eventID
* @param {string} pluginName
* @returns {void}
*/
mErrorHanlerCallback: (error, eventName, eventID, pluginName) => {
logger.error(`Info: ${pluginName}-${eventName}-${eventID} Exception: ${error.message}\n${error.stack}`);
},
/**
* 监听事件(兼容旧版)
* @param {string} eventName
* @param {function} callback
* @param {boolean}
*/
listen: function (eventName, callback) {
try {
if (typeof callback !== "function") return false;
const eventReflection = {
onServerStopping: "ll::ServerStoppingEvent",
onClientLogin: "gmlib::ClientLoginAfterEvent",
onWeatherChange: "gmlib::WeatherUpdateBeforeEvent",
onMobPick: "gmlib::MobPickupItemBeforeEvent",
onItemTrySpawn: "gmlib::ItemActorSpawnBeforeEvent",
onItemSpawned: "gmlib::ItemActorSpawnAfterEvent",
onEntityTryChangeDim: "gmlib::ActorChangeDimensionBeforeEvent",
onLeaveBed: "gmlib::PlayerStopSleepBeforeEvent",
onDeathMessage: "gmlib::DeathMessageAfterEvent",
onMobHurted: "gmlib::MobHurtAfterEvent",
onEndermanTake: "gmlib::EndermanTakeBlockBeforeEvent",
onEntityChangeDim: "gmlib::ActorChangeDimensionAfterEvent",
onDragonRespawn: "gmlib::DragonRespawnBeforeEvent",
onProjectileTryCreate: "gmlib::ProjectileCreateBeforeEvent",
onProjectileCreate: "gmlib::ProjectileCreateAfterEvent",
onSpawnWanderingTrader: "gmlib::SpawnWanderingTraderBeforeEvent",
onHandleRequestAction: "gmlib::HandleRequestActionBeforeEvent",
onSendContainerClosePacket: "gmlib::ContainerClosePacketSendAfterEvent"
};
this.emplaceListener(eventReflection[eventName] ?? eventName, event => {
const result = callback(...event.params);
if (typeof (result) === "boolean" && !result) event.cancel();
});
return true;
} catch { }
return false;
},
/**
* 订阅事件
* @param {string} eventName
* @param {function} callback
* @param {number?} priority
* @param {string?} pluginName
* @returns {number}
*/
emplaceListener: function (eventName, callback, priority = this.EventPriority.Normal, pluginName = getPluginName()) {
if (typeof callback !== "function") throw new Error("callback must be a function!");
const /** @type {number} */ eventId = ll.imports("GMLIB_Event_API", "emplaceListener")(pluginName, eventName, priority);
if (eventId === -1) throw new Error(`Event ${eventName} creation failed!`);
ll.exports((...data) => {
let /** @type {boolean} */ result = typeof (data.slice(-1)[0]) === "boolean" ? data.pop() : false;
try {
callback({
params: data,
cancel: () => result = true,
setCancelled: (/** @type {boolean} */value) => { result = value; },
isCancelled: () => result,
getId: () => eventId,
getEventType: () => eventName
});
} catch (error) {
try {
this.mErrorHanlerCallback(error, eventName, eventId, pluginName);
} catch { }
}
return result;
}, pluginName, eventName + "_" + eventId);
(this.mEventData[eventName] ??= []).push(eventId);
return eventId;
},
/**
* 取消事件订阅
* @param {number} eventId
* @param {boolean}
*/
removeListener: function (eventId) {
const result = ll.imports("GMLIB_Event_API", "removeListener")(eventId);
if (result) {
for (let [eventName, eventIds] of Object.entries(this.mEventData)) {
this.mEventData[eventName] = eventIds.filter(id => id !== eventId);
if (this.mEventData[eventName].length === 0) delete this.mEventData[eventName];
}
}
return result;
},
/**
* 判断事件订阅是否存在
* @param {number} eventId
* @returns {boolean}
*/
hasListener: function (eventId) {
return ll.imports("GMLIB_Event_API", "hasListener")(eventId);
},
/**
* 获取订阅事件优先级
* @param {number} eventId
* @returns {number?}
*/
getListenerPriority: function (eventId) {
const priority = ll.imports("GMLIB_Event_API", "getListenerPriority")(eventId);
return priority === -1 ? undefined : priority;
},
/**
* 获取订阅事件列表
* @param {string | undefined} eventName
* @returns {number[] | Object.<string, number[]>}
*/
getListener: function (eventName) {
return eventName === undefined ? this.mEventData : this.mEventData[eventName] ?? [];
},
/**
* 设置异常处理回调
* @param {function(Error, string, number, string): void} callback
* @returns {boolean}
*/
setErrorHanlerCallback: function (callback) {
if (callback === undefined || typeof callback !== "function") return false;
this.mErrorHanlerCallback = callback;
return true;
},
/**
* 事件优先级
*/
EventPriority: {
Highest: 0,
High: 100,
Normal: 200,
Low: 300,
Lowest: 400
}
}
}; };
+182
View File
@@ -0,0 +1,182 @@
// // const getNextCallbackId = ll.imports("GMLIB_FormAPI", "getNextFormCallbackId");
// class ServerSettingForm {
// constructor() {
// throw new Error("Static class cannot be instantiated");
// }
// static getDefaultPriority() {
// return ll.imports("GMLIB_ServerSettingForm", "getDefaultPriority")();
// }
// static hasTitle() {
// return ll.imports("GMLIB_ServerSettingForm", "hasTitle")();
// }
// static getTitle() {
// return ll.imports("GMLIB_ServerSettingForm", "getTitle")();
// }
// static setTitle(title, forceModify = false) {
// return ll.imports("GMLIB_ServerSettingForm", "setTitle")(title, forceModify);
// }
// static hasIcon() {
// return ll.imports("GMLIB_ServerSettingForm", "hasIcon")();
// }
// static getIconData() {
// return hasIcon() ? ll.imports("GMLIB_ServerSettingForm", "getIconData")() : null;
// }
// static getIconType() {
// return ll.imports("GMLIB_ServerSettingForm", "getIconType")();
// }
// static setIcon(data, type = 0, forceModify = false) {
// return ll.imports("GMLIB_ServerSettingForm", "setIcon")(data, type, forceModify);
// }
// static addLabel(
// text,
// playerDetector = (pl) => { return true; },
// priority = this.getDefaultPriority()
// ) {
// let detectorId = getNextCallbackId();
// ll.export(playerDetector, "GMLIB_FORM_CALLBACK", detectorId);
// return ll.imports("GMLIB_ServerSettingForm", "addLabel")(text, detectorId, priority);
// }
// static addInput(
// text,
// placeholder,
// defaultVal,
// callback = (pl, input) => { },
// playerDetector = (pl) => { return true; },
// priority = this.getDefaultPriority()
// ) {
// let callbackId = getNextCallbackId();
// ll.export(callback, "GMLIB_FORM_CALLBACK", callbackId);
// let detectorId = getNextCallbackId();
// ll.export(playerDetector, "GMLIB_FORM_CALLBACK", detectorId);
// return ll.imports("GMLIB_ServerSettingForm", "addInput")(text, placeholder, defaultVal, callbackId, detectorId, priority);
// }
// static addToggle(
// text,
// defaultVal = false,
// callback = (pl, input) => { },
// playerDetector = (pl) => { return true; },
// priority = this.getDefaultPriority()
// ) {
// let callbackId = getNextCallbackId();
// ll.export(callback, "GMLIB_FORM_CALLBACK", callbackId);
// let detectorId = getNextCallbackId();
// ll.export(playerDetector, "GMLIB_FORM_CALLBACK", detectorId);
// return ll.imports("GMLIB_ServerSettingForm", "addToggle")(text, defaultVal, callbackId, detectorId, priority);
// }
// static addDropdown(
// text,
// options,
// defaultVal = 0,
// callback = (pl, input) => { },
// playerDetector = (pl) => { return true; },
// priority = this.getDefaultPriority()
// ) {
// let callbackId = getNextCallbackId();
// ll.export(callback, "GMLIB_FORM_CALLBACK", callbackId);
// let detectorId = getNextCallbackId();
// ll.export(playerDetector, "GMLIB_FORM_CALLBACK", detectorId);
// return ll.imports("GMLIB_ServerSettingForm", "addDropdown")(text, options, defaultVal, callbackId, detectorId, priority);
// }
// static addSlider(
// text,
// min,
// max,
// step = 0.0,
// defaultVal = 0.0,
// callback = (pl, input) => { },
// playerDetector = (pl) => { return true; },
// priority = this.getDefaultPriority()
// ) {
// let callbackId = getNextCallbackId();
// ll.export(callback, "GMLIB_FORM_CALLBACK", callbackId);
// let detectorId = getNextCallbackId();
// ll.export(playerDetector, "GMLIB_FORM_CALLBACK", detectorId);
// return ll.imports("GMLIB_ServerSettingForm", "addSlider")(text, min, max, step, defaultVal, callbackId, detectorId, priority);
// }
// static addStepSlider(
// text,
// steps,
// defaultVal = 0,
// callback = (pl, input) => { },
// playerDetector = (pl) => { return true; },
// priority = this.getDefaultPriority()
// ) {
// let callbackId = getNextCallbackId();
// ll.export(callback, "GMLIB_FORM_CALLBACK", callbackId);
// let detectorId = getNextCallbackId();
// ll.export(playerDetector, "GMLIB_FORM_CALLBACK", detectorId);
// return ll.imports("GMLIB_ServerSettingForm", "addStepSlider")(text, steps, defaultVal, callbackId, detectorId, priority);
// }
// static removeElement(id) {
// return ll.imports("GMLIB_ServerSettingForm", "removeElement")(id);
// }
// }
// class NpcDialogueForm {
// constructor(npcName, sceneName, dialogue) {
// this.mFormId = ll.imports("GMLIB_NpcDialogueForm", "createForm")(npcName, sceneName, dialogue);
// }
// addButton(button) {
// return ll.imports("GMLIB_NpcDialogueForm", "addButton")(this.mFormId, button);
// }
// sendTo(pl, callback = (pl, index, type) => { }, free = true) {
// let callbackId = getNextCallbackId();
// ll.export(callback, "GMLIB_FORM_CALLBACK", callbackId);
// ll.imports("GMLIB_NpcDialogueForm", "sendTo")(this.mFormId, pl, callbackId);
// if (free) {
// this.destroy();
// }
// }
// destroy() {
// ll.imports("GMLIB_NpcDialogueForm", "destroyForm")(this.mFormId);
// }
// }
// class ChestForm {
// constructor(npcName, sceneName, dialogue) {
// this.mFormId = ll.imports("GMLIB_NpcDialogueForm", "createForm")(npcName, sceneName, dialogue);
// }
// addButton(button) {
// return ll.imports("GMLIB_NpcDialogueForm", "addButton")(this.mFormId, button);
// }
// sendTo(pl, free = true) {
// //let callbackId = getNextCallbackId();
// //ll.export(callback, "GMLIB_FORM_CALLBACK", callbackId);
// //ll.imports("GMLIB_NpcDialogueForm", "sendTo")(this.mFormId, pl, callbackId);
// //if (free) {
// // this.destroy();
// //}
// }
// destroy() {
// //ll.imports("GMLIB_NpcDialogueForm", "destroyForm")(this.mFormId);
// }
// }
// module.exports = {
// ServerSettingForm,
// NpcDialogueForm,
// ChestForm
// };
+1888
View File
File diff suppressed because it is too large Load Diff
+2663 -196
View File
File diff suppressed because it is too large Load Diff
+42
View File
@@ -0,0 +1,42 @@
/** 翻译带PAPI变量文本 */
export function translate(
/** 要翻译的文本 */
value: String,
/** 实体对象 */
actor?: Entity,
/** 目标翻译语言 */
language?: String
): String;
/** 注册PAPI变量 */
export function registerPlaceholder(
/** papi变量 */
placeholder: String,
/** 回调 */
callback: (
/** 实体对象 */ actor: Entity,
/** 参数 */ params: String[],
/** 目标翻译语言 */language: String
) => String | undefined
): void;
/** 注销PAPI变量 */
export function unregisterPlaceholder(
/** papi变量 */
placeholder: String
): Boolean;
/** 根据模组名注销PAPI变量 */
export function unregisterPlaceholderFromModName(
/** 模组名 */
modName: String
): Boolean;
/** 获取一个papi变量的值 */
export function getValue(
/** papi变量名 */
placeholder: String,
actor?: Entity,
params?: Record<String, String>,
language?: string
): Boolean;
+83
View File
@@ -0,0 +1,83 @@
/// <reference path='d:/dts/dts/helperlib/src/index.d.ts'/>
const getPluginName = () => {
if (getPluginName.PluginNameCache) return getPluginName.PluginNameCache;
return getPluginName.PluginNameCache = (() => {
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();
if (line.includes("<anonymous>")) {
return line.slice(
line.indexOf("(") + 1,
line.indexOf("\\")
);
}
if (line.includes("<eval>")) {
return line.slice(
line.indexOf("/", line.indexOf("/") + 1) + 1,
line.indexOf("\\")
);
}
break;
}
case "V8 12.4.254.21-node.21": {
try {
const selfFileName = require('path').basename(__filename);
const pluginDirectory = Object.entries(
require('module')._pathCache
).find(
([key, _]) => key.includes(selfFileName)
)[0].split("\u0000")[1];
const directories = pluginDirectory.split("\\");
const pluginName = directories[directories.findIndex(value => value === "plugins") + 1].trim();
if (pluginName) return pluginName;
} catch { }
if (!error.stack) break;
const /** @type {string} */ line = error.stack.trim().split("\n").pop().trim();
if (line.includes(".js") && /:\d+:\d+$/.test(line)) {
const directories = line.split("\\");
const pluginName = directories[directories.findIndex(value => value === "plugins") + 1].trim();
if (pluginName) return pluginName;
}
break;
}
default: break;
}
return "Unknown";
})();
};
module.exports = {
translate(value, actor = undefined, language = "") {
return actor instanceof LLSE_Entity
? ll.imports("PlaceholderAPI", "translateFromActor")(value, actor, language)
: ll.imports("PlaceholderAPI", "translate")(value, language);
},
registerPlaceholder(placeholder, callback) {
const pluginName = getPluginName();
ll.exports((...args) => {
if(!args[0].uniqueId) args[0] = undefined;
return callback(...args) ?? "<std::nullopt>";
}, pluginName, `Placeholder_${placeholder}`);
ll.imports("PlaceholderAPI", "registerPlaceholder")(placeholder, `Placeholder_${placeholder}`, pluginName);
},
unregisterPlaceholder(placeholder) {
return ll.imports("PlaceholderAPI", "unregisterPlaceholder")(placeholder);
},
unregisterPlaceholderFromModName(placeholder) {
return ll.imports("PlaceholderAPI", "unregisterPlaceholderFromModName")(placeholder);
},
getValue(placeholder, actor = undefined, params = {}, language = "") {
if (actor instanceof LLSE_Player) actor = ll.imports("GMLib_ServerAPI", "PlayerToEntity")(actor);
const result = actor instanceof LLSE_Entity
? ll.imports("PlaceholderAPI", "getValueFromActor")(placeholder, actor, params, language)
: ll.imports("PlaceholderAPI", "getValue")(placeholder, params, language);
return result !== "<std::nullopt>" ? result : undefined;
}
};
+10 -3
View File
@@ -1,15 +1,22 @@
{ {
"name": "${pluginName}", "name": "${modName}",
"entry": "${pluginFile}", "entry": "${modFile}",
"version": "0.12.5", "version": "${modVersion}",
"author": "GroupMountain", "author": "GroupMountain",
"type": "native", "type": "native",
"passive": true,
"dependencies": [ "dependencies": [
{ {
"name": "GMLIB" "name": "GMLIB"
}, },
{ {
"name": "LegacyRemoteCall" "name": "LegacyRemoteCall"
},
{
"name": "iListenAttentively"
},
{
"name": "ModAPI"
} }
] ]
} }
-121
View File
@@ -1,121 +0,0 @@
function beautify_json(value, indent)
import("core.base.json")
local json_text = ""
local stack = {}
local function escape_str(s)
return string.gsub(s, '[%c\\"]', function(c)
local replacements = {['\b'] = '\\b', ['\f'] = '\\f', ['\n'] = '\\n', ['\r'] = '\\r', ['\t'] = '\\t', ['"'] = '\\"', ['\\'] = '\\\\'}
return replacements[c] or string.format('\\u%04x', c:byte())
end)
end
local function is_null(v)
return v == json.null
end
local function is_empty_table(t)
if type(t) ~= 'table' then return false end
for _ in pairs(t) do
return false
end
return true
end
local function is_array(t)
return type(t) == 'table' and json.is_marked_as_array(t) or #t > 0
end
local function serialize(val, level)
local spaces = string.rep(" ", level * indent)
if type(val) == "table" and not stack[val] then
if is_empty_table(val) then
json_text = json_text .. (is_array(val) and "[]" or "{}")
return
end
stack[val] = true
local isArray = is_array(val)
json_text = json_text .. (isArray and "[\n" or "{\n")
local keys = isArray and {} or {}
for k in pairs(val) do
table.insert(keys, k)
end
if not isArray then
table.sort(keys)
end
for _, k in ipairs(keys) do
local v = val[k]
json_text = json_text .. spaces .. (isArray and "" or '"' .. escape_str(tostring(k)) .. '": ')
serialize(v, level + 1)
json_text = json_text .. ",\n"
end
json_text = string.sub(json_text, 1, -3) .. "\n" .. string.rep(" ", (level - 1) * indent) .. (isArray and "]" or "}")
stack[val] = nil
elseif type(val) == "string" then
json_text = json_text .. '"' .. escape_str(val) .. '"'
elseif type(val) == "number" then
if val % 1 == 0 then
json_text = json_text .. tostring(math.floor(val))
else
json_text = json_text .. tostring(val)
end
elseif type(val) == "boolean" then
json_text = json_text .. tostring(val)
elseif is_null(val) then
json_text = json_text .. "null"
else
error("Invalid value type: " .. type(val))
end
end
serialize(value, 1)
return json_text
end
function string_formatter(str, variables)
return str:gsub("%${(.-)}", function(var)
return variables[var] or "${" .. var .. "}"
end)
end
function pack_plugin(target,plugin_define)
import("lib.detect.find_file")
local manifest_path = find_file("manifest.json", os.projectdir())
if manifest_path then
local manifest = io.readfile(manifest_path)
local bindir = path.join(os.projectdir(), "bin/DLL")
local pdbdir = path.join(os.projectdir(), "bin/PDB")
local outputdir = path.join(bindir, plugin_define.pluginName)
local targetfile = path.join(outputdir, plugin_define.pluginFile)
local pdbfile = path.join(pdbdir, path.basename(plugin_define.pluginFile) .. ".pdb")
local libfile = path.join(os.projectdir(), "lib")
local manifestfile = path.join(outputdir, "manifest.json")
local oritargetfile = target:targetfile()
local oripdbfile = path.join(path.directory(oritargetfile), path.basename(oritargetfile) .. ".pdb")
os.mkdir(outputdir)
os.cp(oritargetfile, targetfile)
if os.isfile(oripdbfile) then
os.cp(oripdbfile, pdbfile)
end
os.cp(libfile, outputdir)
formattedmanifest = string_formatter(manifest, plugin_define)
io.writefile(manifestfile,formattedmanifest)
cprint("${bright green}[Plugin Packer]: ${reset}plugin already generated to " .. outputdir)
else
cprint("${bright yellow}warn: ${reset}not found manifest.json in root dir!")
end
end
return {
pack_plugin = pack_plugin,
beautify_json = beautify_json,
string_formatter = string_formatter
}
+97
View File
@@ -0,0 +1,97 @@
#include "Global.h"
class LegacyScriptBinaryStreamManager {
private:
int64 mNextBinaryStreamId = 0;
std::unordered_map<uint64, std::shared_ptr<GMBinaryStream>> mBinaryStream;
public:
uint getNextId() { return mNextBinaryStreamId++; }
void cretateBinaryStream(uint id) { mBinaryStream[id] = std::make_shared<GMBinaryStream>(); }
uint64 copyBinaryStream(uint id) {
auto nextId = getNextId();
cretateBinaryStream(nextId);
if (auto bs = getBinaryStream(nextId); bs != nullptr) {
getBinaryStream(nextId)->mBuffer = getBinaryStream(id)->mBuffer;
}
return nextId;
}
void removeBinaryStream(uint64 id) { mBinaryStream.erase(id); }
std::shared_ptr<GMBinaryStream> getBinaryStream(uint64 id) {
return mBinaryStream.contains(id) ? mBinaryStream.at(id) : nullptr;
}
public:
static LegacyScriptBinaryStreamManager& getInstance() {
static std::unique_ptr<LegacyScriptBinaryStreamManager> instance;
if (!instance) instance = std::make_unique<LegacyScriptBinaryStreamManager>();
return *instance;
}
};
#define BinaryStreamManager LegacyScriptBinaryStreamManager::getInstance()
#define EXPORTAPI(funcName, type, fuc) \
RemoteCall::exportAs("GMLIB_BinaryStream_API", funcName, [](uint64 id, type value) -> void { \
auto bs = BinaryStreamManager.getBinaryStream(id); \
if (bs != nullptr) fuc; \
})
template <typename T>
struct Info;
template <typename T, typename R, typename A, typename... AS>
struct Info<R (T::*)(A, AS...)> {
using ArgT = A;
};
#define EXPORTAPI2(T) EXPORTAPI(#T, Info<decltype(&BinaryStream::T)>::ArgT, bs->T(value))
void Export_BinaryStream_API() {
RemoteCall::exportAs("GMLIB_BinaryStream_API", "create", []() -> uint64 {
auto id = BinaryStreamManager.getNextId();
BinaryStreamManager.cretateBinaryStream(id);
return id;
});
RemoteCall::exportAs("GMLIB_BinaryStream_API", "copy", [](uint64 id) -> uint64 {
return BinaryStreamManager.copyBinaryStream(id);
});
RemoteCall::exportAs("GMLIB_BinaryStream_API", "reset", [](uint64 id) -> void {
if (BinaryStreamManager.getBinaryStream(id) == nullptr) BinaryStreamManager.cretateBinaryStream(id);
else {
auto bs = BinaryStreamManager.getBinaryStream(id);
bs->mBuffer.clear();
bs->mReadPointer = 0;
bs->mHasOverflowed = false;
}
});
RemoteCall::exportAs("GMLIB_BinaryStream_API", "sendTo", [](uint64 id, Player* player) -> void {
if (auto bs = BinaryStreamManager.getBinaryStream(id); bs != nullptr)
bs->sendTo(static_cast<GMPlayer&>(*player));
});
RemoteCall::exportAs("GMLIB_BinaryStream_API", "destroy", [](uint64 id) -> void {
BinaryStreamManager.removeBinaryStream(id);
});
EXPORTAPI("writePacketHeader", int, bs->writePacketHeader((MinecraftPacketIds)value));
EXPORTAPI("writeUuid", std::string const&, bs->writeUuid(mce::UUID::fromString(value)));
EXPORTAPI("writeItem", ItemStack*, bs->writeNetworkItemStackDescriptor(NetworkItemStackDescriptor(*value)));
EXPORTAPI("writeString", std::string const&, bs->writeString(value));
EXPORTAPI("writeCompoundTag", CompoundTag*, bs->writeCompoundTag(*value));
EXPORTAPI("writeUnsignedChar", uchar, bs->writeUnsignedChar(value));
EXPORTAPI2(writeBool);
EXPORTAPI2(writeByte);
EXPORTAPI2(writeDouble);
EXPORTAPI2(writeFloat);
EXPORTAPI2(writeSignedBigEndianInt);
EXPORTAPI2(writeSignedInt);
EXPORTAPI2(writeSignedInt64);
EXPORTAPI2(writeSignedShort);
EXPORTAPI2(writeUnsignedInt);
EXPORTAPI2(writeUnsignedInt64);
EXPORTAPI2(writeUnsignedShort);
EXPORTAPI2(writeUnsignedVarInt);
EXPORTAPI2(writeUnsignedVarInt64);
EXPORTAPI2(writeVarInt);
EXPORTAPI2(writeVarInt64);
}
+805 -294
View File
File diff suppressed because it is too large Load Diff
+25 -16
View File
@@ -1,36 +1,45 @@
#include "Entry.h" #include "Entry.h"
#include "Global.h" #include "Global.h"
ll::Logger logger(PLUGIN_NAME); namespace gmlib {
namespace GMLIB_LegacyRemoteCallApi { LegacyRemoteCallApi& LegacyRemoteCallApi::getInstance() {
static LegacyRemoteCallApi instance;
std::unique_ptr<LRCA>& LRCA::getInstance() {
static std::unique_ptr<LRCA> instance;
return instance; return instance;
} }
bool LRCA::load() { bool LegacyRemoteCallApi::load() {
(void)CustomRecipeRegistry::getInstance();
Export_Legacy_GMLib_ModAPI(); Export_Legacy_GMLib_ModAPI();
Export_Legacy_GMLib_ServerAPI(); Export_Legacy_GMLib_ServerAPI();
Export_Compatibility_API(); Export_Compatibility_API();
ExportPAPI(); ExportPAPI();
Export_Event_API(); Export_Event_API();
logger.info("GMLIB-LegacyRemoteCallApi Loaded!"); Export_BinaryStream_API();
logger.info( // Export_Form_API();
auto logger = ll::io::LoggerRegistry::getInstance().getOrCreate(PLUGIN_NAME);
logger->info("GMLIB-LegacyRemoteCallApi Loaded!");
logger->info(
"Loaded Version: {} with {}", "Loaded Version: {} with {}",
fmt::format(fg(fmt::color::pink), "GMLIB-" + GMLIB::Version::getLibVersionString()), fmt::format(fg(fmt::color::pink), "GMLIB-" GMLIB_FILE_VERSION_STRING),
fmt::format(fg(fmt::color::light_green), "GMLIB-LegacyRemoteCallApi-"+LIB_VERSION.asString()) fmt::format(fg(fmt::color::light_green), "GMLIB-LegacyRemoteCallApi-{}", LIB_VERSION.to_string())
); );
logger.info("Author: GroupMountain"); logger->info("Author: GroupMountain");
logger.info("Repository: https://github.com/GroupMountain/GMLIB-LegacyRemoteCallApi"); logger->info("Repository: https://github.com/GroupMountain/GMLIB-LegacyRemoteCallApi");
return true; return true;
} }
bool LRCA::enable() { return true; } bool LegacyRemoteCallApi::enable() { return true; }
bool LRCA::disable() { return true; } bool LegacyRemoteCallApi::disable() { return true; }
} // namespace GMLIB_LegacyRemoteCallApi } // namespace gmlib
LL_REGISTER_PLUGIN(GMLIB_LegacyRemoteCallApi::LRCA, GMLIB_LegacyRemoteCallApi::LRCA::getInstance()); LL_REGISTER_MOD(gmlib::LegacyRemoteCallApi, gmlib::LegacyRemoteCallApi::getInstance());
ll::thread::ThreadPoolExecutor const& getThreadPoolExecutor() {
return gmlib::LegacyRemoteCallApi::getInstance().getThreadPoolExecutor();
}
ll::io::Logger& getLogger() { return gmlib::LegacyRemoteCallApi::getInstance().getSelf().getLogger(); }
+13 -9
View File
@@ -1,17 +1,18 @@
#pragma once #pragma once
#include <ll/api/plugin/NativePlugin.h> #include <ll/api/mod/NativeMod.h>
#include <ll/api/plugin/RegisterHelper.h> #include <ll/api/mod/RegisterHelper.h>
#include <ll/api/thread/ThreadPoolExecutor.h>
namespace GMLIB_LegacyRemoteCallApi { namespace gmlib {
class LRCA { class LegacyRemoteCallApi {
public: public:
static std::unique_ptr<LRCA>& getInstance(); static LegacyRemoteCallApi& getInstance();
LRCA(ll::plugin::NativePlugin& self) : mSelf(self) {} LegacyRemoteCallApi() : mSelf(*ll::mod::NativeMod::current()), mThreadPoolExecutor(getSelf().getName()) {}
[[nodiscard]] ll::plugin::NativePlugin& getSelf() const { return mSelf; } [[nodiscard]] ll::mod::NativeMod& getSelf() const { return mSelf; }
/// @return True if the plugin is loaded successfully. /// @return True if the plugin is loaded successfully.
bool load(); bool load();
@@ -26,8 +27,11 @@ public:
// /// @return True if the plugin is unloaded successfully. // /// @return True if the plugin is unloaded successfully.
// bool unload(); // bool unload();
ll::thread::ThreadPoolExecutor& getThreadPoolExecutor() { return mThreadPoolExecutor; }
private: private:
ll::plugin::NativePlugin& mSelf; ll::mod::NativeMod& mSelf;
ll::thread::ThreadPoolExecutor mThreadPoolExecutor;
}; };
} // namespace GMLIB_LegacyRemoteCallApi } // namespace gmlib
+287 -167
View File
@@ -1,199 +1,319 @@
#include "Global.h" #include "Global.h"
using namespace ll::hash_utils; using namespace ll::hash_utils;
class EventManager {
private:
std::unordered_map<ullong, ll::event::ListenerPtr> mEventIds;
public:
static EventManager& getInstance() {
static std::unique_ptr<EventManager> instance;
if (!instance) instance = std::make_unique<EventManager>();
return *instance;
}
ullong getNextId() {
auto id = mEventIds.size();
mEventIds.emplace(id, nullptr);
return id;
}
bool addListener(ullong id, ll::event::ListenerPtr const& listener) {
if (mEventIds.contains(id) && mEventIds[id]) return false;
mEventIds[id] = listener;
return true;
}
bool removeListener(ullong id) {
if (ll::event::EventBus::getInstance().removeListener(mEventIds[id])) {
mEventIds[id] = nullptr;
return true;
}
return false;
}
bool hasListener(ullong id) { return mEventIds.contains(id) && mEventIds[id]; }
ll::event::ListenerPtr getListener(ullong id) { return mEventIds.contains(id) ? mEventIds[id] : nullptr; }
};
#define REGISTER_EVENT_LISTEN(eventType, paramType, params, cancelFun, ...) \
auto eventPtr = ll::event::EventBus::getInstance().emplaceListener<eventType>( \
[pluginName, eventName, eventId](eventType& event) -> void { \
if (!RemoteCall::hasFunc(pluginName, eventName + "_" + std::to_string(eventId))) { \
EventManager::getInstance().removeListener(eventId); \
return; \
} \
try { \
__VA_ARGS__ \
auto result = \
RemoteCall::importAs<bool paramType>(pluginName, eventName + "_" + std::to_string(eventId)) \
params; \
cancelFun \
} catch (...) {} \
}, \
ll::event::EventPriority(priority) \
); \
return eventId
void Export_Event_API() { void Export_Event_API() {
auto eventBus = &ll::event::EventBus::getInstance(); RemoteCall::exportAs("GMLIB_Event_API", "removeListener", [](ll::event::ListenerId eventId) -> bool {
return EventManager::getInstance().removeListener(eventId);
});
RemoteCall::exportAs("GMLIB_Event_API", "hasListener", [](ll::event::ListenerId eventId) -> bool {
return EventManager::getInstance().hasListener(eventId);
});
RemoteCall::exportAs("GMLIB_Event_API", "getListenerPriority", [](ll::event::ListenerId eventId) -> int {
if (auto event = EventManager::getInstance().getListener(eventId); event != nullptr) {
return (int)event->getPriority();
}
return -1;
});
RemoteCall::exportAs( RemoteCall::exportAs(
"GMLIB_API", "GMLIB_Event_API",
"callCustomEvent", "emplaceListener",
[eventBus](std::string eventName, std::string eventId) -> bool { [](std::string const& pluginName, std::string const& eventName, int priority) -> llong {
if (RemoteCall::hasFunc(eventName, eventId)) { auto eventId = EventManager::getInstance().getNextId();
switch (doHash(eventName)) { switch (doHash(eventName)) {
case doHash("onClientLogin"): { case doHash("ll::ServerStoppingEvent"): {
auto Call = RemoteCall::importAs< REGISTER_EVENT_LISTEN(ll::event::ServerStoppingEvent, (), (), , );
bool(std::string realName, std::string uuid, std::string serverXuid, std::string clientXuid)>( }
eventName, case doHash("gmlib::ClientLoginAfterEvent"): {
eventId REGISTER_EVENT_LISTEN(
ila::mc::ClientLoginAfterEvent,
(std::string const& realName,
std::string const& uuid,
std::string const& serverXuid,
std::string const& clientXuid),
(event.realName(), event.uuid().asString(), event.serverAuthXuid(), event.clientAuthXuid()),
if (result) event.disConnectClient();
); );
eventBus->emplaceListener<GMLIB::Event::PacketEvent::ClientLoginAfterEvent>( }
[Call](GMLIB::Event::PacketEvent::ClientLoginAfterEvent& ev) { case doHash("gmlib::WeatherUpdateBeforeEvent"): {
try { REGISTER_EVENT_LISTEN(
Call( ila::mc::WeatherUpdateBeforeEvent,
ev.getRealName(), (float rainLevel, int rainTime, float lightningLevel, int lightningTime, bool isCancelled),
ev.getUuid().asString(), (event.rainLevel(),
ev.getServerAuthXuid(), event.rainTime(),
ev.getClientAuthXuid() event.lightningLevel(),
event.lightningTime(),
event.isCancelled()),
event.setCancelled(result);
); );
} catch (...) {}
} }
case doHash("gmlib::WeatherUpdateAfterEvent"): {
REGISTER_EVENT_LISTEN(
ila::mc::WeatherUpdateAfterEvent,
(float rainLevel, int rainTime, float lightningLevel, int lightningTime),
(event.rainLevel(), event.rainTime(), event.lightningLevel(), event.lightningTime()),
,
); );
return true;
} }
case doHash("onWeatherChange"): { case doHash("gmlib::MobPickupItemBeforeEvent"): {
auto Call = REGISTER_EVENT_LISTEN(ila::mc::ActorPickupItemBeforeEvent,
RemoteCall::importAs<bool(int lightningLevel, int rainLevel, int lightningLast, int rainLast)>( (Actor * mob, Actor * item, bool isCancelled),
eventName, (&event.self(), (Actor*)&event.itemActor(), event.isCancelled()),
eventId event.setCancelled(result););
}
case doHash("gmlib::MobPickupItemAfterEvent"): {
REGISTER_EVENT_LISTEN(
ila::mc::ActorPickupItemAfterEvent,
(Actor * mob, Actor * item),
(&event.self(), (Actor*)&event.itemActor()),
,
); );
eventBus->emplaceListener<GMLIB::Event::LevelEvent::WeatherUpdateBeforeEvent>( }
[Call](GMLIB::Event::LevelEvent::WeatherUpdateBeforeEvent& ev) { case doHash("gmlib::ItemActorSpawnBeforeEvent"): {
bool result = true; REGISTER_EVENT_LISTEN(
try { ila::mc::SpawnItemActorBeforeEvent,
result = Call( (ItemStack * item, std::pair<Vec3, int> position, int64 spawnerUniqueId, bool isCancelled),
ev.getLightningLevel(), (&event.item(),
ev.getRainLevel(), {event.pos(), event.blockSource().getDimensionId().id},
ev.getLightningLastTick(), event.spawner() ? event.spawner()->getOrCreateUniqueID().rawID : -1,
ev.getRainingLastTick() event.isCancelled()),
event.setCancelled(result);
); );
} catch (...) {}
if (!result) {
ev.cancel();
}
} }
case doHash("gmlib::ItemActorSpawnAfterEvent"): {
REGISTER_EVENT_LISTEN(
ila::mc::SpawnItemActorAfterEvent,
(Actor * item, std::pair<Vec3, int> position, int64 spawnerUniqueId),
(&event.itemActor(),
{event.pos(), event.blockSource().getDimensionId().id},
event.spawner() ? event.spawner()->getOrCreateUniqueID().rawID : -1),
,
); );
return true;
}
case doHash("onMobPick"): {
auto Call = RemoteCall::importAs<bool(Actor * mob, Actor * item)>(eventName, eventId);
eventBus->emplaceListener<GMLIB::Event::EntityEvent::MobPickupItemBeforeEvent>(
[Call](GMLIB::Event::EntityEvent::MobPickupItemBeforeEvent& ev) {
bool result = true;
try {
result = Call(&ev.self(), (Actor*)&ev.getItemActor());
} catch (...) {}
if (!result) {
ev.cancel();
} }
case doHash("gmlib::ActorChangeDimensionBeforeEvent"): {
REGISTER_EVENT_LISTEN(ila::mc::ActorChangeDimensionBeforeEvent,
(Actor * entity, int toDimId, bool isCancelled),
(&event.self(), event.toDimensionId(), event.isCancelled()),
event.setCancelled(result););
} }
case doHash("gmlib::ActorChangeDimensionAfterEvent"): {
REGISTER_EVENT_LISTEN(
ila::mc::ActorChangeDimensionAfterEvent,
(Actor * entity, int fromDimId, int toDimId),
(&event.self(), event.fromDimensionId(), event.toDimensionId()),
,
); );
return true;
}
case doHash("onItemTrySpawn"): {
auto Call = RemoteCall::importAs<
bool(const ItemStack* item, std::pair<Vec3, int> position, Actor* spawner)>(eventName, eventId);
eventBus->emplaceListener<GMLIB::Event::EntityEvent::ItemActorSpawnBeforeEvent>(
[Call](GMLIB::Event::EntityEvent::ItemActorSpawnBeforeEvent& ev) {
auto pos = ev.getPosition();
auto dimid = ev.getBlockSource().getDimensionId().id;
std::pair<Vec3, int> lsePos = {pos, dimid};
bool result = true;
try {
result = Call(&ev.getItem(), lsePos, ev.getSpawner());
} catch (...) {}
if (!result) {
ev.cancel();
} }
case doHash("gmlib::PlayerStartSleepBeforeEvent"): {
REGISTER_EVENT_LISTEN(ila::mc::PlayerStartSleepBeforeEvent,
(Player * entity, BlockPos pos, bool isCancelled),
(&event.self(), event.pos(), event.isCancelled()),
event.setCancelled(result););
} }
case doHash("gmlib::PlayerStartSleepAfterEvent"): {
REGISTER_EVENT_LISTEN(
ila::mc::PlayerStartSleepAfterEvent,
(Player * entity, BlockPos pos, int result),
(&event.self(), event.pos(), (int)event.result()),
,
); );
return true;
} }
case doHash("onItemSpawned"): { case doHash("gmlib::PlayerStopSleepBeforeEvent"): {
auto Call = RemoteCall::importAs< REGISTER_EVENT_LISTEN(
bool(const ItemStack* item, Actor* itemActor, std::pair<Vec3, int> position, Actor* spawner)>( ila::mc::PlayerStopSleepBeforeEvent,
eventName, (Player * entity, bool forcefulWakeUp, bool updateLevelList, bool isCancelled),
eventId (&event.self(), event.forcefulWakeUp(), event.updateLevelList(), false),
); );
eventBus->emplaceListener<GMLIB::Event::EntityEvent::ItemActorSpawnAfterEvent>(
[Call](GMLIB::Event::EntityEvent::ItemActorSpawnAfterEvent& ev) {
auto pos = ev.getPosition();
auto dimid = ev.getBlockSource().getDimensionId().id;
std::pair<Vec3, int> lsePos = {pos, dimid};
try {
Call(&ev.getItem(), (Actor*)&ev.getItemActor(), lsePos, ev.getSpawner());
} catch (...) {}
} }
case doHash("gmlib::PlayerStopSleepAfterEvent"): {
REGISTER_EVENT_LISTEN(
ila::mc::PlayerStopSleepAfterEvent,
(Player * entity, bool forcefulWakeUp, bool updateLevelList, bool),
(&event.self(), event.forcefulWakeUp(), event.updateLevelList(), false),
,
); );
return true;
}
case doHash("onEntityChangeDim"): {
auto Call = RemoteCall::importAs<bool(Actor * entity, int toDimId)>(eventName, eventId);
eventBus->emplaceListener<GMLIB::Event::EntityEvent::ActorChangeDimensionBeforeEvent>(
[Call](GMLIB::Event::EntityEvent::ActorChangeDimensionBeforeEvent& ev) {
bool result = true;
try {
result = Call(&ev.self(), ev.getToDimensionId());
} catch (...) {}
if (!result) {
ev.cancel();
}
} }
case doHash("gmlib::DeathMessageAfterEvent"): {
REGISTER_EVENT_LISTEN(
ila::mc::DeathMessageAfterEvent,
(std::string const& message, std::vector<std::string>, Actor* dead),
(event.result().first, event.result().second, &event.self()),
,
); );
return true;
} }
case doHash("onLeaveBed"): { case doHash("gmlib::MobHurtAfterEvent"): {
auto Call = RemoteCall::importAs<bool(Player * pl)>(eventName, eventId); REGISTER_EVENT_LISTEN(
eventBus->emplaceListener<GMLIB::Event::PlayerEvent::PlayerStopSleepBeforeEvent>( ila::mc::MobHealthChangeAfterEvent,
[Call](GMLIB::Event::PlayerEvent::PlayerStopSleepBeforeEvent& ev) { (Actor * mob, Actor * source, float damage, int cause),
bool result = true; (&event.self(), source, event.oldValue() - event.newValue(), (int)damageSource->mCause),
try { ,
result = Call(&ev.self()); if (event.newValue() > event.oldValue()) return;
} catch (...) {} auto& damageSource = event.buff().mSource;
if (!result) {
ev.cancel();
}
}
);
return true;
}
case doHash("onDeathMessage"): {
auto Call = RemoteCall::importAs<bool(std::string message, std::vector<std::string>, Actor * dead)>(
eventName,
eventId
);
eventBus->emplaceListener<GMLIB::Event::EntityEvent::DeathMessageAfterEvent>(
[Call](GMLIB::Event::EntityEvent::DeathMessageAfterEvent& ev) {
auto msg = ev.getDeathMessage();
auto source = ev.getDamageSource();
try {
Call(msg.first, msg.second, &ev.self());
} catch (...) {}
}
);
return true;
}
case doHash("onMobHurted"): {
auto Call = RemoteCall::importAs<bool(Actor * mob, Actor * source, float damage, int cause)>(
eventName,
eventId
);
eventBus->emplaceListener<GMLIB::Event::EntityEvent::MobHurtAfterEvent>(
[Call](GMLIB::Event::EntityEvent::MobHurtAfterEvent& ev) {
auto& damageSource = ev.getSource();
Actor* source = nullptr; Actor* source = nullptr;
if (damageSource.isEntitySource()) { if (damageSource->isEntitySource()) {
auto uniqueId = damageSource.getDamagingEntityUniqueID(); auto uniqueId = damageSource->getDamagingEntityUniqueID();
source = ll::service::getLevel()->fetchEntity(uniqueId); source = ll::service::getLevel()->fetchEntity(uniqueId, false);
if (source->getOwner()) { if (source->getOwner()) source = source->getOwner();
source = source->getOwner(); }
} );
} }
try { case doHash("gmlib::EndermanTakeBlockBeforeEvent"): {
Call(&ev.self(), source, ev.getDamage(), (int)damageSource.getCause()); REGISTER_EVENT_LISTEN(ila::mc::MobTakeBlockBeforeEvent,
} catch (...) {} (Actor * mob, bool isCancelled),
} (&event.self(), event.isCancelled()),
); event.setCancelled(result);
return true; , if (!event.self().isType(ActorType::EnderMan)) return;);
} }
case doHash("onEndermanTake"): { case doHash("gmlib::DragonRespawnBeforeEvent"): {
auto Call = RemoteCall::importAs<bool(Actor * mob)>(eventName, eventId); REGISTER_EVENT_LISTEN(ila::mc::DragonRespawnBeforeEvent,
eventBus->emplaceListener<GMLIB::Event::EntityEvent::EndermanTakeBlockBeforeEvent>( (bool isCancelled),
[Call](GMLIB::Event::EntityEvent::EndermanTakeBlockBeforeEvent& ev) { (event.isCancelled()),
bool result = true; event.setCancelled(result););
try { }
result = Call(&ev.self()); case doHash("gmlib::DragonRespawnAfterEvent"): {
} catch (...) {} REGISTER_EVENT_LISTEN(ila::mc::DragonRespawnAfterEvent, (Actor * mob), (&event.self()), );
if (!result) { }
ev.cancel(); case doHash("gmlib::ProjectileCreateBeforeEvent"): {
} REGISTER_EVENT_LISTEN(ila::mc::ProjectileCreateBeforeEvent,
} (Actor * mob, int64 uniqueId, bool isCancelled),
); (&event.self(), event.self().getOwnerId().rawID, event.isCancelled()),
return true; event.setCancelled(result););
} }
default: case doHash("gmlib::ProjectileCreateAfterEvent"): {
return false; REGISTER_EVENT_LISTEN(
} ila::mc::ProjectileCreateAfterEvent,
} (Actor * mob, int64 uniqueId),
return false; (&event.self(), event.self().getOwnerId().rawID),
);
}
case doHash("gmlib::SpawnWanderingTraderBeforeEvent"): {
REGISTER_EVENT_LISTEN(ila::mc::SpawnWanderingTraderBeforeEvent,
(std::pair<BlockPos, int> pos, bool isCancelled),
({event.pos(), event.blockSource().getDimensionId()}, event.isCancelled()),
event.setCancelled(result););
}
case doHash("gmlib::HandleRequestActionBeforeEvent"): {
// clang-format off
REGISTER_EVENT_LISTEN(
ila::mc::PlayerRequestItemActionBeforeEvent,
(
Player * player,
std::string const& actionType,
int count,
std::string const& sourceContainerNetId,
int sourceSlot,
std::string const& destinationContainerNetId,
int destinationSlot,
bool isCancelled
),
(
(Player*)&event.self(),
magic_enum::enum_name(event.actionType()).data(),
event.amount(),
magic_enum::enum_name(event.src().mFullContainerName.mName).data(),
(int)event.src().mSlot,
magic_enum::enum_name(event.dst().mFullContainerName.mName).data(),
(int)event.dst().mSlot,
event.isCancelled()
),
event.setCancelled(result);,
);
// clang-format on
}
case doHash("gmlib::HandleRequestActionAfterEvent"): {
// clang-format off
REGISTER_EVENT_LISTEN(
ila::mc::PlayerRequestItemActionAfterEvent,
(
Player * player,
std::string const& actionType,
int count,
std::string const& sourceContainerNetId,
int sourceSlot,
std::string const& destinationContainerNetId,
int destinationSlot
),
(
(Player*)&event.self(),
magic_enum::enum_name(event.actionType()).data(),
event.amount(),
magic_enum::enum_name(event.src().mFullContainerName.mName).data(),
(int)event.src().mSlot,
magic_enum::enum_name(event.dst().mFullContainerName.mName).data(),
(int)event.dst().mSlot
),
,
);
// clang-format on
}
case doHash("gmlib::ContainerClosePacketSendAfterEvent"): {
REGISTER_EVENT_LISTEN(
ila::mc::PlayerCloseContainerAfterEvent,
(Player * player, int containerId, bool serverInitiatedClose, bool),
(&event.self(), (int)event.containerId(), event.serverInitiatedClose(), false),
,
);
}
}
return -1;
} }
); );
} }
+288
View File
@@ -0,0 +1,288 @@
// #include "Global.h"
// using namespace ll::hash_utils;
// class LegacyScriptFormManager {
// private:
// int64 mNextFormCallbackId = 0;
// int64 mNextFormId = 0;
// std::unordered_map<int64, std::unique_ptr<gmlib::form::NpcDialogueForm>> mNpcDialogueForms;
// // std::unordered_map<int64, std::unique_ptr<ChestForm>> mChestForms;
// public:
// // std::string getNextFormCallbackId() {
// // return "GMLIB_FormApi_" + std::to_string(mNextFormCallbackId++);
// // }
// int64 getNextFormId() {
// mNextFormId++;
// return mNextFormId;
// }
// int64 createNpcDialogueForm(std::string const& npcName, std::string const& sceneName, std::string const& dialogue) {
// auto formId = LegacyScriptFormManager::getInstance().getNextFormId();
// auto formPtr = std::make_unique<gmlib::form::NpcDialogueForm>(npcName, sceneName, dialogue);
// mNpcDialogueForms[formId] = std::move(formPtr);
// return formId;
// }
// bool destroyNpcDialogueForm(int64 formId) {
// if (mNpcDialogueForms.contains(formId)) {
// mNpcDialogueForms.erase(formId);
// return true;
// }
// return false;
// }
// optional_ref<gmlib::form::NpcDialogueForm> getNpcDialogueForm(int64 formId) {
// if (mNpcDialogueForms.contains(formId)) {
// return mNpcDialogueForms[formId].get();
// }
// return {};
// }
// /*
// int64 createChestForm(std::string const& npcName, std::string const& sceneName, std::string const& dialogue) {
// auto formId = LegacyScriptFormManager::getInstance().getNextFormId();
// auto formPtr = std::make_unique<ChestForm>(npcName, sceneName, dialogue);
// mChestForms[formId] = std::move(formPtr);
// return formId;
// }
// bool destroyChestForm(int64 formId) {
// if (mChestForms.contains(formId)) {
// mChestForms.erase(formId);
// return true;
// }
// return false;
// }
// optional_ref<ChestForm> getChestForm(int64 formId) {
// if (mChestForms.contains(formId)) {
// return mChestForms[formId].get();
// }
// return {};
// }
// */
// public:
// static LegacyScriptFormManager& getInstance() {
// static std::unique_ptr<LegacyScriptFormManager> instance;
// if (!instance) {
// instance = std::make_unique<LegacyScriptFormManager>();
// }
// return *instance;
// }
// };
// #define PLAYER_DETECROR \
// [detectorId, result](::Player& pl) -> bool { \
// try { \
// if (RemoteCall::hasFunc("GMLIB_FORM_CALLBACK", detectorId)) { \
// auto const& detector = RemoteCall::importAs<bool(::Player*)>("GMLIB_FORM_CALLBACK", detectorId); \
// return detector(&pl); \
// } else { \
// gmlib::form::ServerSettingForm::removeElement(result); \
// } \
// } catch (...) {} \
// return false; \
// }
// #define CALLBACK_TYPE(type) \
// [callbackId, result](Player& pl, type data) { \
// try { \
// if (RemoteCall::hasFunc("GMLIB_FORM_CALLBACK", callbackId)) { \
// auto const& callback = RemoteCall::importAs<void(Player*, type)>("GMLIB_FORM_CALLBACK", callbackId); \
// callback(&pl, data); \
// } else { \
// gmlib::form::ServerSettingForm::removeElement(result); \
// } \
// } catch (...) {} \
// }
// #define CALLBACK_TYPE_NORMAL \
// [callbackId](::Player& pl) { \
// try { \
// if (RemoteCall::hasFunc("GMLIB_FORM_CALLBACK", callbackId)) { \
// auto const& callback = RemoteCall::importAs<void(::Player*)>("GMLIB_FORM_CALLBACK", callbackId); \
// callback(&pl); \
// } \
// } catch (...) {} \
// }
// void Export_Form_API() {
// //////////////////////////////// Form Manager /////////////////////////////////
// // RemoteCall::exportAs("GMLIB_FormAPI", "getNextFormCallbackId", []() -> std::string {
// // return LegacyScriptFormManager::getInstance().getNextFormCallbackId();
// // });
// ////////////////////////////// ServerSettingForm //////////////////////////////
// RemoteCall::exportAs("GMLIB_ServerSettingForm", "getDefaultPriority", []() -> int {
// return gmlib::form::ServerSettingForm::getDefaultPriority();
// });
// RemoteCall::exportAs("GMLIB_ServerSettingForm", "hasTitle", []() -> bool { return gmlib::form::ServerSettingForm::hasTitle(); });
// RemoteCall::exportAs("GMLIB_ServerSettingForm", "getTitle", []() -> std::string {
// return gmlib::form::ServerSettingForm::getTitle();
// });
// RemoteCall::exportAs("GMLIB_gmlib::form::ServerSettingForm", "setTitle", [](std::string const& title, bool forceModify) -> bool {
// return gmlib::form::ServerSettingForm::setTitle(title, forceModify);
// });
// RemoteCall::exportAs("GMLIB_gmlib::form::ServerSettingForm", "hasIcon", []() -> bool { return gmlib::form::ServerSettingForm::hasIcon(); });
// RemoteCall::exportAs("GMLIB_gmlib::form::ServerSettingForm", "getIconData", []() -> std::string {
// return gmlib::form::ServerSettingForm::getIconData().value_or("");
// });
// RemoteCall::exportAs("GMLIB_gmlib::form::ServerSettingForm", "getIconType", []() -> int {
// return gmlib::form::ServerSettingForm::getIconType()
// .transform([](gmlib::form::IconType&& type) -> int { return (int)type; })
// .value_or(-1);
// });
// RemoteCall::exportAs(
// "GMLIB_gmlib::form::ServerSettingForm",
// "setIcon",
// [](std::string const& title, uchar type, bool forceModify) -> bool {
// return gmlib::form::ServerSettingForm::setIcon(title, gmlib::form::IconType(type), forceModify);
// }
// );
// RemoteCall::exportAs(
// "GMLIB_gmlib::form::ServerSettingForm",
// "addLabel",
// [](std::string const& text, std::string const& detectorId, int priority) -> uint {
// uint result = gmlib::form::ServerSettingForm::addLabel(text, PLAYER_DETECROR, priority);
// return result;
// }
// );
// RemoteCall::exportAs(
// "GMLIB_gmlib::form::ServerSettingForm",
// "addInput",
// [](std::string const& text,
// std::string const& placeholder,
// std::string const& defaultVal,
// std::string const& callbackId,
// std::string const& detectorId,
// int priority) -> uint {
// uint result = gmlib::form::ServerSettingForm::addInput(
// text,
// placeholder,
// defaultVal,
// CALLBACK_TYPE(std::string const&),
// PLAYER_DETECROR,
// priority
// );
// return result;
// }
// );
// RemoteCall::exportAs(
// "GMLIB_gmlib::form::ServerSettingForm",
// "addToggle",
// [](std::string const& text,
// bool defaultVal,
// std::string const& callbackId,
// std::string const& detectorId,
// int priority) -> uint {
// uint result = gmlib::form::ServerSettingForm::addToggle(text, defaultVal, CALLBACK_TYPE(bool), PLAYER_DETECROR, priority);
// return result;
// }
// );
// RemoteCall::exportAs(
// "GMLIB_gmlib::form::ServerSettingForm",
// "addDropdown",
// [](std::string const& text,
// std::vector<std::string> options,
// int64 defaultVal,
// std::string const& callbackId,
// std::string const& detectorId,
// int priority) -> uint {
// uint result = gmlib::form::ServerSettingForm::addDropdown(
// text,
// options,
// defaultVal,
// CALLBACK_TYPE(int64),
// PLAYER_DETECROR,
// priority
// );
// return result;
// }
// );
// RemoteCall::exportAs(
// "GMLIB_gmlib::form::ServerSettingForm",
// "addSlider",
// [](std::string const& text,
// double min,
// double max,
// double step,
// double defaultVal,
// std::string const& callbackId,
// std::string const& detectorId,
// int priority) -> uint {
// uint result = gmlib::form::ServerSettingForm::addSlider(
// text,
// min,
// max,
// step,
// defaultVal,
// CALLBACK_TYPE(double),
// PLAYER_DETECROR,
// priority
// );
// return result;
// }
// );
// RemoteCall::exportAs(
// "GMLIB_gmlib::form::ServerSettingForm",
// "addStepSlider",
// [](std::string const& text,
// std::vector<std::string> steps,
// int64 defaultVal,
// std::string const& callbackId,
// std::string const& detectorId,
// int priority) -> uint {
// uint result = gmlib::form::ServerSettingForm::addStepSlider(
// text,
// steps,
// defaultVal,
// CALLBACK_TYPE(int64),
// PLAYER_DETECROR,
// priority
// );
// return result;
// }
// );
// RemoteCall::exportAs("GMLIB_gmlib::form::ServerSettingForm", "removeElement", [](uint id) -> bool {
// return gmlib::form::ServerSettingForm::removeElement(id);
// });
// ////////////////////////////// NpcDialogueForm //////////////////////////////
// RemoteCall::exportAs(
// "GMLIB_NpcDialogueForm",
// "createForm",
// [](std::string const& npcName, std::string const& sceneName, std::string const& dialogue) -> int64 {
// return LegacyScriptFormManager::getInstance().createNpcDialogueForm(npcName, sceneName, dialogue);
// }
// );
// RemoteCall::exportAs("GMLIB_NpcDialogueForm", "destroyForm", [](int64 formId) -> bool {
// return LegacyScriptFormManager::getInstance().destroyNpcDialogueForm(formId);
// });
// RemoteCall::exportAs(
// "GMLIB_NpcDialogueForm",
// "addButton",
// [](int64 formId, std::string const& button, std::string const& callbackId) -> void {
// if (auto formPtr = LegacyScriptFormManager::getInstance().getNpcDialogueForm(formId)) {
// formPtr->addButton(button, CALLBACK_TYPE_NORMAL);
// }
// }
// );
// RemoteCall::exportAs(
// "GMLIB_NpcDialogueForm",
// "onPlayerClose",
// [](int64 formId, std::string const& callbackId) -> void {
// if (auto formPtr = LegacyScriptFormManager::getInstance().getNpcDialogueForm(formId)) {
// formPtr->onPlayerClose(CALLBACK_TYPE_NORMAL);
// }
// }
// );
// RemoteCall::exportAs("GMLIB_NpcDialogueForm", "sendTo", [](int64 formId, ::Player* pl) -> void {
// if (auto formPtr = LegacyScriptFormManager::getInstance().getNpcDialogueForm(formId)) {
// formPtr->sendTo(*pl);
// }
// });
// ////////////////////////////// ChestForm //////////////////////////////
// }
+31 -4
View File
@@ -1,16 +1,43 @@
#pragma once #pragma once
#include <include_all.h> // clang-format off
#pragma warning(push)
#pragma warning(disable : 4996)
#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 <modapi/addons/AddonsLoader.h>
#include <modapi/recipe/CustomRecipeRegistry.h>
#include <modapi/item/CustomItemRegistry.h>
#include <RemoteCallAPI.h> #include <RemoteCallAPI.h>
using namespace gmlib;
using namespace gmlib::ui;
using namespace gmlib::i18n;
using namespace gmlib::memory;
using namespace modapi;
#pragma warning(pop)
// 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 GMLIB::Version(0, 12, 5) #define LIB_VERSION_MAJOR 1
#define LIB_VERSION_MINOR 0
#define LIB_VERSION_PATCH 0
#define LIB_VERSION_PRERELEASE std::nullopt
extern ll::Logger logger; #ifdef LIB_VERSION_PRERELEASE
#define LIB_VERSION ll::data::Version(LIB_VERSION_MAJOR, LIB_VERSION_MINOR, LIB_VERSION_PATCH, LIB_VERSION_PRERELEASE)
#else
#define LIB_VERSION ll::data::Version(LIB_VERSION_MAJOR, LIB_VERSION_MINOR, LIB_VERSION_PATCH)
#endif
extern void Export_Legacy_GMLib_ModAPI(); extern void Export_Legacy_GMLib_ModAPI();
extern void Export_Legacy_GMLib_ServerAPI(); extern void Export_Legacy_GMLib_ServerAPI();
extern void Export_Compatibility_API(); extern void Export_Compatibility_API();
extern void ExportPAPI(); extern void ExportPAPI();
extern void Export_Event_API(); extern void Export_Event_API();
extern void Export_BinaryStream_API();
extern ll::thread::ThreadPoolExecutor const& getThreadPoolExecutor();
extern ll::io::Logger& getLogger();
// extern void Export_Form_API();
+95 -117
View File
@@ -1,15 +1,10 @@
#include "Global.h" #include "Global.h"
std::unordered_set<std::string> HardCodedKeys = {"AlwaysUnlocked", "PlayerHasManyItems", "PlayerInWater", "None"}; ICustomRecipe::UnlockingRequirement makeRecipeUnlockingKey(std::string const& key) {
if (auto context = magic_enum::enum_cast<RecipeUnlockingContext>(key)) {
std::variant<std::string, std::vector<RecipeIngredient>> makeRecipeUnlockingKey(std::string& key) { return ICustomRecipe::UnlockingRequirement(*context);
if (HardCodedKeys.count(key)) {
return key;
} }
std::vector<RecipeIngredient> result; return ICustomRecipe::UnlockingRequirement({ICustomRecipe::Ingredient(key)});
auto item = RecipeIngredient(key, 0, 1);
result.emplace_back(item);
return result;
} }
void Export_Legacy_GMLib_ModAPI() { void Export_Legacy_GMLib_ModAPI() {
@@ -17,171 +12,154 @@ void Export_Legacy_GMLib_ModAPI() {
RemoteCall::exportAs( RemoteCall::exportAs(
"GMLib_ModAPI", "GMLib_ModAPI",
"registerShapelessRecipe", "registerShapelessRecipe",
[](std::string recipe_id, [](std::string const& recipe_id,
std::vector<std::string> ingredients, std::vector<std::string> ingredients,
std::string result, std::string const& result,
int count, int count,
std::string unlock) -> void { std::string const& unlock) -> void {
auto level = GMLIB_Level::getInstance(); if (!GMLevel::getInstance().has_value()) return;
if (!level) { std::vector<ICustomRecipe::Ingredient> types;
return; for (auto& ing : ingredients) {
types.emplace_back(ICustomRecipe::Ingredient{ing, 1});
} }
std::vector<RecipeIngredient> types; CustomRecipeRegistry::getInstance()
for (auto ing : ingredients) { .registerShapelessRecipe(recipe_id, types, ItemInstance(result, count), makeRecipeUnlockingKey(unlock));
auto key = RecipeIngredient(ing, 0, 1);
types.push_back(key);
}
auto res = RecipeIngredient(result, 0, count);
auto unl = makeRecipeUnlockingKey(unlock);
GMLIB::Mod::JsonRecipe::registerShapelessCraftingTableRecipe(recipe_id, types, res, unl);
} }
); );
RemoteCall::exportAs( RemoteCall::exportAs(
"GMLib_ModAPI", "GMLib_ModAPI",
"registerShapedRecipe", "registerShapedRecipe",
[](std::string recipe_id, [](std::string const& recipe_id,
std::vector<std::string> shape, std::vector<std::string> shape,
std::vector<std::string> ingredients, std::vector<std::string> ingredients,
std::string result, std::string const& result,
int count, int count,
std::string unlock) -> void { std::string const& unlock) -> void {
auto level = GMLIB_Level::getInstance(); if (!GMLevel::getInstance().has_value()) return;
if (!level) { ICustomShapedRecipe::ShapedIngredients types;
return; char index = 'A';
for (auto& ing : ingredients) {
types.add(std::string(1, index++), ICustomRecipe::Ingredient{ing});
} }
std::vector<RecipeIngredient> types; CustomRecipeRegistry::getInstance().registerShapedRecipe(
for (auto ing : ingredients) { recipe_id,
auto key = RecipeIngredient(ing, 0, 1); shape,
types.push_back(key); types,
} ItemInstance(result, count),
auto res = RecipeIngredient(result, 0, count); makeRecipeUnlockingKey(unlock)
auto unl = makeRecipeUnlockingKey(unlock); );
GMLIB::Mod::JsonRecipe::registerShapedCraftingTableRecipe(recipe_id, shape, types, res, unl);
} }
); );
RemoteCall::exportAs( RemoteCall::exportAs(
"GMLib_ModAPI", "GMLib_ModAPI",
"registerFurnaceRecipe", "registerFurnaceRecipe",
[](std::string recipe_id, std::string input, std::string output, std::vector<std::string> tags) -> void { [](std::string const& recipe_id,
auto level = GMLIB_Level::getInstance(); std::string const& input,
if (!level) { std::string const& output,
return; std::vector<std::string> tags) -> void {
} if (!GMLevel::getInstance().has_value()) return;
auto inp = RecipeIngredient(input, 0, 1); CustomRecipeRegistry::getInstance()
auto outp = RecipeIngredient(output, 0, 1); .registerFurnaceRecipe(ICustomRecipe::Ingredient{input}, ItemInstance{output}, tags);
GMLIB::Mod::JsonRecipe::registerFurnaceRecipe(recipe_id, inp, outp, tags);
} }
); );
RemoteCall::exportAs( RemoteCall::exportAs(
"GMLib_ModAPI", "GMLib_ModAPI",
"registerBrewingMixRecipe", "registerBrewingMixRecipe",
[](std::string recipe_id, std::string input, std::string output, std::string reagent) -> void { [](std::string const& recipe_id, std::string const& input, std::string const& output, std::string const& reagent
auto level = GMLIB_Level::getInstance(); ) -> void {
if (!level) { if (!GMLevel::getInstance().has_value()) return;
return; CustomRecipeRegistry::getInstance().registerBrewingRecipe(
} ICustomRecipe::Ingredient{input},
auto rea = RecipeIngredient(reagent, 0, 1); ICustomRecipe::Ingredient{reagent},
GMLIB::Mod::JsonRecipe::registerBrewingMixRecipe(recipe_id, input, output, rea); ICustomRecipe::Ingredient{output}
);
} }
); );
RemoteCall::exportAs( RemoteCall::exportAs(
"GMLib_ModAPI", "GMLib_ModAPI",
"registerBrewingContainerRecipe", "registerBrewingContainerRecipe",
[](std::string recipe_id, std::string input, std::string output, std::string reagent) -> void { [](std::string const& recipe_id, std::string const& input, std::string const& output, std::string const& reagent
auto level = GMLIB_Level::getInstance(); ) -> void {
if (!level) { if (!GMLevel::getInstance().has_value()) return;
return; CustomRecipeRegistry::getInstance().registerBrewingRecipe(
} ICustomRecipe::Ingredient{input},
auto inp = RecipeIngredient(input, 0, 1); ICustomRecipe::Ingredient{reagent},
auto outp = RecipeIngredient(output, 0, 1); ICustomRecipe::Ingredient{output}
auto rea = RecipeIngredient(reagent, 0, 1); );
GMLIB::Mod::JsonRecipe::registerBrewingContainerRecipe(recipe_id, inp, outp, rea);
} }
); );
RemoteCall::exportAs( RemoteCall::exportAs(
"GMLib_ModAPI", "GMLib_ModAPI",
"registerSmithingTransformRecipe", "registerSmithingTransformRecipe",
[](std::string recipe_id, [](std::string const& recipe_id,
std::string smithing_template, std::string const& smithing_template,
std::string base, std::string const& base,
std::string addition, std::string const& addition,
std::string result) -> void { std::string const& result) -> void {
auto level = GMLIB_Level::getInstance(); if (!GMLevel::getInstance().has_value()) return;
if (!level) { CustomRecipeRegistry::getInstance().registerSmithingTransformRecipe(
return;
}
GMLIB::Mod::JsonRecipe::registerSmithingTransformRecipe(
recipe_id, recipe_id,
smithing_template, ICustomRecipe::Ingredient{smithing_template},
base, ICustomRecipe::Ingredient{base},
addition, ICustomRecipe::Ingredient{addition},
result ItemInstance{result}
); );
} }
); );
RemoteCall::exportAs( RemoteCall::exportAs(
"GMLib_ModAPI", "GMLib_ModAPI",
"registerSmithingTrimRecipe", "registerSmithingTrimRecipe",
[](std::string recipe_id, std::string smithing_template, std::string base, std::string addition) -> void { [](std::string const& recipe_id,
auto level = GMLIB_Level::getInstance(); std::string const& smithing_template,
if (!level) { std::string const& base,
return; std::string const& addition) -> void {
} if (!GMLevel::getInstance().has_value()) return;
GMLIB::Mod::JsonRecipe::registerSmithingTrimRecipe(recipe_id, smithing_template, base, addition); CustomRecipeRegistry::getInstance().registerSmithingTrimRecipe(
recipe_id,
ICustomRecipe::Ingredient{smithing_template},
ICustomRecipe::Ingredient{base},
ICustomRecipe::Ingredient{addition}
);
} }
); );
RemoteCall::exportAs( RemoteCall::exportAs(
"GMLib_ModAPI", "GMLib_ModAPI",
"registerStoneCutterRecipe", "registerStoneCutterRecipe",
[](std::string recipe_id, [](std::string const& recipe_id,
std::string input, std::string const& input,
int input_data, int input_data,
std::string output, std::string const& output,
int output_data, int output_data,
int output_count) -> void { int output_count) -> void {
auto level = GMLIB_Level::getInstance(); if (!GMLevel::getInstance().has_value()) return;
if (!level) { CustomRecipeRegistry::getInstance().registerStoneCutterRecipe(
return; recipe_id,
} ICustomRecipe::Ingredient{input, 1, input_data},
auto inp = RecipeIngredient(input, 0, 1); {output, output_count, output_data}
auto outp = RecipeIngredient(output, 0, 1); );
GMLIB::Mod::JsonRecipe::registerStoneCutterRecipe(recipe_id, inp, outp);
} }
); );
// 错误方块清理 // 错误方块清理
RemoteCall::exportAs("GMLib_ModAPI", "setUnknownBlockCleaner", []() -> void { RemoteCall::exportAs("GMLib_ModAPI", "setUnknownBlockCleaner", []() -> void {
GMLIB::Mod::VanillaFix::setAutoCleanUnknownBlockEnabled(); getLogger().error("setUnknownBlockCleaner is not implemented");
}); });
// 实验性 // 实验性
RemoteCall::exportAs("GMLib_ModAPI", "registerExperimentsRequire", [](int experiment_id) -> void { RemoteCall::exportAs("GMLib_ModAPI", "registerExperimentsRequire", [](int experiment_id) -> void {
auto map = GMLIB_Level::getAllExperiments(); GMLevel::getInstance().and_then([&](GMLevel& level) {
if (map.count(experiment_id)) { level.setExperimentEnabled((AllExperiments)experiment_id);
GMLIB_Level::addExperimentsRequire((AllExperiments)experiment_id); return true;
} else { });
ll::Logger("Server").error("Experiment ID '{}' does not exist!", experiment_id);
}
}); });
RemoteCall::exportAs("GMLib_ModAPI", "setExperimentEnabled", [](int experiment_id, bool value) -> void { RemoteCall::exportAs("GMLib_ModAPI", "setExperimentEnabled", [](int experiment_id, bool value) -> void {
auto level = GMLIB_Level::getInstance(); GMLevel::getInstance().and_then([&](GMLevel& level) {
if (!level) { level.setExperimentEnabled((AllExperiments)experiment_id, value);
return; return true;
} });
auto map = GMLIB_Level::getAllExperiments();
if (map.count(experiment_id)) {
GMLIB_Level::getInstance()->setExperimentEnabled(((AllExperiments)experiment_id), value);
} else ll::Logger("Server").error("Experiment ID '{}' does not exist!", experiment_id);
}); });
RemoteCall::exportAs("GMLib_ModAPI", "getExperimentEnabled", [](int experiment_id) -> bool { RemoteCall::exportAs("GMLib_ModAPI", "getExperimentEnabled", [](int experiment_id) -> bool {
auto level = GMLIB_Level::getInstance(); return GMLevel::getInstance()
if (!level) { .transform([&](GMLevel& level) { return level.getExperimentEnabled((AllExperiments)experiment_id); })
return false; .value_or(false);
}
auto map = GMLIB_Level::getAllExperiments();
if (map.count(experiment_id)) {
return GMLIB_Level::getInstance()->getExperimentEnabled(((AllExperiments)experiment_id));
} else {
ll::Logger("Server").error("Experiment ID '{}' does not exist!", experiment_id);
return false;
}
}); });
RemoteCall::exportAs("GMLib_ModAPI", "setFixI18nEnabled", []() -> void {});
} }
+57 -24
View File
@@ -2,53 +2,86 @@
void Export_Legacy_GMLib_ServerAPI() { void Export_Legacy_GMLib_ServerAPI() {
RemoteCall::exportAs("GMLib_ServerAPI", "setEducationFeatureEnabled", []() -> void { RemoteCall::exportAs("GMLib_ServerAPI", "setEducationFeatureEnabled", []() -> void {
GMLIB_Level::tryEnableEducationEdition(); getLogger().error("GMLib_ServerAPI::setEducationFeatureEnabled is not implemented");
}); });
RemoteCall::exportAs("GMLib_ServerAPI", "registerAbilityCommand", []() -> void { RemoteCall::exportAs("GMLib_ServerAPI", "registerAbilityCommand", []() -> void {
GMLIB_Level::tryRegisterAbilityCommand(); getLogger().error("GMLib_ServerAPI::registerAbilityCommand is not implemented");
}); });
RemoteCall::exportAs("GMLib_ServerAPI", "setEnableAchievement", []() -> void { RemoteCall::exportAs("GMLib_ServerAPI", "setEnableAchievement", []() -> void {
GMLIB_Level::setForceAchievementsEnabled(); getLogger().error("GMLib_ServerAPI::setEnableAchievement is not implemented");
});
RemoteCall::exportAs("GMLib_ServerAPI", "setForceTrustSkins", []() -> void {
getLogger().error("GMLib_ServerAPI::setForceTrustSkins is not implemented");
}); });
RemoteCall::exportAs("GMLib_ServerAPI", "setForceTrustSkins", []() -> void { GMLIB_Level::trustAllSkins(); });
RemoteCall::exportAs("GMLib_ServerAPI", "enableCoResourcePack", []() -> void { RemoteCall::exportAs("GMLib_ServerAPI", "enableCoResourcePack", []() -> void {
GMLIB_Level::requireServerResourcePackAndAllowClientResourcePack(); getLogger().error("GMLib_ServerAPI::enableCoResourcePack is not implemented");
}); });
RemoteCall::exportAs("GMLib_ServerAPI", "getLevelName", []() -> std::string { RemoteCall::exportAs("GMLib_ServerAPI", "getLevelName", []() -> std::string {
auto level = GMLIB_Level::getInstance(); return GMLevel::getInstance().transform(
if (!level) { [](GMLevel& level) -> std::string { return level.getLevelName(); }
return ""; ).value_or("");
}
return level->getLevelName();
}); });
RemoteCall::exportAs("GMLib_ServerAPI", "setLevelName", [](std::string name) -> void { RemoteCall::exportAs("GMLib_ServerAPI", "setLevelName", [](std::string const& name) -> void {
auto level = GMLIB_Level::getInstance(); if (auto level = GMLevel::getInstance()) {
if (!level) { level->setLevelName(name);
return;
} }
return level->setLevelName(name); });
RemoteCall::exportAs("GMLib_ServerAPI", "getLevelSeed", []() -> std::string {
return GMLevel::getInstance()
.transform([](GMLevel& level) -> std::string { return std::to_string(level.getSeed()); })
.value_or("");
}); });
RemoteCall::exportAs("GMLib_ServerAPI", "setFakeSeed", [](int64_t seed) -> void { RemoteCall::exportAs("GMLib_ServerAPI", "setFakeSeed", [](int64_t seed) -> void {
return GMLIB_Level::setFakeSeed(seed); getLogger().error("GMLib_ServerAPI::setFakeSeed is not implemented");
});
RemoteCall::exportAs("GMLib_ServerAPI", "spawnEntity", [](std::pair<Vec3, int> pos, std::string name) -> Actor* {
return GMLIB_Spawner::spawnEntity(pos.first, pos.second, name);
}); });
RemoteCall::exportAs(
"GMLib_ServerAPI",
"spawnEntity",
[](std::pair<Vec3, int> pos, std::string const& name) -> Actor* {
return GMSpawner::spawnEntity(pos.first, pos.second, name).as_ptr();
}
);
RemoteCall::exportAs( RemoteCall::exportAs(
"GMLib_ServerAPI", "GMLib_ServerAPI",
"shootProjectile", "shootProjectile",
[](Actor* owner, std::string name, float speed, float offset) -> Actor* { [](Actor* owner, std::string const& name, float speed, float offset) -> Actor* {
auto ac = (GMLIB_Actor*)owner; auto actor = GMSpawner::spawnEntity(owner->getPosition(), owner->getDimensionId(), name);
return ac->shootProjectile(name, speed, offset); if (!actor) return nullptr;
((GMActor*)owner)->setProjectile((GMActor&)*actor, speed, offset);
return actor.as_ptr();
} }
); );
RemoteCall::exportAs( RemoteCall::exportAs(
"GMLib_ServerAPI", "GMLib_ServerAPI",
"throwEntity", "throwEntity",
[](Actor* owner, Actor* actor, float speed, float offset) -> bool { [](Actor* owner, Actor* actor, float speed, float offset) -> bool {
auto ac = (GMLIB_Actor*)owner; auto ac = (GMActor*)owner;
return ac->throwEntity(actor, speed, offset); ac->setProjectile((GMActor&)*actor, speed, offset);
return true;
} }
); );
RemoteCall::exportAs("GMLib_ServerAPI", "PlayerToEntity", [](Player* player) -> Actor* { return (Actor*)player; }); RemoteCall::exportAs("GMLib_ServerAPI", "PlayerToEntity", [](Player* player) -> Actor* { return (Actor*)player; });
RemoteCall::exportAs(
"GMLib_ServerAPI",
"addFakeList",
[](const std::string& name, const std::string& xuid) -> bool {
PlayerListAPI::push_back(name, xuid);
return true;
}
);
RemoteCall::exportAs("GMLib_ServerAPI", "removeFakeList", [](const std::string& nameOrXuid) -> bool {
PlayerListAPI::erase(nameOrXuid);
return true;
});
RemoteCall::exportAs("GMLib_ServerAPI", "removeAllFakeList", []() -> void { PlayerListAPI::clear(); });
RemoteCall::exportAs("GMLib_ServerAPI", "getMaxPlayers", []() -> int {
return GMLevel::getInstance().transform(
[](GMLevel& level) -> int { return level.getMaxPlayerCount(); }
).value_or(0);
});
RemoteCall::exportAs("GMLib_ServerAPI", "setMaxPlayers", [&](int count, bool ignoreVanillaLimit) {
if (auto level = GMLevel::getInstance(); level) {
level->setMaxPlayerCount(count, ignoreVanillaLimit);
}
});
} }
+154 -71
View File
@@ -2,123 +2,198 @@
#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 removeBrackets(std::string a1) { std::string GetValueWithPlayer(std::string const& key, Player* player) {
a1.erase(a1.find_last_not_of("%") + 1); return PlaceholderAPI::getValue(key, (GMActor*)player).value_or("");
return a1;
} }
bool isParameters(std::string str) { void registerPlayerPlaceholder(
std::regex reg("[<]([^<>]+)[>]");
return std::regex_search(removeBrackets(str), reg);
}
std::string GetValue(std::string const& from) { return GMLIB::Server::PlaceholderAPI::getValue(from); }
std::string GetValueWithPlayer(std::string const& a1, std::string const& a2) {
return GMLIB::Server::PlaceholderAPI::getValue(a1, ll::service::bedrock::getLevel()->getPlayer(a2));
}
bool registerPlayerPlaceholder(
std::string const& PluginName, std::string const& PluginName,
std::string const& FuncName, std::string const& FuncName,
std::string const& PAPIName std::string const& PAPIName
) { ) {
if (RemoteCall::hasFunc(PluginName, FuncName)) { if (!RemoteCall::hasFunc(PluginName, FuncName)) return;
if (isParameters(PAPIName)) { auto func = [=]() -> void {
auto Call = RemoteCall::importAs<std::string(Player * pl, std::unordered_map<std::string, std::string>)>( PlaceholderAPI::unregisterPlaceholder(PAPIName);
std::weak_ptr mod = ll::mod::ModManagerRegistry::getInstance().getMod(PluginName);
if (mod.expired()) return;
PlaceholderAPI::registerPlaceholder(
PAPIName,
[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&&...
) -> std::optional<std::string> {
if (actor.has_value() && ((Actor*)actor.as_ptr())->isPlayer()) {
std::unordered_map<std::string, std::string> paramMap;
for (auto& [key, val] : params) {
paramMap[key] = val;
}
return Call((Player*)actor.as_ptr(), paramMap);
}
return std::nullopt;
},
mod
); );
GMLIB::Server::PlaceholderAPI::registerPlayerPlaceholder( };
PAPIName, if (ll::mod::ModManagerRegistry::getInstance().hasMod(PluginName)) {
[Call](Player* sp, std::unordered_map<std::string, std::string> map) { return Call(sp, map); }, func();
PluginName
);
} else { } else {
auto Call = RemoteCall::importAs<std::string(Player * pl)>(PluginName, FuncName); getThreadPoolExecutor().execute(func);
GMLIB::Server::PlaceholderAPI::registerPlayerPlaceholder(
PAPIName,
[Call](Player* sp) { return Call(sp); },
PluginName
);
} }
return true;
}
return false;
} }
bool registerServerPlaceholder( void registerServerPlaceholder(
std::string const& PluginName, std::string const& PluginName,
std::string const& FuncName, std::string const& FuncName,
std::string const& PAPIName std::string const& PAPIName
) { ) {
if (RemoteCall::hasFunc(PluginName, FuncName)) { if (!RemoteCall::hasFunc(PluginName, FuncName)) return;
if (isParameters(PAPIName)) { auto func = [=]() -> void {
auto Call = PlaceholderAPI::unregisterPlaceholder(PAPIName);
RemoteCall::importAs<std::string(std::unordered_map<std::string, std::string>)>(PluginName, FuncName); std::weak_ptr mod = ll::mod::ModManagerRegistry::getInstance().getMod(PluginName);
GMLIB::Server::PlaceholderAPI::registerServerPlaceholder( if (mod.expired()) return;
PlaceholderAPI::registerPlaceholder(
PAPIName, PAPIName,
[Call](std::unordered_map<std::string, std::string> map) { return Call(map); }, [Call = RemoteCall::importAs<std::string(std::unordered_map<std::string, std::string>)>(
PluginName PluginName,
FuncName
)](auto, ll::StringMap<std::string> const& params, auto&&...) -> std::optional<std::string> {
std::unordered_map<std::string, std::string> paramMap;
for (auto& [key, val] : params) {
paramMap[key] = val;
}
return Call(paramMap);
},
mod
); );
};
if (ll::mod::ModManagerRegistry::getInstance().hasMod(PluginName)) {
func();
} else { } else {
auto Call = RemoteCall::importAs<std::string()>(PluginName, FuncName); getThreadPoolExecutor().execute(func);
GMLIB::Server::PlaceholderAPI::registerServerPlaceholder(
PAPIName,
[Call]() { return Call(); },
PluginName
);
} }
return true;
}
return false;
} }
bool registerStaticPlaceholder( void registerStaticPlaceholder(
std::string const& PluginName, std::string const& PluginName,
std::string const& FuncName, std::string const& FuncName,
std::string const& PAPIName, std::string const& PAPIName,
int num int num
) { ) {
if (RemoteCall::hasFunc(PluginName, FuncName)) { if (!RemoteCall::hasFunc(PluginName, FuncName)) return;
if (isParameters(PAPIName)) { auto func = [=]() -> void {
auto Call = RemoteCall::importAs<std::string()>(PluginName, FuncName); PlaceholderAPI::unregisterPlaceholder(PAPIName);
if (num == -1) { std::weak_ptr mod = ll::mod::ModManagerRegistry::getInstance().getMod(PluginName);
GMLIB::Server::PlaceholderAPI::registerStaticPlaceholder( if (mod.expired()) return;
PlaceholderAPI::registerPlaceholder(
PAPIName, PAPIName,
[Call] { return Call(); }, [Call = RemoteCall::importAs<std::string()>(PluginName, FuncName)](auto&&...)
PluginName -> std::optional<std::string> { return Call(); },
mod
); );
};
if (ll::mod::ModManagerRegistry::getInstance().hasMod(PluginName)) {
func();
} else { } else {
GMLIB::Server::PlaceholderAPI::registerStaticPlaceholder( getThreadPoolExecutor().execute(func);
PAPIName,
num,
[Call] { return Call(); },
PluginName
);
} }
} }
return true;
}
return false;
}
std::string translateStringWithPlayer(std::string const& str, Player* pl) { std::string translateStringWithPlayer(std::string const& str, Player* pl) {
return GMLIB::Server::PlaceholderAPI::translateString(str, pl); return PlaceholderAPI::translate(str, (GMActor*)pl);
} }
std::string translateString(std::string const& str) { return GMLIB::Server::PlaceholderAPI::translateString(str); } std::string translateString(std::string const& str) { return PlaceholderAPI::translate(str, std::nullopt); }
bool unRegisterPlaceholder(std::string const& str) { return GMLIB::Server::PlaceholderAPI::unRegisterPlaceholder(str); } bool unRegisterPlaceholder(std::string const& str) { return PlaceholderAPI::unregisterPlaceholder(str); }
std::vector<std::string> getAllPAPI() { return GMLIB::Server::PlaceholderAPI::getAllPAPI(); } std::vector<std::string> getAllPAPI() {
std::vector<std::string> result;
for (auto& papi : PlaceholderAPI::getAllPlaceholderData()) {
result.push_back(papi.first);
}
return result;
}
} // namespace PAPIRemoteCall } // namespace PAPIRemoteCall
namespace NewPapiRemoteCall {
std::string translate(std::string const& value, std::string const& language) {
return PlaceholderAPI::translate(value, std::nullopt, language);
}
std::string translateFromActor(std::string const& value, Actor* actor, std::string const& language) {
return PlaceholderAPI::translate(value, (GMActor*)actor, language);
}
void registerPlaceholder(std::string const& placeholder, std::string const& funcName, std::string const& pluginName) {
if (!RemoteCall::hasFunc(pluginName, funcName)) return;
auto func = [=]() -> void {
if (std::weak_ptr mod = ll::mod::ModManagerRegistry::getInstance().getMod(pluginName); !mod.expired()) {
PlaceholderAPI::unregisterPlaceholder(placeholder);
PlaceholderAPI::registerPlaceholder(
placeholder,
[Call = RemoteCall::importAs<
std::string(Actor*, std::unordered_map<std::string, std::string>, std::string)>(
pluginName,
funcName
)](optional_ref<Actor> actor, ll::StringMap<std::string> const& params, std::string const& language
) -> std::optional<std::string> {
std::unordered_map<std::string, std::string> paramMap;
for (auto& [key, val] : params) {
paramMap[key] = val;
}
auto result = Call((Actor*)actor.as_ptr(), paramMap, language);
return result == "<std::nullopt>" ? std::nullopt : std::optional(result);
},
mod
);
}
};
if (ll::mod::ModManagerRegistry::getInstance().hasMod(pluginName)) {
func();
} else {
getThreadPoolExecutor().execute(func);
}
}
bool unregisterPlaceholder(std::string const& placeholder) {
return PlaceholderAPI::unregisterPlaceholder(placeholder);
}
bool unregisterPlaceholderFromModName(std::string const& pluginName) {
std::weak_ptr plugin = ll::mod::ModManagerRegistry::getInstance().getMod(pluginName);
if (plugin.expired()) return false;
return PlaceholderAPI::unregisterPlaceholder(plugin);
}
std::string getValue(
std::string const& placeholder,
std::unordered_map<std::string, std::string> params,
std::string const& language
) {
ll::StringMap<std::string> paramMap;
for (auto& [key, val] : params) {
paramMap[key] = val;
}
return PlaceholderAPI::getValue(placeholder, std::nullopt, paramMap, language).value_or("<std::nullopt>");
}
std::string getValueFromActor(
std::string const& placeholder,
Actor* actor,
std::unordered_map<std::string, std::string> params,
std::string const& language
) {
ll::StringMap<std::string> paramMap;
for (auto& [key, val] : params) {
paramMap[key] = val;
}
return PlaceholderAPI::getValue(placeholder, (GMActor*)actor, paramMap, language).value_or("<std::nullopt>");
}
} // namespace NewPapiRemoteCall
#define EXPORTAPI(T) \ #define EXPORTAPI(T) \
RemoteCall::exportAs("BEPlaceholderAPI", ll::utils::string_utils::replaceAll(#T, "PAPIRemoteCall::", ""), T); RemoteCall::exportAs("BEPlaceholderAPI", ll::utils::string_utils::replaceAll(#T, "PAPIRemoteCall::", ""), T);
#define EXPORTAPI2(T) RemoteCall::exportAs("PlaceholderAPI", #T, NewPapiRemoteCall::T);
void ExportPAPI() { void ExportPAPI() {
EXPORTAPI(PAPIRemoteCall::registerPlayerPlaceholder); EXPORTAPI(PAPIRemoteCall::registerPlayerPlaceholder);
EXPORTAPI(PAPIRemoteCall::registerServerPlaceholder); EXPORTAPI(PAPIRemoteCall::registerServerPlaceholder);
@@ -129,4 +204,12 @@ void ExportPAPI() {
EXPORTAPI(PAPIRemoteCall::translateStringWithPlayer); EXPORTAPI(PAPIRemoteCall::translateStringWithPlayer);
EXPORTAPI(PAPIRemoteCall::unRegisterPlaceholder); EXPORTAPI(PAPIRemoteCall::unRegisterPlaceholder);
EXPORTAPI(PAPIRemoteCall::getAllPAPI); EXPORTAPI(PAPIRemoteCall::getAllPAPI);
EXPORTAPI2(translate);
EXPORTAPI2(translateFromActor);
EXPORTAPI2(registerPlaceholder);
EXPORTAPI2(unregisterPlaceholder);
EXPORTAPI2(unregisterPlaceholderFromModName);
EXPORTAPI2(getValue);
EXPORTAPI2(getValueFromActor);
} }
+32 -14
View File
@@ -1,29 +1,47 @@
{ {
"format_version": 2, "format_version": 3,
"format_uuid": "289f771f-2c9a-4d73-9f3f-8492495a924d",
"tooth": "github.com/GroupMountain/GMLIB-LegacyRemoteCallApi", "tooth": "github.com/GroupMountain/GMLIB-LegacyRemoteCallApi",
"version": "0.12.5", "version": "1.5.1",
"info": { "info": {
"name": "GMLIB-LegacyRemoteCallApi", "name": "GMLIB-LegacyRemoteCallApi",
"description": "Legacy RemoteCall API for GMLIB", "description": "Legacy RemoteCall API for GMLIB",
"source": "github.com/GroupMountain/GMLIB-LegacyRemoteCallApi",
"author": "GroupMountain",
"tags": [ "tags": [
"levilamina", "platform:levilamina",
"type:mod",
"gmlib", "gmlib",
"lse", "lse",
"library" "library"
] ],
"avatar_url": "https://raw.githubusercontent.com/GroupMountain/GMLIB-LegacyRemoteCallApi/refs/heads/main/icon.jpg"
}, },
"asset_url": "https://github.com/GroupMountain/GMLIB-LegacyRemoteCallApi/releases/download/v0.12.5/GMLIB-LegacyRemoteCallApi-windows-x64.zip", "variants": [
"dependencies": {
"github.com/GroupMountain/GMLIB": ">=0.12.4"
},
"files": {
"place": [
{ {
"src": "GMLIB-LegacyRemoteCallApi/*", "platform": "win-x64",
"dest": "plugins/GMLIB-LegacyRemoteCallApi" "dependencies": {
"github.com/LiteLDev/LeviLamina": ">=1.5.0",
"github.com/GroupMountain/GMLIB-Release": ">=1.5.2",
"github.com/GroupMountain/ModAPI-Release": ">=0.1.0",
"github.com/MiracleForest/iListenAttentively-Release": ">=0.6.0"
},
"assets": [
{
"type": "zip",
"urls": [
"https://{{tooth}}/releases/download/v{{version}}/GMLIB-LegacyRemoteCallApi-windows-x64.zip"
],
"placements": [
{
"type": "dir",
"src": "GMLIB-LegacyRemoteCallApi",
"dest": "plugins/GMLIB-LegacyRemoteCallApi/"
} }
] ]
} }
],
"remove_files": [
"plugins/GMLIB-LegacyRemoteCallApi"
]
}
]
} }
+25 -55
View File
@@ -1,84 +1,54 @@
add_rules("mode.debug", "mode.release") add_rules("mode.debug", "mode.release")
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-repo https://github.com/MiracleForest/xmake-repo.git")
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. add_requires("levilamina 1.5.2", {configs = {target_type = "server"}})
add_requires("levilamina")
add_requires("legacyremotecall") add_requires("legacyremotecall")
add_requires("levibuildscript 0.5.2")
add_requires("ilistenattentively 0.8.0")
add_requires("gmlib 1.5.2")
add_requires("modapi 0.1.1")
-- Option 2: Use a specific version of LeviLamina released on GitHub. target("GMLIB-LegacyRemoteCallApi")
-- add_requires("levilamina x.x.x")
-- Option 3: Use the latest commit of LeviLamina on GitHub.
-- -- Here, "develop" is the branch name. You can change it to any branch name you want.
-- add_requires("levilamina develop")
-- -- You can also use debug build of LeviLamina.
-- -- add_requires("levilamina develop", {debug = true})
-- package("levilamina")
-- add_urls("https://github.com/LiteLDev/LeviLamina.git")
-- add_deps("ctre 3.8.1")
-- add_deps("entt 3.12.2")
-- add_deps("fmt 10.1.1")
-- add_deps("gsl 4.0.0")
-- add_deps("leveldb 1.23")
-- add_deps("magic_enum 0.9.0")
-- add_deps("nlohmann_json 3.11.2")
-- add_deps("rapidjson 1.1.0")
-- add_deps("pcg_cpp 1.0.0")
-- add_deps("pfr 2.1.1")
-- add_deps("preloader 1.4.0")
-- add_deps("symbolprovider 1.1.0")
-- -- You may need to change this to the target BDS version of your choice.
-- add_deps("bdslibrary 1.20.50.03")
-- on_install(function (package)
-- import("package.tools.xmake").install(package)
-- end)
target("GMLIB-LegacyRemoteCallApi") -- Change this to your plugin name.
add_cxflags( add_cxflags(
"/EHa", "/EHa",
"/utf-8" "/utf-8",
"/bigobj"
) )
add_defines( add_defines(
"NOMINMAX", "NOMINMAX",
"UNICODE" "UNICODE",
"_HAS_CXX23=1"
) )
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",
"legacyremotecall" "legacyremotecall",
"ilistenattentively",
"gmlib",
"modapi"
) )
add_shflags( add_rules("@levibuildscript/linkrule")
"/DELAYLOAD:bedrock_server.dll" -- Magic to import symbols from BDS add_rules("@levibuildscript/modpacker")
) set_exceptions("none")
set_exceptions("none") -- To avoid conflicts with /EHa
set_kind("shared") set_kind("shared")
set_languages("c++23") set_languages("cxx20")
set_symbols("debug") set_symbols("debug")
after_build(function (target) after_build(function (target)
local plugin_packer = import("scripts.after_build") local target_path = path.join("bin", target:name(), "lib")
if os.exists(target_path) then
local plugin_define = { os.rm(target_path)
pluginName = target:name(), end
pluginFile = path.filename(target:targetfile()), os.cp("lib", target_path)
}
plugin_packer.pack_plugin(target,plugin_define)
end) end)