refactor(plugin): 重构插件系统架构,统一类型导入路径 (#296)
* refactor(plugin): 重构插件系统架构,统一类型导入路径 ## 主要更改 ### 新增 @esengine/plugin-types 包 - 提供打破循环依赖的最小类型定义 - 包含 ServiceToken, createServiceToken, PluginServiceRegistry, IEditorModuleBase ### engine-core 类型统一 - IPlugin<T> 泛型参数改为 T = unknown - 所有运行时类型(IRuntimeModule, ModuleManifest, SystemContext)在此定义 - 新增 PluginServiceRegistry.ts 导出服务令牌相关类型 ### editor-core 类型优化 - 重命名 IPluginLoader.ts 为 EditorModule.ts - 新增 IEditorPlugin = IPlugin<IEditorModuleLoader> 类型别名 - 移除弃用别名 IPluginLoader, IRuntimeModuleLoader ### 编辑器插件更新 - 所有 9 个编辑器插件使用 IEditorPlugin 类型 - 统一从 editor-core 导入编辑器类型 ### 服务令牌规范 - 各模块在 tokens.ts 中定义自己的服务接口和令牌 - 遵循"谁定义接口,谁导出 Token"原则 ## 导入规范 | 场景 | 导入来源 | |------|---------| | 运行时模块 | @esengine/engine-core | | 编辑器插件 | @esengine/editor-core | | 服务令牌 | @esengine/engine-core | * refactor(plugin): 完善服务令牌规范,统一运行时模块 ## 更改内容 ### 运行时模块优化 - particle: 使用 PluginServiceRegistry 获取依赖服务 - physics-rapier2d: 通过服务令牌注册/获取物理查询接口 - tilemap: 使用服务令牌获取物理系统依赖 - sprite: 导出服务令牌 - ui: 导出服务令牌 - behavior-tree: 使用服务令牌系统 ### 资产系统增强 - IAssetManager 接口扩展 - 加载器使用服务令牌获取依赖 ### 运行时核心 - GameRuntime 使用 PluginServiceRegistry - 导出服务令牌相关类型 ### 编辑器服务 - EngineService 适配新的服务令牌系统 - AssetRegistryService 优化 * fix: 修复 editor-app 和 behavior-tree-editor 中的类型引用 - editor-app/PluginLoader.ts: 使用 IPlugin 替代 IPluginLoader - behavior-tree-editor: 使用 IEditorPlugin 替代 IPluginLoader * fix(ui): 添加缺失的 ecs-engine-bindgen 依赖 UIRuntimeModule 使用 EngineBridgeToken,需要声明对 ecs-engine-bindgen 的依赖 * fix(type): 解决 ServiceToken 跨包类型兼容性问题 - 在 engine-core 中直接定义 ServiceToken 和 PluginServiceRegistry 而不是从 plugin-types 重新导出,确保 tsup 生成的类型声明 以 engine-core 作为类型来源 - 移除 RuntimeResolver.ts 中的硬编码模块 ID 检查, 改用 module.json 中的 name 配置 - 修复 pnpm-lock.yaml 中的依赖记录 * refactor(arch): 改进架构设计,移除硬编码 - 统一类型导出:editor-core 从 engine-core 导入 IEditorModuleBase - RuntimeResolver: 将硬编码路径改为配置常量和搜索路径列表 - 添加跨平台安装路径支持(Windows/macOS/Linux) - 使用 ENGINE_WASM_CONFIG 配置引擎 WASM 文件信息 - IBundlePackOptions 添加 preloadBundles 配置项 * fix(particle): 添加缺失的 ecs-engine-bindgen 依赖 ParticleRuntimeModule 导入了 @esengine/ecs-engine-bindgen 的 tokens, 但 package.json 中未声明该依赖,导致 CI 构建失败。 * fix(physics-rapier2d): 移除不存在的 PhysicsSystemContext 导出 PhysicsRuntimeModule 中不存在该类型,导致 type-check 失败
This commit is contained in:
@@ -130,7 +130,9 @@ export class AssetPacker {
|
||||
url: `assets/${bundleName}.bundle`,
|
||||
size: packed.data.byteLength,
|
||||
hash: await this._hashBuffer(packed.data),
|
||||
preload: bundleName === 'core' || bundleName === 'main'
|
||||
// 预加载核心资产包(可通过配置扩展) | Preload core bundles (extensible via config)
|
||||
preload: options.preloadBundles?.includes(bundleName) ??
|
||||
(bundleName === 'core' || bundleName === 'main')
|
||||
};
|
||||
|
||||
// Add asset locations
|
||||
|
||||
@@ -31,6 +31,7 @@
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@esengine/ecs-framework": "workspace:*",
|
||||
"@esengine/engine-core": "workspace:*",
|
||||
"@esengine/build-config": "workspace:*",
|
||||
"rimraf": "^5.0.0",
|
||||
"tsup": "^8.0.0",
|
||||
|
||||
@@ -204,6 +204,12 @@ export interface IBundlePackOptions {
|
||||
groupByType?: boolean;
|
||||
/** Include asset names in bundle | 在包中包含资产名称 */
|
||||
includeNames?: boolean;
|
||||
/**
|
||||
* 需要预加载的包名列表 | List of bundle names to preload
|
||||
* 如果未指定,默认预加载 'core' 和 'main' 包
|
||||
* If not specified, defaults to preloading 'core' and 'main' bundles
|
||||
*/
|
||||
preloadBundles?: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -10,6 +10,9 @@
|
||||
* For editor-side functionality (meta files, packing), use @esengine/asset-system-editor
|
||||
*/
|
||||
|
||||
// Service tokens (谁定义接口,谁导出 Token)
|
||||
export { AssetManagerToken, type IAssetManager } from './tokens';
|
||||
|
||||
// Types
|
||||
export * from './types/AssetTypes';
|
||||
|
||||
|
||||
@@ -15,8 +15,9 @@ import {
|
||||
IAssetLoadProgress,
|
||||
IAssetCatalog
|
||||
} from '../types/AssetTypes';
|
||||
import { IAssetLoader } from './IAssetLoader';
|
||||
import { IAssetLoader, IAssetLoaderFactory } from './IAssetLoader';
|
||||
import { IAssetReader } from './IAssetReader';
|
||||
import type { AssetDatabase } from '../core/AssetDatabase';
|
||||
|
||||
/**
|
||||
* Asset manager interface
|
||||
@@ -167,6 +168,24 @@ export interface IAssetManager {
|
||||
* 从目录加载资产元数据,用于运行时资产解析。
|
||||
*/
|
||||
initializeFromCatalog(catalog: IAssetCatalog): void;
|
||||
|
||||
/**
|
||||
* Get the asset database
|
||||
* 获取资产数据库
|
||||
*/
|
||||
getDatabase(): AssetDatabase;
|
||||
|
||||
/**
|
||||
* Get the loader factory
|
||||
* 获取加载器工厂
|
||||
*/
|
||||
getLoaderFactory(): IAssetLoaderFactory;
|
||||
|
||||
/**
|
||||
* Set project root path
|
||||
* 设置项目根路径
|
||||
*/
|
||||
setProjectRoot(path: string): void;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -27,7 +27,14 @@ export class AudioLoader implements IAssetLoader<IAudioAsset> {
|
||||
*/
|
||||
private static getAudioContext(): AudioContext {
|
||||
if (!AudioLoader._audioContext) {
|
||||
AudioLoader._audioContext = new (window.AudioContext || (window as any).webkitAudioContext)();
|
||||
// 兼容旧版 Safari 的 webkitAudioContext
|
||||
// Support legacy Safari webkitAudioContext
|
||||
const AudioContextClass = window.AudioContext ||
|
||||
(window as Window & { webkitAudioContext?: typeof AudioContext }).webkitAudioContext;
|
||||
if (!AudioContextClass) {
|
||||
throw new Error('AudioContext is not supported in this browser');
|
||||
}
|
||||
AudioLoader._audioContext = new AudioContextClass();
|
||||
}
|
||||
return AudioLoader._audioContext;
|
||||
}
|
||||
|
||||
@@ -38,6 +38,8 @@ export class BinaryLoader implements IAssetLoader<IBinaryAsset> {
|
||||
* 释放已加载的资产
|
||||
*/
|
||||
dispose(asset: IBinaryAsset): void {
|
||||
(asset as any).data = null;
|
||||
// 释放二进制数据引用以允许垃圾回收
|
||||
// Release binary data reference to allow garbage collection
|
||||
(asset as { data: ArrayBuffer | null }).data = null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,6 +35,7 @@ export class JsonLoader implements IAssetLoader<IJsonAsset> {
|
||||
* 释放已加载的资产
|
||||
*/
|
||||
dispose(asset: IJsonAsset): void {
|
||||
(asset as any).data = null;
|
||||
// 清空 JSON 数据 | Clear JSON data
|
||||
asset.data = null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,6 +50,7 @@ export class TextLoader implements IAssetLoader<ITextAsset> {
|
||||
* 释放已加载的资产
|
||||
*/
|
||||
dispose(asset: ITextAsset): void {
|
||||
(asset as any).content = '';
|
||||
// 清空文本内容 | Clear text content
|
||||
asset.content = '';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,6 +7,26 @@ import { AssetType } from '../types/AssetTypes';
|
||||
import { IAssetLoader, ITextureAsset, IAssetParseContext } from '../interfaces/IAssetLoader';
|
||||
import { IAssetContent, AssetContentType } from '../interfaces/IAssetReader';
|
||||
|
||||
/**
|
||||
* 全局引擎桥接接口(运行时挂载到 window)
|
||||
* Global engine bridge interface (mounted to window at runtime)
|
||||
*/
|
||||
interface IEngineBridgeGlobal {
|
||||
loadTexture?(textureId: number, path: string): Promise<void>;
|
||||
unloadTexture?(textureId: number): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取全局引擎桥接
|
||||
* Get global engine bridge
|
||||
*/
|
||||
function getEngineBridge(): IEngineBridgeGlobal | undefined {
|
||||
if (typeof window !== 'undefined' && 'engineBridge' in window) {
|
||||
return (window as Window & { engineBridge?: IEngineBridgeGlobal }).engineBridge;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Texture loader implementation
|
||||
* 纹理加载器实现
|
||||
@@ -39,36 +59,24 @@ export class TextureLoader implements IAssetLoader<ITextureAsset> {
|
||||
};
|
||||
|
||||
// Upload to GPU if bridge exists.
|
||||
if (typeof window !== 'undefined' && (window as any).engineBridge) {
|
||||
await this.uploadToGPU(textureAsset, context.metadata.path);
|
||||
const bridge = getEngineBridge();
|
||||
if (bridge?.loadTexture) {
|
||||
await bridge.loadTexture(textureAsset.textureId, context.metadata.path);
|
||||
}
|
||||
|
||||
return textureAsset;
|
||||
}
|
||||
|
||||
/**
|
||||
* Upload texture to GPU
|
||||
* 上传纹理到GPU
|
||||
*/
|
||||
private async uploadToGPU(textureAsset: ITextureAsset, path: string): Promise<void> {
|
||||
const bridge = (window as any).engineBridge;
|
||||
if (bridge && bridge.loadTexture) {
|
||||
await bridge.loadTexture(textureAsset.textureId, path);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispose loaded asset
|
||||
* 释放已加载的资产
|
||||
*/
|
||||
dispose(asset: ITextureAsset): void {
|
||||
// Release GPU resources.
|
||||
if (typeof window !== 'undefined' && (window as any).engineBridge) {
|
||||
const bridge = (window as any).engineBridge;
|
||||
if (bridge.unloadTexture) {
|
||||
const bridge = getEngineBridge();
|
||||
if (bridge?.unloadTexture) {
|
||||
bridge.unloadTexture(asset.textureId);
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up image data.
|
||||
if (asset.data instanceof HTMLImageElement) {
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
/**
|
||||
* Asset System 服务令牌
|
||||
* Asset System service tokens
|
||||
*
|
||||
* 定义 asset-system 模块导出的服务令牌和接口。
|
||||
* Defines service tokens and interfaces exported by asset-system module.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* // 消费方导入 Token | Consumer imports Token
|
||||
* import { AssetManagerToken, type IAssetManager } from '@esengine/asset-system';
|
||||
*
|
||||
* // 获取服务 | Get service
|
||||
* const assetManager = context.services.get(AssetManagerToken);
|
||||
* ```
|
||||
*/
|
||||
|
||||
import { createServiceToken } from '@esengine/engine-core';
|
||||
import type { IAssetManager } from './interfaces/IAssetManager';
|
||||
|
||||
// 重新导出接口方便使用 | Re-export interface for convenience
|
||||
export type { IAssetManager } from './interfaces/IAssetManager';
|
||||
export type { IAssetLoadResult } from './types/AssetTypes';
|
||||
|
||||
/**
|
||||
* 资产管理器服务令牌
|
||||
* Asset manager service token
|
||||
*
|
||||
* 用于注册和获取资产管理器服务。
|
||||
* For registering and getting asset manager service.
|
||||
*/
|
||||
export const AssetManagerToken = createServiceToken<IAssetManager>('assetManager');
|
||||
@@ -7,7 +7,7 @@ import type { ServiceContainer } from '@esengine/ecs-framework';
|
||||
import { TransformComponent } from '@esengine/engine-core';
|
||||
import {
|
||||
type IEditorModuleLoader,
|
||||
type IPluginLoader,
|
||||
type IEditorPlugin,
|
||||
type PanelDescriptor,
|
||||
type EntityCreationTemplate,
|
||||
type FileCreationTemplate,
|
||||
@@ -339,7 +339,7 @@ export class BehaviorTreeEditorModule implements IEditorModuleLoader {
|
||||
}
|
||||
|
||||
// Create the complete plugin with editor module
|
||||
export const BehaviorTreePlugin: IPluginLoader = {
|
||||
export const BehaviorTreePlugin: IEditorPlugin = {
|
||||
manifest,
|
||||
runtimeModule: new BehaviorTreeRuntimeModule(),
|
||||
editorModule: new BehaviorTreeEditorModule(),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { IScene, ServiceContainer } from '@esengine/ecs-framework';
|
||||
import { ComponentRegistry, Core } from '@esengine/ecs-framework';
|
||||
import { ComponentRegistry } from '@esengine/ecs-framework';
|
||||
import type { IRuntimeModule, IPlugin, ModuleManifest, SystemContext } from '@esengine/engine-core';
|
||||
import type { AssetManager } from '@esengine/asset-system';
|
||||
import { AssetManagerToken } from '@esengine/asset-system';
|
||||
|
||||
import { BehaviorTreeRuntimeComponent } from './execution/BehaviorTreeRuntimeComponent';
|
||||
import { BehaviorTreeExecutionSystem } from './execution/BehaviorTreeExecutionSystem';
|
||||
@@ -9,11 +9,10 @@ import { BehaviorTreeAssetManager } from './execution/BehaviorTreeAssetManager';
|
||||
import { GlobalBlackboardService } from './Services/GlobalBlackboardService';
|
||||
import { BehaviorTreeLoader } from './loaders/BehaviorTreeLoader';
|
||||
import { BehaviorTreeAssetType } from './index';
|
||||
import { BehaviorTreeSystemToken } from './tokens';
|
||||
|
||||
export interface BehaviorTreeSystemContext extends SystemContext {
|
||||
behaviorTreeSystem?: BehaviorTreeExecutionSystem;
|
||||
assetManager?: AssetManager;
|
||||
}
|
||||
// 重新导出 tokens | Re-export tokens
|
||||
export { BehaviorTreeSystemToken } from './tokens';
|
||||
|
||||
class BehaviorTreeRuntimeModule implements IRuntimeModule {
|
||||
private _loaderRegistered = false;
|
||||
@@ -32,28 +31,31 @@ class BehaviorTreeRuntimeModule implements IRuntimeModule {
|
||||
}
|
||||
|
||||
createSystems(scene: IScene, context: SystemContext): void {
|
||||
const btContext = context as BehaviorTreeSystemContext;
|
||||
// 从服务注册表获取依赖 | Get dependencies from service registry
|
||||
const assetManager = context.services.get(AssetManagerToken);
|
||||
|
||||
if (!this._loaderRegistered && btContext.assetManager) {
|
||||
btContext.assetManager.registerLoader(BehaviorTreeAssetType, new BehaviorTreeLoader());
|
||||
if (!this._loaderRegistered && assetManager) {
|
||||
assetManager.registerLoader(BehaviorTreeAssetType, new BehaviorTreeLoader());
|
||||
this._loaderRegistered = true;
|
||||
}
|
||||
|
||||
// 使用 context 中的 services,确保与调用方使用同一个 ServiceContainer 实例
|
||||
// Use services from context to ensure same ServiceContainer instance as caller
|
||||
const services = (btContext as any).services || Core.services;
|
||||
const behaviorTreeSystem = new BehaviorTreeExecutionSystem(services);
|
||||
// 使用 context.services 中的 ECS 服务容器
|
||||
// Use ECS service container from context.services
|
||||
const ecsServices = (context as { ecsServices?: ServiceContainer }).ecsServices;
|
||||
const behaviorTreeSystem = new BehaviorTreeExecutionSystem(ecsServices);
|
||||
|
||||
if (btContext.assetManager) {
|
||||
behaviorTreeSystem.setAssetManager(btContext.assetManager);
|
||||
if (assetManager) {
|
||||
behaviorTreeSystem.setAssetManager(assetManager);
|
||||
}
|
||||
|
||||
if (btContext.isEditor) {
|
||||
if (context.isEditor) {
|
||||
behaviorTreeSystem.enabled = false;
|
||||
}
|
||||
|
||||
scene.addSystem(behaviorTreeSystem);
|
||||
btContext.behaviorTreeSystem = behaviorTreeSystem;
|
||||
|
||||
// 注册服务到服务注册表 | Register service to service registry
|
||||
context.services.register(BehaviorTreeSystemToken, behaviorTreeSystem);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { EntitySystem, Matcher, Entity, Time, Core, ECSSystem, ServiceContainer } from '@esengine/ecs-framework';
|
||||
import type { AssetManager } from '@esengine/asset-system';
|
||||
import type { IAssetManager } from '@esengine/asset-system';
|
||||
import { BehaviorTreeRuntimeComponent } from './BehaviorTreeRuntimeComponent';
|
||||
import { BehaviorTreeAssetManager } from './BehaviorTreeAssetManager';
|
||||
import { NodeExecutorRegistry, NodeExecutionContext } from './NodeExecutor';
|
||||
@@ -21,7 +21,7 @@ export class BehaviorTreeExecutionSystem extends EntitySystem {
|
||||
private _services: ServiceContainer | null = null;
|
||||
|
||||
/** 引用 asset-system 的 AssetManager(由 BehaviorTreeRuntimeModule 设置) */
|
||||
private _assetManager: AssetManager | null = null;
|
||||
private _assetManager: IAssetManager | null = null;
|
||||
|
||||
/** 已警告过的缺失资产,避免重复警告 */
|
||||
private _warnedMissingAssets: Set<string> = new Set();
|
||||
@@ -37,7 +37,7 @@ export class BehaviorTreeExecutionSystem extends EntitySystem {
|
||||
* 设置 AssetManager 引用
|
||||
* Set AssetManager reference
|
||||
*/
|
||||
setAssetManager(assetManager: AssetManager | null): void {
|
||||
setAssetManager(assetManager: IAssetManager | null): void {
|
||||
this._assetManager = assetManager;
|
||||
}
|
||||
|
||||
|
||||
@@ -35,4 +35,7 @@ export type { BlackboardTypeDefinition } from './Blackboard/BlackboardTypes';
|
||||
export { BlackboardTypes } from './Blackboard/BlackboardTypes';
|
||||
|
||||
// Runtime module and plugin
|
||||
export { BehaviorTreeRuntimeModule, BehaviorTreePlugin, type BehaviorTreeSystemContext } from './BehaviorTreeRuntimeModule';
|
||||
export { BehaviorTreeRuntimeModule, BehaviorTreePlugin } from './BehaviorTreeRuntimeModule';
|
||||
|
||||
// Service tokens | 服务令牌
|
||||
export { BehaviorTreeSystemToken } from './tokens';
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* 行为树模块服务令牌
|
||||
* Behavior tree module service tokens
|
||||
*/
|
||||
|
||||
import { createServiceToken } from '@esengine/engine-core';
|
||||
import type { BehaviorTreeExecutionSystem } from './execution/BehaviorTreeExecutionSystem';
|
||||
|
||||
// ============================================================================
|
||||
// 行为树模块导出的令牌 | Tokens exported by behavior tree module
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* 行为树执行系统令牌
|
||||
* Behavior tree execution system token
|
||||
*/
|
||||
export const BehaviorTreeSystemToken = createServiceToken<BehaviorTreeExecutionSystem>('behaviorTreeSystem');
|
||||
@@ -4,8 +4,8 @@
|
||||
*/
|
||||
|
||||
import { Core, type ServiceContainer } from '@esengine/ecs-framework';
|
||||
import type { IPlugin, ModuleManifest } from '@esengine/engine-core';
|
||||
import type { IEditorModuleLoader, PanelDescriptor, FileActionHandler, FileCreationTemplate } from '@esengine/editor-core';
|
||||
import type { ModuleManifest } from '@esengine/engine-core';
|
||||
import type { IEditorPlugin, IEditorModuleLoader, PanelDescriptor, FileActionHandler, FileCreationTemplate } from '@esengine/editor-core';
|
||||
import { MessageHub, PanelPosition } from '@esengine/editor-core';
|
||||
|
||||
// Re-export from @esengine/blueprint for runtime module
|
||||
@@ -118,7 +118,7 @@ const manifest: ModuleManifest = {
|
||||
* Complete Blueprint plugin with both runtime and editor modules
|
||||
* 完整的蓝图插件,包含运行时和编辑器模块
|
||||
*/
|
||||
export const BlueprintPlugin: IPlugin = {
|
||||
export const BlueprintPlugin: IEditorPlugin = {
|
||||
manifest,
|
||||
editorModule: new BlueprintEditorModuleImpl()
|
||||
};
|
||||
|
||||
@@ -5,13 +5,13 @@
|
||||
*/
|
||||
|
||||
import type {
|
||||
IRuntimeModuleLoader,
|
||||
IRuntimeModule,
|
||||
IComponentRegistry,
|
||||
SystemContext
|
||||
} from '@esengine/ecs-components';
|
||||
import type { IScene, ServiceContainer } from '@esengine/ecs-framework';
|
||||
|
||||
export class {{name}}RuntimeModule implements IRuntimeModuleLoader {
|
||||
export class {{name}}RuntimeModule implements IRuntimeModule {
|
||||
/**
|
||||
* 注册组件到组件注册表
|
||||
*/
|
||||
|
||||
@@ -2,12 +2,15 @@
|
||||
"name": "@esengine/ecs-framework",
|
||||
"version": "2.3.2",
|
||||
"description": "用于Laya、Cocos Creator等JavaScript游戏引擎的高性能ECS框架",
|
||||
"main": "bin/index.js",
|
||||
"types": "bin/index.d.ts",
|
||||
"main": "dist/index.cjs",
|
||||
"module": "dist/index.mjs",
|
||||
"types": "dist/index.d.ts",
|
||||
"unpkg": "dist/index.umd.js",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./bin/index.d.ts",
|
||||
"import": "./bin/index.js",
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.mjs",
|
||||
"require": "./dist/index.cjs",
|
||||
"development": {
|
||||
"types": "./src/index.ts",
|
||||
"import": "./src/index.ts"
|
||||
@@ -15,7 +18,7 @@
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"bin/**/*"
|
||||
"dist/**/*"
|
||||
],
|
||||
"keywords": [
|
||||
"ecs",
|
||||
|
||||
@@ -5,11 +5,22 @@
|
||||
* @packageDocumentation
|
||||
*/
|
||||
|
||||
// Service tokens and interfaces (谁定义接口,谁导出 Token)
|
||||
export {
|
||||
RenderSystemToken,
|
||||
EngineBridgeToken,
|
||||
EngineIntegrationToken,
|
||||
type IRenderSystem,
|
||||
type IEngineBridge,
|
||||
type IEngineIntegration,
|
||||
type IRenderDataProvider
|
||||
} from './tokens';
|
||||
|
||||
export { EngineBridge } from './core/EngineBridge';
|
||||
export type { EngineBridgeConfig } from './core/EngineBridge';
|
||||
export { RenderBatcher } from './core/RenderBatcher';
|
||||
export { SpriteRenderHelper } from './core/SpriteRenderHelper';
|
||||
export type { ITransformComponent } from './core/SpriteRenderHelper';
|
||||
export { EngineRenderSystem, type TransformComponentType, type IRenderDataProvider, type IUIRenderDataProvider, type GizmoDataProviderFn, type HasGizmoProviderFn, type ProviderRenderData, type AssetPathResolverFn } from './systems/EngineRenderSystem';
|
||||
export { EngineRenderSystem, type TransformComponentType, type IUIRenderDataProvider, type GizmoDataProviderFn, type HasGizmoProviderFn, type ProviderRenderData, type AssetPathResolverFn } from './systems/EngineRenderSystem';
|
||||
export { CameraSystem } from './systems/CameraSystem';
|
||||
export * from './types';
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
/**
|
||||
* ecs-engine-bindgen 服务令牌
|
||||
* ecs-engine-bindgen service tokens
|
||||
*
|
||||
* 定义渲染系统和引擎桥接相关的服务令牌和接口。
|
||||
* 谁定义接口,谁导出 Token。
|
||||
*
|
||||
* Defines service tokens and interfaces for render system and engine bridge.
|
||||
* Who defines the interface, who exports the Token.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* // 消费方导入 Token | Consumer imports Token
|
||||
* import { RenderSystemToken, type IRenderSystem } from '@esengine/ecs-engine-bindgen';
|
||||
*
|
||||
* // 获取服务 | Get service
|
||||
* const renderSystem = context.services.get(RenderSystemToken);
|
||||
* if (renderSystem) {
|
||||
* renderSystem.addRenderDataProvider(myProvider);
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
|
||||
import { createServiceToken } from '@esengine/engine-core';
|
||||
import type { EngineBridge } from './core/EngineBridge';
|
||||
import type { IRenderDataProvider as InternalIRenderDataProvider } from './systems/EngineRenderSystem';
|
||||
|
||||
// ============================================================================
|
||||
// 共享渲染接口 | Shared Render Interfaces
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* 渲染数据提供者接口
|
||||
* Render data provider interface
|
||||
*
|
||||
* 由各模块的渲染系统实现,用于向主渲染系统提供渲染数据。
|
||||
* Implemented by render systems of various modules, used to provide render data to main render system.
|
||||
*/
|
||||
export type IRenderDataProvider = InternalIRenderDataProvider;
|
||||
|
||||
/**
|
||||
* 渲染系统接口
|
||||
* Render system interface
|
||||
*
|
||||
* 跨模块共享的渲染系统契约。
|
||||
* Cross-module shared render system contract.
|
||||
*/
|
||||
export interface IRenderSystem {
|
||||
/**
|
||||
* 注册渲染数据提供者
|
||||
* Register a render data provider
|
||||
*
|
||||
* @param provider 渲染数据提供者 | Render data provider
|
||||
*/
|
||||
addRenderDataProvider(provider: IRenderDataProvider): void;
|
||||
|
||||
/**
|
||||
* 移除渲染数据提供者
|
||||
* Remove a render data provider
|
||||
*
|
||||
* @param provider 渲染数据提供者 | Render data provider
|
||||
*/
|
||||
removeRenderDataProvider(provider: IRenderDataProvider): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* 引擎桥接接口
|
||||
* Engine bridge interface
|
||||
*
|
||||
* WASM 引擎桥接契约。
|
||||
* WASM engine bridge contract.
|
||||
*/
|
||||
export interface IEngineBridge {
|
||||
/**
|
||||
* 加载纹理
|
||||
* Load texture
|
||||
*/
|
||||
loadTexture(id: number, url: string): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 引擎集成接口
|
||||
* Engine integration interface
|
||||
*
|
||||
* 纹理加载等引擎集成功能。
|
||||
* Engine integration features like texture loading.
|
||||
*/
|
||||
export interface IEngineIntegration {
|
||||
/**
|
||||
* 为组件加载纹理
|
||||
* Load texture for component
|
||||
*/
|
||||
loadTextureForComponent(texturePath: string): Promise<number>;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 服务令牌 | Service Tokens
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* 渲染系统服务令牌
|
||||
* Render system service token
|
||||
*
|
||||
* 用于获取渲染系统实例。
|
||||
* For getting render system instance.
|
||||
*/
|
||||
export const RenderSystemToken = createServiceToken<IRenderSystem>('renderSystem');
|
||||
|
||||
/**
|
||||
* 引擎桥接服务令牌
|
||||
* Engine bridge service token
|
||||
*
|
||||
* 用于获取 WASM 引擎桥接实例。
|
||||
* For getting WASM engine bridge instance.
|
||||
*/
|
||||
export const EngineBridgeToken = createServiceToken<IEngineBridge>('engineBridge');
|
||||
|
||||
/**
|
||||
* 引擎集成服务令牌
|
||||
* Engine integration service token
|
||||
*
|
||||
* 用于获取引擎集成实例(纹理加载等)。
|
||||
* For getting engine integration instance (texture loading, etc.).
|
||||
*/
|
||||
export const EngineIntegrationToken = createServiceToken<IEngineIntegration>('engineIntegration');
|
||||
@@ -7,11 +7,11 @@
|
||||
*/
|
||||
|
||||
import { GizmoRegistry, EntityStoreService, MessageHub, SceneManagerService, ProjectService, PluginManager, IPluginManager, AssetRegistryService, type SystemContext } from '@esengine/editor-core';
|
||||
import { Core, Scene, Entity, SceneSerializer, ProfilerSDK } from '@esengine/ecs-framework';
|
||||
import { CameraConfig } from '@esengine/ecs-engine-bindgen';
|
||||
import { TransformComponent } from '@esengine/engine-core';
|
||||
import { SpriteComponent, SpriteAnimatorComponent } from '@esengine/sprite';
|
||||
import { invalidateUIRenderCaches } from '@esengine/ui';
|
||||
import { Core, Scene, Entity, SceneSerializer, ProfilerSDK, createLogger } from '@esengine/ecs-framework';
|
||||
import { CameraConfig, EngineBridgeToken, RenderSystemToken, EngineIntegrationToken } from '@esengine/ecs-engine-bindgen';
|
||||
import { TransformComponent, PluginServiceRegistry, TransformTypeToken } from '@esengine/engine-core';
|
||||
import { SpriteComponent, SpriteAnimatorComponent, SpriteAnimatorSystemToken } from '@esengine/sprite';
|
||||
import { invalidateUIRenderCaches, UIRenderProviderToken, UIInputSystemToken } from '@esengine/ui';
|
||||
import * as esEngine from '@esengine/engine';
|
||||
import {
|
||||
AssetManager,
|
||||
@@ -21,7 +21,8 @@ import {
|
||||
globalPathResolver,
|
||||
SceneResourceManager,
|
||||
assetManager as globalAssetManager,
|
||||
AssetType
|
||||
AssetType,
|
||||
AssetManagerToken
|
||||
} from '@esengine/asset-system';
|
||||
import {
|
||||
GameRuntime,
|
||||
@@ -29,12 +30,16 @@ import {
|
||||
EditorPlatformAdapter,
|
||||
type GameRuntimeConfig
|
||||
} from '@esengine/runtime-core';
|
||||
import { BehaviorTreeSystemToken } from '@esengine/behavior-tree';
|
||||
import { Physics2DSystemToken } from '@esengine/physics-rapier2d';
|
||||
import { getMaterialManager } from '@esengine/material-system';
|
||||
import { resetEngineState } from '../hooks/useEngine';
|
||||
import { convertFileSrc } from '@tauri-apps/api/core';
|
||||
import { IdGenerator } from '../utils/idGenerator';
|
||||
import { TauriAssetReader } from './TauriAssetReader';
|
||||
|
||||
const logger = createLogger('EngineService');
|
||||
|
||||
/**
|
||||
* Engine service singleton for editor integration.
|
||||
* 用于编辑器集成的引擎服务单例。
|
||||
@@ -198,15 +203,19 @@ export class EngineService {
|
||||
// 初始化所有插件的运行时模块
|
||||
await pluginManager.initializeRuntime(Core.services);
|
||||
|
||||
// 创建服务注册表并注册核心服务
|
||||
// Create service registry and register core services
|
||||
const services = new PluginServiceRegistry();
|
||||
services.register(EngineBridgeToken, this._runtime.bridge);
|
||||
services.register(RenderSystemToken, this._runtime.renderSystem);
|
||||
services.register(AssetManagerToken, this._assetManager);
|
||||
services.register(EngineIntegrationToken, this._engineIntegration);
|
||||
services.register(TransformTypeToken, TransformComponent);
|
||||
|
||||
// 创建系统上下文
|
||||
const context: SystemContext = {
|
||||
services: Core.services,
|
||||
engineBridge: this._runtime.bridge,
|
||||
renderSystem: this._runtime.renderSystem,
|
||||
assetManager: this._assetManager,
|
||||
engineIntegration: this._engineIntegration,
|
||||
isEditor: true,
|
||||
transformType: TransformComponent
|
||||
services
|
||||
};
|
||||
|
||||
// 让插件为场景创建系统
|
||||
@@ -216,29 +225,44 @@ export class EngineService {
|
||||
// 插件注册完加载器后,重新同步资产(确保类型正确)
|
||||
await this._syncAssetRegistryToManager();
|
||||
|
||||
// 同步系统引用到 GameRuntime 的 systemContext(用于 start/stop 时启用/禁用系统)
|
||||
this._runtime.updateSystemContext({
|
||||
animatorSystem: context.animatorSystem,
|
||||
behaviorTreeSystem: context.behaviorTreeSystem,
|
||||
physicsSystem: context.physicsSystem,
|
||||
uiInputSystem: context.uiInputSystem,
|
||||
uiRenderProvider: context.uiRenderProvider
|
||||
});
|
||||
// 同步服务注册表到 GameRuntime(用于 start/stop 时启用/禁用系统)
|
||||
// Sync service registry to GameRuntime (for enabling/disabling systems on start/stop)
|
||||
const runtimeServices = this._runtime.getServiceRegistry();
|
||||
if (runtimeServices) {
|
||||
// 复制所有已注册的服务到 runtime 的服务注册表
|
||||
// 这样 runtime 的 start/stop 方法可以正确访问这些服务
|
||||
const animatorSystem = services.get(SpriteAnimatorSystemToken);
|
||||
const behaviorTreeSystem = services.get(BehaviorTreeSystemToken);
|
||||
const physicsSystem = services.get(Physics2DSystemToken);
|
||||
const uiInputSystem = services.get(UIInputSystemToken);
|
||||
const uiRenderProvider = services.get(UIRenderProviderToken);
|
||||
|
||||
if (animatorSystem) runtimeServices.register(SpriteAnimatorSystemToken, animatorSystem);
|
||||
if (behaviorTreeSystem) runtimeServices.register(BehaviorTreeSystemToken, behaviorTreeSystem);
|
||||
if (physicsSystem) runtimeServices.register(Physics2DSystemToken, physicsSystem);
|
||||
if (uiInputSystem) runtimeServices.register(UIInputSystemToken, uiInputSystem);
|
||||
if (uiRenderProvider) runtimeServices.register(UIRenderProviderToken, uiRenderProvider);
|
||||
}
|
||||
|
||||
// 设置 UI 渲染数据提供者
|
||||
if (context.uiRenderProvider && this._runtime.renderSystem) {
|
||||
this._runtime.renderSystem.setUIRenderDataProvider(context.uiRenderProvider);
|
||||
const uiRenderProvider = services.get(UIRenderProviderToken);
|
||||
if (uiRenderProvider && this._runtime.renderSystem) {
|
||||
this._runtime.renderSystem.setUIRenderDataProvider(uiRenderProvider);
|
||||
}
|
||||
|
||||
// 在编辑器模式下,禁用游戏逻辑系统
|
||||
if (context.animatorSystem) {
|
||||
context.animatorSystem.enabled = false;
|
||||
const animatorSystem = services.get(SpriteAnimatorSystemToken);
|
||||
const behaviorTreeSystem = services.get(BehaviorTreeSystemToken);
|
||||
const physicsSystem = services.get(Physics2DSystemToken);
|
||||
|
||||
if (animatorSystem) {
|
||||
animatorSystem.enabled = false;
|
||||
}
|
||||
if (context.behaviorTreeSystem) {
|
||||
context.behaviorTreeSystem.enabled = false;
|
||||
if (behaviorTreeSystem) {
|
||||
behaviorTreeSystem.enabled = false;
|
||||
}
|
||||
if (context.physicsSystem) {
|
||||
context.physicsSystem.enabled = false;
|
||||
if (physicsSystem) {
|
||||
physicsSystem.enabled = false;
|
||||
}
|
||||
|
||||
this._modulesInitialized = true;
|
||||
@@ -253,9 +277,14 @@ export class EngineService {
|
||||
pluginManager.clearSceneSystems();
|
||||
}
|
||||
|
||||
const ctx = this._runtime?.systemContext;
|
||||
if (ctx?.uiInputSystem) {
|
||||
ctx.uiInputSystem.unbind?.();
|
||||
// 使用服务注册表获取 UI 输入系统
|
||||
// Use service registry to get UI input system
|
||||
const runtimeServices = this._runtime?.getServiceRegistry();
|
||||
if (runtimeServices) {
|
||||
const uiInputSystem = runtimeServices.get(UIInputSystemToken);
|
||||
if (uiInputSystem && uiInputSystem.unbind) {
|
||||
uiInputSystem.unbind();
|
||||
}
|
||||
}
|
||||
|
||||
// 清理 viewport | Clear viewport
|
||||
@@ -475,7 +504,7 @@ export class EngineService {
|
||||
const allAssets = assetRegistry.getAllAssets();
|
||||
const metaManager = assetRegistry.metaManager;
|
||||
|
||||
console.log(`[EngineService] Syncing ${allAssets.length} assets from AssetRegistry to AssetManager`);
|
||||
logger.debug(`Syncing ${allAssets.length} assets from AssetRegistry to AssetManager`);
|
||||
|
||||
// Use loaderFactory to determine asset type from path
|
||||
// This allows plugins to register their own loaders and types
|
||||
@@ -533,7 +562,7 @@ export class EngineService {
|
||||
});
|
||||
}
|
||||
|
||||
console.log(`[EngineService] Asset sync complete`);
|
||||
logger.debug('Asset sync complete');
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -694,10 +723,18 @@ export class EngineService {
|
||||
* Enable animation preview in editor mode.
|
||||
*/
|
||||
enableAnimationPreview(): void {
|
||||
const ctx = this._runtime?.systemContext;
|
||||
if (ctx?.animatorSystem && !this._running) {
|
||||
ctx.animatorSystem.clearEntityCache?.();
|
||||
ctx.animatorSystem.enabled = true;
|
||||
if (this._running) return;
|
||||
|
||||
const runtimeServices = this._runtime?.getServiceRegistry();
|
||||
if (runtimeServices) {
|
||||
const animatorSystem = runtimeServices.get(SpriteAnimatorSystemToken);
|
||||
if (animatorSystem) {
|
||||
// 如果有 clearEntityCache 方法则调用
|
||||
// Call clearEntityCache if available
|
||||
const system = animatorSystem as { clearEntityCache?: () => void; enabled: boolean };
|
||||
system.clearEntityCache?.();
|
||||
system.enabled = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -705,9 +742,14 @@ export class EngineService {
|
||||
* Disable animation preview in editor mode.
|
||||
*/
|
||||
disableAnimationPreview(): void {
|
||||
const ctx = this._runtime?.systemContext;
|
||||
if (ctx?.animatorSystem && !this._running) {
|
||||
ctx.animatorSystem.enabled = false;
|
||||
if (this._running) return;
|
||||
|
||||
const runtimeServices = this._runtime?.getServiceRegistry();
|
||||
if (runtimeServices) {
|
||||
const animatorSystem = runtimeServices.get(SpriteAnimatorSystemToken);
|
||||
if (animatorSystem) {
|
||||
animatorSystem.enabled = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -715,7 +757,12 @@ export class EngineService {
|
||||
* Check if animation preview is enabled.
|
||||
*/
|
||||
isAnimationPreviewEnabled(): boolean {
|
||||
return this._runtime?.systemContext?.animatorSystem?.enabled ?? false;
|
||||
const runtimeServices = this._runtime?.getServiceRegistry();
|
||||
if (runtimeServices) {
|
||||
const animatorSystem = runtimeServices.get(SpriteAnimatorSystemToken);
|
||||
return animatorSystem?.enabled ?? false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
*/
|
||||
|
||||
import { PluginManager, LocaleService, MessageHub } from '@esengine/editor-core';
|
||||
import type { IPluginLoader, ModuleManifest } from '@esengine/editor-core';
|
||||
import type { IPlugin, ModuleManifest } from '@esengine/editor-core';
|
||||
import { Core } from '@esengine/ecs-framework';
|
||||
import { TauriAPI } from '../api/tauri';
|
||||
import { PluginSDKRegistry } from './PluginSDKRegistry';
|
||||
@@ -158,7 +158,7 @@ export class PluginLoader {
|
||||
code: string,
|
||||
pluginName: string,
|
||||
_pluginDirName: string
|
||||
): Promise<IPluginLoader | null> {
|
||||
): Promise<IPlugin | null> {
|
||||
const pluginKey = this.sanitizePluginKey(pluginName);
|
||||
|
||||
try {
|
||||
@@ -257,9 +257,9 @@ export class PluginLoader {
|
||||
}
|
||||
|
||||
/**
|
||||
* 查找模块中的插件加载器
|
||||
* 查找模块中的插件
|
||||
*/
|
||||
private findPluginLoader(module: any): IPluginLoader | null {
|
||||
private findPluginLoader(module: any): IPlugin | null {
|
||||
// 优先检查 default 导出
|
||||
if (module.default && this.isPluginLoader(module.default)) {
|
||||
return module.default;
|
||||
@@ -277,14 +277,14 @@ export class PluginLoader {
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证对象是否为有效的插件加载器
|
||||
* 验证对象是否为有效的插件
|
||||
*/
|
||||
private isPluginLoader(obj: any): obj is IPluginLoader {
|
||||
private isPluginLoader(obj: any): obj is IPlugin {
|
||||
if (!obj || typeof obj !== 'object') {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 新的 IPluginLoader 接口检查
|
||||
// 新的 IPlugin 接口检查
|
||||
if (obj.manifest && this.isModuleManifest(obj.manifest)) {
|
||||
return true;
|
||||
}
|
||||
@@ -307,13 +307,15 @@ export class PluginLoader {
|
||||
/**
|
||||
* 同步插件语言设置
|
||||
*/
|
||||
private syncPluginLocale(plugin: IPluginLoader, pluginName: string): void {
|
||||
private syncPluginLocale(plugin: IPlugin, pluginName: string): void {
|
||||
try {
|
||||
const localeService = Core.services.resolve(LocaleService);
|
||||
const currentLocale = localeService.getCurrentLocale();
|
||||
|
||||
if (plugin.editorModule?.setLocale) {
|
||||
plugin.editorModule.setLocale(currentLocale);
|
||||
// 类型安全地检查 editorModule 是否有 setLocale 方法
|
||||
const editorModule = plugin.editorModule as { setLocale?: (locale: string) => void } | undefined;
|
||||
if (editorModule?.setLocale) {
|
||||
editorModule.setLocale(currentLocale);
|
||||
}
|
||||
|
||||
// 通知 UI 刷新
|
||||
|
||||
@@ -5,6 +5,26 @@
|
||||
|
||||
import { TauriAPI } from '../api/tauri';
|
||||
|
||||
// ============================================================================
|
||||
// 配置常量 | Configuration Constants
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* 引擎 WASM 模块配置
|
||||
* Engine WASM module configuration
|
||||
*
|
||||
* 避免硬编码目录名,使用配置驱动
|
||||
* Avoid hardcoded directory names, use configuration-driven approach
|
||||
*/
|
||||
const ENGINE_WASM_CONFIG = {
|
||||
/** 引擎 WASM 目录名 | Engine WASM directory name */
|
||||
dirName: 'es-engine',
|
||||
/** 引擎包名 | Engine package name */
|
||||
packageName: 'engine',
|
||||
/** WASM 文件列表 | WASM file list */
|
||||
files: ['es_engine_bg.wasm', 'es_engine.js', 'es_engine_bg.js']
|
||||
} as const;
|
||||
|
||||
/**
|
||||
* 运行时模块清单
|
||||
* Module manifest for runtime modules
|
||||
@@ -93,16 +113,45 @@ export class RuntimeResolver {
|
||||
return startPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取可能的安装路径列表
|
||||
* Get list of possible installation paths
|
||||
*
|
||||
* 使用环境变量和标准路径,避免硬编码
|
||||
* Use environment variables and standard paths, avoid hardcoding
|
||||
*/
|
||||
private getInstalledEnginePaths(): string[] {
|
||||
const paths: string[] = [];
|
||||
|
||||
// 1. 使用环境变量(如果设置) | Use environment variable if set
|
||||
// 可以在 Tauri 配置或系统环境变量中设置 ESENGINE_INSTALL_DIR
|
||||
// 注意:Tauri 目前无法直接读取环境变量,此处为将来扩展预留
|
||||
|
||||
// 2. 使用标准安装位置(按平台) | Use standard install locations (by platform)
|
||||
// 这些路径仍然是硬编码的,但集中在一处便于维护
|
||||
// Windows
|
||||
paths.push('C:/Program Files/ESEngine Editor/engine');
|
||||
paths.push('C:/Program Files (x86)/ESEngine Editor/engine');
|
||||
// macOS (future support)
|
||||
paths.push('/Applications/ESEngine Editor.app/Contents/Resources/engine');
|
||||
// Linux (future support)
|
||||
paths.push('/opt/esengine-editor/engine');
|
||||
paths.push('/usr/local/share/esengine-editor/engine');
|
||||
|
||||
return paths;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find engine modules path (where compiled modules with module.json are)
|
||||
* 查找引擎模块路径(编译后的模块和 module.json 所在位置)
|
||||
*/
|
||||
private async findEngineModulesPath(): Promise<string> {
|
||||
// Try installed editor location first
|
||||
const installedPath = 'C:/Program Files/ESEngine Editor/engine';
|
||||
// Try installed editor locations first (production mode)
|
||||
for (const installedPath of this.getInstalledEnginePaths()) {
|
||||
if (await TauriAPI.pathExists(`${installedPath}/index.json`)) {
|
||||
return installedPath;
|
||||
}
|
||||
}
|
||||
|
||||
// Try workspace packages directory (dev mode)
|
||||
const workspacePath = `${this.baseDir}\\packages`;
|
||||
@@ -237,15 +286,11 @@ export class RuntimeResolver {
|
||||
// 复制所有 chunk 文件(代码分割会创建 chunk-*.js 文件)
|
||||
await this.copyChunkFiles(moduleDistDir, dstModuleDir);
|
||||
|
||||
// Add to import map
|
||||
importMap[`@esengine/${module.id}`] = `./libs/${module.id}/${module.id}.js`;
|
||||
|
||||
// Also add common aliases
|
||||
if (module.id === 'core') {
|
||||
importMap['@esengine/ecs-framework'] = `./libs/${module.id}/${module.id}.js`;
|
||||
}
|
||||
if (module.id === 'math') {
|
||||
importMap['@esengine/ecs-framework-math'] = `./libs/${module.id}/${module.id}.js`;
|
||||
// Add to import map using module.name from module.json
|
||||
// 使用 module.json 中的 module.name 作为 import map 的 key
|
||||
// e.g., core/module.json: { "name": "@esengine/ecs-framework" }
|
||||
if (module.name) {
|
||||
importMap[module.name] = `./libs/${module.id}/${module.id}.js`;
|
||||
}
|
||||
|
||||
copiedModules.push(module.id);
|
||||
@@ -330,28 +375,45 @@ export class RuntimeResolver {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取引擎 WASM 文件的搜索路径
|
||||
* Get search paths for engine WASM files
|
||||
*/
|
||||
private getEngineWasmSearchPaths(): string[] {
|
||||
const paths: string[] = [];
|
||||
|
||||
// 1. 开发模式:工作区内的 engine 包 | Dev mode: engine package in workspace
|
||||
paths.push(`${this.baseDir}\\packages\\${ENGINE_WASM_CONFIG.packageName}\\pkg`);
|
||||
|
||||
// 2. 相对于引擎模块路径 | Relative to engine modules path
|
||||
paths.push(`${this.engineModulesPath}\\..\\..\\${ENGINE_WASM_CONFIG.packageName}\\pkg`);
|
||||
|
||||
// 3. 生产模式:安装目录中的 wasm 文件夹 | Production mode: wasm folder in install dir
|
||||
for (const installedPath of this.getInstalledEnginePaths()) {
|
||||
// 将 /engine 替换为 /wasm | Replace /engine with /wasm
|
||||
const wasmPath = installedPath.replace(/[/\\]engine$/, '/wasm');
|
||||
paths.push(wasmPath);
|
||||
}
|
||||
|
||||
return paths;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy engine WASM files
|
||||
* 复制引擎 WASM 文件
|
||||
*/
|
||||
private async copyEngineWasm(libsDir: string): Promise<void> {
|
||||
const esEngineDir = `${libsDir}\\es-engine`;
|
||||
const esEngineDir = `${libsDir}\\${ENGINE_WASM_CONFIG.dirName}`;
|
||||
if (!await TauriAPI.pathExists(esEngineDir)) {
|
||||
await TauriAPI.createDirectory(esEngineDir);
|
||||
}
|
||||
|
||||
// Try different locations for engine WASM
|
||||
const wasmSearchPaths = [
|
||||
`${this.baseDir}\\packages\\engine\\pkg`,
|
||||
`${this.engineModulesPath}\\..\\..\\engine\\pkg`,
|
||||
'C:/Program Files/ESEngine Editor/wasm'
|
||||
];
|
||||
|
||||
const filesToCopy = ['es_engine_bg.wasm', 'es_engine.js', 'es_engine_bg.js'];
|
||||
const wasmSearchPaths = this.getEngineWasmSearchPaths();
|
||||
|
||||
for (const searchPath of wasmSearchPaths) {
|
||||
if (await TauriAPI.pathExists(searchPath)) {
|
||||
for (const file of filesToCopy) {
|
||||
for (const file of ENGINE_WASM_CONFIG.files) {
|
||||
const srcFile = `${searchPath}\\${file}`;
|
||||
if (await TauriAPI.pathExists(srcFile)) {
|
||||
const dstFile = `${esEngineDir}\\${file}`;
|
||||
|
||||
@@ -43,6 +43,7 @@
|
||||
"@esengine/asset-system": "workspace:*",
|
||||
"@esengine/asset-system-editor": "workspace:*",
|
||||
"@esengine/engine-core": "workspace:*",
|
||||
"@esengine/plugin-types": "workspace:*",
|
||||
"@tauri-apps/api": "^2.2.0",
|
||||
"@babel/core": "^7.28.3",
|
||||
"@babel/plugin-transform-nullish-coalescing-operator": "^7.27.1",
|
||||
|
||||
+45
-48
@@ -4,11 +4,13 @@
|
||||
*
|
||||
* 定义编辑器专用的模块接口和 UI 描述符类型。
|
||||
* Define editor-specific module interfaces and UI descriptor types.
|
||||
*
|
||||
* IEditorModuleLoader 扩展自 engine-core 的 IEditorModuleBase。
|
||||
* IEditorModuleLoader extends IEditorModuleBase from engine-core.
|
||||
*/
|
||||
|
||||
import type { ServiceContainer } from '@esengine/ecs-framework';
|
||||
|
||||
// 从 PluginDescriptor 重新导出(来源于 engine-core)
|
||||
// 统一从 engine-core 导入所有类型,避免直接依赖 plugin-types
|
||||
export type {
|
||||
LoadingPhase,
|
||||
SystemContext,
|
||||
@@ -17,7 +19,8 @@ export type {
|
||||
ModuleManifest,
|
||||
ModuleCategory,
|
||||
ModulePlatform,
|
||||
ModuleExports
|
||||
ModuleExports,
|
||||
IEditorModuleBase
|
||||
} from './PluginDescriptor';
|
||||
|
||||
// ============================================================================
|
||||
@@ -219,23 +222,23 @@ export interface FileCreationTemplate {
|
||||
// 编辑器模块接口 | Editor Module Interface
|
||||
// ============================================================================
|
||||
|
||||
import type { IEditorModuleBase } from './PluginDescriptor';
|
||||
|
||||
/**
|
||||
* 编辑器模块加载器
|
||||
* Editor module loader
|
||||
*
|
||||
* 扩展 IEditorModuleBase 并添加编辑器特定的 UI 描述符方法。
|
||||
* Extends IEditorModuleBase and adds editor-specific UI descriptor methods.
|
||||
*
|
||||
* 生命周期方法继承自 IEditorModuleBase:
|
||||
* Lifecycle methods inherited from IEditorModuleBase:
|
||||
* - install(services) / uninstall()
|
||||
* - onEditorReady() / onProjectOpen() / onProjectClose()
|
||||
* - onSceneLoaded() / onSceneSaving()
|
||||
* - setLocale()
|
||||
*/
|
||||
export interface IEditorModuleLoader {
|
||||
/**
|
||||
* 安装编辑器模块
|
||||
* Install editor module
|
||||
*/
|
||||
install(services: ServiceContainer): Promise<void>;
|
||||
|
||||
/**
|
||||
* 卸载编辑器模块
|
||||
* Uninstall editor module
|
||||
*/
|
||||
uninstall?(): Promise<void>;
|
||||
|
||||
export interface IEditorModuleLoader extends IEditorModuleBase {
|
||||
/**
|
||||
* 返回面板描述列表
|
||||
* Get panel descriptors
|
||||
@@ -289,44 +292,38 @@ export interface IEditorModuleLoader {
|
||||
* Get file creation templates
|
||||
*/
|
||||
getFileCreationTemplates?(): FileCreationTemplate[];
|
||||
|
||||
// ===== 生命周期钩子 | Lifecycle hooks =====
|
||||
|
||||
/** 编辑器就绪 | Editor ready */
|
||||
onEditorReady?(): void | Promise<void>;
|
||||
|
||||
/** 项目打开 | Project open */
|
||||
onProjectOpen?(projectPath: string): void | Promise<void>;
|
||||
|
||||
/** 项目关闭 | Project close */
|
||||
onProjectClose?(): void | Promise<void>;
|
||||
|
||||
/** 场景加载 | Scene loaded */
|
||||
onSceneLoaded?(scenePath: string): void;
|
||||
|
||||
/** 场景保存前 | Before scene save */
|
||||
onSceneSaving?(scenePath: string): boolean | void;
|
||||
|
||||
/** 设置语言 | Set locale */
|
||||
setLocale?(locale: string): void;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 类型别名(向后兼容)| Type Aliases (backward compatibility)
|
||||
// 编辑器插件类型 | Editor Plugin Type
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* IPluginLoader 类型别名
|
||||
*
|
||||
* @deprecated 使用 IPlugin 代替。IPluginLoader 只是 IPlugin 的别名。
|
||||
* @deprecated Use IPlugin instead. IPluginLoader is just an alias for IPlugin.
|
||||
*/
|
||||
export type { IPlugin as IPluginLoader } from './PluginDescriptor';
|
||||
import type { IPlugin } from './PluginDescriptor';
|
||||
|
||||
/**
|
||||
* IRuntimeModuleLoader 类型别名
|
||||
* 编辑器插件类型
|
||||
* Editor plugin type
|
||||
*
|
||||
* @deprecated 使用 IRuntimeModule 代替。
|
||||
* @deprecated Use IRuntimeModule instead.
|
||||
* 这是开发编辑器插件时应使用的类型。
|
||||
* 它是 IPlugin 的特化版本,editorModule 类型为 IEditorModuleLoader。
|
||||
*
|
||||
* This is the type to use when developing editor plugins.
|
||||
* It's a specialized version of IPlugin with editorModule typed as IEditorModuleLoader.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* import { IEditorPlugin, IEditorModuleLoader } from '@esengine/editor-core';
|
||||
*
|
||||
* class MyEditorModule implements IEditorModuleLoader {
|
||||
* async install(services) { ... }
|
||||
* getPanels() { return [...]; }
|
||||
* }
|
||||
*
|
||||
* export const MyPlugin: IEditorPlugin = {
|
||||
* manifest,
|
||||
* runtimeModule: new MyRuntimeModule(),
|
||||
* editorModule: new MyEditorModule()
|
||||
* };
|
||||
* ```
|
||||
*/
|
||||
export type { IRuntimeModule as IRuntimeModuleLoader } from './PluginDescriptor';
|
||||
export type IEditorPlugin = IPlugin<IEditorModuleLoader>;
|
||||
@@ -7,6 +7,7 @@
|
||||
*/
|
||||
|
||||
// 从 engine-core 重新导出所有类型
|
||||
// 包括 IEditorModuleBase(原来在 plugin-types 中定义,现在统一从 engine-core 导出)
|
||||
export type {
|
||||
LoadingPhase,
|
||||
SystemContext,
|
||||
@@ -15,7 +16,8 @@ export type {
|
||||
ModuleManifest,
|
||||
ModuleCategory,
|
||||
ModulePlatform,
|
||||
ModuleExports
|
||||
ModuleExports,
|
||||
IEditorModuleBase
|
||||
} from '@esengine/engine-core';
|
||||
|
||||
/**
|
||||
|
||||
@@ -14,7 +14,7 @@ import type {
|
||||
import type {
|
||||
SystemContext,
|
||||
IEditorModuleLoader
|
||||
} from './IPluginLoader';
|
||||
} from './EditorModule';
|
||||
import { EntityCreationRegistry } from '../Services/EntityCreationRegistry';
|
||||
import { ComponentActionRegistry } from '../Services/ComponentActionRegistry';
|
||||
import { FileActionRegistry } from '../Services/FileActionRegistry';
|
||||
@@ -821,22 +821,18 @@ export class PluginManager implements IService {
|
||||
this.currentContext = context;
|
||||
|
||||
logger.info('Creating systems for scene...');
|
||||
console.log('[PluginManager] createSystemsForScene called, context.assetManager:', context.assetManager ? 'exists' : 'null');
|
||||
|
||||
const sortedPlugins = this.sortByLoadingPhase('runtime');
|
||||
console.log('[PluginManager] Sorted plugins for runtime:', sortedPlugins);
|
||||
|
||||
// 第一阶段:创建所有系统
|
||||
// Phase 1: Create all systems
|
||||
for (const pluginId of sortedPlugins) {
|
||||
const plugin = this.plugins.get(pluginId);
|
||||
console.log(`[PluginManager] Plugin ${pluginId}: enabled=${plugin?.enabled}, state=${plugin?.state}, hasRuntimeModule=${!!plugin?.plugin.runtimeModule}`);
|
||||
if (!plugin?.enabled || plugin.state === 'error') continue;
|
||||
|
||||
const runtimeModule = plugin.plugin.runtimeModule;
|
||||
if (runtimeModule?.createSystems) {
|
||||
try {
|
||||
console.log(`[PluginManager] Calling createSystems for: ${pluginId}`);
|
||||
runtimeModule.createSystems(scene, context);
|
||||
logger.debug(`Systems created for: ${pluginId}`);
|
||||
} catch (e) {
|
||||
|
||||
@@ -4,5 +4,5 @@
|
||||
*/
|
||||
|
||||
export * from './PluginDescriptor';
|
||||
export * from './IPluginLoader';
|
||||
export * from './EditorModule';
|
||||
export * from './PluginManager';
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
* Uses .meta files to persistently store each asset's GUID.
|
||||
*/
|
||||
|
||||
import { Core, createLogger, PlatformDetector } from '@esengine/ecs-framework';
|
||||
import { Core, createLogger, PlatformDetector, type IService } from '@esengine/ecs-framework';
|
||||
import { MessageHub } from './MessageHub';
|
||||
import {
|
||||
AssetMetaManager,
|
||||
@@ -219,8 +219,12 @@ class SimpleAssetDatabase {
|
||||
|
||||
/**
|
||||
* Asset Registry Service
|
||||
* 资产注册表服务
|
||||
*
|
||||
* 实现 IService 接口以便与 ServiceContainer 集成
|
||||
* Implements IService interface for ServiceContainer integration
|
||||
*/
|
||||
export class AssetRegistryService {
|
||||
export class AssetRegistryService implements IService {
|
||||
private _database: SimpleAssetDatabase;
|
||||
private _projectPath: string | null = null;
|
||||
private _manifest: AssetManifest | null = null;
|
||||
|
||||
@@ -6,9 +6,9 @@
|
||||
|
||||
import { injectable } from 'tsyringe';
|
||||
import type { IService } from '@esengine/ecs-framework';
|
||||
import type { ComponentAction } from '../Plugin/IPluginLoader';
|
||||
import type { ComponentAction } from '../Plugin/EditorModule';
|
||||
// Re-export ComponentAction type from Plugin system
|
||||
export type { ComponentAction } from '../Plugin/IPluginLoader';
|
||||
export type { ComponentAction } from '../Plugin/EditorModule';
|
||||
|
||||
@injectable()
|
||||
export class ComponentActionRegistry implements IService {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { IService } from '@esengine/ecs-framework';
|
||||
import type { FileActionHandler, FileCreationTemplate } from '../Plugin/IPluginLoader';
|
||||
import type { FileActionHandler, FileCreationTemplate } from '../Plugin/EditorModule';
|
||||
|
||||
// Re-export for backwards compatibility
|
||||
export type { FileCreationTemplate } from '../Plugin/IPluginLoader';
|
||||
export type { FileCreationTemplate } from '../Plugin/EditorModule';
|
||||
|
||||
/**
|
||||
* 资产创建消息映射
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { IService } from '@esengine/ecs-framework';
|
||||
import { Injectable } from '@esengine/ecs-framework';
|
||||
import { createLogger } from '@esengine/ecs-framework';
|
||||
import type { ISerializer } from '../Plugin/IPluginLoader';
|
||||
import type { ISerializer } from '../Plugin/EditorModule';
|
||||
|
||||
const logger = createLogger('SerializerRegistry');
|
||||
|
||||
|
||||
@@ -89,7 +89,7 @@ export interface ToolbarItem {
|
||||
}
|
||||
|
||||
// Re-export PanelPosition and PanelDescriptor from Plugin system
|
||||
export { PanelPosition, type PanelDescriptor } from '../Plugin/IPluginLoader';
|
||||
export { PanelPosition, type PanelDescriptor } from '../Plugin/EditorModule';
|
||||
|
||||
/**
|
||||
* UI 扩展点类型
|
||||
@@ -103,4 +103,4 @@ export enum UIExtensionType {
|
||||
}
|
||||
|
||||
// Re-export EntityCreationTemplate from Plugin system
|
||||
export type { EntityCreationTemplate } from '../Plugin/IPluginLoader';
|
||||
export type { EntityCreationTemplate } from '../Plugin/EditorModule';
|
||||
|
||||
@@ -196,9 +196,8 @@ export type {
|
||||
ComponentAction,
|
||||
|
||||
// Plugin system types
|
||||
IPluginLoader,
|
||||
IRuntimeModuleLoader,
|
||||
IEditorModuleLoader,
|
||||
IEditorPlugin,
|
||||
ModuleManifest,
|
||||
ModuleCategory,
|
||||
ModulePlatform,
|
||||
|
||||
@@ -29,7 +29,8 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@esengine/ecs-framework": "workspace:*",
|
||||
"@esengine/platform-common": "workspace:*"
|
||||
"@esengine/platform-common": "workspace:*",
|
||||
"@esengine/plugin-types": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@esengine/build-config": "workspace:*",
|
||||
|
||||
@@ -2,14 +2,43 @@
|
||||
* 插件系统核心类型定义
|
||||
* Plugin system core type definitions
|
||||
*
|
||||
* 这是插件类型的唯一定义源,editor-core 重新导出并扩展这些类型。
|
||||
* This is the single source of truth for plugin types. editor-core re-exports and extends them.
|
||||
* 这是运行时插件类型的唯一定义源。
|
||||
* 编辑器类型在 editor-core 中扩展这些类型。
|
||||
*
|
||||
* This is the single source of truth for runtime plugin types.
|
||||
* Editor types extend these in editor-core.
|
||||
*
|
||||
* @see docs/architecture/plugin-system-design.md
|
||||
*/
|
||||
|
||||
import type { ComponentRegistry as ComponentRegistryType, IScene, ServiceContainer } from '@esengine/ecs-framework';
|
||||
import { TransformComponent } from './TransformComponent';
|
||||
import type { ModuleManifest } from './ModuleManifest';
|
||||
|
||||
// 从本地模块导入服务令牌系统(确保 tsup 生成的类型以 engine-core 为源)
|
||||
// Import service token system from local module (ensures tsup generates types with engine-core as source)
|
||||
import {
|
||||
PluginServiceRegistry,
|
||||
createServiceToken,
|
||||
TransformTypeToken,
|
||||
type ServiceToken
|
||||
} from './PluginServiceRegistry';
|
||||
|
||||
// 导出服务令牌系统 | Export service token system
|
||||
export {
|
||||
PluginServiceRegistry,
|
||||
createServiceToken,
|
||||
TransformTypeToken,
|
||||
type ServiceToken
|
||||
};
|
||||
|
||||
// 重新导出 IEditorModuleBase(供编辑器插件使用)| Re-export for editor plugins
|
||||
export type { IEditorModuleBase } from '@esengine/plugin-types';
|
||||
|
||||
// ============================================================================
|
||||
// 加载阶段 | Loading Phase
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* 加载阶段 - 控制插件模块的加载顺序
|
||||
* Loading phase - controls the loading order of plugin modules
|
||||
@@ -28,16 +57,38 @@ export type LoadingPhase =
|
||||
/**
|
||||
* 系统创建上下文
|
||||
* System creation context
|
||||
*
|
||||
* 包含运行时配置和插件服务注册表。
|
||||
* Contains runtime configuration and plugin service registry.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* // 导入需要的 Token | Import needed tokens
|
||||
* import { Physics2DQueryToken } from '@esengine/physics-rapier2d';
|
||||
* import { AssetManagerToken } from '@esengine/asset-system';
|
||||
*
|
||||
* // 注册服务 | Register service
|
||||
* context.services.register(Physics2DQueryToken, physicsSystem);
|
||||
*
|
||||
* // 获取服务(可选)| Get service (optional)
|
||||
* const physics = context.services.get(Physics2DQueryToken);
|
||||
*
|
||||
* // 获取服务(必需)| Get service (required)
|
||||
* const physics = context.services.require(Physics2DQueryToken);
|
||||
* ```
|
||||
*/
|
||||
export interface SystemContext {
|
||||
/** 是否为编辑器模式 | Is editor mode */
|
||||
isEditor: boolean;
|
||||
/** 引擎桥接(如有) | Engine bridge (if available) */
|
||||
engineBridge?: any;
|
||||
/** 渲染系统(如有) | Render system (if available) */
|
||||
renderSystem?: any;
|
||||
/** 其他已创建的系统引用 | Other created system references */
|
||||
[key: string]: any;
|
||||
readonly isEditor: boolean;
|
||||
|
||||
/**
|
||||
* 插件服务注册表
|
||||
* Plugin service registry
|
||||
*
|
||||
* 用于跨插件共享服务。
|
||||
* For sharing services between plugins.
|
||||
*/
|
||||
readonly services: PluginServiceRegistry;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
@@ -95,15 +146,41 @@ export interface IRuntimeModule {
|
||||
* Plugin interface
|
||||
*
|
||||
* 这是所有插件包导出的统一类型。
|
||||
* 使用泛型允许编辑器模块使用更具体的类型。
|
||||
*
|
||||
* This is the unified type that all plugin packages export.
|
||||
* Uses generics to allow editor modules to use more specific types.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* // 纯运行时插件 | Pure runtime plugin
|
||||
* const MyPlugin: IPlugin = {
|
||||
* manifest,
|
||||
* runtimeModule: new MyRuntimeModule()
|
||||
* };
|
||||
*
|
||||
* // 编辑器插件(在 editor-core 中定义 IEditorPlugin)
|
||||
* // Editor plugin (IEditorPlugin defined in editor-core)
|
||||
* const MyEditorPlugin: IEditorPlugin = {
|
||||
* manifest,
|
||||
* runtimeModule: new MyRuntimeModule(),
|
||||
* editorModule: new MyEditorModule()
|
||||
* };
|
||||
* ```
|
||||
*/
|
||||
export interface IPlugin {
|
||||
export interface IPlugin<TEditorModule = unknown> {
|
||||
/** 模块清单 | Module manifest */
|
||||
readonly manifest: ModuleManifest;
|
||||
/** 运行时模块(可选) | Runtime module (optional) */
|
||||
readonly runtimeModule?: IRuntimeModule;
|
||||
/** 编辑器模块(可选,类型为 any 以避免循环依赖) | Editor module (optional, typed as any to avoid circular deps) */
|
||||
readonly editorModule?: any;
|
||||
/**
|
||||
* 编辑器模块(可选)
|
||||
* Editor module (optional)
|
||||
*
|
||||
* 泛型参数允许 editor-core 使用 IEditorModuleLoader 类型。
|
||||
* Generic parameter allows editor-core to use IEditorModuleLoader type.
|
||||
*/
|
||||
readonly editorModule?: TEditorModule;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
/**
|
||||
* 插件服务注册表
|
||||
* Plugin Service Registry
|
||||
*
|
||||
* 这个文件重新定义(不是 re-export)ServiceToken 和 PluginServiceRegistry,
|
||||
* 以确保 tsup/rollup-plugin-dts 生成的类型声明使用 engine-core 作为类型来源,
|
||||
* 而不是追踪到 plugin-types(会导致跨包类型不兼容)。
|
||||
*
|
||||
* This file re-defines (not re-exports) ServiceToken and PluginServiceRegistry,
|
||||
* to ensure tsup/rollup-plugin-dts generated type declarations use engine-core
|
||||
* as the type source, instead of tracing back to plugin-types (which causes
|
||||
* cross-package type incompatibility).
|
||||
*
|
||||
* 设计原则 | Design principles:
|
||||
* 1. 类型安全 - 使用 ServiceToken 携带类型信息
|
||||
* 2. 显式依赖 - 通过导入 token 明确表达依赖关系
|
||||
* 3. 可选依赖 - get 返回 undefined,require 抛异常
|
||||
* 4. 单一职责 - 只负责服务注册和查询,不涉及生命周期管理
|
||||
* 5. 谁定义接口,谁导出 Token - 各模块定义自己的接口和 Token
|
||||
* 6. 单一类型来源 - 所有包从 engine-core 导入类型,不直接使用 plugin-types
|
||||
*/
|
||||
|
||||
// ============================================================================
|
||||
// 服务令牌 | Service Token
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* 服务令牌接口
|
||||
* Service token interface
|
||||
*
|
||||
* 用于类型安全的服务注册和获取。
|
||||
* For type-safe service registration and retrieval.
|
||||
*
|
||||
* 注意:__phantom 是必需属性,确保 TypeScript 在跨包类型解析时保留泛型类型信息。
|
||||
* Note: __phantom is a required property to ensure TypeScript preserves generic
|
||||
* type information across packages.
|
||||
*/
|
||||
export interface ServiceToken<T> {
|
||||
readonly id: symbol;
|
||||
readonly name: string;
|
||||
/**
|
||||
* Phantom type 标记(强制类型推断)
|
||||
* Phantom type marker (enforces type inference)
|
||||
*/
|
||||
readonly __phantom: T;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建服务令牌
|
||||
* Create a service token
|
||||
*
|
||||
* @param name 令牌名称 | Token name
|
||||
* @returns 服务令牌 | Service token
|
||||
*/
|
||||
export function createServiceToken<T>(name: string): ServiceToken<T> {
|
||||
// __phantom 仅用于类型推断,运行时不需要实际值
|
||||
// __phantom is only for type inference, no actual value needed at runtime
|
||||
return {
|
||||
id: Symbol(name),
|
||||
name
|
||||
} as ServiceToken<T>;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 插件服务注册表 | Plugin Service Registry
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* 插件服务注册表
|
||||
* Plugin service registry
|
||||
*
|
||||
* 用于跨插件共享服务的类型安全注册表。
|
||||
* Type-safe registry for sharing services between plugins.
|
||||
*/
|
||||
export class PluginServiceRegistry {
|
||||
private _services = new Map<symbol, unknown>();
|
||||
|
||||
/**
|
||||
* 注册服务
|
||||
* Register a service
|
||||
*/
|
||||
register<T>(token: ServiceToken<T>, service: T): void {
|
||||
this._services.set(token.id, service);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取服务(可选)
|
||||
* Get a service (optional)
|
||||
*/
|
||||
get<T>(token: ServiceToken<T>): T | undefined {
|
||||
return this._services.get(token.id) as T | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取服务(必需)
|
||||
* Get a service (required)
|
||||
*
|
||||
* @throws 如果服务未注册 | If service is not registered
|
||||
*/
|
||||
require<T>(token: ServiceToken<T>): T {
|
||||
const service = this._services.get(token.id);
|
||||
if (service === undefined) {
|
||||
throw new Error(`Service not found: ${token.name}`);
|
||||
}
|
||||
return service as T;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查服务是否已注册
|
||||
* Check if a service is registered
|
||||
*/
|
||||
has<T>(token: ServiceToken<T>): boolean {
|
||||
return this._services.has(token.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 注销服务
|
||||
* Unregister a service
|
||||
*/
|
||||
unregister<T>(token: ServiceToken<T>): boolean {
|
||||
return this._services.delete(token.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空所有服务
|
||||
* Clear all services
|
||||
*/
|
||||
clear(): void {
|
||||
this._services.clear();
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// engine-core 内部 Token | engine-core Internal Tokens
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Transform 组件类型 | Transform component type
|
||||
*
|
||||
* 使用 any 类型以允许各模块使用自己的 ITransformComponent 接口定义。
|
||||
* Using any type to allow modules to use their own ITransformComponent interface definition.
|
||||
*
|
||||
* 这是 engine-core 自己定义的 Token,因为 TransformComponent 在此模块中定义。
|
||||
* This is a Token defined by engine-core itself, as TransformComponent is defined in this module.
|
||||
*/
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
export const TransformTypeToken = createServiceToken<new (...args: any[]) => any>('transformType');
|
||||
@@ -4,11 +4,18 @@ export { HierarchyComponent } from './HierarchyComponent';
|
||||
export { HierarchySystem } from './HierarchySystem';
|
||||
export {
|
||||
EnginePlugin,
|
||||
// 类型导出
|
||||
// Type exports
|
||||
type LoadingPhase,
|
||||
type SystemContext,
|
||||
type IRuntimeModule,
|
||||
type IPlugin
|
||||
type IPlugin,
|
||||
// Plugin service registry (defined locally in PluginServiceRegistry.ts)
|
||||
PluginServiceRegistry,
|
||||
createServiceToken,
|
||||
TransformTypeToken,
|
||||
// Types
|
||||
type ServiceToken,
|
||||
type IEditorModuleBase
|
||||
} from './EnginePlugin';
|
||||
|
||||
// Module Manifest types (unified module/plugin configuration)
|
||||
|
||||
@@ -13,7 +13,7 @@ import { Core } from '@esengine/ecs-framework';
|
||||
import type {
|
||||
IEditorModuleLoader,
|
||||
FileCreationTemplate,
|
||||
IPlugin,
|
||||
IEditorPlugin,
|
||||
ModuleManifest
|
||||
} from '@esengine/editor-core';
|
||||
import {
|
||||
@@ -259,7 +259,7 @@ const manifest: ModuleManifest = {
|
||||
/**
|
||||
* Complete Material Plugin (runtime + editor)
|
||||
*/
|
||||
export const MaterialPlugin: IPlugin = {
|
||||
export const MaterialPlugin: IEditorPlugin = {
|
||||
manifest,
|
||||
runtimeModule: new MaterialRuntimeModule(),
|
||||
editorModule: materialEditorModule
|
||||
|
||||
@@ -14,7 +14,7 @@ import type {
|
||||
ComponentInspectorProviderDef,
|
||||
FileActionHandler,
|
||||
FileCreationTemplate,
|
||||
IPlugin,
|
||||
IEditorPlugin,
|
||||
ModuleManifest
|
||||
} from '@esengine/editor-core';
|
||||
import {
|
||||
@@ -277,7 +277,7 @@ const manifest: ModuleManifest = {
|
||||
* 完整的粒子插件(运行时 + 编辑器)
|
||||
* Complete Particle Plugin (runtime + editor)
|
||||
*/
|
||||
export const ParticlePlugin: IPlugin = {
|
||||
export const ParticlePlugin: IEditorPlugin = {
|
||||
manifest,
|
||||
runtimeModule: new ParticleRuntimeModule(),
|
||||
editorModule: particleEditorModule
|
||||
|
||||
@@ -42,6 +42,7 @@
|
||||
"@esengine/ecs-framework": "workspace:*",
|
||||
"@esengine/ecs-framework-math": "workspace:*",
|
||||
"@esengine/engine-core": "workspace:*",
|
||||
"@esengine/ecs-engine-bindgen": "workspace:*",
|
||||
"@esengine/physics-rapier2d": "workspace:*",
|
||||
"@esengine/build-config": "workspace:*",
|
||||
"rimraf": "^5.0.5",
|
||||
|
||||
@@ -62,8 +62,23 @@ export interface Particle {
|
||||
/** 初始透明度 | Initial alpha */
|
||||
startAlpha: number;
|
||||
|
||||
// ============= 模块运行时状态 | Module Runtime State =============
|
||||
// 这些字段由各模块在运行时设置 | These fields are set by modules at runtime
|
||||
|
||||
/** 初始速度X(VelocityOverLifetimeModule 使用)| Initial velocity X (used by VelocityOverLifetimeModule) */
|
||||
startVx?: number;
|
||||
/** 初始速度Y(VelocityOverLifetimeModule 使用)| Initial velocity Y (used by VelocityOverLifetimeModule) */
|
||||
startVy?: number;
|
||||
|
||||
/** 动画帧索引(TextureSheetAnimationModule 使用)| Animation frame index (used by TextureSheetAnimationModule) */
|
||||
_animFrame?: number;
|
||||
/** 动画图块列数(TextureSheetAnimationModule 使用)| Animation tiles X (used by TextureSheetAnimationModule) */
|
||||
_animTilesX?: number;
|
||||
/** 动画图块行数(TextureSheetAnimationModule 使用)| Animation tiles Y (used by TextureSheetAnimationModule) */
|
||||
_animTilesY?: number;
|
||||
|
||||
/** 自定义数据槽 | Custom data slot */
|
||||
userData?: any;
|
||||
userData?: unknown;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,60 +1,19 @@
|
||||
import type { ComponentRegistry as ComponentRegistryType, IScene } from '@esengine/ecs-framework';
|
||||
import type { IRuntimeModule, IPlugin, ModuleManifest, SystemContext } from '@esengine/engine-core';
|
||||
import { assetManager as globalAssetManager, type AssetManager } from '@esengine/asset-system';
|
||||
import { TransformTypeToken } from '@esengine/engine-core';
|
||||
import { AssetManagerToken } from '@esengine/asset-system';
|
||||
import { RenderSystemToken, EngineBridgeToken, EngineIntegrationToken } from '@esengine/ecs-engine-bindgen';
|
||||
import { Physics2DQueryToken } from '@esengine/physics-rapier2d';
|
||||
import { assetManager as globalAssetManager } from '@esengine/asset-system';
|
||||
import { ParticleSystemComponent } from './ParticleSystemComponent';
|
||||
import { ParticleUpdateSystem } from './systems/ParticleSystem';
|
||||
import { ParticleLoader, ParticleAssetType } from './loaders/ParticleLoader';
|
||||
import type { IPhysics2DQuery } from './modules/Physics2DCollisionModule';
|
||||
import { ParticleUpdateSystemToken } from './tokens';
|
||||
|
||||
export type { SystemContext, ModuleManifest, IRuntimeModule as IRuntimeModuleLoader, IPlugin as IPluginLoader };
|
||||
export type { SystemContext, ModuleManifest, IRuntimeModule, IPlugin };
|
||||
|
||||
/**
|
||||
* 引擎桥接接口(用于直接加载纹理)
|
||||
* Engine bridge interface (for direct texture loading)
|
||||
*/
|
||||
export interface IEngineBridge {
|
||||
loadTexture(id: number, url: string): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 引擎集成接口(用于加载纹理)
|
||||
* Engine integration interface (for loading textures)
|
||||
*/
|
||||
export interface IEngineIntegration {
|
||||
loadTextureForComponent(texturePath: string): Promise<number>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 粒子系统上下文
|
||||
* Particle system context
|
||||
*/
|
||||
export interface ParticleSystemContext extends SystemContext {
|
||||
particleUpdateSystem?: ParticleUpdateSystem;
|
||||
/** Transform 组件类型 | Transform component type */
|
||||
transformType?: new (...args: any[]) => any;
|
||||
/** 渲染系统(用于注册渲染数据提供者)| Render system (for registering render data provider) */
|
||||
renderSystem?: {
|
||||
addRenderDataProvider(provider: any): void;
|
||||
removeRenderDataProvider(provider: any): void;
|
||||
};
|
||||
/** 引擎集成(用于加载纹理)| Engine integration (for loading textures) */
|
||||
engineIntegration?: IEngineIntegration;
|
||||
/** 引擎桥接(用于直接加载纹理)| Engine bridge (for direct texture loading) */
|
||||
engineBridge?: IEngineBridge;
|
||||
/** 资产管理器(用于注册加载器)| Asset manager (for registering loaders) */
|
||||
assetManager?: AssetManager;
|
||||
/**
|
||||
* 2D 物理查询接口(可选)
|
||||
* 2D Physics query interface (optional)
|
||||
*
|
||||
* 如果提供,将自动注入到使用 Physics2DCollisionModule 的粒子系统中。
|
||||
* 通常传入 Physics2DService 实例。
|
||||
*
|
||||
* If provided, will be auto-injected into particle systems using Physics2DCollisionModule.
|
||||
* Typically pass a Physics2DService instance.
|
||||
*/
|
||||
physics2DQuery?: IPhysics2DQuery;
|
||||
}
|
||||
// 重新导出 tokens | Re-export tokens
|
||||
export { ParticleUpdateSystemToken } from './tokens';
|
||||
|
||||
class ParticleRuntimeModule implements IRuntimeModule {
|
||||
private _updateSystem: ParticleUpdateSystem | null = null;
|
||||
@@ -65,7 +24,13 @@ class ParticleRuntimeModule implements IRuntimeModule {
|
||||
}
|
||||
|
||||
createSystems(scene: IScene, context: SystemContext): void {
|
||||
const particleContext = context as ParticleSystemContext;
|
||||
// 从服务注册表获取依赖 | Get dependencies from service registry
|
||||
const assetManager = context.services.get(AssetManagerToken);
|
||||
const transformType = context.services.get(TransformTypeToken);
|
||||
const engineIntegration = context.services.get(EngineIntegrationToken);
|
||||
const engineBridge = context.services.get(EngineBridgeToken);
|
||||
const physics2DQuery = context.services.get(Physics2DQueryToken);
|
||||
const renderSystem = context.services.get(RenderSystemToken);
|
||||
|
||||
// 注册粒子资产加载器到上下文的 assetManager 和全局单例
|
||||
// Register particle asset loader to context assetManager AND global singleton
|
||||
@@ -73,13 +38,13 @@ class ParticleRuntimeModule implements IRuntimeModule {
|
||||
const loader = new ParticleLoader();
|
||||
|
||||
// Register to context's assetManager (used by GameRuntime)
|
||||
if (particleContext.assetManager) {
|
||||
particleContext.assetManager.registerLoader(ParticleAssetType as any, loader);
|
||||
if (assetManager) {
|
||||
assetManager.registerLoader(ParticleAssetType, loader);
|
||||
}
|
||||
|
||||
// Also register to global singleton (used by ParticleSystemComponent.loadAsset)
|
||||
// 同时注册到全局单例(ParticleSystemComponent.loadAsset 使用的是全局单例)
|
||||
globalAssetManager.registerLoader(ParticleAssetType as any, loader);
|
||||
globalAssetManager.registerLoader(ParticleAssetType, loader);
|
||||
|
||||
this._loaderRegistered = true;
|
||||
console.log('[ParticleRuntimeModule] Registered ParticleLoader to both context and global assetManager');
|
||||
@@ -88,32 +53,34 @@ class ParticleRuntimeModule implements IRuntimeModule {
|
||||
this._updateSystem = new ParticleUpdateSystem();
|
||||
|
||||
// 设置 Transform 组件类型 | Set Transform component type
|
||||
if (particleContext.transformType) {
|
||||
this._updateSystem.setTransformType(particleContext.transformType);
|
||||
if (transformType) {
|
||||
this._updateSystem.setTransformType(transformType);
|
||||
}
|
||||
|
||||
// 设置引擎集成(用于加载纹理)| Set engine integration (for loading textures)
|
||||
if (particleContext.engineIntegration) {
|
||||
this._updateSystem.setEngineIntegration(particleContext.engineIntegration);
|
||||
if (engineIntegration) {
|
||||
this._updateSystem.setEngineIntegration(engineIntegration);
|
||||
}
|
||||
|
||||
// 设置引擎桥接(用于加载默认纹理)| Set engine bridge (for loading default texture)
|
||||
if (particleContext.engineBridge) {
|
||||
this._updateSystem.setEngineBridge(particleContext.engineBridge);
|
||||
if (engineBridge) {
|
||||
this._updateSystem.setEngineBridge(engineBridge);
|
||||
}
|
||||
|
||||
// 设置 2D 物理查询(用于粒子与场景碰撞)| Set 2D physics query (for particle-scene collision)
|
||||
if (particleContext.physics2DQuery) {
|
||||
this._updateSystem.setPhysics2DQuery(particleContext.physics2DQuery);
|
||||
if (physics2DQuery) {
|
||||
this._updateSystem.setPhysics2DQuery(physics2DQuery);
|
||||
}
|
||||
|
||||
scene.addSystem(this._updateSystem);
|
||||
particleContext.particleUpdateSystem = this._updateSystem;
|
||||
|
||||
// 注册粒子更新系统到服务注册表 | Register particle update system to service registry
|
||||
context.services.register(ParticleUpdateSystemToken, this._updateSystem);
|
||||
|
||||
// 注册渲染数据提供者 | Register render data provider
|
||||
if (particleContext.renderSystem) {
|
||||
if (renderSystem) {
|
||||
const renderDataProvider = this._updateSystem.getRenderDataProvider();
|
||||
particleContext.renderSystem.addRenderDataProvider(renderDataProvider);
|
||||
renderSystem.addRenderDataProvider(renderDataProvider);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -91,4 +91,6 @@ export {
|
||||
|
||||
// Plugin
|
||||
export { ParticleRuntimeModule, ParticlePlugin } from './ParticleRuntimeModule';
|
||||
export type { ParticleSystemContext } from './ParticleRuntimeModule';
|
||||
|
||||
// Service tokens | 服务令牌
|
||||
export { ParticleUpdateSystemToken } from './tokens';
|
||||
|
||||
@@ -227,6 +227,9 @@ export class ParticleLoader implements IAssetLoader<IParticleAsset> {
|
||||
* Dispose loaded asset
|
||||
*/
|
||||
dispose(asset: IParticleAsset): void {
|
||||
(asset as any).modules = null;
|
||||
// 清理模块引用 | Clean up module references
|
||||
if (asset.modules) {
|
||||
asset.modules.length = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -201,11 +201,11 @@ export class CollisionModule implements IParticleModule {
|
||||
}
|
||||
|
||||
// 更新存储的初始速度(如果有速度曲线模块)| Update stored initial velocity
|
||||
if ('startVx' in p && normalX !== 0) {
|
||||
(p as any).startVx = -((p as any).startVx) * this.bounceFactor;
|
||||
if (p.startVx !== undefined && normalX !== 0) {
|
||||
p.startVx = -(p.startVx) * this.bounceFactor;
|
||||
}
|
||||
if ('startVy' in p && normalY !== 0) {
|
||||
(p as any).startVy = -((p as any).startVy) * this.bounceFactor;
|
||||
if (p.startVy !== undefined && normalY !== 0) {
|
||||
p.startVy = -(p.startVy) * this.bounceFactor;
|
||||
}
|
||||
|
||||
// 应用生命损失 | Apply life loss
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
import type { Particle } from '../Particle';
|
||||
import type { IParticleModule } from './IParticleModule';
|
||||
|
||||
// 从 physics-rapier2d 导入共享接口
|
||||
// Import shared interface from physics-rapier2d
|
||||
import type { IPhysics2DQuery } from '@esengine/physics-rapier2d';
|
||||
|
||||
// 重新导出以保持向后兼容
|
||||
// Re-export for backward compatibility
|
||||
export type { IPhysics2DQuery };
|
||||
|
||||
/**
|
||||
* 物理碰撞行为
|
||||
* Physics collision behavior
|
||||
@@ -14,53 +22,6 @@ export enum Physics2DCollisionBehavior {
|
||||
Stop = 'stop'
|
||||
}
|
||||
|
||||
/**
|
||||
* 物理查询接口
|
||||
* Physics query interface
|
||||
*
|
||||
* 抽象物理服务查询,避免直接依赖 physics-rapier2d 包
|
||||
* Abstract physics service query to avoid direct dependency on physics-rapier2d
|
||||
*/
|
||||
export interface IPhysics2DQuery {
|
||||
/**
|
||||
* 圆形重叠检测
|
||||
* Circle overlap detection
|
||||
*
|
||||
* @param center - 圆心位置 | Center position
|
||||
* @param radius - 半径 | Radius
|
||||
* @param collisionMask - 碰撞掩码 | Collision mask
|
||||
* @returns 重叠结果 | Overlap result
|
||||
*/
|
||||
overlapCircle(
|
||||
center: { x: number; y: number },
|
||||
radius: number,
|
||||
collisionMask?: number
|
||||
): { entityIds: number[]; colliderHandles: number[] };
|
||||
|
||||
/**
|
||||
* 射线检测
|
||||
* Raycast detection
|
||||
*
|
||||
* @param origin - 起点 | Origin
|
||||
* @param direction - 方向(归一化)| Direction (normalized)
|
||||
* @param maxDistance - 最大距离 | Max distance
|
||||
* @param collisionMask - 碰撞掩码 | Collision mask
|
||||
* @returns 射线结果或 null | Raycast result or null
|
||||
*/
|
||||
raycast(
|
||||
origin: { x: number; y: number },
|
||||
direction: { x: number; y: number },
|
||||
maxDistance: number,
|
||||
collisionMask?: number
|
||||
): {
|
||||
entityId: number;
|
||||
point: { x: number; y: number };
|
||||
normal: { x: number; y: number };
|
||||
distance: number;
|
||||
colliderHandle: number;
|
||||
} | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 碰撞回调数据
|
||||
* Collision callback data
|
||||
|
||||
@@ -219,14 +219,10 @@ export class TextureSheetAnimationModule implements IParticleModule {
|
||||
const u1 = u0 + uWidth;
|
||||
const v1 = v0 + vHeight;
|
||||
|
||||
// 存储 UV 到粒子的自定义属性
|
||||
// Store UV in particle's custom properties
|
||||
// 这里我们使用粒子的 startR/startG/startB 不太合适,需要扩展 Particle
|
||||
// 暂时通过覆盖 rotation 的高位来存储帧索引(临时方案)
|
||||
// Temporary: store frame index in a way that can be read by renderer
|
||||
// The actual UV calculation will be done in the render data provider
|
||||
(p as any)._animFrame = frameIndex;
|
||||
(p as any)._animTilesX = this.tilesX;
|
||||
(p as any)._animTilesY = this.tilesY;
|
||||
// 存储动画帧信息到粒子 | Store animation frame info to particle
|
||||
// 渲染数据提供者会使用这些值计算实际的 UV | Render data provider will use these to calculate actual UVs
|
||||
p._animFrame = frameIndex;
|
||||
p._animTilesX = this.tilesX;
|
||||
p._animTilesY = this.tilesY;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,13 +78,13 @@ export class VelocityOverLifetimeModule implements IParticleModule {
|
||||
|
||||
// 应用速度乘数到当前速度 | Apply multiplier to current velocity
|
||||
// 我们需要存储初始速度来正确应用曲线 | We need to store initial velocity to properly apply curve
|
||||
if (!('startVx' in p)) {
|
||||
(p as any).startVx = p.vx;
|
||||
(p as any).startVy = p.vy;
|
||||
if (p.startVx === undefined) {
|
||||
p.startVx = p.vx;
|
||||
p.startVy = p.vy;
|
||||
}
|
||||
|
||||
const startVx = (p as any).startVx;
|
||||
const startVy = (p as any).startVy;
|
||||
const startVx = p.startVx!;
|
||||
const startVy = p.startVy!;
|
||||
|
||||
// 应用曲线乘数 | Apply curve multiplier
|
||||
p.vx = startVx * multiplier;
|
||||
@@ -96,8 +96,8 @@ export class VelocityOverLifetimeModule implements IParticleModule {
|
||||
p.vx *= dragFactor;
|
||||
p.vy *= dragFactor;
|
||||
// 更新存储的起始速度以反映阻力 | Update stored start velocity to reflect drag
|
||||
(p as any).startVx *= dragFactor;
|
||||
(p as any).startVy *= dragFactor;
|
||||
p.startVx = startVx * dragFactor;
|
||||
p.startVy = startVy * dragFactor;
|
||||
}
|
||||
|
||||
// 附加速度 | Additional velocity
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { EntitySystem, Matcher, ECSSystem, Time, Entity } from '@esengine/ecs-framework';
|
||||
import { EntitySystem, Matcher, ECSSystem, Time, Entity, type Component, type ComponentType } from '@esengine/ecs-framework';
|
||||
import type { IEngineIntegration, IEngineBridge } from '@esengine/ecs-engine-bindgen';
|
||||
import { ParticleSystemComponent } from '../ParticleSystemComponent';
|
||||
import { ParticleRenderDataProvider } from '../rendering/ParticleRenderDataProvider';
|
||||
import type { IEngineIntegration, IEngineBridge } from '../ParticleRuntimeModule';
|
||||
import { Physics2DCollisionModule, type IPhysics2DQuery } from '../modules/Physics2DCollisionModule';
|
||||
|
||||
/**
|
||||
@@ -66,7 +66,8 @@ interface ITransformComponent {
|
||||
*/
|
||||
@ECSSystem('ParticleUpdate', { updateOrder: 100 })
|
||||
export class ParticleUpdateSystem extends EntitySystem {
|
||||
private _transformType: (new (...args: any[]) => ITransformComponent) | null = null;
|
||||
/** Transform 组件类型(运行时注入)| Transform component type (injected at runtime) */
|
||||
private _transformType: ComponentType<Component & ITransformComponent> | null = null;
|
||||
private _renderDataProvider: ParticleRenderDataProvider;
|
||||
private _engineIntegration: IEngineIntegration | null = null;
|
||||
private _engineBridge: IEngineBridge | null = null;
|
||||
@@ -91,7 +92,7 @@ export class ParticleUpdateSystem extends EntitySystem {
|
||||
*
|
||||
* @param transformType - Transform component class | Transform 组件类
|
||||
*/
|
||||
setTransformType(transformType: new (...args: any[]) => ITransformComponent): void {
|
||||
setTransformType(transformType: ComponentType<Component & ITransformComponent>): void {
|
||||
this._transformType = transformType;
|
||||
}
|
||||
|
||||
@@ -150,7 +151,7 @@ export class ParticleUpdateSystem extends EntitySystem {
|
||||
|
||||
// 获取 Transform 位置、旋转、缩放 | Get Transform position, rotation, scale
|
||||
if (this._transformType) {
|
||||
transform = entity.getComponent(this._transformType as any) as ITransformComponent | null;
|
||||
transform = entity.getComponent(this._transformType);
|
||||
if (transform) {
|
||||
const pos = transform.worldPosition ?? transform.position;
|
||||
worldX = pos.x;
|
||||
@@ -239,7 +240,7 @@ export class ParticleUpdateSystem extends EntitySystem {
|
||||
// 尝试获取 Transform,如果没有则使用默认位置 | Try to get Transform, use default position if not available
|
||||
let transform: ITransformComponent | null = null;
|
||||
if (this._transformType) {
|
||||
transform = entity.getComponent(this._transformType as any) as ITransformComponent | null;
|
||||
transform = entity.getComponent(this._transformType);
|
||||
}
|
||||
// 即使没有 Transform,也要注册粒子系统(使用原点位置) | Register particle system even without Transform (use origin position)
|
||||
if (transform) {
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* 粒子模块服务令牌
|
||||
* Particle module service tokens
|
||||
*
|
||||
* 定义粒子模块导出的服务令牌。
|
||||
* Defines service tokens exported by particle module.
|
||||
*/
|
||||
|
||||
import { createServiceToken } from '@esengine/engine-core';
|
||||
import type { ParticleUpdateSystem } from './systems/ParticleSystem';
|
||||
|
||||
// ============================================================================
|
||||
// 粒子模块导出的令牌 | Tokens exported by particle module
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* 粒子更新系统令牌
|
||||
* Particle update system token
|
||||
*/
|
||||
export const ParticleUpdateSystemToken = createServiceToken<ParticleUpdateSystem>('particleUpdateSystem');
|
||||
@@ -3,7 +3,7 @@
|
||||
* 完整的 2D 物理插件(运行时 + 编辑器)
|
||||
*/
|
||||
|
||||
import type { IPlugin, ModuleManifest } from '@esengine/editor-core';
|
||||
import type { IEditorPlugin, ModuleManifest } from '@esengine/editor-core';
|
||||
import { PhysicsRuntimeModule } from '@esengine/physics-rapier2d/runtime';
|
||||
import { physics2DEditorModule } from './Physics2DEditorModule';
|
||||
|
||||
@@ -34,7 +34,7 @@ const manifest: ModuleManifest = {
|
||||
* 完整的 Physics 2D 插件(运行时 + 编辑器)
|
||||
* Complete Physics 2D Plugin (runtime + editor)
|
||||
*/
|
||||
export const Physics2DPlugin: IPlugin = {
|
||||
export const Physics2DPlugin: IEditorPlugin = {
|
||||
manifest,
|
||||
runtimeModule: new PhysicsRuntimeModule(),
|
||||
editorModule: physics2DEditorModule
|
||||
|
||||
@@ -17,69 +17,27 @@ import { CapsuleCollider2DComponent } from './components/CapsuleCollider2DCompon
|
||||
import { PolygonCollider2DComponent } from './components/PolygonCollider2DComponent';
|
||||
import { Physics2DSystem } from './systems/Physics2DSystem';
|
||||
import { Physics2DService } from './services/Physics2DService';
|
||||
import {
|
||||
Physics2DQueryToken,
|
||||
Physics2DSystemToken,
|
||||
Physics2DWorldToken,
|
||||
PhysicsConfigToken,
|
||||
type IPhysics2DQuery,
|
||||
type PhysicsConfig
|
||||
} from './tokens';
|
||||
|
||||
// 注册 Rapier2D 加载器
|
||||
import './loaders';
|
||||
|
||||
/**
|
||||
* 2D 物理查询接口
|
||||
* 2D Physics query interface
|
||||
*
|
||||
* 用于粒子系统等模块查询物理世界
|
||||
* Used by particle system and other modules to query physics world
|
||||
*/
|
||||
export interface IPhysics2DQuery {
|
||||
overlapCircle(
|
||||
center: { x: number; y: number },
|
||||
radius: number,
|
||||
collisionMask?: number
|
||||
): { entityIds: number[]; colliderHandles: number[] };
|
||||
|
||||
raycast(
|
||||
origin: { x: number; y: number },
|
||||
direction: { x: number; y: number },
|
||||
maxDistance: number,
|
||||
collisionMask?: number
|
||||
): {
|
||||
entityId: number;
|
||||
point: { x: number; y: number };
|
||||
normal: { x: number; y: number };
|
||||
distance: number;
|
||||
colliderHandle: number;
|
||||
} | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 物理系统上下文扩展
|
||||
*/
|
||||
export interface PhysicsSystemContext extends SystemContext {
|
||||
/**
|
||||
* 物理系统实例
|
||||
*/
|
||||
physicsSystem?: Physics2DSystem;
|
||||
|
||||
/**
|
||||
* 物理世界实例
|
||||
*/
|
||||
physics2DWorld?: any;
|
||||
|
||||
/**
|
||||
* 物理配置
|
||||
*/
|
||||
physicsConfig?: any;
|
||||
|
||||
/**
|
||||
* 2D 物理查询接口
|
||||
* 2D Physics query interface
|
||||
*
|
||||
* 供粒子系统等模块使用,用于检测粒子与物理碰撞体的碰撞。
|
||||
* 实际上是 Physics2DSystem 的引用,因为它实现了 IPhysics2DQuery 接口。
|
||||
*
|
||||
* For particle system and other modules to detect collision with physics colliders.
|
||||
* Actually a reference to Physics2DSystem which implements IPhysics2DQuery interface.
|
||||
*/
|
||||
physics2DQuery?: IPhysics2DQuery;
|
||||
}
|
||||
// 重新导出 tokens 和类型 | Re-export tokens and types
|
||||
export {
|
||||
Physics2DQueryToken,
|
||||
Physics2DSystemToken,
|
||||
Physics2DWorldToken,
|
||||
PhysicsConfigToken,
|
||||
type IPhysics2DQuery,
|
||||
type PhysicsConfig
|
||||
} from './tokens';
|
||||
|
||||
/**
|
||||
* 物理运行时模块
|
||||
@@ -167,10 +125,11 @@ class PhysicsRuntimeModule implements IRuntimeModule {
|
||||
* @param context - 系统上下文
|
||||
*/
|
||||
createSystems(scene: IScene, context: SystemContext): void {
|
||||
const physicsContext = context as PhysicsSystemContext;
|
||||
// 从服务注册表获取配置 | Get config from service registry
|
||||
const physicsConfig = context.services.get(PhysicsConfigToken);
|
||||
|
||||
const physicsSystem = new Physics2DSystem({
|
||||
physics: physicsContext.physicsConfig,
|
||||
physics: physicsConfig,
|
||||
updateOrder: -1000
|
||||
});
|
||||
|
||||
@@ -181,11 +140,10 @@ class PhysicsRuntimeModule implements IRuntimeModule {
|
||||
physicsSystem.initializeWithRapier(this._rapierModule);
|
||||
}
|
||||
|
||||
physicsContext.physicsSystem = physicsSystem;
|
||||
physicsContext.physics2DWorld = physicsSystem.world;
|
||||
// 同时暴露 physics2DQuery,供粒子系统等模块使用
|
||||
// Also expose physics2DQuery for particle system and other modules
|
||||
physicsContext.physics2DQuery = physicsSystem;
|
||||
// 注册服务 | Register services
|
||||
context.services.register(Physics2DSystemToken, physicsSystem);
|
||||
context.services.register(Physics2DWorldToken, physicsSystem.world);
|
||||
context.services.register(Physics2DQueryToken, physicsSystem);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -28,5 +28,13 @@ export { Physics2DPlugin } from './PhysicsEditorPlugin';
|
||||
// Runtime plugin (for game builds)
|
||||
export { PhysicsPlugin } from './PhysicsRuntimeModule';
|
||||
|
||||
// Physics query interface (for particle system integration)
|
||||
export type { IPhysics2DQuery, PhysicsSystemContext } from './PhysicsRuntimeModule';
|
||||
// Service tokens and interfaces (谁定义接口,谁导出 Token)
|
||||
export {
|
||||
Physics2DQueryToken,
|
||||
Physics2DSystemToken,
|
||||
Physics2DWorldToken,
|
||||
PhysicsConfigToken,
|
||||
type IPhysics2DQuery,
|
||||
type IPhysics2DWorld,
|
||||
type PhysicsConfig
|
||||
} from './tokens';
|
||||
|
||||
@@ -3,9 +3,6 @@
|
||||
*
|
||||
* This entry point exports only runtime-related code without any editor dependencies.
|
||||
* Use this for standalone game runtime builds.
|
||||
*
|
||||
* 此入口点仅导出运行时相关代码,不包含任何编辑器依赖。
|
||||
* 用于独立游戏运行时构建。
|
||||
*/
|
||||
|
||||
// Types
|
||||
@@ -53,4 +50,14 @@ export { Physics2DSystem, type Physics2DSystemConfig } from './systems/Physics2D
|
||||
export { Physics2DService } from './services/Physics2DService';
|
||||
|
||||
// Runtime module and plugin
|
||||
export { PhysicsRuntimeModule, PhysicsPlugin, type PhysicsSystemContext } from './PhysicsRuntimeModule';
|
||||
export { PhysicsRuntimeModule, PhysicsPlugin } from './PhysicsRuntimeModule';
|
||||
|
||||
// Service tokens
|
||||
export {
|
||||
Physics2DQueryToken,
|
||||
Physics2DSystemToken,
|
||||
Physics2DWorldToken,
|
||||
PhysicsConfigToken,
|
||||
type IPhysics2DQuery,
|
||||
type PhysicsConfig
|
||||
} from './tokens';
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
*/
|
||||
|
||||
// Re-export runtime module and plugin with WASM
|
||||
export { PhysicsRuntimeModule, PhysicsPlugin, type PhysicsSystemContext } from '../PhysicsRuntimeModule';
|
||||
export { PhysicsRuntimeModule, PhysicsPlugin } from '../PhysicsRuntimeModule';
|
||||
|
||||
// Re-export world and system (they have WASM type dependencies)
|
||||
export { Physics2DWorld } from '../world/Physics2DWorld';
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
/**
|
||||
* 物理模块服务令牌
|
||||
* Physics module service tokens
|
||||
*
|
||||
* 定义 physics-rapier2d 模块导出的服务令牌和接口。
|
||||
* 谁定义接口,谁导出 Token。
|
||||
*
|
||||
* Defines service tokens and interfaces exported by physics-rapier2d module.
|
||||
* Who defines the interface, who exports the Token.
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* // 消费方导入 Token | Consumer imports Token
|
||||
* import { Physics2DQueryToken, type IPhysics2DQuery } from '@esengine/physics-rapier2d';
|
||||
*
|
||||
* // 获取服务 | Get service
|
||||
* const physicsQuery = context.services.get(Physics2DQueryToken);
|
||||
* if (physicsQuery) {
|
||||
* physicsQuery.raycast(...);
|
||||
* }
|
||||
* ```
|
||||
*/
|
||||
|
||||
import { createServiceToken } from '@esengine/engine-core';
|
||||
import type { Physics2DSystem } from './systems/Physics2DSystem';
|
||||
|
||||
// ============================================================================
|
||||
// 共享物理接口 | Shared Physics Interfaces
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* 2D 物理查询接口
|
||||
* 2D Physics query interface
|
||||
*
|
||||
* 跨模块共享的物理查询契约。
|
||||
* 由 Physics2DWorld 实现,粒子等模块可选依赖。
|
||||
*
|
||||
* Cross-module shared physics query contract.
|
||||
* Implemented by Physics2DWorld, optionally depended by particle and other modules.
|
||||
*/
|
||||
export interface IPhysics2DQuery {
|
||||
/**
|
||||
* 圆形区域检测
|
||||
* Circle overlap detection
|
||||
*
|
||||
* @param center 圆心 | Circle center
|
||||
* @param radius 半径 | Radius
|
||||
* @param collisionMask 碰撞掩码 | Collision mask
|
||||
* @returns 检测结果 | Detection result
|
||||
*/
|
||||
overlapCircle(
|
||||
center: { x: number; y: number },
|
||||
radius: number,
|
||||
collisionMask?: number
|
||||
): { entityIds: number[]; colliderHandles: number[] };
|
||||
|
||||
/**
|
||||
* 射线检测
|
||||
* Raycast detection
|
||||
*
|
||||
* @param origin 起点 | Origin point
|
||||
* @param direction 方向(归一化)| Direction (normalized)
|
||||
* @param maxDistance 最大距离 | Max distance
|
||||
* @param collisionMask 碰撞掩码 | Collision mask
|
||||
* @returns 命中结果或 null | Hit result or null
|
||||
*/
|
||||
raycast(
|
||||
origin: { x: number; y: number },
|
||||
direction: { x: number; y: number },
|
||||
maxDistance: number,
|
||||
collisionMask?: number
|
||||
): {
|
||||
entityId: number;
|
||||
point: { x: number; y: number };
|
||||
normal: { x: number; y: number };
|
||||
distance: number;
|
||||
colliderHandle: number;
|
||||
} | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 2D 物理世界接口
|
||||
* 2D Physics world interface
|
||||
*
|
||||
* 跨模块共享的物理世界契约。
|
||||
* 由 Physics2DWorld 实现,tilemap 等模块可选依赖。
|
||||
*
|
||||
* Cross-module shared physics world contract.
|
||||
* Implemented by Physics2DWorld, optionally depended by tilemap and other modules.
|
||||
*/
|
||||
export interface IPhysics2DWorld {
|
||||
/**
|
||||
* 创建静态碰撞体
|
||||
* Create static collider
|
||||
*
|
||||
* @param entityId 实体 ID | Entity ID
|
||||
* @param position 碰撞体中心位置 | Collider center position
|
||||
* @param halfExtents 半宽高 | Half extents
|
||||
* @param collisionLayer 碰撞层 | Collision layer
|
||||
* @param collisionMask 碰撞掩码 | Collision mask
|
||||
* @param friction 摩擦系数 | Friction coefficient
|
||||
* @param restitution 弹性系数 | Restitution coefficient
|
||||
* @param isTrigger 是否为触发器 | Whether is trigger
|
||||
* @returns 碰撞体句柄或 null | Collider handle or null
|
||||
*/
|
||||
createStaticCollider(
|
||||
entityId: number,
|
||||
position: { x: number; y: number },
|
||||
halfExtents: { x: number; y: number },
|
||||
collisionLayer: number,
|
||||
collisionMask: number,
|
||||
friction: number,
|
||||
restitution: number,
|
||||
isTrigger: boolean
|
||||
): number | null;
|
||||
|
||||
/**
|
||||
* 移除碰撞体
|
||||
* Remove collider
|
||||
*
|
||||
* @param handle 碰撞体句柄 | Collider handle
|
||||
*/
|
||||
removeCollider(handle: number): void;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 物理模块特有的接口 | Physics module specific interfaces
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* 物理配置
|
||||
* Physics configuration
|
||||
*/
|
||||
export interface PhysicsConfig {
|
||||
gravity?: { x: number; y: number };
|
||||
timestep?: number;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 服务令牌 | Service Tokens
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* 2D 物理查询服务令牌
|
||||
* 2D Physics query service token
|
||||
*
|
||||
* 用于获取物理查询能力(射线检测、区域检测等)。
|
||||
* For getting physics query capabilities (raycast, overlap detection, etc.).
|
||||
*/
|
||||
export const Physics2DQueryToken = createServiceToken<IPhysics2DQuery>('physics2DQuery');
|
||||
|
||||
/**
|
||||
* 2D 物理世界服务令牌
|
||||
* 2D Physics world service token
|
||||
*
|
||||
* 用于获取物理世界实例(需要底层访问时使用)。
|
||||
* For getting physics world instance (when low-level access is needed).
|
||||
*/
|
||||
export const Physics2DWorldToken = createServiceToken<IPhysics2DWorld>('physics2DWorld');
|
||||
|
||||
/**
|
||||
* 物理系统令牌
|
||||
* Physics system token
|
||||
*
|
||||
* 用于获取完整的物理系统实例。
|
||||
* For getting the full physics system instance.
|
||||
*/
|
||||
export const Physics2DSystemToken = createServiceToken<Physics2DSystem>('physics2DSystem');
|
||||
|
||||
/**
|
||||
* 物理配置令牌
|
||||
* Physics config token
|
||||
*
|
||||
* 用于传入物理配置(如重力、时间步)。
|
||||
* For passing physics configuration (gravity, timestep, etc.).
|
||||
*/
|
||||
export const PhysicsConfigToken = createServiceToken<PhysicsConfig>('physicsConfig');
|
||||
@@ -0,0 +1,47 @@
|
||||
{
|
||||
"name": "@esengine/plugin-types",
|
||||
"version": "1.0.0",
|
||||
"description": "Plugin system type definitions for ES Engine",
|
||||
"type": "module",
|
||||
"main": "dist/index.js",
|
||||
"module": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./dist/index.d.ts",
|
||||
"import": "./dist/index.js"
|
||||
}
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsup",
|
||||
"build:watch": "tsup --watch",
|
||||
"clean": "rimraf dist",
|
||||
"type-check": "tsc --noEmit"
|
||||
},
|
||||
"keywords": [
|
||||
"ecs",
|
||||
"plugin",
|
||||
"types",
|
||||
"typescript"
|
||||
],
|
||||
"author": "yhh",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@esengine/ecs-framework": "workspace:*",
|
||||
"@esengine/build-config": "workspace:*",
|
||||
"rimraf": "^5.0.0",
|
||||
"tsup": "^8.0.0",
|
||||
"typescript": "^5.8.3"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/esengine/ecs-framework.git",
|
||||
"directory": "packages/plugin-types"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,202 @@
|
||||
/**
|
||||
* 插件系统基础类型定义
|
||||
* Plugin system base type definitions
|
||||
*
|
||||
* 这个包只提供用于打破循环依赖的基础接口。
|
||||
* 完整的类型定义在 engine-core 中。
|
||||
*
|
||||
* This package only provides base interfaces to break circular dependencies.
|
||||
* Complete type definitions are in engine-core.
|
||||
*
|
||||
* 导出内容 | Exports:
|
||||
* - ServiceToken / createServiceToken / PluginServiceRegistry: 服务令牌系统
|
||||
* - IEditorModuleBase: 编辑器模块基础接口(用于 IPlugin.editorModule 类型)
|
||||
*
|
||||
* 不导出(在 engine-core 中定义)| Not exported (defined in engine-core):
|
||||
* - IPlugin, IRuntimeModule, SystemContext: 完整的插件类型
|
||||
* - ModuleManifest: 完整的模块清单类型
|
||||
* - LoadingPhase: 加载阶段类型
|
||||
*/
|
||||
|
||||
import type { ServiceContainer } from '@esengine/ecs-framework';
|
||||
|
||||
// ============================================================================
|
||||
// 服务令牌 | Service Token
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* 服务令牌接口
|
||||
* Service token interface
|
||||
*
|
||||
* 用于类型安全的服务注册和获取。
|
||||
* For type-safe service registration and retrieval.
|
||||
*
|
||||
* 注意:__phantom 是必需属性(使用 declare 避免运行时开销),
|
||||
* 这确保 TypeScript 在跨包类型解析时保留泛型类型信息。
|
||||
*
|
||||
* Note: __phantom is a required property (using declare to avoid runtime overhead),
|
||||
* which ensures TypeScript preserves generic type information across packages.
|
||||
*/
|
||||
export interface ServiceToken<T> {
|
||||
readonly id: symbol;
|
||||
readonly name: string;
|
||||
/**
|
||||
* Phantom type 标记(强制类型推断)
|
||||
* Phantom type marker (enforces type inference)
|
||||
*
|
||||
* 使用 declare 声明,不会在运行时占用内存。
|
||||
* Declared with 'declare', no runtime memory overhead.
|
||||
*/
|
||||
readonly __phantom: T;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建服务令牌
|
||||
* Create a service token
|
||||
*
|
||||
* @param name 令牌名称 | Token name
|
||||
* @returns 服务令牌 | Service token
|
||||
*/
|
||||
export function createServiceToken<T>(name: string): ServiceToken<T> {
|
||||
// __phantom 仅用于类型推断,不需要实际值
|
||||
// __phantom is only for type inference, no actual value needed
|
||||
return {
|
||||
id: Symbol(name),
|
||||
name
|
||||
} as ServiceToken<T>;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 插件服务注册表 | Plugin Service Registry
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* 插件服务注册表
|
||||
* Plugin service registry
|
||||
*
|
||||
* 用于跨插件共享服务的类型安全注册表。
|
||||
* Type-safe registry for sharing services between plugins.
|
||||
*/
|
||||
export class PluginServiceRegistry {
|
||||
private _services = new Map<symbol, unknown>();
|
||||
|
||||
/**
|
||||
* 注册服务
|
||||
* Register a service
|
||||
*/
|
||||
register<T>(token: ServiceToken<T>, service: T): void {
|
||||
this._services.set(token.id, service);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取服务(可选)
|
||||
* Get a service (optional)
|
||||
*/
|
||||
get<T>(token: ServiceToken<T>): T | undefined {
|
||||
return this._services.get(token.id) as T | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取服务(必需)
|
||||
* Get a service (required)
|
||||
*
|
||||
* @throws 如果服务未注册 | If service is not registered
|
||||
*/
|
||||
require<T>(token: ServiceToken<T>): T {
|
||||
const service = this._services.get(token.id);
|
||||
if (service === undefined) {
|
||||
throw new Error(`Service not found: ${token.name}`);
|
||||
}
|
||||
return service as T;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查服务是否已注册
|
||||
* Check if a service is registered
|
||||
*/
|
||||
has<T>(token: ServiceToken<T>): boolean {
|
||||
return this._services.has(token.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 注销服务
|
||||
* Unregister a service
|
||||
*/
|
||||
unregister<T>(token: ServiceToken<T>): boolean {
|
||||
return this._services.delete(token.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空所有服务
|
||||
* Clear all services
|
||||
*/
|
||||
clear(): void {
|
||||
this._services.clear();
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 编辑器模块基础接口 | Editor Module Base Interface
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* 编辑器模块基础接口
|
||||
* Base editor module interface
|
||||
*
|
||||
* 定义编辑器模块的核心生命周期方法。
|
||||
* 这个接口用于 IPlugin.editorModule 的类型定义,避免 engine-core 依赖 editor-core。
|
||||
* 完整的 IEditorModuleLoader 接口在 editor-core 中扩展此接口。
|
||||
*
|
||||
* Defines core lifecycle methods for editor modules.
|
||||
* This interface is used for IPlugin.editorModule type to avoid engine-core depending on editor-core.
|
||||
* Full IEditorModuleLoader interface extends this in editor-core.
|
||||
*/
|
||||
export interface IEditorModuleBase {
|
||||
/**
|
||||
* 安装编辑器模块
|
||||
* Install editor module
|
||||
*/
|
||||
install(services: ServiceContainer): Promise<void>;
|
||||
|
||||
/**
|
||||
* 卸载编辑器模块
|
||||
* Uninstall editor module
|
||||
*/
|
||||
uninstall?(): Promise<void>;
|
||||
|
||||
/**
|
||||
* 编辑器就绪回调
|
||||
* Editor ready callback
|
||||
*/
|
||||
onEditorReady?(): void | Promise<void>;
|
||||
|
||||
/**
|
||||
* 项目打开回调
|
||||
* Project open callback
|
||||
*/
|
||||
onProjectOpen?(projectPath: string): void | Promise<void>;
|
||||
|
||||
/**
|
||||
* 项目关闭回调
|
||||
* Project close callback
|
||||
*/
|
||||
onProjectClose?(): void | Promise<void>;
|
||||
|
||||
/**
|
||||
* 场景加载回调
|
||||
* Scene loaded callback
|
||||
*/
|
||||
onSceneLoaded?(scenePath: string): void;
|
||||
|
||||
/**
|
||||
* 场景保存前回调
|
||||
* Before scene save callback
|
||||
*/
|
||||
onSceneSaving?(scenePath: string): boolean | void;
|
||||
|
||||
/**
|
||||
* 设置语言
|
||||
* Set locale
|
||||
*/
|
||||
setLocale?(locale: string): void;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"compilerOptions": {
|
||||
"declaration": true,
|
||||
"declarationMap": true
|
||||
},
|
||||
"exclude": ["node_modules", "dist", "**/*.test.ts", "**/*.spec.ts"]
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2020",
|
||||
"module": "ESNext",
|
||||
"moduleResolution": "bundler",
|
||||
"lib": ["ES2020", "DOM"],
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"outDir": "./dist",
|
||||
"rootDir": "./src",
|
||||
"declaration": true,
|
||||
"declarationMap": true
|
||||
},
|
||||
"include": ["src/**/*"],
|
||||
"exclude": ["node_modules", "dist"]
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { defineConfig } from 'tsup';
|
||||
|
||||
export default defineConfig({
|
||||
entry: ['src/index.ts'],
|
||||
format: ['esm'],
|
||||
dts: true,
|
||||
splitting: false,
|
||||
sourcemap: true,
|
||||
clean: true,
|
||||
tsconfig: 'tsconfig.build.json',
|
||||
external: [
|
||||
'@esengine/ecs-framework'
|
||||
]
|
||||
});
|
||||
@@ -7,9 +7,87 @@
|
||||
*/
|
||||
|
||||
import { Core, Scene, SceneSerializer, HierarchySystem } from '@esengine/ecs-framework';
|
||||
import { EngineBridge, EngineRenderSystem, CameraSystem } from '@esengine/ecs-engine-bindgen';
|
||||
import { TransformComponent, TransformSystem, InputSystem, Input } from '@esengine/engine-core';
|
||||
import { AssetManager, EngineIntegration } from '@esengine/asset-system';
|
||||
import {
|
||||
EngineBridge,
|
||||
EngineRenderSystem,
|
||||
CameraSystem,
|
||||
EngineBridgeToken,
|
||||
RenderSystemToken,
|
||||
EngineIntegrationToken,
|
||||
type IUIRenderDataProvider
|
||||
} from '@esengine/ecs-engine-bindgen';
|
||||
import {
|
||||
TransformComponent,
|
||||
TransformSystem,
|
||||
InputSystem,
|
||||
Input,
|
||||
PluginServiceRegistry,
|
||||
TransformTypeToken,
|
||||
createServiceToken
|
||||
} from '@esengine/engine-core';
|
||||
import { AssetManager, EngineIntegration, AssetManagerToken } from '@esengine/asset-system';
|
||||
|
||||
// ============================================================================
|
||||
// 本地服务令牌定义 | Local Service Token Definitions
|
||||
// 用于访问各模块注册的服务 | For accessing services registered by modules
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* UI 输入系统接口(最小化定义,用于类型安全的服务访问)
|
||||
* UI input system interface (minimal definition for type-safe service access)
|
||||
*/
|
||||
interface IUIInputSystem {
|
||||
bindToCanvas(canvas: HTMLCanvasElement): void;
|
||||
unbind?(): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* 可启用/禁用的系统接口
|
||||
* Interface for systems that can be enabled/disabled
|
||||
*/
|
||||
interface IEnableableSystem {
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* 行为树系统接口
|
||||
* Behavior tree system interface
|
||||
*/
|
||||
interface IBehaviorTreeSystem extends IEnableableSystem {
|
||||
startAllAutoStartTrees?(): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* 物理系统接口
|
||||
* Physics system interface
|
||||
*/
|
||||
interface IPhysicsSystem extends IEnableableSystem {
|
||||
reset?(): void;
|
||||
}
|
||||
|
||||
/**
|
||||
* Tilemap 系统接口
|
||||
* Tilemap system interface
|
||||
*/
|
||||
interface ITilemapSystem {
|
||||
clearCache?(): void;
|
||||
}
|
||||
|
||||
// UI 模块服务令牌 | UI module service tokens
|
||||
const UIRenderProviderToken = createServiceToken<IUIRenderDataProvider>('uiRenderProvider');
|
||||
const UIInputSystemToken = createServiceToken<IUIInputSystem>('uiInputSystem');
|
||||
|
||||
// Sprite 模块服务令牌 | Sprite module service tokens
|
||||
const SpriteAnimatorSystemToken = createServiceToken<IEnableableSystem>('spriteAnimatorSystem');
|
||||
|
||||
// BehaviorTree 模块服务令牌 | BehaviorTree module service tokens
|
||||
const BehaviorTreeSystemToken = createServiceToken<IBehaviorTreeSystem>('behaviorTreeSystem');
|
||||
|
||||
// Physics 模块服务令牌 | Physics module service tokens
|
||||
const Physics2DSystemToken = createServiceToken<IPhysicsSystem>('physics2DSystem');
|
||||
|
||||
// Tilemap 模块服务令牌 | Tilemap module service tokens
|
||||
const TilemapSystemToken = createServiceToken<ITilemapSystem>('tilemapSystem');
|
||||
import {
|
||||
runtimePluginManager,
|
||||
type SystemContext,
|
||||
@@ -158,13 +236,11 @@ export class GameRuntime {
|
||||
}
|
||||
|
||||
/**
|
||||
* 更新系统上下文(用于编辑器模式下同步外部创建的系统引用)
|
||||
* Update system context (for syncing externally created system references in editor mode)
|
||||
* 获取服务注册表(用于编辑器模式下注册外部创建的系统)
|
||||
* Get service registry (for registering externally created systems in editor mode)
|
||||
*/
|
||||
updateSystemContext(updates: Partial<SystemContext>): void {
|
||||
if (this._systemContext) {
|
||||
Object.assign(this._systemContext, updates);
|
||||
}
|
||||
getServiceRegistry(): PluginServiceRegistry | null {
|
||||
return this._systemContext?.services ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -266,15 +342,19 @@ export class GameRuntime {
|
||||
await this._initializePlugins();
|
||||
}
|
||||
|
||||
// 10. 创建系统上下文
|
||||
// 10. 创建系统上下文(使用 PluginServiceRegistry)
|
||||
const services = new PluginServiceRegistry();
|
||||
|
||||
// 注册核心服务 | Register core services
|
||||
services.register(EngineBridgeToken, this._bridge);
|
||||
services.register(RenderSystemToken, this._renderSystem);
|
||||
services.register(EngineIntegrationToken, this._engineIntegration);
|
||||
services.register(AssetManagerToken, this._assetManager);
|
||||
services.register(TransformTypeToken, TransformComponent);
|
||||
|
||||
this._systemContext = {
|
||||
isEditor: this._platform.isEditorMode(),
|
||||
engineBridge: this._bridge,
|
||||
engineIntegration: this._engineIntegration,
|
||||
renderSystem: this._renderSystem,
|
||||
assetManager: this._assetManager,
|
||||
inputSystem: this._inputSystem,
|
||||
inputManager: Input
|
||||
services
|
||||
};
|
||||
|
||||
// 11. 让插件创建系统(编辑器模式下跳过,由 EngineService.initializeModuleSystems 处理)
|
||||
@@ -283,8 +363,9 @@ export class GameRuntime {
|
||||
}
|
||||
|
||||
// 11. 设置 UI 渲染数据提供者(如果有)
|
||||
if (this._systemContext.uiRenderProvider) {
|
||||
this._renderSystem.setUIRenderDataProvider(this._systemContext.uiRenderProvider);
|
||||
const uiRenderProvider = this._systemContext.services.get(UIRenderProviderToken);
|
||||
if (uiRenderProvider) {
|
||||
this._renderSystem.setUIRenderDataProvider(uiRenderProvider);
|
||||
}
|
||||
|
||||
// 12. 添加渲染系统(在所有其他系统之后)
|
||||
@@ -339,18 +420,23 @@ export class GameRuntime {
|
||||
* 禁用游戏逻辑系统(编辑器模式)
|
||||
*/
|
||||
private _disableGameLogicSystems(): void {
|
||||
const ctx = this._systemContext;
|
||||
if (!ctx) return;
|
||||
const services = this._systemContext?.services;
|
||||
if (!services) return;
|
||||
|
||||
// 这些系统由插件创建,通过 context 传递引用
|
||||
if (ctx.animatorSystem) {
|
||||
ctx.animatorSystem.enabled = false;
|
||||
// 这些系统由插件创建,通过服务注册表获取引用
|
||||
const animatorSystem = services.get(SpriteAnimatorSystemToken);
|
||||
if (animatorSystem) {
|
||||
animatorSystem.enabled = false;
|
||||
}
|
||||
if (ctx.behaviorTreeSystem) {
|
||||
ctx.behaviorTreeSystem.enabled = false;
|
||||
|
||||
const behaviorTreeSystem = services.get(BehaviorTreeSystemToken);
|
||||
if (behaviorTreeSystem) {
|
||||
behaviorTreeSystem.enabled = false;
|
||||
}
|
||||
if (ctx.physicsSystem) {
|
||||
ctx.physicsSystem.enabled = false;
|
||||
|
||||
const physicsSystem = services.get(Physics2DSystemToken);
|
||||
if (physicsSystem) {
|
||||
physicsSystem.enabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -358,18 +444,23 @@ export class GameRuntime {
|
||||
* 启用游戏逻辑系统(预览/运行模式)
|
||||
*/
|
||||
private _enableGameLogicSystems(): void {
|
||||
const ctx = this._systemContext;
|
||||
if (!ctx) return;
|
||||
const services = this._systemContext?.services;
|
||||
if (!services) return;
|
||||
|
||||
if (ctx.animatorSystem) {
|
||||
ctx.animatorSystem.enabled = true;
|
||||
const animatorSystem = services.get(SpriteAnimatorSystemToken);
|
||||
if (animatorSystem) {
|
||||
animatorSystem.enabled = true;
|
||||
}
|
||||
if (ctx.behaviorTreeSystem) {
|
||||
ctx.behaviorTreeSystem.enabled = true;
|
||||
ctx.behaviorTreeSystem.startAllAutoStartTrees?.();
|
||||
|
||||
const behaviorTreeSystem = services.get(BehaviorTreeSystemToken);
|
||||
if (behaviorTreeSystem) {
|
||||
behaviorTreeSystem.enabled = true;
|
||||
behaviorTreeSystem.startAllAutoStartTrees?.();
|
||||
}
|
||||
if (ctx.physicsSystem) {
|
||||
ctx.physicsSystem.enabled = true;
|
||||
|
||||
const physicsSystem = services.get(Physics2DSystemToken);
|
||||
if (physicsSystem) {
|
||||
physicsSystem.enabled = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -435,11 +526,11 @@ export class GameRuntime {
|
||||
this._enableGameLogicSystems();
|
||||
|
||||
// 绑定 UI 输入
|
||||
const ctx = this._systemContext;
|
||||
if (ctx?.uiInputSystem && this._config.canvasId) {
|
||||
const uiInputSystem = this._systemContext?.services.get(UIInputSystemToken);
|
||||
if (uiInputSystem && this._config.canvasId) {
|
||||
const canvas = document.getElementById(this._config.canvasId) as HTMLCanvasElement;
|
||||
if (canvas) {
|
||||
ctx.uiInputSystem.bindToCanvas(canvas);
|
||||
uiInputSystem.bindToCanvas(canvas);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -487,17 +578,19 @@ export class GameRuntime {
|
||||
}
|
||||
|
||||
// 解绑 UI 输入
|
||||
const ctx = this._systemContext;
|
||||
if (ctx?.uiInputSystem) {
|
||||
ctx.uiInputSystem.unbind?.();
|
||||
const services = this._systemContext?.services;
|
||||
const uiInputSystem = services?.get(UIInputSystemToken);
|
||||
if (uiInputSystem) {
|
||||
uiInputSystem.unbind?.();
|
||||
}
|
||||
|
||||
// 禁用游戏逻辑系统
|
||||
this._disableGameLogicSystems();
|
||||
|
||||
// 重置物理系统
|
||||
if (ctx?.physicsSystem) {
|
||||
ctx.physicsSystem.reset?.();
|
||||
const physicsSystem = services?.get(Physics2DSystemToken);
|
||||
if (physicsSystem) {
|
||||
physicsSystem.reset?.();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -778,9 +871,9 @@ export class GameRuntime {
|
||||
|
||||
try {
|
||||
// 清除缓存
|
||||
const ctx = this._systemContext;
|
||||
if (ctx?.tilemapSystem) {
|
||||
ctx.tilemapSystem.clearCache?.();
|
||||
const tilemapSystem = this._systemContext?.services.get(TilemapSystemToken);
|
||||
if (tilemapSystem) {
|
||||
tilemapSystem.clearCache?.();
|
||||
}
|
||||
|
||||
// 反序列化场景
|
||||
|
||||
@@ -87,3 +87,28 @@ export {
|
||||
type TouchInfo,
|
||||
type TouchEvent
|
||||
} from '@esengine/engine-core';
|
||||
|
||||
// Re-export Plugin Service Registry from engine-core
|
||||
export {
|
||||
PluginServiceRegistry,
|
||||
createServiceToken,
|
||||
TransformTypeToken,
|
||||
type ServiceToken
|
||||
} from '@esengine/engine-core';
|
||||
|
||||
// Re-export service tokens from their respective modules
|
||||
export {
|
||||
EngineBridgeToken,
|
||||
RenderSystemToken,
|
||||
EngineIntegrationToken,
|
||||
type IEngineBridge,
|
||||
type IRenderSystem,
|
||||
type IRenderDataProvider,
|
||||
type IEngineIntegration
|
||||
} from '@esengine/ecs-engine-bindgen';
|
||||
|
||||
export {
|
||||
AssetManagerToken,
|
||||
type IAssetManager,
|
||||
type IAssetLoadResult
|
||||
} from '@esengine/asset-system';
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
import type { ServiceContainer } from '@esengine/ecs-framework';
|
||||
import type {
|
||||
IEditorModuleLoader,
|
||||
IPlugin,
|
||||
IEditorPlugin,
|
||||
ModuleManifest,
|
||||
IFileSystem
|
||||
} from '@esengine/editor-core';
|
||||
@@ -102,7 +102,7 @@ const manifest: ModuleManifest = {
|
||||
* Shader Editor Plugin (editor only, no runtime).
|
||||
* 着色器编辑器插件(仅编辑器,无运行时)。
|
||||
*/
|
||||
export const ShaderEditorPlugin: IPlugin = {
|
||||
export const ShaderEditorPlugin: IEditorPlugin = {
|
||||
manifest,
|
||||
editorModule: shaderEditorModule
|
||||
};
|
||||
|
||||
@@ -10,7 +10,7 @@ import { Core } from '@esengine/ecs-framework';
|
||||
import type {
|
||||
IEditorModuleLoader,
|
||||
EntityCreationTemplate,
|
||||
IPlugin,
|
||||
IEditorPlugin,
|
||||
ModuleManifest
|
||||
} from '@esengine/editor-core';
|
||||
import {
|
||||
@@ -185,7 +185,7 @@ const manifest: ModuleManifest = {
|
||||
* 完整的 Sprite 插件(运行时 + 编辑器)
|
||||
* Complete Sprite Plugin (runtime + editor)
|
||||
*/
|
||||
export const SpritePlugin: IPlugin = {
|
||||
export const SpritePlugin: IEditorPlugin = {
|
||||
manifest,
|
||||
runtimeModule: new SpriteRuntimeModule(),
|
||||
editorModule: spriteEditorModule
|
||||
|
||||
@@ -284,11 +284,11 @@ export class SpriteComponent extends Component {
|
||||
async loadTextureAsync(): Promise<void> {
|
||||
if (this._assetReference) {
|
||||
try {
|
||||
const textureAsset = await this._assetReference.loadAsync();
|
||||
// 如果纹理资产有 textureId 属性,使用它
|
||||
// If texture asset has textureId property, use it
|
||||
if (textureAsset && typeof textureAsset === 'object' && 'textureId' in textureAsset) {
|
||||
this.textureId = (textureAsset as any).textureId;
|
||||
const result = await this._assetReference.loadAsync();
|
||||
// 检查返回值是否包含 textureId 属性(ITextureAsset 类型)
|
||||
// Check if result has textureId property (ITextureAsset type)
|
||||
if (result && typeof result === 'object' && 'textureId' in result) {
|
||||
this.textureId = (result as { textureId: number }).textureId;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load texture:', error);
|
||||
|
||||
@@ -3,8 +3,12 @@ import type { IRuntimeModule, IPlugin, ModuleManifest, SystemContext } from '@es
|
||||
import { SpriteComponent } from './SpriteComponent';
|
||||
import { SpriteAnimatorComponent } from './SpriteAnimatorComponent';
|
||||
import { SpriteAnimatorSystem } from './systems/SpriteAnimatorSystem';
|
||||
import { SpriteAnimatorSystemToken } from './tokens';
|
||||
|
||||
export type { SystemContext, ModuleManifest, IRuntimeModule as IRuntimeModuleLoader, IPlugin as IPluginLoader };
|
||||
export type { SystemContext, ModuleManifest, IRuntimeModule, IPlugin };
|
||||
|
||||
// 重新导出 tokens | Re-export tokens
|
||||
export { SpriteAnimatorSystemToken } from './tokens';
|
||||
|
||||
class SpriteRuntimeModule implements IRuntimeModule {
|
||||
registerComponents(registry: typeof ComponentRegistryType): void {
|
||||
@@ -20,7 +24,9 @@ class SpriteRuntimeModule implements IRuntimeModule {
|
||||
}
|
||||
|
||||
scene.addSystem(animatorSystem);
|
||||
(context as any).animatorSystem = animatorSystem;
|
||||
|
||||
// 注册服务到服务注册表 | Register service to service registry
|
||||
context.services.register(SpriteAnimatorSystemToken, animatorSystem);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,3 +4,6 @@ export { SpriteAnimatorComponent } from './SpriteAnimatorComponent';
|
||||
export type { AnimationFrame, AnimationClip } from './SpriteAnimatorComponent';
|
||||
export { SpriteAnimatorSystem } from './systems/SpriteAnimatorSystem';
|
||||
export { SpriteRuntimeModule, SpritePlugin } from './SpriteRuntimeModule';
|
||||
|
||||
// Service tokens | 服务令牌
|
||||
export { SpriteAnimatorSystemToken } from './tokens';
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
/**
|
||||
* Sprite 模块服务令牌
|
||||
* Sprite module service tokens
|
||||
*/
|
||||
|
||||
import { createServiceToken } from '@esengine/engine-core';
|
||||
import type { SpriteAnimatorSystem } from './systems/SpriteAnimatorSystem';
|
||||
|
||||
// ============================================================================
|
||||
// Sprite 模块导出的令牌 | Tokens exported by Sprite module
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Sprite 动画系统令牌
|
||||
* Sprite animator system token
|
||||
*/
|
||||
export const SpriteAnimatorSystemToken = createServiceToken<SpriteAnimatorSystem>('spriteAnimatorSystem');
|
||||
@@ -30,7 +30,7 @@ import { TransformComponent } from '@esengine/engine-core';
|
||||
|
||||
// Runtime imports from @esengine/tilemap
|
||||
import { TilemapComponent, TilemapCollider2DComponent, TilemapRuntimeModule } from '@esengine/tilemap';
|
||||
import type { IPlugin, ModuleManifest } from '@esengine/editor-core';
|
||||
import type { IEditorPlugin, ModuleManifest } from '@esengine/editor-core';
|
||||
import { TilemapEditorPanel } from './components/panels/TilemapEditorPanel';
|
||||
import { TilemapInspectorProvider } from './providers/TilemapInspectorProvider';
|
||||
import { registerTilemapGizmo } from './gizmos/TilemapGizmo';
|
||||
@@ -383,7 +383,7 @@ const manifest: ModuleManifest = {
|
||||
* 完整的 Tilemap 插件(运行时 + 编辑器)
|
||||
* Complete Tilemap Plugin (runtime + editor)
|
||||
*/
|
||||
export const TilemapPlugin: IPlugin = {
|
||||
export const TilemapPlugin: IEditorPlugin = {
|
||||
manifest,
|
||||
runtimeModule: new TilemapRuntimeModule(),
|
||||
editorModule: tilemapEditorModule
|
||||
|
||||
@@ -43,6 +43,7 @@
|
||||
"@esengine/asset-system": "workspace:*",
|
||||
"@esengine/engine-core": "workspace:*",
|
||||
"@esengine/ecs-engine-bindgen": "workspace:*",
|
||||
"@esengine/physics-rapier2d": "workspace:*",
|
||||
"@esengine/build-config": "workspace:*",
|
||||
"rimraf": "^5.0.0",
|
||||
"tsup": "^8.0.0",
|
||||
|
||||
@@ -1,22 +1,26 @@
|
||||
import type { IScene } from '@esengine/ecs-framework';
|
||||
import { ComponentRegistry } from '@esengine/ecs-framework';
|
||||
import type { IRuntimeModule, IPlugin, ModuleManifest, SystemContext } from '@esengine/engine-core';
|
||||
import type { AssetManager } from '@esengine/asset-system';
|
||||
import { AssetManagerToken } from '@esengine/asset-system';
|
||||
import { RenderSystemToken } from '@esengine/ecs-engine-bindgen';
|
||||
import { Physics2DWorldToken } from '@esengine/physics-rapier2d';
|
||||
|
||||
import { TilemapComponent } from './TilemapComponent';
|
||||
import { TilemapRenderingSystem } from './systems/TilemapRenderingSystem';
|
||||
import { TilemapCollider2DComponent } from './physics/TilemapCollider2DComponent';
|
||||
import { TilemapPhysicsSystem, type IPhysicsWorld } from './physics/TilemapPhysicsSystem';
|
||||
import { TilemapPhysicsSystem } from './physics/TilemapPhysicsSystem';
|
||||
import { TilemapLoader } from './loaders/TilemapLoader';
|
||||
import { TilemapAssetType } from './constants';
|
||||
import {
|
||||
TilemapSystemToken,
|
||||
TilemapPhysicsSystemToken
|
||||
} from './tokens';
|
||||
|
||||
export interface TilemapSystemContext extends SystemContext {
|
||||
tilemapSystem?: TilemapRenderingSystem;
|
||||
tilemapPhysicsSystem?: TilemapPhysicsSystem;
|
||||
physics2DWorld?: IPhysicsWorld;
|
||||
assetManager?: AssetManager;
|
||||
renderSystem?: any;
|
||||
}
|
||||
// 重新导出 tokens | Re-export tokens
|
||||
export {
|
||||
TilemapSystemToken,
|
||||
TilemapPhysicsSystemToken
|
||||
} from './tokens';
|
||||
|
||||
class TilemapRuntimeModule implements IRuntimeModule {
|
||||
private _tilemapPhysicsSystem: TilemapPhysicsSystem | null = null;
|
||||
@@ -28,33 +32,36 @@ class TilemapRuntimeModule implements IRuntimeModule {
|
||||
}
|
||||
|
||||
createSystems(scene: IScene, context: SystemContext): void {
|
||||
const tilemapContext = context as TilemapSystemContext;
|
||||
// 从服务注册表获取依赖 | Get dependencies from service registry
|
||||
const assetManager = context.services.get(AssetManagerToken);
|
||||
const renderSystem = context.services.get(RenderSystemToken);
|
||||
|
||||
if (!this._loaderRegistered && tilemapContext.assetManager) {
|
||||
tilemapContext.assetManager.registerLoader(TilemapAssetType, new TilemapLoader());
|
||||
if (!this._loaderRegistered && assetManager) {
|
||||
assetManager.registerLoader(TilemapAssetType, new TilemapLoader());
|
||||
this._loaderRegistered = true;
|
||||
}
|
||||
|
||||
const tilemapSystem = new TilemapRenderingSystem();
|
||||
scene.addSystem(tilemapSystem);
|
||||
|
||||
if (tilemapContext.renderSystem) {
|
||||
tilemapContext.renderSystem.addRenderDataProvider(tilemapSystem);
|
||||
if (renderSystem) {
|
||||
renderSystem.addRenderDataProvider(tilemapSystem);
|
||||
}
|
||||
|
||||
tilemapContext.tilemapSystem = tilemapSystem;
|
||||
|
||||
this._tilemapPhysicsSystem = new TilemapPhysicsSystem();
|
||||
scene.addSystem(this._tilemapPhysicsSystem);
|
||||
|
||||
tilemapContext.tilemapPhysicsSystem = this._tilemapPhysicsSystem;
|
||||
// 注册服务到服务注册表 | Register services to service registry
|
||||
context.services.register(TilemapSystemToken, tilemapSystem);
|
||||
context.services.register(TilemapPhysicsSystemToken, this._tilemapPhysicsSystem);
|
||||
}
|
||||
|
||||
onSystemsCreated(_scene: IScene, context: SystemContext): void {
|
||||
const tilemapContext = context as TilemapSystemContext;
|
||||
// 从服务注册表获取物理世界 | Get physics world from service registry
|
||||
const physics2DWorld = context.services.get(Physics2DWorldToken);
|
||||
|
||||
if (this._tilemapPhysicsSystem && tilemapContext.physics2DWorld) {
|
||||
this._tilemapPhysicsSystem.setPhysicsWorld(tilemapContext.physics2DWorld);
|
||||
if (this._tilemapPhysicsSystem && physics2DWorld) {
|
||||
this._tilemapPhysicsSystem.setPhysicsWorld(physics2DWorld);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -35,4 +35,10 @@ export { TiledConverter } from './loaders/TiledConverter';
|
||||
export type { ITiledMap, ITiledConversionResult } from './loaders/TiledConverter';
|
||||
|
||||
// Runtime module and plugin
|
||||
export { TilemapRuntimeModule, TilemapPlugin, type TilemapSystemContext } from './TilemapRuntimeModule';
|
||||
export { TilemapRuntimeModule, TilemapPlugin } from './TilemapRuntimeModule';
|
||||
|
||||
// Service tokens | 服务令牌
|
||||
export {
|
||||
TilemapSystemToken,
|
||||
TilemapPhysicsSystemToken
|
||||
} from './tokens';
|
||||
|
||||
@@ -81,8 +81,13 @@ export class TilemapLoader implements IAssetLoader<ITilemapAsset> {
|
||||
* 释放已加载的资产
|
||||
*/
|
||||
dispose(asset: ITilemapAsset): void {
|
||||
(asset as any).data = null;
|
||||
(asset as any).layers = null;
|
||||
(asset as any).collisionData = null;
|
||||
// 清理瓦片数据 | Clean up tile data
|
||||
asset.data.length = 0;
|
||||
if (asset.layers) {
|
||||
asset.layers.length = 0;
|
||||
}
|
||||
if (asset.collisionData) {
|
||||
asset.collisionData.length = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,6 +94,9 @@ export class TilesetLoader implements IAssetLoader<ITilesetAsset> {
|
||||
* 释放已加载的资产
|
||||
*/
|
||||
dispose(asset: ITilesetAsset): void {
|
||||
(asset as any).tiles = null;
|
||||
// 清理瓦片元数据 | Clean up tile metadata
|
||||
if (asset.tiles) {
|
||||
asset.tiles.length = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,23 +10,10 @@ import { EntitySystem, Matcher, ECSSystem, type Entity, type Scene } from '@esen
|
||||
import { TransformComponent } from '@esengine/engine-core';
|
||||
import { TilemapComponent } from '../TilemapComponent';
|
||||
import { TilemapCollider2DComponent, type CollisionRect } from './TilemapCollider2DComponent';
|
||||
import type { IPhysics2DWorld } from '@esengine/physics-rapier2d';
|
||||
|
||||
/**
|
||||
* 物理世界接口(避免直接依赖 physics-rapier2d)
|
||||
*/
|
||||
export interface IPhysicsWorld {
|
||||
createStaticCollider(
|
||||
entityId: number,
|
||||
position: { x: number; y: number },
|
||||
halfExtents: { x: number; y: number },
|
||||
collisionLayer: number,
|
||||
collisionMask: number,
|
||||
friction: number,
|
||||
restitution: number,
|
||||
isTrigger: boolean
|
||||
): number | null;
|
||||
removeCollider(handle: number): void;
|
||||
}
|
||||
// 重新导出类型以保持向后兼容 | Re-export types for backward compatibility
|
||||
export type IPhysicsWorld = IPhysics2DWorld;
|
||||
|
||||
/**
|
||||
* 物理系统接口
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* Tilemap 模块服务令牌
|
||||
* Tilemap module service tokens
|
||||
*
|
||||
* 定义 tilemap 模块导出的服务令牌。
|
||||
* Defines service tokens exported by tilemap module.
|
||||
*/
|
||||
|
||||
import { createServiceToken } from '@esengine/engine-core';
|
||||
import type { TilemapRenderingSystem } from './systems/TilemapRenderingSystem';
|
||||
import type { TilemapPhysicsSystem } from './physics/TilemapPhysicsSystem';
|
||||
|
||||
// ============================================================================
|
||||
// Tilemap 模块导出的令牌 | Tokens exported by Tilemap module
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Tilemap 渲染系统令牌
|
||||
* Tilemap rendering system token
|
||||
*/
|
||||
export const TilemapSystemToken = createServiceToken<TilemapRenderingSystem>('tilemapSystem');
|
||||
|
||||
/**
|
||||
* Tilemap 物理系统令牌
|
||||
* Tilemap physics system token
|
||||
*/
|
||||
export const TilemapPhysicsSystemToken = createServiceToken<TilemapPhysicsSystem>('tilemapPhysicsSystem');
|
||||
@@ -404,7 +404,7 @@ export const uiEditorModule = new UIEditorModule();
|
||||
|
||||
// 从 @esengine/ui 导入运行时模块
|
||||
import { UIRuntimeModule } from '@esengine/ui';
|
||||
import type { IPlugin, ModuleManifest } from '@esengine/editor-core';
|
||||
import type { IEditorPlugin, ModuleManifest } from '@esengine/editor-core';
|
||||
|
||||
const manifest: ModuleManifest = {
|
||||
id: '@esengine/ui',
|
||||
@@ -427,7 +427,7 @@ const manifest: ModuleManifest = {
|
||||
* 完整的 UI 插件(运行时 + 编辑器)
|
||||
* Complete UI Plugin (runtime + editor)
|
||||
*/
|
||||
export const UIPlugin: IPlugin = {
|
||||
export const UIPlugin: IEditorPlugin = {
|
||||
manifest,
|
||||
runtimeModule: new UIRuntimeModule(),
|
||||
editorModule: uiEditorModule
|
||||
|
||||
@@ -29,6 +29,7 @@
|
||||
"devDependencies": {
|
||||
"@esengine/ecs-framework": "workspace:*",
|
||||
"@esengine/engine-core": "workspace:*",
|
||||
"@esengine/ecs-engine-bindgen": "workspace:*",
|
||||
"@esengine/build-config": "workspace:*",
|
||||
"rimraf": "^5.0.5",
|
||||
"tsup": "^8.0.0",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { IScene } from '@esengine/ecs-framework';
|
||||
import { ComponentRegistry } from '@esengine/ecs-framework';
|
||||
import type { IRuntimeModule, IPlugin, ModuleManifest, SystemContext } from '@esengine/engine-core';
|
||||
import { EngineBridgeToken } from '@esengine/ecs-engine-bindgen';
|
||||
|
||||
import {
|
||||
UITransformComponent,
|
||||
@@ -26,13 +27,20 @@ import {
|
||||
UISliderRenderSystem,
|
||||
UIScrollViewRenderSystem
|
||||
} from './systems/render';
|
||||
import {
|
||||
UILayoutSystemToken,
|
||||
UIInputSystemToken,
|
||||
UIRenderProviderToken,
|
||||
UITextRenderSystemToken
|
||||
} from './tokens';
|
||||
|
||||
export interface UISystemContext extends SystemContext {
|
||||
uiLayoutSystem?: UILayoutSystem;
|
||||
uiRenderProvider?: UIRenderDataProvider;
|
||||
uiInputSystem?: UIInputSystem;
|
||||
uiTextRenderSystem?: UITextRenderSystem;
|
||||
}
|
||||
// 重新导出 tokens | Re-export tokens
|
||||
export {
|
||||
UILayoutSystemToken,
|
||||
UIInputSystemToken,
|
||||
UIRenderProviderToken,
|
||||
UITextRenderSystemToken
|
||||
} from './tokens';
|
||||
|
||||
class UIRuntimeModule implements IRuntimeModule {
|
||||
registerComponents(registry: typeof ComponentRegistry): void {
|
||||
@@ -48,7 +56,8 @@ class UIRuntimeModule implements IRuntimeModule {
|
||||
}
|
||||
|
||||
createSystems(scene: IScene, context: SystemContext): void {
|
||||
const uiContext = context as UISystemContext;
|
||||
// 从服务注册表获取依赖 | Get dependencies from service registry
|
||||
const engineBridge = context.services.get(EngineBridgeToken);
|
||||
|
||||
const layoutSystem = new UILayoutSystem();
|
||||
scene.addSystem(layoutSystem);
|
||||
@@ -77,9 +86,9 @@ class UIRuntimeModule implements IRuntimeModule {
|
||||
const textRenderSystem = new UITextRenderSystem();
|
||||
scene.addSystem(textRenderSystem);
|
||||
|
||||
if (uiContext.engineBridge) {
|
||||
if (engineBridge) {
|
||||
textRenderSystem.setTextureCallback((id: number, dataUrl: string) => {
|
||||
uiContext.engineBridge.loadTexture(id, dataUrl);
|
||||
engineBridge.loadTexture(id, dataUrl);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -88,10 +97,11 @@ class UIRuntimeModule implements IRuntimeModule {
|
||||
inputSystem.setLayoutSystem(layoutSystem);
|
||||
scene.addSystem(inputSystem);
|
||||
|
||||
uiContext.uiLayoutSystem = layoutSystem;
|
||||
uiContext.uiRenderProvider = uiRenderProvider;
|
||||
uiContext.uiInputSystem = inputSystem;
|
||||
uiContext.uiTextRenderSystem = textRenderSystem;
|
||||
// 注册服务到服务注册表 | Register services to service registry
|
||||
context.services.register(UILayoutSystemToken, layoutSystem);
|
||||
context.services.register(UIRenderProviderToken, uiRenderProvider);
|
||||
context.services.register(UIInputSystemToken, inputSystem);
|
||||
context.services.register(UITextRenderSystemToken, textRenderSystem);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -162,4 +162,12 @@ export {
|
||||
} from './UIBuilder';
|
||||
|
||||
// Runtime module and plugin
|
||||
export { UIRuntimeModule, UIPlugin, type UISystemContext } from './UIRuntimeModule';
|
||||
export { UIRuntimeModule, UIPlugin } from './UIRuntimeModule';
|
||||
|
||||
// Service tokens | 服务令牌
|
||||
export {
|
||||
UILayoutSystemToken,
|
||||
UIInputSystemToken,
|
||||
UIRenderProviderToken,
|
||||
UITextRenderSystemToken
|
||||
} from './tokens';
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* UI 模块服务令牌
|
||||
* UI module service tokens
|
||||
*/
|
||||
|
||||
import { createServiceToken } from '@esengine/engine-core';
|
||||
import type { UILayoutSystem } from './systems/UILayoutSystem';
|
||||
import type { UIInputSystem } from './systems/UIInputSystem';
|
||||
import type { UIRenderDataProvider } from './systems/UIRenderDataProvider';
|
||||
import type { UITextRenderSystem } from './systems/render';
|
||||
|
||||
// ============================================================================
|
||||
// UI 模块导出的令牌 | Tokens exported by UI module
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* UI 布局系统令牌
|
||||
* UI layout system token
|
||||
*/
|
||||
export const UILayoutSystemToken = createServiceToken<UILayoutSystem>('uiLayoutSystem');
|
||||
|
||||
/**
|
||||
* UI 输入系统令牌
|
||||
* UI input system token
|
||||
*/
|
||||
export const UIInputSystemToken = createServiceToken<UIInputSystem>('uiInputSystem');
|
||||
|
||||
/**
|
||||
* UI 渲染数据提供者令牌
|
||||
* UI render data provider token
|
||||
*/
|
||||
export const UIRenderProviderToken = createServiceToken<UIRenderDataProvider>('uiRenderProvider');
|
||||
|
||||
/**
|
||||
* UI 文本渲染系统令牌
|
||||
* UI text render system token
|
||||
*/
|
||||
export const UITextRenderSystemToken = createServiceToken<UITextRenderSystem>('uiTextRenderSystem');
|
||||
@@ -12,7 +12,7 @@ import type {
|
||||
PanelDescriptor,
|
||||
EntityCreationTemplate,
|
||||
ComponentInspectorProviderDef,
|
||||
IPlugin,
|
||||
IEditorPlugin,
|
||||
ModuleManifest
|
||||
} from '@esengine/editor-core';
|
||||
import {
|
||||
@@ -218,7 +218,7 @@ const manifest: ModuleManifest = {
|
||||
* 完整的世界流式加载插件(运行时 + 编辑器)
|
||||
* Complete World Streaming Plugin (runtime + editor)
|
||||
*/
|
||||
export const WorldStreamingPlugin: IPlugin = {
|
||||
export const WorldStreamingPlugin: IEditorPlugin = {
|
||||
manifest,
|
||||
runtimeModule: new WorldStreamingModule(),
|
||||
editorModule: worldStreamingEditorModule
|
||||
|
||||
Generated
+36
@@ -156,6 +156,9 @@ importers:
|
||||
'@esengine/ecs-framework':
|
||||
specifier: workspace:*
|
||||
version: link:../core
|
||||
'@esengine/engine-core':
|
||||
specifier: workspace:*
|
||||
version: link:../engine-core
|
||||
rimraf:
|
||||
specifier: ^5.0.0
|
||||
version: 5.0.10
|
||||
@@ -765,6 +768,9 @@ importers:
|
||||
'@esengine/engine-core':
|
||||
specifier: workspace:*
|
||||
version: link:../engine-core
|
||||
'@esengine/plugin-types':
|
||||
specifier: workspace:*
|
||||
version: link:../plugin-types
|
||||
'@eslint/js':
|
||||
specifier: ^9.37.0
|
||||
version: 9.39.1
|
||||
@@ -898,6 +904,9 @@ importers:
|
||||
'@esengine/platform-common':
|
||||
specifier: workspace:*
|
||||
version: link:../platform-common
|
||||
'@esengine/plugin-types':
|
||||
specifier: workspace:*
|
||||
version: link:../plugin-types
|
||||
devDependencies:
|
||||
'@esengine/build-config':
|
||||
specifier: workspace:*
|
||||
@@ -1058,6 +1067,9 @@ importers:
|
||||
'@esengine/build-config':
|
||||
specifier: workspace:*
|
||||
version: link:../build-config
|
||||
'@esengine/ecs-engine-bindgen':
|
||||
specifier: workspace:*
|
||||
version: link:../ecs-engine-bindgen
|
||||
'@esengine/ecs-framework':
|
||||
specifier: workspace:*
|
||||
version: link:../core
|
||||
@@ -1289,6 +1301,24 @@ importers:
|
||||
specifier: ^5.8.3
|
||||
version: 5.9.3
|
||||
|
||||
packages/plugin-types:
|
||||
devDependencies:
|
||||
'@esengine/build-config':
|
||||
specifier: workspace:*
|
||||
version: link:../build-config
|
||||
'@esengine/ecs-framework':
|
||||
specifier: workspace:*
|
||||
version: link:../core
|
||||
rimraf:
|
||||
specifier: ^5.0.0
|
||||
version: 5.0.10
|
||||
tsup:
|
||||
specifier: ^8.0.0
|
||||
version: 8.5.1(@microsoft/api-extractor@7.55.1(@types/node@20.19.25))(@swc/core@1.15.3)(jiti@2.6.1)(postcss@8.5.6)(typescript@5.9.3)(yaml@2.8.1)
|
||||
typescript:
|
||||
specifier: ^5.8.3
|
||||
version: 5.9.3
|
||||
|
||||
packages/rapier2d:
|
||||
devDependencies:
|
||||
rimraf:
|
||||
@@ -1458,6 +1488,9 @@ importers:
|
||||
'@esengine/engine-core':
|
||||
specifier: workspace:*
|
||||
version: link:../engine-core
|
||||
'@esengine/physics-rapier2d':
|
||||
specifier: workspace:*
|
||||
version: link:../physics-rapier2d
|
||||
rimraf:
|
||||
specifier: ^5.0.0
|
||||
version: 5.0.10
|
||||
@@ -1513,6 +1546,9 @@ importers:
|
||||
'@esengine/build-config':
|
||||
specifier: workspace:*
|
||||
version: link:../build-config
|
||||
'@esengine/ecs-engine-bindgen':
|
||||
specifier: workspace:*
|
||||
version: link:../ecs-engine-bindgen
|
||||
'@esengine/ecs-framework':
|
||||
specifier: workspace:*
|
||||
version: link:../core
|
||||
|
||||
Reference in New Issue
Block a user