Files
esengine/packages/framework/behavior-tree/src/BehaviorTreePlugin.ts

119 lines
3.4 KiB
TypeScript
Raw Normal View History

import type { Core, ServiceContainer, IPlugin, IScene } from '@esengine/ecs-framework';
import { BehaviorTreeExecutionSystem } from './execution/BehaviorTreeExecutionSystem';
import { BehaviorTreeAssetManager } from './execution/BehaviorTreeAssetManager';
import { GlobalBlackboardService } from './Services/GlobalBlackboardService';
/**
* @zh
* @en Behavior Tree Plugin
*
* @zh ECS
* @esengine/ecs-framework CocosLayaNode.js
*
* @en Plugin that provides behavior tree support for ECS framework.
* Can be integrated with any engine based on @esengine/ecs-framework (Cocos, Laya, Node.js, etc.).
*
* @example
* ```typescript
* import { Core, Scene } from '@esengine/ecs-framework';
* import { BehaviorTreePlugin, BehaviorTreeBuilder, BehaviorTreeStarter } from '@esengine/behavior-tree';
*
* // Initialize
* Core.create();
* const plugin = new BehaviorTreePlugin();
* await Core.installPlugin(plugin);
*
* // Setup scene
* const scene = new Scene();
* plugin.setupScene(scene);
* Core.setScene(scene);
*
* // Create and start behavior tree
* const tree = BehaviorTreeBuilder.create('MyAI')
* .selector('Root')
* .log('Hello from behavior tree!')
* .end()
* .build();
*
* const entity = scene.createEntity('AIEntity');
* BehaviorTreeStarter.start(entity, tree);
* ```
*/
export class BehaviorTreePlugin implements IPlugin {
/**
* @zh
* @en Plugin name
*/
readonly name = '@esengine/behavior-tree';
/**
* @zh
* @en Plugin version
*/
readonly version = '1.0.0';
/**
* @zh
* @en Plugin dependencies
*/
readonly dependencies: readonly string[] = [];
private _services: ServiceContainer | null = null;
/**
* @zh
* @en Install plugin
*
* @param _core - Core
* @param services -
*/
install(_core: Core, services: ServiceContainer): void {
this._services = services;
// Register services
if (!services.isRegistered(GlobalBlackboardService)) {
services.registerSingleton(GlobalBlackboardService);
}
if (!services.isRegistered(BehaviorTreeAssetManager)) {
services.registerSingleton(BehaviorTreeAssetManager);
}
}
/**
* @zh
* @en Uninstall plugin
*/
uninstall(): void {
if (this._services) {
const assetManager = this._services.tryResolve(BehaviorTreeAssetManager);
if (assetManager) {
assetManager.dispose();
}
const blackboardService = this._services.tryResolve(GlobalBlackboardService);
if (blackboardService) {
blackboardService.dispose();
}
}
this._services = null;
}
/**
* @zh
* @en Setup scene, add behavior tree execution system
*
* @param scene -
*
* @example
* ```typescript
* const scene = new Scene();
* plugin.setupScene(scene);
* Core.setScene(scene);
* ```
*/
setupScene(scene: IScene): void {
const system = new BehaviorTreeExecutionSystem(this._services ?? undefined);
scene.addSystem(system);
}
}