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:
YHH
2025-12-08 21:10:57 +08:00
committed by GitHub
parent 2476379af1
commit c3b7250f85
86 changed files with 1813 additions and 551 deletions
@@ -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
+1
View File
@@ -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[];
}
/**
+3
View File
@@ -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,35 +59,23 @@ 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) {
bridge.unloadTexture(asset.textureId);
}
const bridge = getEngineBridge();
if (bridge?.unloadTexture) {
bridge.unloadTexture(asset.textureId);
}
// Clean up image data.
+32
View File
@@ -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');
+2 -2
View File
@@ -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;
}
+4 -1
View File
@@ -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';
+17
View File
@@ -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 {
/**
* 注册组件到组件注册表
*/
+8 -5
View File
@@ -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",
+12 -1
View File
@@ -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';
+125
View File
@@ -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,15 +113,44 @@ 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';
if (await TauriAPI.pathExists(`${installedPath}/index.json`)) {
return installedPath;
// 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)
@@ -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}`;
+1
View 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",
@@ -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) {
+1 -1
View File
@@ -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');
+2 -2
View File
@@ -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';
+1 -2
View File
@@ -196,9 +196,8 @@ export type {
ComponentAction,
// Plugin system types
IPluginLoader,
IRuntimeModuleLoader,
IEditorModuleLoader,
IEditorPlugin,
ModuleManifest,
ModuleCategory,
ModulePlatform,
+2 -1
View File
@@ -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:*",
+89 -12
View File
@@ -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-exportServiceToken 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 undefinedrequire
* 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');
+9 -2
View File
@@ -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)
+2 -2
View File
@@ -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
+1
View File
@@ -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",
+16 -1
View File
@@ -62,8 +62,23 @@ export interface Particle {
/** 初始透明度 | Initial alpha */
startAlpha: number;
// ============= 模块运行时状态 | Module Runtime State =============
// 这些字段由各模块在运行时设置 | These fields are set by modules at runtime
/** 初始速度XVelocityOverLifetimeModule 使用)| Initial velocity X (used by VelocityOverLifetimeModule) */
startVx?: number;
/** 初始速度YVelocityOverLifetimeModule 使用)| 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;
}
/**
+32 -65
View File
@@ -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);
}
}
+3 -1
View File
@@ -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) {
+20
View File
@@ -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);
}
/**
+10 -2
View File
@@ -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';
+11 -4
View File
@@ -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';
+177
View File
@@ -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');
+47
View File
@@ -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"
}
}
+202
View File
@@ -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"]
}
+17
View File
@@ -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"]
}
+14
View File
@@ -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'
]
});
+140 -47
View File
@@ -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?.();
}
// 反序列化场景
+25
View File
@@ -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';
+2 -2
View File
@@ -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
};
+2 -2
View File
@@ -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
+5 -5
View File
@@ -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);
+8 -2
View File
@@ -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);
}
}
+3
View File
@@ -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';
+17
View File
@@ -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');
+2 -2
View File
@@ -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
+1
View File
@@ -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",
+27 -20
View File
@@ -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);
}
}
+7 -1
View File
@@ -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;
/**
*
+27
View File
@@ -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');
+2 -2
View File
@@ -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
+1
View File
@@ -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",
+23 -13
View File
@@ -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);
}
}
+9 -1
View File
@@ -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';
+38
View File
@@ -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