Files
esengine/packages/behavior-tree/src/Services/GlobalBlackboardService.ts

180 lines
4.0 KiB
TypeScript
Raw Normal View History

import { IService } from '@esengine/ecs-framework';
import { BlackboardValueType, BlackboardVariable } from '../Types/TaskStatus';
/**
*
*/
export interface GlobalBlackboardConfig {
version: string;
variables: BlackboardVariable[];
}
/**
*
*
*
*
* 使
* ```typescript
* // 注册服务(在 BehaviorTreePlugin.install 中自动完成)
* core.services.registerSingleton(GlobalBlackboardService);
*
* // 获取服务
* const blackboard = core.services.resolve(GlobalBlackboardService);
* ```
*/
export class GlobalBlackboardService implements IService {
private variables: Map<string, BlackboardVariable> = new Map();
dispose(): void {
this.variables.clear();
}
/**
*
*/
defineVariable(
name: string,
type: BlackboardValueType,
initialValue: any,
options?: {
readonly?: boolean;
description?: string;
}
): void {
const variable: BlackboardVariable = {
name,
type,
value: initialValue,
readonly: options?.readonly ?? false
};
if (options?.description !== undefined) {
variable.description = options.description;
}
this.variables.set(name, variable);
}
/**
*
*/
getValue<T = any>(name: string): T | undefined {
const variable = this.variables.get(name);
return variable?.value as T;
}
/**
*
*/
setValue(name: string, value: any, force: boolean = false): boolean {
const variable = this.variables.get(name);
if (!variable) {
return false;
}
if (variable.readonly && !force) {
return false;
}
variable.value = value;
return true;
}
/**
*
*/
hasVariable(name: string): boolean {
return this.variables.has(name);
}
/**
*
*/
removeVariable(name: string): boolean {
return this.variables.delete(name);
}
/**
*
*/
getVariableNames(): string[] {
return Array.from(this.variables.keys());
}
/**
*
*/
getAllVariables(): BlackboardVariable[] {
return Array.from(this.variables.values());
}
/**
*
*/
clear(): void {
this.variables.clear();
}
/**
*
*/
setVariables(values: Record<string, any>): void {
for (const [name, value] of Object.entries(values)) {
const variable = this.variables.get(name);
if (variable && !variable.readonly) {
variable.value = value;
}
}
}
/**
*
*/
getVariables(names: string[]): Record<string, any> {
const result: Record<string, any> = {};
for (const name of names) {
const value = this.getValue(name);
if (value !== undefined) {
result[name] = value;
}
}
return result;
}
/**
*
*/
exportConfig(): GlobalBlackboardConfig {
return {
version: '1.0',
variables: Array.from(this.variables.values())
};
}
/**
*
*/
importConfig(config: GlobalBlackboardConfig): void {
this.variables.clear();
for (const variable of config.variables) {
this.variables.set(variable.name, variable);
}
}
/**
* JSON
*/
toJSON(): string {
return JSON.stringify(this.exportConfig(), null, 2);
}
/**
* JSON
*/
static fromJSON(json: string): GlobalBlackboardConfig {
return JSON.parse(json);
}
}