Compare commits

...

191 Commits

32 changed files with 8224 additions and 518 deletions
+2 -6
View File
@@ -9,10 +9,6 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v2
with:
submodules: recursive
- uses: actions/checkout@v4
- uses: xmake-io/github-action-setup-xmake@v1
@@ -25,8 +21,8 @@ jobs:
- run: |
xmake -w -y
- uses: actions/upload-artifact@v3
- uses: actions/upload-artifact@v4
with:
name: ${{ github.event.repository.name }}-windows-x64-${{ github.sha }}
path: |
bin/
bin/
+13 -15
View File
@@ -9,10 +9,6 @@ jobs:
steps:
- name: Checkout repository
uses: actions/checkout@v2
with:
submodules: recursive
- uses: actions/checkout@v4
- uses: xmake-io/github-action-setup-xmake@v1
@@ -25,7 +21,7 @@ jobs:
- run: |
xmake -w -y
- uses: actions/upload-artifact@v3
- uses: actions/upload-artifact@v4
with:
name: ${{ github.event.repository.name }}-windows-x64-${{ github.sha }}
path: |
@@ -38,24 +34,26 @@ jobs:
contents: write
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Checkout code
uses: actions/checkout@v4
- uses: actions/download-artifact@v3
- name: Download Mod
uses: actions/download-artifact@v4
with:
name: ${{ github.event.repository.name }}-windows-x64-${{ github.sha }}
path: release/
path: artifact
- run: |
cp LICENSE README.md release/
- name: Copy additional files
run: |
cp -v LICENSE README.md artifact/
- name: Archive release
run: |
cd release
zip -r ../${{ github.event.repository.name }}-windows-x64.zip *
cd ..
working-directory: artifact
- uses: softprops/action-gh-release@v1
- name: Create GitHub Release
uses: softprops/action-gh-release@v1
with:
append_body: true
files: |
${{ github.event.repository.name }}-windows-x64.zip
${{ github.event.repository.name }}-windows-x64.zip
+2 -1
View File
@@ -14,4 +14,5 @@ CMakeSettings.json
build/
/.xmake
/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插件的兼容性保留。
- 通过本模块,可以使LSE插件调用 `GMLIB` 内部的API。
# 注意事项
- 本模块仅为兼容性保留模块,仅保留过去的接口以保留兼容性。
- 本模块不会提供 `GMLIB` 在迁移到 `LeviLamina` 后新开发的接口。
# 开发文档
- https://groupmountain.github.io/Documentation/
Submodule SDK-GMLIB deleted from 58cec5c0c5
+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
): boolean;
/** 注册一个服务器PAPI变量 */
static registerServerPlaceholder(
/** PAPI调用函数 */
func: (
/** 变量参数 */
param: null | object.<string, string>
) => string,
/** 插件名字 */
pluginsName: string,
/** PAPI变量 */
PAPIName: string
): boolean;
/** 注册一个静态PAPI变量 */
static registerStaticPlaceholder(
/** PAPI调用函数 */
func: () => string,
/** 插件名字 */
pluginsName: string,
/** PAPI变量 */
PAPIName: string,
/** 更新时间 */
UpdateInterval: number
): boolean;
/** 获取一个服务器变量的值 */
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[];
}
+109 -24
View File
@@ -1,54 +1,139 @@
const PAPIgetValueAPI = ll.import("BEPlaceholderAPI", "GetValue")
const PAPIgetValueByPlayerAPI = ll.import("BEPlaceholderAPI", "GetValueWithPlayer")
const PAPIregisterPlayerPlaceholderAPI = ll.import("BEPlaceholderAPI", "registerPlayerPlaceholder")
const PAPIregisterServerPlaceholderAPI = ll.import("BEPlaceholderAPI", "registerServerPlaceholder")
const PAPIregisterStaticPlaceholderAPI = ll.import("BEPlaceholderAPI", "registerStaticPlaceholder")
const PAPItranslateStringAPI = ll.import("BEPlaceholderAPI", "translateString")
const PAPIunRegisterPlaceholderAPI = ll.import("BEPlaceholderAPI", "unRegisterPlaceholder")
const PAPIgetAllPAPI = ll.import("BEPlaceholderAPI", "getAllPAPI")
Function.prototype.getName = function () {
return this.name || this.toString().match(/function\s*([^(]*)\(/)[1]
const PlaceholderAPI = {
/** 获取一个服务器变量的值 @type {function(string):string} */
getValueAPI: ll.import("BEPlaceholderAPI", "GetValue"),
/** 获取一个玩家变量的值 @type {function(string,Player):string} */
getValueByPlayerAPI: ll.import("BEPlaceholderAPI", "GetValueWithPlayer"),
/** 注册一个玩家变量 @type {function(string,string,string):boolean} */
registerPlayerPlaceholderAPI: ll.import("BEPlaceholderAPI", "registerPlayerPlaceholder"),
/** 注册一个服务器变量 @type {function(string,string,string):boolean} */
registerServerPlaceholderAPI: ll.import("BEPlaceholderAPI", "registerServerPlaceholder"),
/** 注册一个静态变量 @type {function(string,string,string,number):boolean} */
registerStaticPlaceholderAPI: ll.import("BEPlaceholderAPI", "registerStaticPlaceholder"),
/** 翻译包含PAPI服务器变量的字符串 @type {function(string):string} */
translateStringAPI: ll.import("BEPlaceholderAPI", "translateString"),
/** 翻译包含PAPI玩家变量的字符串 @type {function(string,Player):string} */
translateStringWithPlayerAPI: ll.import("BEPlaceholderAPI", "translateStringWithPlayer"),
/** 注销PAPI变量 @type {function(string):boolean} */
unRegisterPlaceholderAPI: ll.import("BEPlaceholderAPI", "unRegisterPlaceholder"),
/** 获取所有已注册的PAPI变量 @type {function():Array.<string>} */
getAllPAPI: ll.import("BEPlaceholderAPI", "getAllPAPI")
}
Function.prototype.getName =
/**
* 获取函数名字
* @returns {string}
*/
function () {
return this.name || this.toString().match(/function\s*([^(]*)\(/)?.[1] || getStringHashCode(this.toString()).toString(16);
}
/**
* 获取字符串哈希值
* @param {string} str 字符串
* @returns {number}
*/
function getStringHashCode(str) {
let hash = 0, chr;
if (str.length === 0) return hash;
for (let i = 0; i < str.length; i++) {
chr = str.charCodeAt(i);
hash = ((hash << 5) - hash) + chr;
hash |= 0;
}
return hash;
}
/** PAPI变量类 */
class PAPI {
constructor() {
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) {
ll.export(func, PluginName, func.getName())
PAPIregisterPlayerPlaceholderAPI(PluginName, func.getName(), PAPIName)
ll.export(func, PluginName, func.getName());
return PlaceholderAPI.registerPlayerPlaceholderAPI(PluginName, func.getName(), PAPIName);
}
/**
* 注册一个服务器PAPI变量
* @param {function} func 变量调用的函数
* @param {string} PluginName 插件名字
* @param {string} PAPIName PAPI变量名
* @returns {boolean} 是否注册成功
*/
static registerServerPlaceholder(func, PluginName, PAPIName) {
ll.export(func, PluginName, func.getName())
PAPIregisterServerPlaceholderAPI(PluginName, func.getName(), PAPIName)
ll.export(func, PluginName, func.getName());
return PlaceholderAPI.registerServerPlaceholderAPI(PluginName, func.getName(), 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) {
ll.export(func, PluginName, func.getName())
PAPIregisterStaticPlaceholderAPI(PluginName, func.getName(), PAPIName, UpdateInterval)
ll.export(func, PluginName, func.getName());
return PlaceholderAPI.registerStaticPlaceholderAPI(PluginName, func.getName(), PAPIName, UpdateInterval);
}
/**
* 获取一个服务器变量的值
* @param {string} key PAPI变量名
* @returns {string} 值
*/
static getValue(key) {
return PAPIgetValueAPI(key)
return PlaceholderAPI.getValueAPI(key);
}
static getValueByPlayer(key, xuid) {
return PAPIgetValueByPlayerAPI(key, xuid)
/**
* 获取一个玩家变量的值
* @param {string} key PAPI变量名
* @param {Player} pl 玩家对象
* @returns {string} 值
*/
static getValueByPlayer(key, pl) {
return PlaceholderAPI.getValueByPlayerAPI(key, pl);
}
static translateString(str, xuid = "") {
return PAPItranslateStringAPI(str, xuid)
/**
* 翻译带PAPI变量的字符串
* @param {string} str 字符串
* @param {Player} pl 玩家对象
* @returns {string} 翻译结果
*/
static translateString(str, pl = null) {
if (pl) {
return PlaceholderAPI.translateStringWithPlayerAPI(str, pl);
}
return PlaceholderAPI.translateStringAPI(str);
}
/**
* 注销一个PAPI变量
* @param {string} str PAPI变量名
* @returns {boolean} 是否注销成功
*/
static unRegisterPlaceholder(str) {
return PAPIunRegisterPlaceholderAPI(str)
return PlaceholderAPI.unRegisterPlaceholderAPI(str);
}
/**
* 获取所有已注册的PAPI变量
* @returns {Array.<string>} 已注册的PAPI变量数组
*/
static getAllPAPI() {
return PAPIgetAllPAPI();
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;
}
+170
View File
@@ -0,0 +1,170 @@
/**
* @returns {string}
*/
const getPluginName = () => {
try {
throw new Error("getPluginName");
} catch (error) {
return error.stack.trim().match(/plugins\\(.*)\\.*\.js:[0-9]+\)$/i)?.[1] || "Unknown";
}
};
module.exports = {
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.import("GMLIB_FormAPI", "getNextFormCallbackId");
// class ServerSettingForm {
// constructor() {
// throw new Error("Static class cannot be instantiated");
// }
// static getDefaultPriority() {
// return ll.import("GMLIB_ServerSettingForm", "getDefaultPriority")();
// }
// static hasTitle() {
// return ll.import("GMLIB_ServerSettingForm", "hasTitle")();
// }
// static getTitle() {
// return ll.import("GMLIB_ServerSettingForm", "getTitle")();
// }
// static setTitle(title, forceModify = false) {
// return ll.import("GMLIB_ServerSettingForm", "setTitle")(title, forceModify);
// }
// static hasIcon() {
// return ll.import("GMLIB_ServerSettingForm", "hasIcon")();
// }
// static getIconData() {
// return hasIcon() ? ll.import("GMLIB_ServerSettingForm", "getIconData")() : null;
// }
// static getIconType() {
// return ll.import("GMLIB_ServerSettingForm", "getIconType")();
// }
// static setIcon(data, type = 0, forceModify = false) {
// return ll.import("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.import("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.import("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.import("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.import("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.import("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.import("GMLIB_ServerSettingForm", "addStepSlider")(text, steps, defaultVal, callbackId, detectorId, priority);
// }
// static removeElement(id) {
// return ll.import("GMLIB_ServerSettingForm", "removeElement")(id);
// }
// }
// class NpcDialogueForm {
// constructor(npcName, sceneName, dialogue) {
// this.mFormId = ll.import("GMLIB_NpcDialogueForm", "createForm")(npcName, sceneName, dialogue);
// }
// addButton(button) {
// return ll.import("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.import("GMLIB_NpcDialogueForm", "sendTo")(this.mFormId, pl, callbackId);
// if (free) {
// this.destroy();
// }
// }
// destroy() {
// ll.import("GMLIB_NpcDialogueForm", "destroyForm")(this.mFormId);
// }
// }
// class ChestForm {
// constructor(npcName, sceneName, dialogue) {
// this.mFormId = ll.import("GMLIB_NpcDialogueForm", "createForm")(npcName, sceneName, dialogue);
// }
// addButton(button) {
// return ll.import("GMLIB_NpcDialogueForm", "addButton")(this.mFormId, button);
// }
// sendTo(pl, free = true) {
// //let callbackId = getNextCallbackId();
// //ll.export(callback, "GMLIB_FORM_CALLBACK", callbackId);
// //ll.import("GMLIB_NpcDialogueForm", "sendTo")(this.mFormId, pl, callbackId);
// //if (free) {
// // this.destroy();
// //}
// }
// destroy() {
// //ll.import("GMLIB_NpcDialogueForm", "destroyForm")(this.mFormId);
// }
// }
// module.exports = {
// ServerSettingForm,
// NpcDialogueForm,
// ChestForm
// };
+1856
View File
File diff suppressed because it is too large Load Diff
+3029 -81
View File
File diff suppressed because it is too large Load Diff
+3
View File
@@ -1,7 +1,10 @@
{
"name": "${pluginName}",
"entry": "${pluginFile}",
"version": "0.13.6",
"author": "GroupMountain",
"type": "native",
"passive": true,
"dependencies": [
{
"name": "GMLIB"
+3 -2
View File
@@ -88,10 +88,11 @@ function pack_plugin(target,plugin_define)
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")
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(outputdir, path.basename(plugin_define.pluginFile) .. ".pdb")
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()
+92
View File
@@ -0,0 +1,92 @@
#include "Global.h"
using namespace ll::hash_utils;
class LegacyScriptBinaryStreamManager {
private:
int64 mNextBinaryStreamId = 0;
std::unordered_map<uint64, std::shared_ptr<GMLIB_BinaryStream>> mBinaryStream;
public:
uint getNextId() { return mNextBinaryStreamId++; }
void cretateBinaryStream(uint id) { mBinaryStream[id] = std::make_shared<GMLIB_BinaryStream>(); }
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<GMLIB_BinaryStream> 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(&GMLIB_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 BinaryStreamManager.getBinaryStream(id)->reset();
});
RemoteCall::exportAs("GMLIB_BinaryStream_API", "sendTo", [](uint64 id, Player* player) -> void {
if (auto bs = BinaryStreamManager.getBinaryStream(id); bs != nullptr) bs->sendTo(*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->writeType(NetworkItemStackDescriptor(*value)));
EXPORTAPI("writeString", std::string const&, bs->writeString(value));
EXPORTAPI("writeCompoundTag", CompoundTag*, bs->writeCompoundTag(*value));
EXPORTAPI2(writeBool);
EXPORTAPI2(writeByte);
EXPORTAPI2(writeDouble);
EXPORTAPI2(writeFloat);
EXPORTAPI2(writeSignedBigEndianInt);
EXPORTAPI2(writeSignedInt);
EXPORTAPI2(writeSignedInt64);
EXPORTAPI2(writeSignedShort);
EXPORTAPI2(writeUnsignedChar);
EXPORTAPI2(writeUnsignedInt);
EXPORTAPI2(writeUnsignedInt64);
EXPORTAPI2(writeUnsignedShort);
EXPORTAPI2(writeUnsignedVarInt);
EXPORTAPI2(writeUnsignedVarInt64);
EXPORTAPI2(writeVarInt);
EXPORTAPI2(writeVarInt64);
}
+864 -65
View File
@@ -1,102 +1,901 @@
#include "GMLIB/Mod/CustomRecipe/CustomRecipe.h"
#include "Global.h"
#include <regex>
bool isInteger(const std::string& str) {
std::regex pattern("^[+-]?\\d+$");
return std::regex_match(str, pattern);
}
ActorUniqueID parseScriptUniqueID(std::string const& uniqueId) {
return isInteger(uniqueId) ? ActorUniqueID(std::stoll(uniqueId)) : ActorUniqueID::INVALID_ID();
}
void Export_Compatibility_API() {
RemoteCall::exportAs("GMLIB_API", "getServerMspt", []() -> float {
auto level = GMLIB_Level::getLevel();
if (!level) {
return 0.0f;
}
return level->getServerMspt();
RemoteCall::exportAs("GMLIB_API", "unregisterRecipe", [](std::string const& id) -> bool {
return GMLIB_Level::getInstance().has_value() ? GMLIB::Mod::CustomRecipe::unregisterRecipe(id) : false;
});
RemoteCall::exportAs("GMLIB_API", "setCustomPackPath", [](std::string const& path) -> void {
GMLIB::Mod::CustomPacks::addCustomPackPath(path);
});
RemoteCall::exportAs("GMLIB_API", "getServerMspt", []() -> double {
return GMLIB_Level::getInstance().transform(
[](GMLIB_Level& level) -> double { return level.getServerMspt(); }
).value_or(0.0);
});
RemoteCall::exportAs("GMLIB_API", "getServerCurrentTps", []() -> float {
auto level = GMLIB_Level::getLevel();
if (!level) {
return 0.0f;
}
return level->getServerCurrentTps();
return GMLIB_Level::getInstance()
.transform([](GMLIB_Level& level) -> float { return level.getServerCurrentTps(); })
.value_or(0.0);
});
RemoteCall::exportAs("GMLIB_API", "getServerAverageTps", []() -> float {
auto level = GMLIB_Level::getLevel();
if (!level) {
return 0.0f;
}
return level->getServerAverageTps();
RemoteCall::exportAs("GMLIB_API", "getServerAverageTps", []() -> double {
return GMLIB_Level::getInstance()
.transform([](GMLIB_Level& level) -> double { return level.getServerAverageTps(); })
.value_or(0.0);
});
RemoteCall::exportAs("GMLIB_API", "getAllPlayerUuids", []() -> std::vector<std::string> {
return GMLIB_Player::getAllUuids();
});
RemoteCall::exportAs("GMLIB_API", "getAllExperiments", []() -> std::vector<int> {
auto map = GMLIB_Level::getAllExperiments();
std::vector<int> result;
for (auto& key : map) {
result.push_back(key.first);
std::vector<std::string> result;
for (auto& uuid : GMLIB_Player::getAllUuids()) {
result.push_back(uuid.asString());
}
return result;
});
RemoteCall::exportAs("GMLIB_API", "getExperimentTranslatedName", [](int id) -> std::string {
auto map = GMLIB_Level::getAllExperimentsTranslateKeys();
if (map.count(id)) {
return std::string(map[id]);
RemoteCall::exportAs("GMLIB_API", "getPlayerNbt", [](std::string const& uuid) -> std::unique_ptr<CompoundTag> {
return std::move(GMLIB_Player::getPlayerNbt(mce::UUID::fromString(uuid)));
});
RemoteCall::exportAs(
"GMLIB_API",
"setPlayerNbt",
[](std::string const& uuid, CompoundTag* nbt, bool forceCreate) -> bool {
return GMLIB_Player::setPlayerNbt(mce::UUID::fromString(uuid), (GMLIB_CompoundTag&)*nbt, forceCreate);
}
return "";
);
RemoteCall::exportAs(
"GMLIB_API",
"setPlayerNbtTags",
[](std::string const& uuid, CompoundTag* nbt, std::vector<std::string> tags) -> bool {
return GMLIB_Player::setPlayerNbtTags(mce::UUID::fromString(uuid), (GMLIB_CompoundTag&)*nbt, tags);
}
);
RemoteCall::exportAs("GMLIB_API", "deletePlayerNbt", [](std::string const& uuid) -> bool {
return GMLIB_Player::deletePlayerNbt(mce::UUID::fromString(uuid));
});
RemoteCall::exportAs("GMLIB_API", "getAllExperiments", []() -> std::vector<int> {
std::vector<int> result;
for (auto& key : GMLIB_Level::getAllExperiments()) {
result.push_back((int)key);
}
return result;
});
RemoteCall::exportAs("GMLIB_API", "getExperimentTranslateKey", [](int id) -> std::string {
std::string result;
try {
result = Experiments::getExperimentTextID(AllExperiments(id));
} catch (...) {}
return result;
});
RemoteCall::exportAs(
"GMLIB_API",
"createFloatingText",
[](std::pair<Vec3, int> pos, std::string text, bool papi) -> int {
auto ft = new GMLIB::Server::FloatingText(text, pos.first, pos.second, papi);
[](std::pair<Vec3, int> pos, std::string const& text, bool papi) -> int {
auto ft = GMLIB::Server::FloatingTextManager::createStatic(text, pos.first, pos.second, papi);
GMLIB::Server::FloatingTextManager::getInstance().add(ft);
return ft->getRuntimeID();
}
);
RemoteCall::exportAs("GMLIB_API", "setFloatingTextData", [](int id, std::string text) -> bool {
auto ft = GMLIB::Server::FloatingText::getFloatingText(id);
if (ft) {
ft->setText(text);
return true;
}
return false;
RemoteCall::exportAs("GMLIB_API", "setFloatingTextData", [](int id, std::string const& text) -> bool {
return GMLIB::Server::FloatingTextManager::getInstance()
.getFloatingText(id)
.transform([&text](GMLIB::Server::FloatingTextBase& ft) -> bool {
ft.setText(text);
return true;
})
.has_value();
});
RemoteCall::exportAs("GMLIB_API", "deleteFloatingText", [](int id) -> bool {
return GMLIB::Server::FloatingText::deleteFloatingText(id);
return GMLIB::Server::FloatingTextManager::getInstance().remove(id);
});
RemoteCall::exportAs("GMLIB_API", "sendFloatingTextToPlayer", [](int id, Player* pl) -> bool {
auto ft = GMLIB::Server::FloatingText::getFloatingText(id);
if (ft) {
ft->sendToClient(pl);
return true;
}
return false;
return GMLIB::Server::FloatingTextManager::getInstance()
.getFloatingText(id)
.transform([&pl](GMLIB::Server::FloatingTextBase& ft) -> bool {
ft.sendTo(*pl);
return true;
})
.has_value();
});
RemoteCall::exportAs("GMLIB_API", "sendFloatingText", [](int id) -> bool {
auto ft = GMLIB::Server::FloatingText::getFloatingText(id);
if (ft) {
ft->sendToAllClients();
return true;
}
return false;
return GMLIB::Server::FloatingTextManager::getInstance()
.getFloatingText(id)
.transform([](GMLIB::Server::FloatingTextBase& ft) -> bool {
ft.sendToClients();
return true;
})
.has_value();
});
RemoteCall::exportAs("GMLIB_API", "removeFloatingTextFromPlayer", [](int id, Player* pl) -> bool {
auto ft = GMLIB::Server::FloatingText::getFloatingText(id);
if (ft) {
ft->removeFromClient(pl);
return true;
}
return false;
return GMLIB::Server::FloatingTextManager::getInstance()
.getFloatingText(id)
.transform([&pl](GMLIB::Server::FloatingTextBase& ft) -> bool {
ft.removeFrom(*pl);
return true;
})
.has_value();
});
RemoteCall::exportAs("GMLIB_API", "removeFloatingText", [](int id) -> bool {
auto ft = GMLIB::Server::FloatingText::getFloatingText(id);
if (ft) {
ft->removeFromAllClients();
return true;
}
return false;
return GMLIB::Server::FloatingTextManager::getInstance()
.getFloatingText(id)
.transform([](GMLIB::Server::FloatingTextBase& ft) -> bool {
ft.removeFromClients();
return true;
})
.has_value();
});
RemoteCall::exportAs("GMLIB_API", "updateClientFloatingTextData", [](int id, Player* pl) -> bool {
return GMLIB::Server::FloatingTextManager::getInstance()
.getFloatingText(id)
.transform([&pl](GMLIB::Server::FloatingTextBase& ft) -> bool {
ft.update(*pl);
return true;
})
.has_value();
});
RemoteCall::exportAs("GMLIB_API", "updateAllClientsFloatingTextData", [](int id) -> bool {
return GMLIB::Server::FloatingTextManager::getInstance()
.getFloatingText(id)
.transform([](GMLIB::Server::FloatingTextBase& ft) -> bool {
ft.updateClients();
return true;
})
.has_value();
});
RemoteCall::exportAs("GMLIB_API", "isVersionMatched", [](int a, int b, int c) -> bool {
auto version = SemVersion(a, b, c, "", "");
return LIB_VERSION.satisfies(version);
return LIB_VERSION >= GMLIB::Version(a, b, c, "", "");
});
RemoteCall::exportAs("GMLIB_API", "getVersion_LRCA", []() -> std::string { return LIB_VERSION.asString(); });
RemoteCall::exportAs("GMLIB_API", "getVersion_GMLIB", []() -> std::string {
return GMLIB::Version::getLibVersionString();
});
RemoteCall::exportAs(
"GMLIB_API",
"resourcePackDefaultTranslate",
[](std::string const& key, std::vector<std::string> params) -> std::string { return I18nAPI::get(key, params); }
);
RemoteCall::exportAs(
"GMLIB_API",
"resourcePackTranslate",
[](std::string const& key, std::vector<std::string> params, std::string const& code) -> std::string {
return I18nAPI::get(key, params, code);
}
);
RemoteCall::exportAs("GMLIB_API", "chooseResourcePackI18nLanguage", [](std::string const& code) -> void {
if (GMLIB_Level::getInstance()) {
I18nAPI::chooseLanguage(code);
}
});
RemoteCall::exportAs("GMLIB_API", "getResourcePackI18nLanguage", []() -> std::string {
return GMLIB_Level::getInstance().has_value() ? I18nAPI::getCurrentLanguageCode() : "unknown";
});
RemoteCall::exportAs("GMLIB_API", "getSupportedLanguages", []() -> std::vector<std::string> {
return GMLIB_Level::getInstance() ? I18nAPI::getSupportedLanguageCodes() : std::vector<std::string>();
});
RemoteCall::exportAs("GMLIB_API", "loadLanguage", [](std::string const& code, std::string const& lang) -> void {
if (GMLIB_Level::getInstance()) {
I18nAPI::loadLanguage(code, lang);
}
});
RemoteCall::exportAs(
"GMLIB_API",
"updateOrCreateLanguageFile",
[](std::string const& code, std::unordered_map<std::string, std::string> lang, std::string const& path
) -> void {
if (GMLIB_Level::getInstance()) {
I18nAPI::updateOrCreateLanguageFile(path, code, lang);
}
}
);
RemoteCall::exportAs("GMLIB_API", "loadLanguagePath", [](std::string const& path) -> void {
if (GMLIB_Level::getInstance()) {
I18nAPI::loadLanguagesFromDirectory(path);
}
});
RemoteCall::exportAs("GMLIB_API", "getPlayerPosition", [](std::string const& uuid) -> std::pair<BlockPos, int> {
return GMLIB_Player::getPlayerPosition(mce::UUID::fromString(uuid))
.value_or(std::pair<BlockPos, int>({0, 0, 0}, -1));
});
RemoteCall::exportAs(
"GMLIB_API",
"setPlayerPosition",
[](std::string const& uuid, std::pair<BlockPos, int> pos) -> bool {
return GMLIB_Player::setPlayerPosition(mce::UUID::fromString(uuid), pos.first, pos.second);
}
);
RemoteCall::exportAs("GMLIB_API", "playerHasScore", [](std::string const& uuid, std::string const& obj) -> bool {
return GMLIB_Player::getPlayerScore(mce::UUID::fromString(uuid), obj).has_value();
});
RemoteCall::exportAs("GMLIB_API", "getPlayerScore", [](std::string const& uuid, std::string const& obj) -> int {
return GMLIB_Player::getPlayerScore(mce::UUID::fromString(uuid), obj).value_or(0);
});
RemoteCall::exportAs(
"GMLIB_API",
"addPlayerScore",
[](std::string const& uuid, std::string const& obj, int value) -> bool {
return GMLIB_Player::setPlayerScore(mce::UUID::fromString(uuid), obj, value, PlayerScoreSetFunction::Add)
.has_value();
}
);
RemoteCall::exportAs(
"GMLIB_API",
"reducePlayerScore",
[](std::string const& uuid, std::string const& obj, int value) -> bool {
return GMLIB_Player::setPlayerScore(
mce::UUID::fromString(uuid),
obj,
value,
PlayerScoreSetFunction::Subtract
)
.has_value();
}
);
RemoteCall::exportAs(
"GMLIB_API",
"setPlayerScore",
[](std::string const& uuid, std::string const& obj, int value) -> bool {
return GMLIB_Player::setPlayerScore(mce::UUID::fromString(uuid), obj, value).has_value();
}
);
RemoteCall::exportAs("GMLIB_API", "resetPlayerScore", [](std::string const& uuid, std::string const& obj) -> bool {
return GMLIB_Player::resetPlayerScore(mce::UUID::fromString(uuid), obj);
});
RemoteCall::exportAs("GMLIB_API", "resetPlayerScores", [](std::string const& uuid) -> bool {
return GMLIB_Player::resetPlayerScore(mce::UUID::fromString(uuid));
});
RemoteCall::exportAs(
"GMLIB_API",
"entityHasScore",
[](std::string const& uniqueId, std::string const& obj) -> bool {
return GMLIB_Scoreboard::getInstance()->getScore(obj, parseScriptUniqueID(uniqueId)).has_value();
}
);
RemoteCall::exportAs("GMLIB_API", "getEntityScore", [](std::string const& uniqueId, std::string const& obj) -> int {
return GMLIB_Scoreboard::getInstance()->getScore(obj, parseScriptUniqueID(uniqueId)).value_or(0);
});
RemoteCall::exportAs(
"GMLIB_API",
"addEntityScore",
[](std::string const& uniqueId, std::string const& obj, int value) -> bool {
return GMLIB_Scoreboard::getInstance()
->setScore(obj, parseScriptUniqueID(uniqueId), value, PlayerScoreSetFunction::Add)
.has_value();
}
);
RemoteCall::exportAs(
"GMLIB_API",
"reduceEntityScore",
[](std::string const& uniqueId, std::string const& obj, int value) -> bool {
return GMLIB_Scoreboard::getInstance()
->setScore(obj, parseScriptUniqueID(uniqueId), value, PlayerScoreSetFunction::Subtract)
.has_value();
}
);
RemoteCall::exportAs(
"GMLIB_API",
"setEntityScore",
[](std::string const& uniqueId, std::string const& obj, int value) -> bool {
return GMLIB_Scoreboard::getInstance()->setScore(obj, parseScriptUniqueID(uniqueId), value).has_value();
}
);
RemoteCall::exportAs(
"GMLIB_API",
"resetEntityScore",
[](std::string const& uniqueId, std::string const& obj) -> bool {
return GMLIB_Scoreboard::getInstance()->resetScore(obj, parseScriptUniqueID(uniqueId));
}
);
RemoteCall::exportAs("GMLIB_API", "resetEntityScores", [](std::string const& uniqueId) -> bool {
return GMLIB_Scoreboard::getInstance()->resetScore(parseScriptUniqueID(uniqueId));
});
RemoteCall::exportAs(
"GMLIB_API",
"fakePlayerHasScore",
[](std::string const& name, std::string const& obj) -> bool {
return GMLIB_Scoreboard::getInstance()->getScore(obj, name).has_value();
}
);
RemoteCall::exportAs("GMLIB_API", "getFakePlayerScore", [](std::string const& name, std::string const& obj) -> int {
return GMLIB_Scoreboard::getInstance()->getScore(obj, name).value_or(0);
});
RemoteCall::exportAs(
"GMLIB_API",
"addFakePlayerScore",
[](std::string const& name, std::string const& obj, int value) -> bool {
return GMLIB_Scoreboard::getInstance()->setScore(obj, name, value, PlayerScoreSetFunction::Add).has_value();
}
);
RemoteCall::exportAs(
"GMLIB_API",
"reduceFakePlayerScore",
[](std::string const& name, std::string const& obj, int value) -> bool {
return GMLIB_Scoreboard::getInstance()
->setScore(obj, name, value, PlayerScoreSetFunction::Subtract)
.has_value();
}
);
RemoteCall::exportAs(
"GMLIB_API",
"setFakePlayerScore",
[](std::string const& name, std::string const& obj, int value) -> bool {
return GMLIB_Scoreboard::getInstance()->setScore(obj, name, value).has_value();
}
);
RemoteCall::exportAs(
"GMLIB_API",
"resetFakePlayerScore",
[](std::string const& name, std::string const& obj) -> bool {
return GMLIB_Scoreboard::getInstance()->resetScore(obj, name);
}
);
RemoteCall::exportAs("GMLIB_API", "resetFakePlayerScores", [](std::string const& name) -> bool {
return GMLIB_Scoreboard::getInstance()->resetScore(name);
});
RemoteCall::exportAs("GMLIB_API", "addObjective", [](std::string const& obj) -> bool {
return GMLIB_Scoreboard::getInstance()->addObjective(obj).has_value();
});
RemoteCall::exportAs(
"GMLIB_API",
"addObjectiveWithDisplayName",
[](std::string const& obj, std::string const& displayName) -> bool {
return GMLIB_Scoreboard::getInstance()->addObjective(obj, displayName).has_value();
}
);
RemoteCall::exportAs("GMLIB_API", "getDisplayName", [](std::string const& obj) -> std::string {
return GMLIB_Scoreboard::getInstance()->getObjectiveDisplayName(obj).value_or("");
});
RemoteCall::exportAs(
"GMLIB_API",
"setDisplayName",
[](std::string const& obj, std::string const& displayName) -> bool {
return GMLIB_Scoreboard::getInstance()->setObjectiveDisplayName(obj, displayName);
}
);
RemoteCall::exportAs("GMLIB_API", "removeObjective", [](std::string const& obj) -> bool {
return GMLIB_Scoreboard::getInstance()->removeObjective(obj);
});
RemoteCall::exportAs(
"GMLIB_API",
"setDisplayObjective",
[](std::string const& obj, std::string const& slot, int order) -> void {
return GMLIB_Scoreboard::getInstance()->setObjectiveDisplay(obj, slot, (ObjectiveSortOrder)order);
}
);
RemoteCall::exportAs("GMLIB_API", "clearDisplayObjective", [](std::string const& slot) -> void {
return GMLIB_Scoreboard::getInstance()->clearObjectiveDisplay(slot);
});
RemoteCall::exportAs("GMLIB_API", "getAllObjectives", []() -> std::vector<std::string> {
std::vector<std::string> result;
for (auto& obj : GMLIB_Scoreboard::getInstance()->getObjectives()) {
result.push_back(obj->getName());
}
return result;
});
RemoteCall::exportAs("GMLIB_API", "getAllScoreboardPlayers", []() -> std::vector<std::string> {
std::vector<std::string> result;
for (auto& uuid : GMLIB_Scoreboard::getInstance()->getAllPlayerUuids()) {
result.push_back(uuid.asString());
}
return result;
});
RemoteCall::exportAs("GMLIB_API", "getAllScoreboardFakePlayers", []() -> std::vector<std::string> {
std::vector<std::string> result;
for (auto& name : GMLIB_Scoreboard::getInstance()->getAllFakePlayers()) {
result.push_back(name);
}
return result;
});
RemoteCall::exportAs("GMLIB_API", "getAllScoreboardEntities", []() -> std::vector<std::string> {
std::vector<std::string> result;
for (auto& uniqueId : GMLIB_Scoreboard::getInstance()->getAllEntities()) {
result.push_back(std::to_string(uniqueId.rawID));
}
return result;
});
RemoteCall::exportAs(
"GMLIB_API",
"getAllTrackedTargets",
[]() -> std::vector<std::unordered_map<std::string, std::string>> {
std::vector<std::unordered_map<std::string, std::string>> result;
for (auto& uuid : GMLIB_Scoreboard::getInstance()->getAllPlayerUuids()) {
result.push_back({
{"Type", "Player" },
{"Uuid", uuid.asString()}
});
}
for (auto& name : GMLIB_Scoreboard::getInstance()->getAllFakePlayers()) {
result.push_back({
{"Type", "FakePlayer"},
{"Name", name }
});
}
for (auto& uniqueId : GMLIB_Scoreboard::getInstance()->getAllEntities()) {
result.push_back({
{"Type", "Entity" },
{"UniqueId", std::to_string(uniqueId.rawID)}
});
}
return result;
}
);
RemoteCall::exportAs("GMLIB_API", "getPlayerFromUuid", [](std::string const& uuid) -> Player* {
return ll::service::getLevel()->getPlayer(mce::UUID::fromString(uuid));
});
RemoteCall::exportAs("GMLIB_API", "getPlayerFromUniqueId", [](std::string const& uniqueId) -> Actor* {
return ll::service::getLevel()->getPlayer(parseScriptUniqueID(uniqueId));
});
RemoteCall::exportAs("GMLIB_API", "getEntityFromUniqueId", [](std::string const& uniqueId) -> Actor* {
return ll::service::getLevel()->fetchEntity(parseScriptUniqueID(uniqueId), false);
});
RemoteCall::exportAs("GMLIB_API", "getWorldSpawn", []() -> std::pair<BlockPos, int> {
return {GMLIB_Level::getInstance()->getWorldSpawn(), 0};
});
RemoteCall::exportAs("GMLIB_API", "setWorldSpawn", [](std::pair<BlockPos, int> pos) -> bool {
if (pos.second != 0) return false;
GMLIB_Level::getInstance()->setWorldSpawn(pos.first);
return true;
});
RemoteCall::exportAs("GMLIB_API", "getPlayerSpawnPoint", [](Player* pl) -> std::pair<BlockPos, int> {
auto res = ((GMLIB_Player*)pl)->getSpawnPoint();
return {res.first, res.second};
});
RemoteCall::exportAs("GMLIB_API", "setPlayerSpawnPoint", [](Player* pl, std::pair<BlockPos, int> pos) -> void {
((GMLIB_Player*)pl)->setSpawnPoint(pos.first, pos.second);
});
RemoteCall::exportAs("GMLIB_API", "clearPlayerSpawnPoint", [](Player* pl) -> void {
((GMLIB_Player*)pl)->clearSpawnPoint();
});
RemoteCall::exportAs(
"GMLIB_API",
"mergePatchJson",
[](std::string const& oldJson, std::string const& patchJson) -> std::string {
auto oldData = nlohmann::ordered_json::parse(oldJson);
auto newData = nlohmann::ordered_json::parse(patchJson);
oldData.merge_patch(newData);
return oldData.dump();
}
);
RemoteCall::exportAs("GMLIB_API", "getXuidByUuid", [](std::string const& uuid) -> std::string {
return GMLIB::UserCache::getXuidByUuid(mce::UUID::fromString(uuid)).value_or("");
});
RemoteCall::exportAs("GMLIB_API", "getXuidByName", [](std::string const& name) -> std::string {
return GMLIB::UserCache::getXuidByName(name).value_or("");
});
RemoteCall::exportAs("GMLIB_API", "getNameByUuid", [](std::string const& uuid) -> std::string {
return GMLIB::UserCache::getNameByUuid(mce::UUID::fromString(uuid)).value_or("");
});
RemoteCall::exportAs("GMLIB_API", "getNameByXuid", [](std::string const& xuid) -> std::string {
return GMLIB::UserCache::getNameByXuid(xuid).value_or("");
});
RemoteCall::exportAs("GMLIB_API", "getUuidByXuid", [](std::string const& xuid) -> std::string {
return GMLIB::UserCache::getUuidByXuid(xuid)
.transform([](mce::UUID&& uuid) -> std::string { return uuid.asString(); })
.value_or("");
});
RemoteCall::exportAs("GMLIB_API", "getUuidByName", [](std::string const& name) -> std::string {
return GMLIB::UserCache::getUuidByName(name)
.transform([](mce::UUID&& uuid) -> std::string { return uuid.asString(); })
.value_or("");
});
RemoteCall::exportAs(
"GMLIB_API",
"getAllPlayerInfo",
[]() -> std::vector<std::unordered_map<std::string, std::string>> {
std::vector<std::unordered_map<std::string, std::string>> result;
GMLIB::UserCache::forEach([&result](const GMLIB::UserCache::UserCacheEntry& entry) -> void {
result.push_back({
{"Name", entry.mName },
{"Xuid", entry.mXuid },
{"Uuid", entry.mUuid.asString()}
});
});
return result;
}
);
RemoteCall::exportAs("GMLIB_API", "getBlockRuntimeId", [](std::string const& blockName, short legacyData) -> uint {
return Block::tryGetFromRegistry(blockName, legacyData)
.transform([](const Block& block) -> uint { return block.getRuntimeId(); })
.value_or(0);
});
RemoteCall::exportAs("GMLIB_API", "getBlockTranslateKey", [](Block const* block) -> std::string {
return block->buildDescriptionId();
});
RemoteCall::exportAs("GMLIB_API", "getItemTranslateKey", [](ItemStack* item) -> std::string {
return item->getDescriptionId();
});
RemoteCall::exportAs("GMLIB_API", "getEntityTranslateKey", [](Actor* entity) -> std::string {
return entity->getEntityLocNameString();
});
RemoteCall::exportAs(
"GMLIB_API",
"readNbtFromFile",
[](std::string const& path, bool isBinary) -> std::unique_ptr<CompoundTag> {
if (auto nbt = GMLIB_CompoundTag::readFromFile(path, isBinary)) {
return std::make_unique<CompoundTag>(nbt.value());
}
return nullptr;
}
);
RemoteCall::exportAs(
"GMLIB_API",
"saveNbtToFile",
[](std::string const& path, CompoundTag* nbt, bool isBinary) -> bool {
return GMLIB_CompoundTag::saveToFile(path, *nbt, isBinary);
}
);
RemoteCall::exportAs("GMLIB_API", "getBlockDestroySpeed", [](Block const* block) -> float {
return block->getDestroySpeed();
});
RemoteCall::exportAs("GMLIB_API", "getDestroyBlockSpeed", [](ItemStack const* item, Block const* block) -> float {
return item->getDestroySpeed(*block);
});
RemoteCall::exportAs(
"GMLIB_API",
"playerDestroyBlock",
[](Block const* block, std::pair<BlockPos, int> pos, Player* player) -> void {
return block->playerDestroy(*player, pos.first);
}
);
RemoteCall::exportAs("GMLIB_API", "itemCanDestroyBlock", [](ItemStack const* item, Block const* block) -> bool {
return item->canDestroy(block);
});
RemoteCall::exportAs("GMLIB_API", "itemCanDestroyInCreative", [](ItemStack const* item) -> bool {
if (auto itemDef = item->getItem()) {
return itemDef->canDestroyInCreative();
}
return false;
});
RemoteCall::exportAs("GMLIB_API", "itemCanDestroySpecial", [](ItemStack const* item, Block const* block) -> bool {
return item->canDestroySpecial(*block);
});
RemoteCall::exportAs("GMLIB_API", "blockCanDropWithAnyTool", [](Block const* block) -> bool {
return !block->requiresCorrectToolForDrops();
});
RemoteCall::exportAs(
"GMLIB_API",
"blockPlayerWillDestroy",
[](Block const* block, Player* player, std::pair<BlockPos, int> pos) -> bool {
return block->playerWillDestroy(*player, pos.first);
}
);
RemoteCall::exportAs("GMLIB_API", "playerAttack", [](Player* player, Actor* entity) -> bool {
return player->attack(*entity, ActorDamageCause::EntityAttack);
});
RemoteCall::exportAs("GMLIB_API", "playerPullInEntity", [](Player* player, Actor* entity) -> bool {
return player->pullInEntity(*entity);
});
RemoteCall::exportAs("GMLIB_API", "getBlockTranslateKeyFromName", [](std::string const& blockName) -> std::string {
return Block::tryGetFromRegistry(blockName)
.transform([](const Block& block) -> std::string { return block.buildDescriptionId(); })
.value_or("tile.unknown.name");
});
RemoteCall::exportAs(
"GMLIB_API",
"getBlockLightEmission",
[](std::string const& blockName, short legacyData) -> char {
return Block::tryGetFromRegistry(blockName)
.transform([](const Block& block) -> char { return (char)block.getLightEmission().mValue; })
.value_or(-1);
}
);
RemoteCall::exportAs(
"GMLIB_API",
"getGameRules",
[]() -> std::vector<std::unordered_map<std::string, std::string>> {
std::vector<std::unordered_map<std::string, std::string>> result;
for (auto& gameRule : ll::service::getLevel()->getGameRules().getRules()) {
switch (gameRule.getType()) {
case GameRule::Type::Bool:
result.push_back({
{"Name", gameRule.getName() },
{"Type", "Bool" },
{"Value", std::to_string(gameRule.getBool())}
});
break;
case GameRule::Type::Float:
result.push_back({
{"Name", gameRule.getName() },
{"Type", "Float" },
{"Value", std::to_string(gameRule.getFloat())}
});
break;
case GameRule::Type::Int:
result.push_back({
{"Name", gameRule.getName() },
{"Type", "Int" },
{"Value", std::to_string(gameRule.getInt())}
});
break;
case GameRule::Type::Invalid:
break;
}
}
return result;
}
);
RemoteCall::exportAs("GMLIB_API", "getEnchantTypeNameFromId", [](int id) -> std::string {
if (auto enchant = Enchant::getEnchant((Enchant::Type)id)) {
return std::string(enchant->getStringId());
}
return "";
});
RemoteCall::exportAs(
"GMLIB_API",
"applyEnchant",
[](ItemStack* item, std::string const& typeName, int level, bool allowNonVanilla) -> bool {
return EnchantUtils::applyEnchant(
*item,
Enchant::getEnchantTypeFromName(HashedString(typeName)),
level,
allowNonVanilla
);
}
);
RemoteCall::exportAs("GMLIB_API", "removeEnchants", [](ItemStack* item) -> void {
EnchantUtils::removeEnchants(*item);
});
RemoteCall::exportAs("GMLIB_API", "hasEnchant", [](ItemStack* item, std::string const& typeName) -> bool {
return EnchantUtils::hasEnchant(Enchant::getEnchantTypeFromName(HashedString(typeName)), *item);
});
RemoteCall::exportAs("GMLIB_API", "getEnchantLevel", [](ItemStack* item, std::string const& typeName) -> int {
return EnchantUtils::getEnchantLevel(Enchant::getEnchantTypeFromName(HashedString(typeName)), *item);
});
RemoteCall::exportAs(
"GMLIB_API",
"getEnchantNameAndLevel",
[](std::string const& typeName, int level) -> std::string {
return EnchantUtils::getEnchantNameAndLevel(Enchant::getEnchantTypeFromName(HashedString(typeName)), level);
}
);
RemoteCall::exportAs(
"GMLIB_API",
"dropPlayerItem",
[](Player* player, ItemStack const* item, bool randomly) -> bool { return player->drop(*item, randomly); }
);
RemoteCall::exportAs("GMLIB_API", "getPlayerRuntimeId", [](Player* player) -> uint64 {
return player->getRuntimeID().rawID;
});
RemoteCall::exportAs("GMLIB_API", "getEntityRuntimeId", [](Actor* entity) -> uint64 {
return entity->getRuntimeID().rawID;
});
RemoteCall::exportAs("GMLIB_API", "getEntityNameTag", [](Actor* entity) -> std::string {
return entity->getNameTag();
});
RemoteCall::exportAs("GMLIB_API", "ItemisUnbreakable", [](ItemStack const* item) -> bool {
return ((GMLIB_ItemStack*)item)->isUnbreakable();
});
RemoteCall::exportAs("GMLIB_API", "setItemUnbreakable", [](ItemStack const* item, bool value) -> void {
((GMLIB_ItemStack*)item)->setUnbreakable(value);
});
RemoteCall::exportAs("GMLIB_API", "getItemShouldKeepOnDeath", [](ItemStack const* item) -> bool {
return ((GMLIB_ItemStack*)item)->getShouldKeepOnDeath();
});
RemoteCall::exportAs("GMLIB_API", "setItemShouldKeepOnDeath", [](ItemStack const* item, bool value) -> void {
((GMLIB_ItemStack*)item)->setShouldKeepOnDeath(value);
});
RemoteCall::exportAs("GMLIB_API", "getItemLockMode", [](ItemStack const* item) -> int {
return (int)((GMLIB_ItemStack*)item)->getItemLockMode();
});
RemoteCall::exportAs("GMLIB_API", "setItemLockMode", [](ItemStack const* item, int value) -> void {
((GMLIB_ItemStack*)item)->setItemLockMode((ItemLockMode)value);
});
RemoteCall::exportAs("GMLIB_API", "getItemRepairCost", [](ItemStack const* item) -> int {
return item->getBaseRepairCost();
});
RemoteCall::exportAs("GMLIB_API", "setItemRepairCost", [](ItemStack* item, int cost) -> void {
(*item).setRepairCost(cost);
});
RemoteCall::exportAs("GMLIB_API", "getItemCanDestroy", [](ItemStack const* item) -> std::vector<std::string> {
std::vector<std::string> result = {};
for (auto& block : ((GMLIB_ItemStack*)item)->getCanDestroy()) {
result.push_back(block->getTypeName());
}
return result;
});
RemoteCall::exportAs(
"GMLIB_API",
"setItemCanDestroy",
[](ItemStack const* item, std::vector<std::string> blocks) -> void {
((GMLIB_ItemStack*)item)->setCanDestroy(blocks);
}
);
RemoteCall::exportAs("GMLIB_API", "getItemCanPlaceOn", [](ItemStack const* item) -> std::vector<std::string> {
std::vector<std::string> result = {};
for (auto& block : ((GMLIB_ItemStack*)item)->getCanPlaceOn()) {
result.push_back(block->getTypeName());
}
return result;
});
RemoteCall::exportAs(
"GMLIB_API",
"setItemCanPlaceOn",
[](ItemStack const* item, std::vector<std::string> blocks) -> void {
((GMLIB_ItemStack*)item)->setCanPlaceOn(blocks);
}
);
RemoteCall::exportAs("GMLIB_API", "getPlayerHungry", [](Player* player) -> float {
return player->getMutableAttribute(Player::HUNGER())->getCurrentValue();
});
RemoteCall::exportAs("GMLIB_API", "getPlayerArmorCoverPercentage", [](Player* player) -> float {
return player->getArmorCoverPercentage();
});
RemoteCall::exportAs("GMLIB_API", "getPlayerArmorValue", [](Player* player) -> int {
return player->getArmorValue();
});
RemoteCall::exportAs("GMLIB_API", "getEntityOwnerUniqueId", [](Actor* entity) -> int64 {
return entity->getOwnerId().rawID;
});
RemoteCall::exportAs("GMLIB_API", "getItemCategoryName", [](ItemStack const* item) -> std::string {
return item->getCategoryName();
});
RemoteCall::exportAs("GMLIB_API", "getItemCustomName", [](ItemStack const* item) -> std::string {
return item->getCustomName();
});
RemoteCall::exportAs("GMLIB_API", "getItemEffecName", [](ItemStack const* item) -> std::string {
return item->getEffectName();
});
RemoteCall::exportAs("GMLIB_API", "itemIsFood", [](ItemStack const* item) -> bool {
if (auto itemDef = item->getItem()) {
return itemDef->isFood();
}
return false;
});
RemoteCall::exportAs("GMLIB_API", "setPlayerUIItem", [](Player* player, int slot, ItemStack const* item) -> void {
player->setPlayerUIItem((PlayerUISlot)slot, *item, false);
});
RemoteCall::exportAs("GMLIB_API", "getPlayerUIItem", [](Player* player, int slot) -> ItemStack* {
return const_cast<ItemStack*>(&player->getPlayerUIItem((PlayerUISlot)slot));
});
RemoteCall::exportAs(
"GMLIB_API",
"sendInventorySlotPacket",
[](Player* player, int containerId, int slot, ItemStack const* item) -> void {
InventorySlotPacket((ContainerID)containerId, slot, *item).sendTo(*player);
}
);
RemoteCall::exportAs("GMLIB_API", "getContainerType", [](Container* container) -> std::string {
return magic_enum::enum_name(container->getContainerType()).data();
});
RemoteCall::exportAs("GMLIB_API", "hasPlayerNbt", [](std::string const& uuid) -> bool {
return GMLIB_Player::getPlayerNbt(mce::UUID::fromString(uuid)) != nullptr;
});
RemoteCall::exportAs("GMLIB_API", "getItemMaxCount", [](ItemStack const* item) -> int {
return item->getMaxStackSize();
});
RemoteCall::exportAs("GMLIB_API", "entityHasFamily", [](Actor* entity, std::string const& family) -> bool {
return entity->hasFamily(HashedString(family));
});
RemoteCall::exportAs("GMLIB_API", "getPlayerDestroyBlockProgress", [](Player* player, Block const* block) -> float {
return player->getDestroyProgress(*block);
});
RemoteCall::exportAs("GMLIB_API", "getEntityEffectVisible", [](Actor* entity, int effectId) -> bool {
if (auto effect = entity->getEffect(effectId)) {
return effect->mEffectVisible;
}
return 0;
});
RemoteCall::exportAs("GMLIB_API", "getEntityEffectDuration", [](Actor* entity, int effectId) -> int {
if (auto effect = entity->getEffect(effectId)) {
return effect->mDuration->mValue;
}
return 0;
});
RemoteCall::exportAs("GMLIB_API", "getEntityEffectDurationEasy", [](Actor* entity, int effectId) -> int {
if (auto effect = entity->getEffect(effectId)) {
return effect->mDurationEasy->transform([](auto&& duration) -> int { return duration.mValue; }).value_or(0);
}
return 0;
});
RemoteCall::exportAs("GMLIB_API", "getEntityEffectDurationHard", [](Actor* entity, int effectId) -> int {
if (auto effect = entity->getEffect(effectId)) {
return effect->mDurationHard->transform([](auto&& duration) -> int { return duration.mValue; }).value_or(0);
}
return 0;
});
RemoteCall::exportAs("GMLIB_API", "getEntityEffectDurationNormal", [](Actor* entity, int effectId) -> int {
if (auto effect = entity->getEffect(effectId)) {
return effect->mDurationNormal->transform([](auto&& duration) -> int { return duration.mValue; }).value_or(0);
}
return 0;
});
RemoteCall::exportAs("GMLIB_API", "getEntityEffectAmplifier", [](Actor* entity, int effectId) -> int {
if (auto effect = entity->getEffect(effectId)) {
return effect->mAmplifier;
}
return 0;
});
RemoteCall::exportAs("GMLIB_API", "getEntityEffectAmbient", [](Actor* entity, int effectId) -> bool {
if (auto effect = entity->getEffect(effectId)) {
return effect->mAmbient;
}
return 0;
});
RemoteCall::exportAs("GMLIB_API", "entityHasEffect", [](Actor* entity, int effectId) -> int {
return entity->hasEffect(*MobEffect::getById(effectId));
});
RemoteCall::exportAs("GMLIB_API", "getGameDifficulty", []() -> int {
return ll::service::getLevel().transform(
[](Level& level) -> int { return (int)level.getDifficulty(); }
).value_or(-1);
});
RemoteCall::exportAs("GMLIB_API", "setGameDifficulty", [](int difficulty) -> void {
if (auto level = ll::service::getLevel()) {
level->setDifficulty((Difficulty)difficulty);
}
});
RemoteCall::exportAs("GMLIB_API", "getDefaultGameMode", []() -> int {
return ll::service::getLevel().transform(
[](Level& level) -> int { return (int)level.getDefaultGameType(); }
).value_or(-1);
});
RemoteCall::exportAs("GMLIB_API", "setDefaultGameMode", [](int gameMode) -> void {
if (auto level = ll::service::getLevel()) {
level->setDefaultGameType((GameType)gameMode);
}
});
RemoteCall::exportAs(
"GMLIB_API",
"registerCustomShapelessRecipe",
[](std::string const& recipe_id, std::vector<std::string> ingredients, ItemStack* result) -> void {
if (!GMLIB_Level::getInstance().has_value()) return;
std::vector<Recipes::Type> types;
char rt = 'A';
for (auto& ing : ingredients) {
auto ingredient = RecipeIngredient{ing, 0,1};
types.push_back(Recipes::Type{
(Item*)ingredient.getItem(),
ingredient.getBlock(),
ingredient,
rt++
});
}
GMLIB::Mod::CustomRecipe::registerShapelessCraftingTableRecipe(recipe_id, types, *result);
}
);
RemoteCall::exportAs(
"GMLIB_API",
"registerCustomShapedRecipe",
[](std::string const& recipe_id,
std::vector<std::string> shape,
std::vector<std::string> ingredients,
ItemStack* result) -> void {
if (!GMLIB_Level::getInstance().has_value()) return;
std::vector<Recipes::Type> types;
char rt = 'A';
for (auto& ing : ingredients) {
auto ingredient = RecipeIngredient{ing, 0, 1};
types.push_back(Recipes::Type{(Item*)ingredient.getItem(), ingredient.getBlock(), ingredient, rt++});
}
auto tmp = RecipeUnlockingRequirement();
tmp.mContext = RecipeUnlockingRequirement::UnlockingContext::AlwaysUnlocked;
ll::service::bedrock::getLevel()->getRecipes().addShapedRecipe(
recipe_id,
ItemInstance(*result),
shape,
types,
{"crafting_table"},
50,
nullptr,
tmp,
SemVersion(1, 20, 80, "", ""),
true
);
}
);
RemoteCall::exportAs("GMLIB_API", "entityIsType", [](Actor* entity, int type) -> bool {
return entity->isType((ActorType)type);
});
RemoteCall::exportAs("GMLIB_API", "entityHasType", [](Actor* entity, int type) -> bool {
return entity->hasType((ActorType)type);
});
RemoteCall::exportAs("GMLIB_API", "getEntityTypeId", [](Actor* entity) -> int {
return (int)entity->getEntityTypeId();
});
}
-32
View File
@@ -1,32 +0,0 @@
#include <memory>
#include <ll/api/plugin/NativePlugin.h>
#include "Plugin.h"
namespace plugin {
// The global plugin instance.
std::unique_ptr<Plugin> plugin = nullptr;
extern "C" {
_declspec(dllexport) bool ll_plugin_load(ll::plugin::NativePlugin& self) {
plugin = std::make_unique<plugin::Plugin>(self);
return true;
}
/// @warning Unloading the plugin may cause a crash if the plugin has not released all of its
/// resources. If you are unsure, keep this function commented out.
// _declspec(dllexport) bool ll_plugin_unload(ll::plugin::Plugin&) {
// plugin.reset();
//
// return true;
// }
_declspec(dllexport) bool ll_plugin_enable(ll::plugin::NativePlugin&) { return plugin->enable(); }
_declspec(dllexport) bool ll_plugin_disable(ll::plugin::NativePlugin&) { return plugin->disable(); }
}
} // namespace plugin
+37
View File
@@ -0,0 +1,37 @@
#include "Entry.h"
#include "Global.h"
namespace gmlib {
LegacyRemoteCallApi& LegacyRemoteCallApi::getInstance() {
static LegacyRemoteCallApi instance;
return instance;
}
bool LegacyRemoteCallApi::load() {
Export_Legacy_GMLib_ModAPI();
Export_Legacy_GMLib_ServerAPI();
Export_Compatibility_API();
ExportPAPI();
Export_Event_API();
Export_BinaryStream_API();
// Export_Form_API();
auto logger = ll::io::LoggerRegistry::getInstance().getOrCreate(PLUGIN_NAME);
logger->info("GMLIB-LegacyRemoteCallApi Loaded!");
logger->info(
"Loaded Version: {} with {}",
fmt::format(fg(fmt::color::pink), "GMLIB-" + GMLIB::Version::getLibVersionString()),
fmt::format(fg(fmt::color::light_green), "GMLIB-LegacyRemoteCallApi-" + LIB_VERSION.asString())
);
logger->info("Author: GroupMountain");
logger->info("Repository: https://github.com/GroupMountain/GMLIB-LegacyRemoteCallApi");
return true;
}
bool LegacyRemoteCallApi::enable() { return true; }
bool LegacyRemoteCallApi::disable() { return true; }
} // namespace gmlib
LL_REGISTER_MOD(gmlib::LegacyRemoteCallApi, gmlib::LegacyRemoteCallApi::getInstance());
+33
View File
@@ -0,0 +1,33 @@
#pragma once
#include <ll/api/mod/NativeMod.h>
#include <ll/api/mod/RegisterHelper.h>
namespace gmlib {
class LegacyRemoteCallApi {
public:
static LegacyRemoteCallApi& getInstance();
LegacyRemoteCallApi() : mSelf(*ll::mod::NativeMod::current()) {}
[[nodiscard]] ll::mod::NativeMod& getSelf() const { return mSelf; }
/// @return True if the plugin is loaded successfully.
bool load();
/// @return True if the plugin is enabled successfully.
bool enable();
/// @return True if the plugin is disabled successfully.
bool disable();
// TODO: Implement this method if you need to unload the plugin.
// /// @return True if the plugin is unloaded successfully.
// bool unload();
private:
ll::mod::NativeMod& mSelf;
};
} // namespace gmlib
+359
View File
@@ -0,0 +1,359 @@
#include "Global.h"
#include "ll/api/service/Bedrock.h"
#include "ll/api/utils/ErrorUtils.h"
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])) {
ll::mod::NativeMod::current()->getLogger().warn("Removed listener with id {}", 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() {
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(
"GMLIB_Event_API",
"emplaceListener",
[](std::string const& pluginName, std::string const& eventName, int priority) -> llong {
auto eventId = EventManager::getInstance().getNextId();
switch (doHash(eventName)) {
case doHash("ll::ServerStoppingEvent"): {
REGISTER_EVENT_LISTEN(ll::event::ServerStoppingEvent, (), (), , );
}
case doHash("gmlib::ClientLoginAfterEvent"): {
REGISTER_EVENT_LISTEN(
GMLIB::Event::PacketEvent::ClientLoginAfterEvent,
(std::string const& realName,
std::string const& uuid,
std::string const& serverXuid,
std::string const& clientXuid),
(event.getRealName(),
event.getUuid().asString(),
event.getServerAuthXuid(),
event.getClientAuthXuid()),
if (result) event.disConnectClient();
);
}
case doHash("gmlib::WeatherUpdateBeforeEvent"): {
REGISTER_EVENT_LISTEN(
GMLIB::Event::LevelEvent::WeatherUpdateBeforeEvent,
(float rainLevel, int rainTime, float lightningLevel, int lightningTime, bool isCancelled),
(event.getRainLevel(),
event.getRainingLastTick(),
event.getLightningLevel(),
event.getLightningLastTick(),
event.isCancelled()),
event.setCancelled(result);
);
}
case doHash("gmlib::WeatherUpdateAfterEvent"): {
REGISTER_EVENT_LISTEN(
GMLIB::Event::LevelEvent::WeatherUpdateAfterEvent,
(float rainLevel, int rainTime, float lightningLevel, int lightningTime),
(event.getRainLevel(),
event.getRainingLastTick(),
event.getLightningLevel(),
event.getLightningLastTick()),
,
);
}
case doHash("gmlib::MobPickupItemBeforeEvent"): {
REGISTER_EVENT_LISTEN(
GMLIB::Event::EntityEvent::MobPickupItemBeforeEvent,
(Actor * mob, Actor * item, bool isCancelled),
(&event.self(), (Actor*)&event.getItemActor(), event.isCancelled()),
event.setCancelled(result);
);
}
case doHash("gmlib::MobPickupItemAfterEvent"): {
REGISTER_EVENT_LISTEN(
GMLIB::Event::EntityEvent::MobPickupItemAfterEvent,
(Actor * mob, Actor * item),
(&event.self(), (Actor*)&event.getItemActor()),
,
);
}
case doHash("gmlib::ItemActorSpawnBeforeEvent"): {
REGISTER_EVENT_LISTEN(
GMLIB::Event::EntityEvent::ItemActorSpawnBeforeEvent,
(ItemStack * item, std::pair<Vec3, int> position, int64 spawnerUniqueId, bool isCancelled),
(&event.getItem(),
{event.getPosition(), event.getBlockSource().getDimensionId().id},
event.getSpawner().has_value() ? event.getSpawner()->getOrCreateUniqueID().rawID : -1,
event.isCancelled()),
event.setCancelled(result);
);
}
case doHash("gmlib::ItemActorSpawnAfterEvent"): {
REGISTER_EVENT_LISTEN(
GMLIB::Event::EntityEvent::ItemActorSpawnAfterEvent,
(Actor * item, std::pair<Vec3, int> position, int64 spawnerUniqueId),
(&event.self(),
{event.getPosition(), event.getBlockSource().getDimensionId().id},
event.getSpawner().has_value() ? event.getSpawner()->getOrCreateUniqueID().rawID : -1),
,
);
}
case doHash("gmlib::ActorChangeDimensionBeforeEvent"): {
REGISTER_EVENT_LISTEN(
GMLIB::Event::EntityEvent::ActorChangeDimensionBeforeEvent,
(Actor * entity, int toDimId, bool isCancelled),
(&event.self(), event.getToDimensionId(), event.isCancelled()),
event.setCancelled(result);
);
}
case doHash("gmlib::ActorChangeDimensionAfterEvent"): {
REGISTER_EVENT_LISTEN(
GMLIB::Event::EntityEvent::ActorChangeDimensionAfterEvent,
(Actor * entity, int fromDimId, int toDimId),
(&event.self(), event.getFromDimensionId(), event.getToDimensionId()),
,
);
}
case doHash("gmlib::PlayerStartSleepBeforeEvent"): {
REGISTER_EVENT_LISTEN(
GMLIB::Event::PlayerEvent::PlayerStartSleepBeforeEvent,
(Player * entity, BlockPos pos, bool isCancelled),
(&event.self(), event.getPosition(), event.isCancelled()),
event.setCancelled(result);
);
}
case doHash("gmlib::PlayerStartSleepAfterEvent"): {
REGISTER_EVENT_LISTEN(
GMLIB::Event::PlayerEvent::PlayerStartSleepAfterEvent,
(Player * entity, BlockPos pos, int result),
(&event.self(), event.getPosition(), (int)event.getResult()),
,
);
}
case doHash("gmlib::PlayerStopSleepBeforeEvent"): {
REGISTER_EVENT_LISTEN(
GMLIB::Event::PlayerEvent::PlayerStopSleepBeforeEvent,
(Player * entity, bool forcefulWakeUp, bool updateLevelList, bool isCancelled),
(&event.self(), event.isForcefulWakeUp(), event.isUpdateLevelList(), event.isCancelled()),
event.setCancelled(result);
);
}
case doHash("gmlib::PlayerStopSleepAfterEvent"): {
REGISTER_EVENT_LISTEN(
GMLIB::Event::PlayerEvent::PlayerStopSleepAfterEvent,
(Player * entity, bool forcefulWakeUp, bool updateLevelList, bool),
(&event.self(), event.isForcefulWakeUp(), event.isUpdateLevelList(), false),
,
);
}
case doHash("gmlib::DeathMessageAfterEvent"): {
REGISTER_EVENT_LISTEN(
GMLIB::Event::EntityEvent::DeathMessageAfterEvent,
(std::string const& message, std::vector<std::string>, Actor* dead),
(event.getDeathMessage().first, event.getDeathMessage().second, &event.self()),
,
);
}
case doHash("gmlib::MobHurtAfterEvent"): {
REGISTER_EVENT_LISTEN(
GMLIB::Event::EntityEvent::MobHurtAfterEvent,
(Actor * mob, Actor * source, float damage, int cause),
(&event.self(), source, -event.getDamage(), (int)damageSource.getCause()),
,
auto& damageSource = event.getSource();
Actor* source = nullptr;
if (damageSource.isEntitySource()) {
auto uniqueId = damageSource.getDamagingEntityUniqueID();
source = ll::service::getLevel()->fetchEntity(uniqueId, false);
if (source->getOwner()) source = source->getOwner();
}
);
}
case doHash("gmlib::EndermanTakeBlockBeforeEvent"): {
REGISTER_EVENT_LISTEN(
GMLIB::Event::EntityEvent::EndermanTakeBlockBeforeEvent,
(Actor * mob, bool isCancelled),
(&event.self(), event.isCancelled()),
event.setCancelled(result);
);
}
case doHash("gmlib::DragonRespawnBeforeEvent"): {
REGISTER_EVENT_LISTEN(
GMLIB::Event::EntityEvent::DragonRespawnBeforeEvent,
(bool isCancelled),
(event.isCancelled()),
event.setCancelled(result);
);
}
case doHash("gmlib::DragonRespawnAfterEvent"): {
REGISTER_EVENT_LISTEN(
GMLIB::Event::EntityEvent::DragonRespawnAfterEvent,
(Actor * mob),
(event.getEnderDragon()),
);
}
case doHash("gmlib::ProjectileCreateBeforeEvent"): {
REGISTER_EVENT_LISTEN(
GMLIB::Event::EntityEvent::ProjectileCreateBeforeEvent,
(Actor * mob, int64 uniqueId, bool isCancelled),
(&event.self(),
event.getShooter() ? event.getShooter()->getOrCreateUniqueID().rawID : -1,
event.isCancelled()),
event.setCancelled(result);
);
}
case doHash("gmlib::ProjectileCreateAfterEvent"): {
REGISTER_EVENT_LISTEN(
GMLIB::Event::EntityEvent::ProjectileCreateAfterEvent,
(Actor * mob, int64 uniqueId),
(&event.self(), event.getShooter() ? event.getShooter()->getOrCreateUniqueID().rawID : -1),
);
}
case doHash("gmlib::SpawnWanderingTraderBeforeEvent"): {
REGISTER_EVENT_LISTEN(
GMLIB::Event::EntityEvent::SpawnWanderingTraderBeforeEvent,
(std::pair<BlockPos, int> pos, bool isCancelled),
({event.getPos(), event.getRegion().getDimensionId()}, event.isCancelled()),
event.setCancelled(result);
);
}
case doHash("gmlib::SpawnWanderingTraderAfterEvent"): {
REGISTER_EVENT_LISTEN(
GMLIB::Event::EntityEvent::SpawnWanderingTraderAfterEvent,
(std::pair<BlockPos, int> pos),
({event.getPos(), event.getRegion().getDimensionId()}),
);
}
case doHash("gmlib::HandleRequestActionBeforeEvent"): {
// clang-format off
REGISTER_EVENT_LISTEN(
GMLIB::Event::PlayerEvent::HandleRequestActionBeforeEvent,
(
Player * player,
std::string const& actionType,
int count,
std::string const& sourceContainerNetId,
int sourceSlot,
std::string const& destinationContainerNetId,
int destinationSlot,
bool isCancelled
),
(
&event.self(),
magic_enum::enum_name(requestAction.mActionType).data(),
(int)requestAction.mAmount,
magic_enum::enum_name(requestAction.mSrc->mFullContainerName.mName).data(),
(int)requestAction.mSrc->mSlot,
magic_enum::enum_name(requestAction.mDst->mFullContainerName.mName).data(),
(int)requestAction.mDst->mSlot,
event.isCancelled()
),
event.setCancelled(result);,
auto& requestAction = (ItemStackRequestActionTransferBase&)event.getRequestAction();
);
// clang-format on
}
case doHash("gmlib::HandleRequestActionAfterEvent"): {
// clang-format off
REGISTER_EVENT_LISTEN(
GMLIB::Event::PlayerEvent::HandleRequestActionAfterEvent,
(
Player * player,
std::string const& actionType,
int count,
std::string const& sourceContainerNetId,
int sourceSlot,
std::string const& destinationContainerNetId,
int destinationSlot
),
(
&event.self(),
magic_enum::enum_name(requestAction.mActionType).data(),
(int)requestAction.mAmount,
magic_enum::enum_name(requestAction.mSrc->mFullContainerName.mName).data(),
(int)requestAction.mSrc->mSlot,
magic_enum::enum_name(requestAction.mDst->mFullContainerName.mName).data(),
(int)requestAction.mDst->mSlot
),
,
auto& requestAction = (ItemStackRequestActionTransferBase&)event.getRequestAction();
);
// clang-format on
}
case doHash("gmlib::ContainerClosePacketSendAfterEvent"): {
REGISTER_EVENT_LISTEN(
GMLIB::Event::PacketEvent::ContainerClosePacketSendAfterEvent,
(Player * player, int containerId, bool serverInitiatedClose, bool),
(ll::service::getServerNetworkHandler()
->_getServerPlayer(event.getNetworkIdentifier(), event.getPacket().mClientSubId),
(int)event.getPacket().mContainerId,
event.getPacket().mServerInitiatedClose,
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 //////////////////////////////
// }
+12 -5
View File
@@ -1,13 +1,20 @@
#pragma once
#include <GMLIB/include_lib.h>
#include <include_all.h>
#include <RemoteCallAPI.h>
#define PLUGIN_NAME "GMLIB-LRCA"
#define LIB_VERSION SemVersion(0, 8, 4, "", "")
#define PLUGIN_NAME fmt::format(fg(fmt::color::light_green), "GMLIB-LRCA")
extern ll::Logger logger;
#define LIB_VERSION_MAJOR 0
#define LIB_VERSION_MINOR 13
#define LIB_VERSION_PATCH 6
#define LIB_VERSION GMLIB::Version(LIB_VERSION_MAJOR, LIB_VERSION_MINOR, LIB_VERSION_PATCH)
extern void Export_Legacy_GMLib_ModAPI();
extern void Export_Legacy_GMLib_ServerAPI();
extern void Export_Compatibility_API();
extern void ExportPAPI();
extern void ExportPAPI();
extern void Export_Event_API();
extern void Export_BinaryStream_API();
// extern void Export_Form_API();
+96 -105
View File
@@ -2,14 +2,9 @@
std::unordered_set<std::string> HardCodedKeys = {"AlwaysUnlocked", "PlayerHasManyItems", "PlayerInWater", "None"};
std::variant<std::string, std::vector<RecipeIngredient>> makeRecipeUnlockingKey(std::string& key) {
if (HardCodedKeys.count(key)) {
return key;
}
std::vector<RecipeIngredient> result;
auto item = RecipeIngredient(key, 0, 1);
result.emplace_back(item);
return result;
std::variant<std::string, std::vector<RecipeIngredient>> makeRecipeUnlockingKey(std::string const& key) {
if (HardCodedKeys.count(key)) return key;
return std::vector<RecipeIngredient>({RecipeIngredient(key, 0, 1)});
}
void Export_Legacy_GMLib_ModAPI() {
@@ -17,100 +12,96 @@ void Export_Legacy_GMLib_ModAPI() {
RemoteCall::exportAs(
"GMLib_ModAPI",
"registerShapelessRecipe",
[](std::string recipe_id,
[](std::string const& recipe_id,
std::vector<std::string> ingredients,
std::string result,
std::string const& result,
int count,
std::string unlock) -> void {
auto level = GMLIB_Level::getLevel();
if (!level) {
return;
}
std::string const& unlock) -> void {
if (!GMLIB_Level::getInstance().has_value()) return;
std::vector<RecipeIngredient> types;
for (auto ing : ingredients) {
auto key = RecipeIngredient(ing, 0, 1);
types.push_back(key);
types.emplace_back(ing, 0, 1);
}
auto res = RecipeIngredient(result, 0, count);
auto unl = makeRecipeUnlockingKey(unlock);
GMLIB::Mod::CustomRecipe::registerShapelessCraftingTableRecipe(recipe_id, types, res, unl);
GMLIB::Mod::JsonRecipe::registerShapelessCraftingTableRecipe(
recipe_id,
types,
RecipeIngredient(result, 0, count),
makeRecipeUnlockingKey(unlock)
);
}
);
RemoteCall::exportAs(
"GMLib_ModAPI",
"registerShapedRecipe",
[](std::string recipe_id,
[](std::string const& recipe_id,
std::vector<std::string> shape,
std::vector<std::string> ingredients,
std::string result,
std::string const& result,
int count,
std::string unlock) -> void {
auto level = GMLIB_Level::getLevel();
if (!level) {
return;
}
std::string const& unlock) -> void {
if (!GMLIB_Level::getInstance().has_value()) return;
std::vector<RecipeIngredient> types;
for (auto ing : ingredients) {
auto key = RecipeIngredient(ing, 0, 1);
types.push_back(key);
types.push_back(RecipeIngredient(ing, 0, 1));
}
auto res = RecipeIngredient(result, 0, count);
auto unl = makeRecipeUnlockingKey(unlock);
GMLIB::Mod::CustomRecipe::registerShapedCraftingTableRecipe(recipe_id, shape, types, res, unl);
GMLIB::Mod::JsonRecipe::registerShapedCraftingTableRecipe(
recipe_id,
shape,
types,
RecipeIngredient(result, 0, count),
makeRecipeUnlockingKey(unlock)
);
}
);
RemoteCall::exportAs(
"GMLib_ModAPI",
"registerFurnaceRecipe",
[](std::string recipe_id, std::string input, std::string output, std::vector<std::string> tags) -> void {
auto level = GMLIB_Level::getLevel();
if (!level) {
return;
}
auto inp = RecipeIngredient(input, 0, 1);
auto outp = RecipeIngredient(output, 0, 1);
GMLIB::Mod::CustomRecipe::registerFurnaceRecipe(recipe_id, inp, outp, tags);
[](std::string const& recipe_id,
std::string const& input,
std::string const& output,
std::vector<std::string> tags) -> void {
if (!GMLIB_Level::getInstance().has_value()) return;
GMLIB::Mod::JsonRecipe::registerFurnaceRecipe(
recipe_id,
RecipeIngredient(input, 0, 1),
RecipeIngredient(output, 0, 1),
tags
);
}
);
RemoteCall::exportAs(
"GMLib_ModAPI",
"registerBrewingMixRecipe",
[](std::string recipe_id, std::string input, std::string output, std::string reagent) -> void {
auto level = GMLIB_Level::getLevel();
if (!level) {
return;
}
auto rea = RecipeIngredient(reagent, 0, 1);
GMLIB::Mod::CustomRecipe::registerBrewingMixRecipe(recipe_id, input, output, rea);
[](std::string const& recipe_id, std::string const& input, std::string const& output, std::string const& reagent
) -> void {
if (!GMLIB_Level::getInstance().has_value()) return;
GMLIB::Mod::JsonRecipe::registerBrewingMixRecipe(recipe_id, input, output, RecipeIngredient(reagent, 0, 1));
}
);
RemoteCall::exportAs(
"GMLib_ModAPI",
"registerBrewingContainerRecipe",
[](std::string recipe_id, std::string input, std::string output, std::string reagent) -> void {
auto level = GMLIB_Level::getLevel();
if (!level) {
return;
}
auto inp = RecipeIngredient(input, 0, 1);
auto outp = RecipeIngredient(output, 0, 1);
auto rea = RecipeIngredient(reagent, 0, 1);
GMLIB::Mod::CustomRecipe::registerBrewingContainerRecipe(recipe_id, inp, outp, rea);
[](std::string const& recipe_id, std::string const& input, std::string const& output, std::string const& reagent
) -> void {
if (!GMLIB_Level::getInstance().has_value()) return;
GMLIB::Mod::JsonRecipe::registerBrewingContainerRecipe(
recipe_id,
RecipeIngredient(input, 0, 1),
RecipeIngredient(output, 0, 1),
RecipeIngredient(reagent, 0, 1)
);
}
);
RemoteCall::exportAs(
"GMLib_ModAPI",
"registerSmithingTransformRecipe",
[](std::string recipe_id,
std::string smithing_template,
std::string base,
std::string addition,
std::string result) -> void {
auto level = GMLIB_Level::getLevel();
if (!level) {
return;
}
GMLIB::Mod::CustomRecipe::registerSmithingTransformRecipe(
[](std::string const& recipe_id,
std::string const& smithing_template,
std::string const& base,
std::string const& addition,
std::string const& result) -> void {
if (!GMLIB_Level::getInstance().has_value()) return;
GMLIB::Mod::JsonRecipe::registerSmithingTransformRecipe(
recipe_id,
smithing_template,
base,
@@ -122,30 +113,29 @@ void Export_Legacy_GMLib_ModAPI() {
RemoteCall::exportAs(
"GMLib_ModAPI",
"registerSmithingTrimRecipe",
[](std::string recipe_id, std::string smithing_template, std::string base, std::string addition) -> void {
auto level = GMLIB_Level::getLevel();
if (!level) {
return;
}
GMLIB::Mod::CustomRecipe::registerSmithingTrimRecipe(recipe_id, smithing_template, base, addition);
[](std::string const& recipe_id,
std::string const& smithing_template,
std::string const& base,
std::string const& addition) -> void {
if (!GMLIB_Level::getInstance().has_value()) return;
GMLIB::Mod::JsonRecipe::registerSmithingTrimRecipe(recipe_id, smithing_template, base, addition);
}
);
RemoteCall::exportAs(
"GMLib_ModAPI",
"registerStoneCutterRecipe",
[](std::string recipe_id,
std::string input,
int input_data,
std::string output,
int output_data,
int output_count) -> void {
auto level = GMLIB_Level::getLevel();
if (!level) {
return;
}
auto inp = RecipeIngredient(input, 0, 1);
auto outp = RecipeIngredient(output, 0, 1);
GMLIB::Mod::CustomRecipe::registerStoneCutterRecipe(recipe_id, inp, outp);
[](std::string const& recipe_id,
std::string const& input,
int input_data,
std::string const& output,
int output_data,
int output_count) -> void {
if (!GMLIB_Level::getInstance().has_value()) return;
GMLIB::Mod::JsonRecipe::registerStoneCutterRecipe(
recipe_id,
RecipeIngredient(input, 0, 1),
RecipeIngredient(output, 0, 1)
);
}
);
// 错误方块清理
@@ -154,34 +144,35 @@ void Export_Legacy_GMLib_ModAPI() {
});
// 实验性
RemoteCall::exportAs("GMLib_ModAPI", "registerExperimentsRequire", [](int experiment_id) -> void {
auto map = GMLIB_Level::getAllExperiments();
if (map.count(experiment_id)) {
auto list = GMLIB_Level::getAllExperiments();
std::unordered_set<AllExperiments> set(list.begin(), list.end());
if (set.contains((AllExperiments)experiment_id)) {
GMLIB_Level::addExperimentsRequire((AllExperiments)experiment_id);
} else {
ll::Logger("Server").error("Experiment ID '{}' does not exist!", experiment_id);
ll::io::LoggerRegistry::getInstance().getOrCreate("Server")->error("Experiment ID '{}' does not exist!", experiment_id);
}
});
RemoteCall::exportAs("GMLib_ModAPI", "setExperimentEnabled", [](int experiment_id, bool value) -> void {
auto level = GMLIB_Level::getLevel();
if (!level) {
return;
if (GMLIB_Level::getInstance()) {
auto list = GMLIB_Level::getAllExperiments();
std::unordered_set<AllExperiments> set(list.begin(), list.end());
if (set.contains((AllExperiments)experiment_id)) {
GMLIB_Level::getInstance()->setExperimentEnabled(((AllExperiments)experiment_id), value);
} else ll::io::LoggerRegistry::getInstance().getOrCreate("Server")->error("Experiment ID '{}' does not exist!", experiment_id);
}
auto map = GMLIB_Level::getAllExperiments();
if (map.count(experiment_id)) {
GMLIB_Level::getLevel()->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 {
auto level = GMLIB_Level::getLevel();
if (!level) {
return false;
}
auto map = GMLIB_Level::getAllExperiments();
if (map.count(experiment_id)) {
return GMLIB_Level::getLevel()->getExperimentEnabled(((AllExperiments)experiment_id));
} else {
ll::Logger("Server").error("Experiment ID '{}' does not exist!", experiment_id);
return false;
if (GMLIB_Level::getInstance()) {
auto list = GMLIB_Level::getAllExperiments();
std::unordered_set<AllExperiments> set(list.begin(), list.end());
if (set.contains((AllExperiments)experiment_id)) {
return GMLIB_Level::getInstance()->getExperimentEnabled(((AllExperiments)experiment_id));
}
ll::io::LoggerRegistry::getInstance().getOrCreate("Server")->error("Experiment ID '{}' does not exist!", experiment_id);
}
return false;
});
RemoteCall::exportAs("GMLib_ModAPI", "setFixI18nEnabled", []() -> void {
GMLIB::Mod::VanillaFix::setFixI18nEnabled();
});
}
+47 -22
View File
@@ -2,42 +2,49 @@
void Export_Legacy_GMLib_ServerAPI() {
RemoteCall::exportAs("GMLib_ServerAPI", "setEducationFeatureEnabled", []() -> void {
GMLIB_Level::addEducationEditionRequired();
GMLIB_Level::tryEnableEducationEdition();
});
RemoteCall::exportAs("GMLib_ServerAPI", "registerAbilityCommand", []() -> void {
GMLIB_Level::forceEnableAbilityCommand();
GMLIB_Level::tryRegisterAbilityCommand();
});
RemoteCall::exportAs("GMLib_ServerAPI", "setEnableAchievement", []() -> void {
GMLIB_Level::setForceAchievementsEnabled();
});
RemoteCall::exportAs("GMLib_ServerAPI", "setForceTrustSkins", []() -> void { GMLIB_Level::setForceTrustSkin(); });
RemoteCall::exportAs("GMLib_ServerAPI", "enableCoResourcePack", []() -> void { GMLIB_Level::setCoResourcePack(); });
RemoteCall::exportAs("GMLib_ServerAPI", "getLevelName", []() -> std::string {
auto level = GMLIB_Level::getLevel();
if (!level) {
return "";
}
return level->getLevelName();
RemoteCall::exportAs("GMLib_ServerAPI", "setForceTrustSkins", []() -> void { GMLIB_Level::trustAllSkins(); });
RemoteCall::exportAs("GMLib_ServerAPI", "enableCoResourcePack", []() -> void {
GMLIB_Level::requireServerResourcePackAndAllowClientResourcePack();
});
RemoteCall::exportAs("GMLib_ServerAPI", "setLevelName", [](std::string name) -> void {
auto level = GMLIB_Level::getLevel();
if (!level) {
return;
RemoteCall::exportAs("GMLib_ServerAPI", "getLevelName", []() -> std::string {
return GMLIB_Level::getInstance()
.transform([](GMLIB_Level& level) -> std::string { return level.getLevelName(); })
.value_or("");
});
RemoteCall::exportAs("GMLib_ServerAPI", "setLevelName", [](std::string const& name) -> void {
if (auto level = GMLIB_Level::getInstance()) {
level->setLevelName(name);
}
return level->setLevelName(name);
});
RemoteCall::exportAs("GMLib_ServerAPI", "getLevelSeed", []() -> std::string {
return GMLIB_Level::getInstance()
.transform([](GMLIB_Level& level) -> std::string { return std::to_string(level.getSeed()); })
.value_or("");
});
RemoteCall::exportAs("GMLib_ServerAPI", "setFakeSeed", [](int64_t seed) -> void {
return GMLIB_Level::setFakeSeed(seed);
});
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 GMLIB_Spawner::spawnEntity(pos.first, pos.second, name).as_ptr();
}
);
RemoteCall::exportAs(
"GMLib_ServerAPI",
"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;
return ac->shootProjectile(name, speed, offset);
return ac->shootProjectile(name, speed, offset).as_ptr();
}
);
RemoteCall::exportAs(
@@ -45,8 +52,26 @@ void Export_Legacy_GMLib_ServerAPI() {
"throwEntity",
[](Actor* owner, Actor* actor, float speed, float offset) -> bool {
auto ac = (GMLIB_Actor*)owner;
return ac->throwEntity(actor, speed, offset);
return ac->throwEntity(*actor, speed, offset);
}
);
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 {
return GMLIB::Server::FakeList::addFakeList(name, xuid, ActorUniqueID(-1));
}
);
RemoteCall::exportAs("GMLib_ServerAPI", "removeFakeList", [](const std::string& nameOrXuid) -> bool {
return GMLIB::Server::FakeList::removeFakeList(nameOrXuid);
});
RemoteCall::exportAs("GMLib_ServerAPI", "removeAllFakeList", []() -> void {
return GMLIB::Server::FakeList::removeAllFakeLists();
});
RemoteCall::exportAs("GMLib_ServerAPI", "getMaxPlayers", []() -> int {
return GMLIB_Level::getInstance().transform(
[](GMLIB_Level& level) -> int { return level.getMaxPlayerCount(); }
).value_or(0);
});
}
-7
View File
@@ -1,7 +0,0 @@
// This file will make your plugin use LeviLamina's memory operators by default.
// This improves the memory management of your plugin and is recommended to use.
// You should not modify anything in this file.
#define LL_MEMORY_OPERATORS
#include <ll/api/memory/MemoryOperators.h>
+1 -1
View File
@@ -4,4 +4,4 @@
#define LL_MEMORY_OPERATORS
#include <ll/api/memory/MemoryOperators.h>
#include <ll/api/memory/MemoryOperators.h>
+37 -38
View File
@@ -8,51 +8,54 @@ std::string removeBrackets(std::string a1) {
return a1;
}
bool isParameters(std::string str) {
bool isParameters(std::string const& str) {
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));
std::string GetValueWithPlayer(std::string const& key, Player* player) {
return GMLIB::Server::PlaceholderAPI::getValue(key, player);
}
std::string
registerPlayerPlaceholder(std::string const& PluginName, std::string const& FuncName, std::string const& PAPIName) {
bool registerPlayerPlaceholder(
std::string const& PluginName,
std::string const& FuncName,
std::string const& PAPIName
) {
if (RemoteCall::hasFunc(PluginName, FuncName)) {
GMLIB::Server::PlaceholderAPI::unregisterPlaceholder(PAPIName);
if (isParameters(PAPIName)) {
auto Call =
RemoteCall::importAs<std::string(std::string const& arg, std::unordered_map<std::string, std::string>)>(
PluginName,
FuncName
);
auto Call = RemoteCall::importAs<std::string(Player * pl, std::unordered_map<std::string, std::string>)>(
PluginName,
FuncName
);
GMLIB::Server::PlaceholderAPI::registerPlayerPlaceholder(
PAPIName,
[Call](Player* sp, std::unordered_map<std::string, std::string> map) {
return Call(sp->getXuid(), map);
},
[Call](Player* sp, std::unordered_map<std::string, std::string> map) { return Call(sp, map); },
PluginName
);
} else {
auto Call = RemoteCall::importAs<std::string(std::string const& arg)>(PluginName, FuncName);
auto Call = RemoteCall::importAs<std::string(Player * pl)>(PluginName, FuncName);
GMLIB::Server::PlaceholderAPI::registerPlayerPlaceholder(
PAPIName,
[Call](Player* sp) { return Call(sp->getXuid()); },
[Call](Player* sp) { return Call(sp); },
PluginName
);
}
} else {
// logger.error("Function no find({}:{})", PluginName, FuncName);
return "Function no find";
return true;
}
return "Register Success";
return false;
}
std::string
registerServerPlaceholder(std::string const& PluginName, std::string const& FuncName, std::string const& PAPIName) {
bool registerServerPlaceholder(
std::string const& PluginName,
std::string const& FuncName,
std::string const& PAPIName
) {
if (RemoteCall::hasFunc(PluginName, FuncName)) {
GMLIB::Server::PlaceholderAPI::unregisterPlaceholder(PAPIName);
if (isParameters(PAPIName)) {
auto Call =
RemoteCall::importAs<std::string(std::unordered_map<std::string, std::string>)>(PluginName, FuncName);
@@ -63,26 +66,21 @@ registerServerPlaceholder(std::string const& PluginName, std::string const& Func
);
} else {
auto Call = RemoteCall::importAs<std::string()>(PluginName, FuncName);
GMLIB::Server::PlaceholderAPI::registerServerPlaceholder(
PAPIName,
[Call]() { return Call(); },
PluginName
);
GMLIB::Server::PlaceholderAPI::registerServerPlaceholder(PAPIName, [Call]() { return Call(); }, PluginName);
}
} else {
// logger.error("Function no find({}:{})", PluginName, FuncName);
return "Function no find";
return true;
}
return "Register Success";
return false;
}
std::string registerStaticPlaceholder(
bool registerStaticPlaceholder(
std::string const& PluginName,
std::string const& FuncName,
std::string const& PAPIName,
int num
) {
if (RemoteCall::hasFunc(PluginName, FuncName)) {
GMLIB::Server::PlaceholderAPI::unregisterPlaceholder(PAPIName);
if (isParameters(PAPIName)) {
auto Call = RemoteCall::importAs<std::string()>(PluginName, FuncName);
if (num == -1) {
@@ -100,18 +98,18 @@ std::string registerStaticPlaceholder(
);
}
}
} else {
// logger.error("Function no find({}:{})", PluginName, FuncName);
return "Function no find";
return true;
}
return "Register Success";
return false;
}
std::string translateString(std::string const& str, std::string const& xuid) {
return GMLIB::Server::PlaceholderAPI::translate(str, ll::service::bedrock::getLevel()->getPlayerByXuid(xuid));
std::string translateStringWithPlayer(std::string const& str, Player* pl) {
return GMLIB::Server::PlaceholderAPI::translateString(str, pl);
}
bool unRegisterPlaceholder(std::string const& str) { return GMLIB::Server::PlaceholderAPI::unRegisterPlaceholder(str); }
std::string translateString(std::string const& str) { return GMLIB::Server::PlaceholderAPI::translateString(str); }
bool unRegisterPlaceholder(std::string const& str) { return GMLIB::Server::PlaceholderAPI::unregisterPlaceholder(str); }
std::vector<std::string> getAllPAPI() { return GMLIB::Server::PlaceholderAPI::getAllPAPI(); }
@@ -127,6 +125,7 @@ void ExportPAPI() {
EXPORTAPI(PAPIRemoteCall::GetValue);
EXPORTAPI(PAPIRemoteCall::GetValueWithPlayer);
EXPORTAPI(PAPIRemoteCall::translateString);
EXPORTAPI(PAPIRemoteCall::translateStringWithPlayer);
EXPORTAPI(PAPIRemoteCall::unRegisterPlaceholder);
EXPORTAPI(PAPIRemoteCall::getAllPAPI);
}
-30
View File
@@ -1,30 +0,0 @@
#include "Plugin.h"
#include "Global.h"
ll::Logger logger(PLUGIN_NAME);
namespace plugin {
Plugin::Plugin(ll::plugin::NativePlugin& self) : mSelf(self) {
// Code for loading the plugin goes here.
Export_Legacy_GMLib_ModAPI();
Export_Legacy_GMLib_ServerAPI();
Export_Compatibility_API();
ExportPAPI();
logger.info("GMLIB-LegacyRemoteCallApi Loaded!");
logger.info("Version: {}", LIB_VERSION.asString());
logger.info("Author: GroupMountain");
logger.info("Repository: https://github.com/GroupMountain/GMLIB-LegacyRemoteCallApi");
}
bool Plugin::enable() {
// Code for enabling the plugin goes here.
return true;
}
bool Plugin::disable() {
// Code for disabling the plugin goes here.
return true;
}
} // namespace plugin
-27
View File
@@ -1,27 +0,0 @@
#pragma once
#include <ll/api/plugin/NativePlugin.h>
namespace plugin {
class Plugin {
public:
explicit Plugin(ll::plugin::NativePlugin& self);
Plugin(Plugin&&) = delete;
Plugin(const Plugin&) = delete;
Plugin& operator=(Plugin&&) = delete;
Plugin& operator=(const Plugin&) = delete;
~Plugin() = default;
/// @return True if the plugin is enabled successfully.
bool enable();
/// @return True if the plugin is disabled successfully.
bool disable();
private:
ll::plugin::NativePlugin& mSelf;
};
} // namespace plugin
+3 -3
View File
@@ -1,7 +1,7 @@
{
"format_version": 2,
"tooth": "github.com/GroupMountain/GMLIB-LegacyRemoteCallApi",
"version": "0.8.4",
"version": "0.13.6",
"info": {
"name": "GMLIB-LegacyRemoteCallApi",
"description": "Legacy RemoteCall API for GMLIB",
@@ -14,9 +14,9 @@
"library"
]
},
"asset_url": "https://github.com/GroupMountain/GMLIB-LegacyRemoteCallApi/releases/download/v0.8.4/GMLIB-LegacyRemoteCallApi-windows-x64.zip",
"asset_url": "https://github.com/GroupMountain/GMLIB-LegacyRemoteCallApi/releases/download/v0.13.6/GMLIB-LegacyRemoteCallApi-windows-x64.zip",
"dependencies": {
"github.com/GroupMountain/GMLIB": ">=0.8.5"
"github.com/GroupMountain/GMLIB": ">=0.13.9"
},
"files": {
"place": [
+18 -47
View File
@@ -1,74 +1,45 @@
add_rules("mode.debug", "mode.release", "mode.releasedbg")
add_rules("mode.debug", "mode.release")
add_repositories("liteldev-repo https://github.com/LiteLDev/xmake-repo.git")
add_repositories("groupmountain-repo https://github.com/GroupMountain/xmake-repo.git")
if not has_config("vs_runtime") then
set_runtimes("MD")
end
-- Option 1: Use the latest version of LeviLamina released on GitHub.
add_requires("levilamina")
add_requires("legacyremotecall")
add_requires("levilamina 1.0.0-rc.3", {configs = {target_type = "server"}})
add_requires("legacyremotecall 0.9.0-rc.1")
add_requires("gmlib 0.13.10")
add_requires("levibuildscript 0.3.0")
-- Option 2: Use a specific version of LeviLamina released on GitHub.
-- 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.
target("GMLIB-LegacyRemoteCallApi")
add_cxflags(
"/EHa",
"/utf-8"
)
add_defines(
"_HAS_CXX23=1" -- To enable C++23 features
"NOMINMAX",
"UNICODE",
"_HAS_CXX17",
"_HAS_CXX20",
"_HAS_CXX23"
)
add_files(
"src/**.cpp"
)
add_links(
"SDK-GMLIB/Lib/GMLIB"
)
add_includedirs(
"SDK-GMLIB",
"src"
)
add_packages(
"levilamina",
"legacyremotecall"
"legacyremotecall",
"gmlib"
)
add_shflags(
"/DELAYLOAD:bedrock_server.dll" -- Magic to import symbols from BDS
)
set_exceptions("none") -- To avoid conflicts with /EHa
add_rules("@levibuildscript/linkrule")
set_exceptions("none")
set_kind("shared")
set_languages("cxx23")
set_languages("cxx20")
set_symbols("debug")
after_build(function (target)
local plugin_packer = import("scripts.after_build")