feat: 预制体系统与架构改进 (#303)

* feat(prefab): 实现预制体系统和编辑器 UX 改进

## 预制体系统
- 新增 PrefabSerializer: 预制体序列化/反序列化
- 新增 PrefabInstanceComponent: 追踪预制体实例来源和修改
- 新增 PrefabService: 预制体核心服务
- 新增 PrefabLoader: 预制体资产加载器
- 新增预制体命令: Create/Instantiate/Apply/Revert/BreakLink

## 预制体编辑模式
- 支持双击 .prefab 文件进入编辑模式
- 预制体编辑模式工具栏 (保存/退出)
- 预制体实例指示器和操作菜单

## 编辑器 UX 改进
- SceneHierarchy 快捷键: F2 重命名, Ctrl+D 复制, ↑↓ 导航
- 支持双击实体名称内联编辑
- 删除实体时显示子节点数量警告
- 右键菜单添加重命名/复制选项及快捷键提示
- 布局持久化和重置功能

## Bug 修复
- 修复 editor-runtime 组件类重复导致的 TransformComponent 不识别问题
- 修复 .prefab-name 样式覆盖导致预制体工具栏文字不可见
- 修复 Inspector 资源字段高度不正确问题

* feat(editor): 改进编辑器 UX 交互体验

- ContentBrowser: 加载动画 spinner、搜索高亮、改进空状态设计
- SceneHierarchy: 选中项自动滚动到视图、搜索清除按钮
- PropertyInspector: 输入框本地状态管理、Enter/Escape 键处理
- EntityInspector: 组件折叠状态持久化、属性搜索清除按钮
- Viewport: 变换操作实时数值显示
- 国际化: 添加相关文本 (en/zh)

* fix(build): 修复 Web 构建资产加载和编辑器 UX 改进

构建系统修复:
- 修复 asset-catalog.json 字段名不匹配 (entries vs assets)
- 修复 BrowserFileSystemService 支持两种目录格式
- 修复 bundle 策略检测逻辑 (空对象判断)
- 修复 module.json 中 assetExtensions 声明和类型推断

行为树修复:
- 修复 BehaviorTreeExecutionSystem 使用 loadAsset 替代 loadAssetByPath
- 修复 BehaviorTreeAssetType 常量与 module.json 类型名一致 (behavior-tree)

编辑器 UX 改进:
- 构建完成对话框添加"打开文件夹"按钮
- 构建完成对话框样式优化 (圆形图标背景、按钮布局)
- SceneHierarchy 响应式布局 (窄窗口自动隐藏 Type 列)
- SceneHierarchy 隐藏滚动条

错误追踪:
- 添加全局错误处理器写入日志文件 (%TEMP%/esengine-editor-crash.log)
- 添加 append_to_log Tauri 命令

* feat(render): 修复 UI 渲染和点击特效系统

## UI 渲染修复
- 修复 GUID 验证 bug,使用统一的 isValidGUID() 函数
- 修复 UI 渲染顺序随机问题,Rust 端使用 IndexMap 替代 HashMap
- Web 运行时添加 assetPathResolver 支持 GUID 解析
- UIInteractableComponent.blockEvents 默认值改为 false

## 点击特效系统
- 新增 ClickFxComponent 和 ClickFxSystem
- 支持在点击位置播放粒子效果
- 支持多种触发模式和粒子轮换

## Camera 系统重构
- CameraSystem 从 ecs-engine-bindgen 移至 camera 包
- 新增 CameraManager 统一管理相机

## 编辑器改进
- 改进属性面板 UI 交互
- 粒子编辑器面板优化
- Transform 命令系统

* feat(render): 实现 Sorting Layer 系统和 Overlay 渲染层

- 新增 SortingLayerManager 管理排序层级 (Background, Default, Foreground, UI, Overlay)
- 实现 ISortable 接口,统一 Sprite、UI、Particle 的排序属性
- 修复粒子 Overlay 层被 UI 遮挡问题:添加独立的 Overlay Pass 在 UI 之后渲染
- 更新粒子资产格式:从 sortingOrder 改为 sortingLayer + orderInLayer
- 更新粒子编辑器面板支持新的排序属性
- 优化 UI 渲染系统使用新的排序层级

* feat(ci): 集成 SignPath 代码签名服务

- 添加 SignPath 自动签名工作流(Windows)
- 配置 release-editor.yml 支持代码签名
- 将构建改为草稿模式,等待签名完成后发布
- 添加证书文件到 .gitignore 防止泄露

* fix(asset): 修复 Web 构建资产路径解析和全局单例移除

## 资产路径修复
- 修复 Tauri 本地服务器 `/asset?path=...` 路径解析,正确与 root 目录连接
- BrowserPathResolver 支持两种模式:
  - 'proxy': 使用 /asset?path=... 格式(编辑器 Run in Browser)
  - 'direct': 使用直接路径 /assets/path.png(独立 Web 构建)
- BrowserRuntime 使用 'direct' 模式,无需 Tauri 代理

## 架构改进 - 移除全局单例
- 移除 globalAssetManager 导出,改用 AssetManagerToken 依赖注入
- 移除 globalPathResolver 导出,改用 PathResolutionService
- 移除 globalPathResolutionService 导出
- ParticleUpdateSystem/ClickFxSystem 通过 setAssetManager() 注入依赖
- EngineService 使用 new AssetManager() 替代全局实例

## 新增服务
- PathResolutionService: 统一路径解析接口
- RuntimeModeService: 运行时模式查询服务
- SerializationContext: EntityRef 序列化上下文

## 其他改进
- 完善 ServiceToken 注释说明本地定义的意图
- 导出 BrowserPathResolveMode 类型

* fix(build): 添加 world-streaming composite 设置修复类型检查

* fix(build): 移除 world-streaming 引用避免 composite 冲突

* fix(build): 将 const enum 改为 enum 兼容 isolatedModules

* fix(build): 添加缺失的 IAssetManager 导入
This commit is contained in:
YHH
2025-12-13 19:44:08 +08:00
committed by GitHub
parent a716d8006c
commit beaa1d09de
258 changed files with 17725 additions and 3030 deletions

View File

@@ -1,6 +1,7 @@
{
"id": "core",
"name": "@esengine/ecs-framework",
"globalKey": "ecsFramework",
"displayName": "Core ECS",
"outputPath": "dist/index.mjs",
"description": "Core Entity-Component-System framework | 核心 ECS 框架",

View File

@@ -42,14 +42,23 @@ export interface ServiceToken<T> {
* 创建服务令牌
* Create a service token
*
* 使用 Symbol.for() 确保相同名称的令牌在不同模块中引用同一个 Symbol。
* Uses Symbol.for() to ensure tokens with the same name reference the same Symbol across modules.
*
* 这解决了跨包场景下服务注册和获取使用不同 Symbol 的问题。
* This fixes the issue where service registration and retrieval use different Symbols across packages.
*
* @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
// 使用 Symbol.for() 从全局 Symbol 注册表获取或创建 Symbol
// 这确保相同名称在任何地方都返回同一个 Symbol
// Use Symbol.for() to get or create Symbol from global Symbol registry
// This ensures the same name returns the same Symbol everywhere
const tokenKey = `@esengine/service:${name}`;
return {
id: Symbol(name),
id: Symbol.for(tokenKey),
name
} as ServiceToken<T>;
}

View File

@@ -0,0 +1,284 @@
/**
* 运行时模式服务
* Runtime Mode Service
*
* 提供统一的运行时模式查询接口,使第三方模块能够感知当前运行环境。
* Provides unified runtime mode query interface for third-party modules to be aware of current runtime environment.
*
* 模式定义 | Mode Definitions:
* - Editor 模式编辑器环境显示网格、Gizmos、坐标轴等
* - Playing 模式游戏运行中Play 按钮已按下)
* - Preview 模式:预览模式(场景预览但不是完整的游戏运行)
*
* @example
* ```typescript
* import { RuntimeModeToken, type IRuntimeMode } from '@esengine/ecs-framework';
*
* // 获取服务
* const runtimeMode = context.services.get(RuntimeModeToken);
*
* // 检查当前模式
* if (runtimeMode?.isEditor) {
* // 编辑器特定逻辑
* }
*
* // 监听模式变化
* const unsubscribe = runtimeMode?.onModeChanged((mode) => {
* console.log('Mode changed:', mode.isPlaying ? 'Playing' : 'Stopped');
* });
* ```
*/
import { createServiceToken } from './PluginServiceRegistry';
// ============================================================================
// 接口定义 | Interface Definitions
// ============================================================================
/**
* 运行时模式接口
* Runtime mode interface
*/
export interface IRuntimeMode {
/**
* 是否为编辑器模式
* Whether in editor mode
*
* 编辑器模式下会显示网格、Gizmos、坐标轴指示器等辅助元素。
* In editor mode, grid, gizmos, axis indicator and other helper elements are shown.
*/
readonly isEditor: boolean;
/**
* 是否正在播放(游戏运行中)
* Whether playing (game is running)
*
* 当用户点击 Play 按钮后为 true点击 Stop 后为 false。
* True after user clicks Play button, false after clicking Stop.
*/
readonly isPlaying: boolean;
/**
* 是否为预览模式
* Whether in preview mode
*
* 预览模式是编辑器中的场景预览,不是完整的游戏运行。
* Preview mode is scene preview in editor, not full game runtime.
*/
readonly isPreview: boolean;
/**
* 是否为独立运行时(非编辑器环境)
* Whether in standalone runtime (non-editor environment)
*
* Web 构建、移动端等独立运行环境中为 true。
* True in standalone runtime environments like web build, mobile, etc.
*/
readonly isStandalone: boolean;
/**
* 订阅模式变化事件
* Subscribe to mode change events
*
* @param callback 模式变化回调
* @returns 取消订阅函数
*/
onModeChanged(callback: (mode: IRuntimeMode) => void): () => void;
}
// ============================================================================
// 服务令牌 | Service Token
// ============================================================================
/**
* 运行时模式服务令牌
* Runtime mode service token
*/
export const RuntimeModeToken = createServiceToken<IRuntimeMode>('runtimeMode');
// ============================================================================
// 默认实现 | Default Implementation
// ============================================================================
/**
* 模式变化回调类型
* Mode change callback type
*/
type ModeChangeCallback = (mode: IRuntimeMode) => void;
/**
* 运行时模式服务配置
* Runtime mode service configuration
*/
export interface RuntimeModeConfig {
/** 是否为编辑器模式 | Whether in editor mode */
isEditor?: boolean;
/** 是否正在播放 | Whether playing */
isPlaying?: boolean;
/** 是否为预览模式 | Whether in preview mode */
isPreview?: boolean;
}
/**
* 运行时模式服务默认实现
* Default runtime mode service implementation
*/
export class RuntimeModeService implements IRuntimeMode {
private _isEditor: boolean;
private _isPlaying: boolean;
private _isPreview: boolean;
private _callbacks: Set<ModeChangeCallback> = new Set();
/**
* 创建运行时模式服务
* Create runtime mode service
*
* @param config 初始配置
*/
constructor(config: RuntimeModeConfig = {}) {
this._isEditor = config.isEditor ?? false;
this._isPlaying = config.isPlaying ?? false;
this._isPreview = config.isPreview ?? false;
}
// ========== IRuntimeMode 实现 ==========
get isEditor(): boolean {
return this._isEditor;
}
get isPlaying(): boolean {
return this._isPlaying;
}
get isPreview(): boolean {
return this._isPreview;
}
get isStandalone(): boolean {
return !this._isEditor;
}
onModeChanged(callback: ModeChangeCallback): () => void {
this._callbacks.add(callback);
return () => {
this._callbacks.delete(callback);
};
}
// ========== 设置方法(供运行时内部使用)==========
/**
* 设置编辑器模式
* Set editor mode
*
* @internal
*/
setEditorMode(isEditor: boolean): void {
if (this._isEditor !== isEditor) {
this._isEditor = isEditor;
this._notifyChange();
}
}
/**
* 设置播放状态
* Set playing state
*
* @internal
*/
setPlaying(isPlaying: boolean): void {
if (this._isPlaying !== isPlaying) {
this._isPlaying = isPlaying;
this._notifyChange();
}
}
/**
* 设置预览模式
* Set preview mode
*
* @internal
*/
setPreview(isPreview: boolean): void {
if (this._isPreview !== isPreview) {
this._isPreview = isPreview;
this._notifyChange();
}
}
/**
* 批量更新模式
* Batch update mode
*
* @internal
*/
updateMode(config: RuntimeModeConfig): void {
let changed = false;
if (config.isEditor !== undefined && this._isEditor !== config.isEditor) {
this._isEditor = config.isEditor;
changed = true;
}
if (config.isPlaying !== undefined && this._isPlaying !== config.isPlaying) {
this._isPlaying = config.isPlaying;
changed = true;
}
if (config.isPreview !== undefined && this._isPreview !== config.isPreview) {
this._isPreview = config.isPreview;
changed = true;
}
if (changed) {
this._notifyChange();
}
}
/**
* 通知模式变化
* Notify mode change
*/
private _notifyChange(): void {
for (const callback of this._callbacks) {
try {
callback(this);
} catch (error) {
console.error('[RuntimeModeService] Callback error:', error);
}
}
}
/**
* 释放资源
* Dispose resources
*/
dispose(): void {
this._callbacks.clear();
}
}
/**
* 创建编辑器模式服务
* Create editor mode service
*/
export function createEditorModeService(): RuntimeModeService {
return new RuntimeModeService({
isEditor: true,
isPlaying: false,
isPreview: false
});
}
/**
* 创建独立运行时模式服务
* Create standalone runtime mode service
*/
export function createStandaloneModeService(): RuntimeModeService {
return new RuntimeModeService({
isEditor: false,
isPlaying: true,
isPreview: false
});
}

View File

@@ -19,7 +19,7 @@ import { Serializable, Serialize } from '../Serialization/SerializationDecorator
* const children = hierarchySystem.getChildren(entity);
* ```
*/
@ECSComponent('Hierarchy')
@ECSComponent('Hierarchy', { editor: { hideInInspector: true } })
@Serializable({ version: 1, typeId: 'Hierarchy' })
export class HierarchyComponent extends Component {
/**

View File

@@ -0,0 +1,211 @@
/**
* 预制体实例组件 - 用于追踪预制体实例
* Prefab instance component - for tracking prefab instances
*
* 当实体从预制体实例化时,会自动添加此组件以追踪其源预制体。
* When an entity is instantiated from a prefab, this component is automatically added to track its source.
*/
import { Component } from '../Component';
import { ECSComponent } from '../Decorators';
import { Serializable, Serialize } from '../Serialization/SerializationDecorators';
/**
* 预制体实例组件
* Prefab instance component
*
* 标记实体为预制体实例,并存储与源预制体的关联信息。
* Marks an entity as a prefab instance and stores association with source prefab.
*
* @example
* ```typescript
* // 检查实体是否为预制体实例 | Check if entity is a prefab instance
* const prefabComp = entity.getComponent(PrefabInstanceComponent);
* if (prefabComp) {
* console.log(`Instance of prefab: ${prefabComp.sourcePrefabGuid}`);
* }
* ```
*/
@ECSComponent('PrefabInstance', { editor: { hideInInspector: true } })
@Serializable({ version: 1, typeId: 'PrefabInstance' })
export class PrefabInstanceComponent extends Component {
/**
* 源预制体的资产 GUID
* Source prefab asset GUID
*/
@Serialize()
public sourcePrefabGuid: string = '';
/**
* 源预制体的资产路径(用于显示和调试)
* Source prefab asset path (for display and debugging)
*/
@Serialize()
public sourcePrefabPath: string = '';
/**
* 是否为预制体层级的根实体
* Whether this is the root entity of the prefab hierarchy
*/
@Serialize()
public isRoot: boolean = false;
/**
* 根预制体实例的实体 ID用于子实体追溯到根实例
* Entity ID of the root prefab instance (for child entities to trace back to root)
*/
@Serialize()
public rootInstanceEntityId: number | null = null;
/**
* 属性覆盖记录
* Property override records
*
* 记录哪些属性被用户修改过格式componentType.propertyPath
* Records which properties have been modified by user, format: componentType.propertyPath
*/
@Serialize()
public modifiedProperties: string[] = [];
/**
* 实例化时间戳
* Instantiation timestamp
*/
@Serialize()
public instantiatedAt: number = 0;
/**
* 属性原始值存储
* Original property values storage
*
* 存储被修改属性的原始值,用于还原操作。
* Stores original values of modified properties for revert operations.
* 格式:{ "ComponentType.propertyPath": originalValue }
* Format: { "ComponentType.propertyPath": originalValue }
*/
@Serialize()
public originalValues: Record<string, unknown> = {};
constructor(
sourcePrefabGuid: string = '',
sourcePrefabPath: string = '',
isRoot: boolean = false
) {
super();
this.sourcePrefabGuid = sourcePrefabGuid;
this.sourcePrefabPath = sourcePrefabPath;
this.isRoot = isRoot;
this.instantiatedAt = Date.now();
}
/**
* 标记属性为已修改
* Mark a property as modified
*
* @param componentType - 组件类型名称 | Component type name
* @param propertyPath - 属性路径 | Property path
*/
public markPropertyModified(componentType: string, propertyPath: string): void {
const key = `${componentType}.${propertyPath}`;
if (!this.modifiedProperties.includes(key)) {
this.modifiedProperties.push(key);
}
}
/**
* 检查属性是否已被修改
* Check if a property has been modified
*
* @param componentType - 组件类型名称 | Component type name
* @param propertyPath - 属性路径 | Property path
* @returns 是否已修改 | Whether it has been modified
*/
public isPropertyModified(componentType: string, propertyPath: string): boolean {
const key = `${componentType}.${propertyPath}`;
return this.modifiedProperties.includes(key);
}
/**
* 清除属性修改标记
* Clear property modification mark
*
* @param componentType - 组件类型名称 | Component type name
* @param propertyPath - 属性路径 | Property path
*/
public clearPropertyModified(componentType: string, propertyPath: string): void {
const key = `${componentType}.${propertyPath}`;
const index = this.modifiedProperties.indexOf(key);
if (index !== -1) {
this.modifiedProperties.splice(index, 1);
}
}
/**
* 清除所有属性修改标记
* Clear all property modification marks
*/
public clearAllModifications(): void {
this.modifiedProperties = [];
this.originalValues = {};
}
/**
* 存储属性的原始值
* Store original value of a property
*
* 只有在第一次修改时才存储,后续修改不覆盖。
* Only stores on first modification, subsequent modifications don't overwrite.
*
* @param componentType - 组件类型名称 | Component type name
* @param propertyPath - 属性路径 | Property path
* @param value - 原始值 | Original value
*/
public storeOriginalValue(componentType: string, propertyPath: string, value: unknown): void {
const key = `${componentType}.${propertyPath}`;
// 只在第一次修改时存储原始值 | Only store on first modification
if (!(key in this.originalValues)) {
// 深拷贝值以防止引用问题 | Deep clone to prevent reference issues
this.originalValues[key] = this.deepClone(value);
}
}
/**
* 获取属性的原始值
* Get original value of a property
*
* @param key - 属性键格式componentType.propertyPath| Property key (format: componentType.propertyPath)
* @returns 原始值,如果不存在则返回 undefined | Original value or undefined if not found
*/
public getOriginalValue(key: string): unknown {
return this.originalValues[key];
}
/**
* 检查是否有属性的原始值
* Check if original value exists for a property
*
* @param componentType - 组件类型名称 | Component type name
* @param propertyPath - 属性路径 | Property path
* @returns 是否存在原始值 | Whether original value exists
*/
public hasOriginalValue(componentType: string, propertyPath: string): boolean {
const key = `${componentType}.${propertyPath}`;
return key in this.originalValues;
}
/**
* 深拷贝值
* Deep clone value
*/
private deepClone(value: unknown): unknown {
if (value === null || value === undefined) return value;
if (typeof value === 'object') {
try {
return JSON.parse(JSON.stringify(value));
} catch {
return value;
}
}
return value;
}
}

View File

@@ -1 +1,2 @@
export { HierarchyComponent } from './HierarchyComponent';
export { PrefabInstanceComponent } from './PrefabInstanceComponent';

View File

@@ -29,6 +29,38 @@ export const COMPONENT_TYPE_NAME = Symbol('ComponentTypeName');
*/
export const COMPONENT_DEPENDENCIES = Symbol('ComponentDependencies');
/**
* 存储组件编辑器选项的 Symbol 键
* Symbol key for storing component editor options
*/
export const COMPONENT_EDITOR_OPTIONS = Symbol('ComponentEditorOptions');
/**
* 组件编辑器选项
* Component editor options
*/
export interface ComponentEditorOptions {
/**
* 是否在 Inspector 中隐藏此组件
* Whether to hide this component in Inspector
*
* @default false
*/
hideInInspector?: boolean;
/**
* 组件分类(用于 Inspector 中的分组显示)
* Component category (for grouping in Inspector)
*/
category?: string;
/**
* 组件图标(用于 Inspector 中的显示)
* Component icon (for display in Inspector)
*/
icon?: string;
}
/**
* 检查组件是否使用了 @ECSComponent 装饰器
* Check if component has @ECSComponent decorator
@@ -81,3 +113,48 @@ export function getComponentInstanceTypeName(component: Component): string {
export function getComponentDependencies(componentType: ComponentType): string[] | undefined {
return (componentType as any)[COMPONENT_DEPENDENCIES];
}
/**
* 获取组件的编辑器选项
* Get component editor options
*
* @param componentType 组件构造函数
* @returns 编辑器选项
*/
export function getComponentEditorOptions(componentType: ComponentType): ComponentEditorOptions | undefined {
return (componentType as any)[COMPONENT_EDITOR_OPTIONS];
}
/**
* 从组件实例获取编辑器选项
* Get editor options from component instance
*
* @param component 组件实例
* @returns 编辑器选项
*/
export function getComponentInstanceEditorOptions(component: Component): ComponentEditorOptions | undefined {
return getComponentEditorOptions(component.constructor as ComponentType);
}
/**
* 检查组件是否应该在 Inspector 中隐藏
* Check if component should be hidden in Inspector
*
* @param componentType 组件构造函数
* @returns 是否隐藏
*/
export function isComponentHiddenInInspector(componentType: ComponentType): boolean {
const options = getComponentEditorOptions(componentType);
return options?.hideInInspector ?? false;
}
/**
* 从组件实例检查是否应该在 Inspector 中隐藏
* Check if component instance should be hidden in Inspector
*
* @param component 组件实例
* @returns 是否隐藏
*/
export function isComponentInstanceHiddenInInspector(component: Component): boolean {
return isComponentHiddenInInspector(component.constructor as ComponentType);
}

View File

@@ -145,3 +145,36 @@ export function getEntityRefMetadata(component: any): EntityRefMetadata | null {
export function hasEntityRef(component: any): boolean {
return getEntityRefMetadata(component) !== null;
}
/**
* 检查特定属性是否为EntityRef
*
* Check if a specific property is an EntityRef.
*
* @param component Component实例或Component类
* @param propertyKey 属性名
* @returns 如果是EntityRef属性返回true
*/
export function isEntityRefProperty(component: any, propertyKey: string): boolean {
const metadata = getEntityRefMetadata(component);
if (!metadata) {
return false;
}
return metadata.properties.has(propertyKey);
}
/**
* 获取组件的所有EntityRef属性名
*
* Get all EntityRef property names of a component.
*
* @param component Component实例或Component类
* @returns EntityRef属性名数组
*/
export function getEntityRefProperties(component: any): string[] {
const metadata = getEntityRefMetadata(component);
if (!metadata) {
return [];
}
return Array.from(metadata.properties);
}

View File

@@ -1,12 +1,15 @@
import 'reflect-metadata';
export type PropertyType = 'number' | 'integer' | 'string' | 'boolean' | 'color' | 'vector2' | 'vector3' | 'enum' | 'asset' | 'animationClips' | 'collisionLayer' | 'collisionMask';
export type PropertyType = 'number' | 'integer' | 'string' | 'boolean' | 'color' | 'vector2' | 'vector3' | 'enum' | 'asset' | 'array' | 'animationClips' | 'collisionLayer' | 'collisionMask';
/**
* 资源类型
* Asset type for asset properties
* 属性资源类型
* Asset type for property decorators
*/
export type AssetType = 'texture' | 'audio' | 'scene' | 'prefab' | 'animation' | 'any';
export type PropertyAssetType = 'texture' | 'audio' | 'scene' | 'prefab' | 'animation' | 'any';
/** @deprecated Use PropertyAssetType instead */
export type AssetType = PropertyAssetType;
/**
* 枚举选项 - 支持简单字符串或带标签的对象
@@ -119,11 +122,52 @@ interface EnumPropertyOptions extends PropertyOptionsBase {
interface AssetPropertyOptions extends PropertyOptionsBase {
type: 'asset';
/** 资源类型 | Asset type */
assetType?: AssetType;
assetType?: PropertyAssetType;
/** 文件扩展名过滤 | File extension filter */
extensions?: string[];
}
/**
* 数组元素类型选项
* Array item type options
*/
export type ArrayItemType =
| { type: 'string' }
| { type: 'number'; min?: number; max?: number }
| { type: 'integer'; min?: number; max?: number }
| { type: 'boolean' }
| { type: 'asset'; assetType?: PropertyAssetType; extensions?: string[] }
| { type: 'vector2' }
| { type: 'vector3' }
| { type: 'color'; alpha?: boolean }
| { type: 'enum'; options: EnumOption[] };
/**
* 数组类型属性选项
* Array property options
*
* @example
* ```typescript
* @Property({
* type: 'array',
* label: 'Particle Assets',
* itemType: { type: 'asset', extensions: ['.particle'] }
* })
* public particleAssets: string[] = [];
* ```
*/
interface ArrayPropertyOptions extends PropertyOptionsBase {
type: 'array';
/** 数组元素类型 | Array item type */
itemType: ArrayItemType;
/** 最小数组长度 | Minimum array length */
minLength?: number;
/** 最大数组长度 | Maximum array length */
maxLength?: number;
/** 是否允许重排序 | Allow reordering */
reorderable?: boolean;
}
/**
* 动画剪辑类型属性选项
* Animation clips property options
@@ -160,6 +204,7 @@ export type PropertyOptions =
| VectorPropertyOptions
| EnumPropertyOptions
| AssetPropertyOptions
| ArrayPropertyOptions
| AnimationClipsPropertyOptions
| CollisionLayerPropertyOptions
| CollisionMaskPropertyOptions;

View File

@@ -13,7 +13,9 @@ import type { EntitySystem } from '../Systems';
import { ComponentRegistry } from '../Core/ComponentStorage/ComponentRegistry';
import {
COMPONENT_TYPE_NAME,
COMPONENT_DEPENDENCIES
COMPONENT_DEPENDENCIES,
COMPONENT_EDITOR_OPTIONS,
type ComponentEditorOptions
} from '../Core/ComponentStorage/ComponentTypeUtils';
/**
@@ -29,6 +31,12 @@ export const SYSTEM_TYPE_NAME = Symbol('SystemTypeName');
export interface ComponentOptions {
/** 依赖的其他组件名称列表 | List of required component names */
requires?: string[];
/**
* 编辑器相关选项
* Editor-related options
*/
editor?: ComponentEditorOptions;
}
/**
@@ -74,6 +82,12 @@ export function ECSComponent(typeName: string, options?: ComponentOptions) {
(target as any)[COMPONENT_DEPENDENCIES] = options.requires;
}
// 存储编辑器选项
// Store editor options
if (options?.editor) {
(target as any)[COMPONENT_EDITOR_OPTIONS] = options.editor;
}
// 自动注册到 ComponentRegistry使组件可以通过名称查找
// Auto-register to ComponentRegistry, enabling lookup by name
ComponentRegistry.register(target);

View File

@@ -5,13 +5,18 @@
export {
COMPONENT_TYPE_NAME,
COMPONENT_DEPENDENCIES,
COMPONENT_EDITOR_OPTIONS,
getComponentTypeName,
getComponentInstanceTypeName,
getComponentDependencies,
getComponentEditorOptions,
getComponentInstanceEditorOptions,
isComponentHiddenInInspector,
isComponentInstanceHiddenInInspector,
hasECSComponentDecorator
} from '../Core/ComponentStorage/ComponentTypeUtils';
export type { ComponentType } from '../Core/ComponentStorage/ComponentTypeUtils';
export type { ComponentType, ComponentEditorOptions } from '../Core/ComponentStorage/ComponentTypeUtils';
// ============================================================================
// Type Decorators (ECSComponent, ECSSystem)
@@ -36,6 +41,8 @@ export {
EntityRef,
getEntityRefMetadata,
hasEntityRef,
isEntityRefProperty,
getEntityRefProperties,
ENTITY_REF_METADATA
} from './EntityRefDecorator';
@@ -57,6 +64,6 @@ export type {
PropertyType,
PropertyControl,
PropertyAction,
AssetType,
PropertyAssetType,
EnumOption
} from './PropertyDecorator';

View File

@@ -4,6 +4,7 @@ import { EEntityLifecyclePolicy } from './Core/EntityLifecyclePolicy';
import { BitMask64Utils, BitMask64Data } from './Utils/BigIntCompatibility';
import { createLogger } from '../Utils/Logger';
import { getComponentInstanceTypeName, getComponentTypeName } from './Decorators';
import { generateGUID } from '../Utils/GUID';
import type { IScene } from './IScene';
/**
@@ -75,10 +76,23 @@ export class Entity {
public name: string;
/**
* 实体唯一标识符
* 实体唯一标识符(运行时 ID
*
* Runtime identifier for fast lookups.
*/
public readonly id: number;
/**
* 持久化唯一标识符GUID
*
* 用于序列化/反序列化时保持实体引用一致性。
* 在场景保存和加载时保持不变。
*
* Persistent identifier for serialization.
* Remains stable across save/load cycles.
*/
public readonly persistentId: string;
/**
* 所属场景引用
*/
@@ -130,11 +144,13 @@ export class Entity {
* 构造函数
*
* @param name - 实体名称
* @param id - 实体唯一标识符
* @param id - 实体唯一标识符(运行时 ID
* @param persistentId - 持久化标识符(可选,用于反序列化时恢复)
*/
constructor(name: string, id: number) {
constructor(name: string, id: number, persistentId?: string) {
this.name = name;
this.id = id;
this.persistentId = persistentId ?? generateGUID();
}
/**
@@ -779,7 +795,7 @@ export class Entity {
* @returns 实体的字符串描述
*/
public toString(): string {
return `Entity[${this.name}:${this.id}]`;
return `Entity[${this.name}:${this.id}:${this.persistentId.slice(0, 8)}]`;
}
/**
@@ -790,6 +806,7 @@ export class Entity {
public getDebugInfo(): {
name: string;
id: number;
persistentId: string;
enabled: boolean;
active: boolean;
destroyed: boolean;
@@ -801,6 +818,7 @@ export class Entity {
return {
name: this.name,
id: this.id,
persistentId: this.persistentId,
enabled: this._enabled,
active: this._active,
destroyed: this._isDestroyed,

View File

@@ -6,10 +6,12 @@
import { Component } from '../Component';
import { ComponentType } from '../Core/ComponentStorage';
import { getComponentTypeName } from '../Decorators';
import { getComponentTypeName, isEntityRefProperty } from '../Decorators';
import {
getSerializationMetadata
} from './SerializationDecorators';
import type { Entity } from '../Entity';
import type { SerializationContext, SerializedEntityRef } from './SerializationContext';
/**
* 可序列化的值类型
@@ -24,7 +26,8 @@ export type SerializableValue =
| { [key: string]: SerializableValue }
| { __type: 'Date'; value: string }
| { __type: 'Map'; value: Array<[SerializableValue, SerializableValue]> }
| { __type: 'Set'; value: SerializableValue[] };
| { __type: 'Set'; value: SerializableValue[] }
| { __entityRef: SerializedEntityRef };
/**
* 序列化后的组件数据
@@ -71,17 +74,25 @@ export class ComponentSerializer {
// 序列化标记的字段
for (const [fieldName, options] of metadata.fields) {
const fieldKey = typeof fieldName === 'symbol' ? fieldName.toString() : fieldName;
const value = (component as unknown as Record<string | symbol, SerializableValue>)[fieldName];
const value = (component as unknown as Record<string | symbol, unknown>)[fieldName];
// 跳过忽略的字段
if (metadata.ignoredFields.has(fieldName)) {
continue;
}
// 使用自定义序列化器或默认序列化
const serializedValue = options.serializer
? options.serializer(value)
: this.serializeValue(value);
let serializedValue: SerializableValue;
// 检查是否为 EntityRef 属性
if (isEntityRefProperty(component, fieldKey)) {
serializedValue = this.serializeEntityRef(value as Entity | null);
} else if (options.serializer) {
// 使用自定义序列化器
serializedValue = options.serializer(value);
} else {
// 使用默认序列化
serializedValue = this.serializeValue(value as SerializableValue);
}
// 使用别名或原始字段名
const key = options.alias || fieldKey;
@@ -100,11 +111,13 @@ export class ComponentSerializer {
*
* @param serializedData 序列化的组件数据
* @param componentRegistry 组件类型注册表 (类型名 -> 构造函数)
* @param context 序列化上下文(可选,用于解析 EntityRef
* @returns 反序列化后的组件实例如果失败则返回null
*/
public static deserialize(
serializedData: SerializedComponent,
componentRegistry: Map<string, ComponentType>
componentRegistry: Map<string, ComponentType>,
context?: SerializationContext
): Component | null {
const componentClass = componentRegistry.get(serializedData.type);
@@ -133,6 +146,18 @@ export class ComponentSerializer {
continue; // 字段不存在于序列化数据中
}
// 检查是否为序列化的 EntityRef
if (this.isSerializedEntityRef(serializedValue)) {
// EntityRef 需要延迟解析
if (context) {
const ref = serializedValue.__entityRef;
context.registerPendingRef(component, fieldKey, ref.id, ref.guid);
}
// 暂时设为 null后续由 context.resolveAllReferences() 填充
(component as unknown as Record<string | symbol, unknown>)[fieldName] = null;
continue;
}
// 使用自定义反序列化器或默认反序列化
const value = options.deserializer
? options.deserializer(serializedValue)
@@ -168,16 +193,18 @@ export class ComponentSerializer {
*
* @param serializedComponents 序列化的组件数据数组
* @param componentRegistry 组件类型注册表
* @param context 序列化上下文(可选,用于解析 EntityRef
* @returns 反序列化后的组件数组
*/
public static deserializeComponents(
serializedComponents: SerializedComponent[],
componentRegistry: Map<string, ComponentType>
componentRegistry: Map<string, ComponentType>,
context?: SerializationContext
): Component[] {
const result: Component[] = [];
for (const serialized of serializedComponents) {
const component = this.deserialize(serialized, componentRegistry);
const component = this.deserialize(serialized, componentRegistry, context);
if (component) {
result.push(component);
}
@@ -349,4 +376,41 @@ export class ComponentSerializer {
isSerializable: true
};
}
/**
* 序列化 Entity 引用
*
* Serialize an Entity reference to a portable format.
*
* @param entity Entity 实例或 null
* @returns 序列化的引用格式
*/
public static serializeEntityRef(entity: Entity | null): SerializableValue {
if (!entity) {
return null;
}
return {
__entityRef: {
id: entity.id,
guid: entity.persistentId
}
};
}
/**
* 检查值是否为序列化的 EntityRef
*
* Check if a value is a serialized EntityRef.
*
* @param value 要检查的值
* @returns 如果是 EntityRef 返回 true
*/
public static isSerializedEntityRef(value: unknown): value is { __entityRef: SerializedEntityRef } {
return (
typeof value === 'object' &&
value !== null &&
'__entityRef' in value
);
}
}

View File

@@ -10,16 +10,26 @@ import { ComponentSerializer, SerializedComponent } from './ComponentSerializer'
import { IScene } from '../IScene';
import { HierarchyComponent } from '../Components/HierarchyComponent';
import { HierarchySystem } from '../Systems/HierarchySystem';
import { SerializationContext } from './SerializationContext';
/**
* 序列化后的实体数据
*/
export interface SerializedEntity {
/**
* 实体ID
* 实体ID运行时ID
*
* Runtime ID.
*/
id: number;
/**
* 持久化 GUID
*
* Persistent GUID for cross-session reference resolution.
*/
guid?: string;
/**
* 实体名称
*/
@@ -84,6 +94,7 @@ export class EntitySerializer {
const serializedEntity: SerializedEntity = {
id: entity.id,
guid: entity.persistentId,
name: entity.name,
tag: entity.tag,
active: entity.active,
@@ -120,12 +131,16 @@ export class EntitySerializer {
/**
* 反序列化实体
*
* Deserialize an entity from serialized data.
*
* @param serializedEntity 序列化的实体数据
* @param componentRegistry 组件类型注册表
* @param idGenerator 实体ID生成器用于生成新ID或保持原ID
* @param preserveIds 是否保持原始ID默认false
* @param scene 目标场景可选用于设置entity.scene以支持添加组件
* @param hierarchySystem 层级系统(可选,用于建立层级关系)
* @param allEntities 所有实体的映射(可选,用于收集所有实体)
* @param context 序列化上下文(可选,用于解析 EntityRef
* @returns 反序列化后的实体
*/
public static deserialize(
@@ -135,15 +150,21 @@ export class EntitySerializer {
preserveIds: boolean = false,
scene?: IScene,
hierarchySystem?: HierarchySystem | null,
allEntities?: Map<number, Entity>
allEntities?: Map<number, Entity>,
context?: SerializationContext
): Entity {
// 创建实体使用原始ID或新生成的ID
// 创建实体使用原始ID或新生成的ID,保留原始 GUID
const entityId = preserveIds ? serializedEntity.id : idGenerator();
const entity = new Entity(serializedEntity.name, entityId);
const entity = new Entity(serializedEntity.name, entityId, serializedEntity.guid);
// 将实体添加到收集 Map 中(用于后续添加到场景)
allEntities?.set(entity.id, entity);
// 注册实体到序列化上下文(用于后续解析 EntityRef
if (context) {
context.registerEntity(entity, serializedEntity.id, serializedEntity.guid);
}
// 如果提供了scene先设置entity.scene以支持添加组件
if (scene) {
entity.scene = scene;
@@ -155,10 +176,11 @@ export class EntitySerializer {
entity.enabled = serializedEntity.enabled;
entity.updateOrder = serializedEntity.updateOrder;
// 反序列化组件
// 反序列化组件(传入 context 以支持 EntityRef 解析)
const components = ComponentSerializer.deserializeComponents(
serializedEntity.components,
componentRegistry
componentRegistry,
context
);
for (const component of components) {
@@ -183,7 +205,8 @@ export class EntitySerializer {
preserveIds,
scene,
hierarchySystem,
allEntities
allEntities,
context
);
// 使用 HierarchySystem 建立层级关系
hierarchySystem?.setParent(childEntity, entity);
@@ -223,12 +246,15 @@ export class EntitySerializer {
/**
* 批量反序列化实体
*
* Deserialize multiple entities from serialized data.
*
* @param serializedEntities 序列化的实体数据数组
* @param componentRegistry 组件类型注册表
* @param idGenerator 实体ID生成器
* @param preserveIds 是否保持原始ID
* @param scene 目标场景可选用于设置entity.scene以支持添加组件
* @param hierarchySystem 层级系统(可选,用于建立层级关系)
* @param context 序列化上下文(可选,用于解析 EntityRef
* @returns 反序列化后的实体数组
*/
public static deserializeEntities(
@@ -237,7 +263,8 @@ export class EntitySerializer {
idGenerator: () => number,
preserveIds: boolean = false,
scene?: IScene,
hierarchySystem?: HierarchySystem | null
hierarchySystem?: HierarchySystem | null,
context?: SerializationContext
): { rootEntities: Entity[]; allEntities: Map<number, Entity> } {
const rootEntities: Entity[] = [];
const allEntities = new Map<number, Entity>();
@@ -250,7 +277,8 @@ export class EntitySerializer {
preserveIds,
scene,
hierarchySystem,
allEntities
allEntities,
context
);
rootEntities.push(entity);
}

View File

@@ -0,0 +1,470 @@
/**
* 预制体序列化器
* Prefab serializer
*
* 提供预制体的创建和实例化功能。
* Provides prefab creation and instantiation functionality.
*/
import { Entity } from '../Entity';
import { IScene } from '../IScene';
import { ComponentType } from '../Core/ComponentStorage';
import { EntitySerializer, SerializedEntity } from './EntitySerializer';
import { HierarchySystem } from '../Systems/HierarchySystem';
import { PrefabInstanceComponent } from '../Components/PrefabInstanceComponent';
/**
* 序列化的预制体实体(扩展自 SerializedEntity
* Serialized prefab entity (extends SerializedEntity)
*/
export interface SerializedPrefabEntity extends SerializedEntity {
/**
* 是否为预制体根节点
* Whether this is the prefab root entity
*/
isPrefabRoot?: boolean;
/**
* 嵌套预制体的 GUID
* GUID of nested prefab
*/
nestedPrefabGuid?: string;
}
/**
* 预制体元数据
* Prefab metadata
*/
export interface PrefabMetadata {
/** 预制体名称 | Prefab name */
name: string;
/** 资产 GUID | Asset GUID */
guid?: string;
/** 创建时间戳 | Creation timestamp */
createdAt: number;
/** 最后修改时间戳 | Last modification timestamp */
modifiedAt: number;
/** 使用的组件类型列表 | List of component types used */
componentTypes: string[];
/** 引用的资产 GUID 列表 | List of referenced asset GUIDs */
referencedAssets: string[];
/** 预制体描述 | Prefab description */
description?: string;
/** 预制体标签 | Prefab tags */
tags?: string[];
}
/**
* 组件类型注册条目
* Component type registry entry
*/
export interface PrefabComponentTypeEntry {
/** 组件类型名称 | Component type name */
typeName: string;
/** 组件版本号 | Component version number */
version: number;
}
/**
* 预制体数据格式
* Prefab data format
*/
export interface PrefabData {
/** 预制体格式版本号 | Prefab format version number */
version: number;
/** 预制体元数据 | Prefab metadata */
metadata: PrefabMetadata;
/** 根实体数据 | Root entity data */
root: SerializedPrefabEntity;
/** 组件类型注册表 | Component type registry */
componentTypeRegistry: PrefabComponentTypeEntry[];
}
/**
* 预制体创建选项
* Prefab creation options
*/
export interface PrefabCreateOptions {
/** 预制体名称 | Prefab name */
name: string;
/** 预制体描述 | Prefab description */
description?: string;
/** 预制体标签 | Prefab tags */
tags?: string[];
/** 是否包含子实体 | Whether to include child entities */
includeChildren?: boolean;
}
/**
* 预制体实例化选项
* Prefab instantiation options
*/
export interface PrefabInstantiateOptions {
/** 父实体 ID | Parent entity ID */
parentId?: number;
/** 位置覆盖 | Position override */
position?: { x: number; y: number };
/** 旋转覆盖(角度) | Rotation override (in degrees) */
rotation?: number;
/** 缩放覆盖 | Scale override */
scale?: { x: number; y: number };
/** 实体名称覆盖 | Entity name override */
name?: string;
/** 是否保留原始实体 ID | Whether to preserve original entity IDs */
preserveIds?: boolean;
/** 是否标记为预制体实例 | Whether to mark as prefab instance */
trackInstance?: boolean;
}
/**
* 预制体格式版本
* Prefab format version
*/
export const PREFAB_FORMAT_VERSION = 1;
/**
* 预制体序列化器类
* Prefab serializer class
*
* 提供预制体的创建、序列化和实例化功能。
* Provides prefab creation, serialization, and instantiation functionality.
*/
export class PrefabSerializer {
/**
* 从实体创建预制体数据
* Create prefab data from entity
*
* @param entity - 源实体 | Source entity
* @param options - 创建选项 | Creation options
* @param hierarchySystem - 层级系统 | Hierarchy system
* @returns 预制体数据 | Prefab data
*/
public static createPrefab(
entity: Entity,
options: PrefabCreateOptions,
hierarchySystem?: HierarchySystem
): PrefabData {
const includeChildren = options.includeChildren ?? true;
// 序列化实体 | Serialize entity
const serializedEntity = EntitySerializer.serialize(
entity,
includeChildren,
hierarchySystem
);
// 转换为预制体实体格式 | Convert to prefab entity format
const prefabEntity = this.toPrefabEntity(serializedEntity, true);
// 收集组件类型信息 | Collect component type information
const { componentTypes, componentTypeRegistry } = this.collectComponentTypes(prefabEntity);
// 收集引用的资产TODO: 实现资产引用扫描)
// Collect referenced assets (TODO: implement asset reference scanning)
const referencedAssets: string[] = [];
const now = Date.now();
const metadata: PrefabMetadata = {
name: options.name,
createdAt: now,
modifiedAt: now,
componentTypes,
referencedAssets
};
// 只在有值时添加可选属性 | Only add optional properties when they have values
if (options.description) {
metadata.description = options.description;
}
if (options.tags) {
metadata.tags = options.tags;
}
return {
version: PREFAB_FORMAT_VERSION,
metadata,
root: prefabEntity,
componentTypeRegistry
};
}
/**
* 从预制体数据实例化实体
* Instantiate entity from prefab data
*
* @param prefabData - 预制体数据 | Prefab data
* @param scene - 目标场景 | Target scene
* @param componentRegistry - 组件类型注册表 | Component type registry
* @param options - 实例化选项 | Instantiation options
* @returns 创建的根实体 | Created root entity
*/
public static instantiate(
prefabData: PrefabData,
scene: IScene,
componentRegistry: Map<string, ComponentType>,
options: PrefabInstantiateOptions = {}
): Entity {
const {
parentId,
name,
preserveIds = false,
trackInstance = true
} = options;
// 获取层级系统 | Get hierarchy system
const hierarchySystem = scene.getSystem(HierarchySystem) ?? null;
// ID 生成器 | ID generator
let nextId = 1;
const idGenerator = (): number => {
while (scene.findEntityById(nextId)) {
nextId++;
}
return nextId++;
};
// 反序列化实体 | Deserialize entity
const { rootEntities, allEntities } = EntitySerializer.deserializeEntities(
[prefabData.root],
componentRegistry,
idGenerator,
preserveIds,
scene,
hierarchySystem
);
const rootEntity = rootEntities[0];
if (!rootEntity) {
throw new Error('Failed to instantiate prefab: no root entity created');
}
// 覆盖名称 | Override name
if (name) {
rootEntity.name = name;
}
// 将所有实体添加到场景 | Add all entities to scene
for (const entity of allEntities.values()) {
scene.entities.add(entity);
}
// 设置父级 | Set parent
if (parentId !== undefined && hierarchySystem) {
const parent = scene.findEntityById(parentId);
if (parent) {
hierarchySystem.setParent(rootEntity, parent);
}
}
// 添加预制体实例组件 | Add prefab instance component
if (trackInstance) {
const prefabGuid = prefabData.metadata.guid || '';
this.addPrefabInstanceComponents(
rootEntity,
allEntities,
prefabGuid,
'',
hierarchySystem
);
}
// TODO: 应用位置、旋转、缩放覆盖(需要 TransformComponent
// TODO: Apply position, rotation, scale overrides (requires TransformComponent)
return rootEntity;
}
/**
* 将序列化实体转换为预制体实体格式
* Convert serialized entity to prefab entity format
*/
private static toPrefabEntity(
entity: SerializedEntity,
isRoot: boolean
): SerializedPrefabEntity {
const prefabEntity: SerializedPrefabEntity = {
...entity,
isPrefabRoot: isRoot,
children: entity.children.map(child => this.toPrefabEntity(child, false))
};
return prefabEntity;
}
/**
* 收集预制体中使用的组件类型
* Collect component types used in prefab
*/
private static collectComponentTypes(
entity: SerializedPrefabEntity
): {
componentTypes: string[];
componentTypeRegistry: PrefabComponentTypeEntry[];
} {
const typeMap = new Map<string, number>();
const collectFromEntity = (e: SerializedPrefabEntity): void => {
for (const comp of e.components) {
if (!typeMap.has(comp.type)) {
typeMap.set(comp.type, comp.version);
}
}
for (const child of e.children as SerializedPrefabEntity[]) {
collectFromEntity(child);
}
};
collectFromEntity(entity);
const componentTypes = Array.from(typeMap.keys());
const componentTypeRegistry: PrefabComponentTypeEntry[] = Array.from(
typeMap.entries()
).map(([typeName, version]) => ({ typeName, version }));
return { componentTypes, componentTypeRegistry };
}
/**
* 为实例化的实体添加预制体实例组件
* Add prefab instance components to instantiated entities
*/
private static addPrefabInstanceComponents(
rootEntity: Entity,
allEntities: Map<number, Entity>,
prefabGuid: string,
prefabPath: string,
_hierarchySystem: HierarchySystem | null
): void {
const rootId = rootEntity.id;
// 为根实体添加组件 | Add component to root entity
const rootComp = new PrefabInstanceComponent(prefabGuid, prefabPath, true);
rootComp.rootInstanceEntityId = rootId;
rootEntity.addComponent(rootComp);
// 为所有子实体添加组件 | Add component to all child entities
for (const entity of allEntities.values()) {
if (entity.id === rootId) continue;
const childComp = new PrefabInstanceComponent(prefabGuid, prefabPath, false);
childComp.rootInstanceEntityId = rootId;
entity.addComponent(childComp);
}
}
/**
* 检查实体是否为预制体实例
* Check if entity is a prefab instance
*/
public static isPrefabInstance(entity: Entity): boolean {
return entity.hasComponent(PrefabInstanceComponent);
}
/**
* 获取预制体实例的源预制体 GUID
* Get source prefab GUID of a prefab instance
*/
public static getSourcePrefabGuid(entity: Entity): string | null {
const comp = entity.getComponent(PrefabInstanceComponent);
return comp?.sourcePrefabGuid || null;
}
/**
* 获取预制体实例的根实体
* Get root entity of a prefab instance
*/
public static getPrefabInstanceRoot(entity: Entity): Entity | null {
const comp = entity.getComponent(PrefabInstanceComponent);
if (!comp || !comp.rootInstanceEntityId) return null;
const scene = entity.scene;
if (!scene) return null;
return scene.findEntityById(comp.rootInstanceEntityId) || null;
}
/**
* 将预制体数据序列化为 JSON 字符串
* Serialize prefab data to JSON string
*/
public static serialize(prefabData: PrefabData, pretty: boolean = true): string {
return JSON.stringify(prefabData, null, pretty ? 2 : undefined);
}
/**
* 从 JSON 字符串解析预制体数据
* Parse prefab data from JSON string
*/
public static deserialize(json: string): PrefabData {
const data = JSON.parse(json) as PrefabData;
// 基本验证 | Basic validation
if (!data.version || !data.metadata || !data.root) {
throw new Error('Invalid prefab data format');
}
return data;
}
/**
* 验证预制体数据格式
* Validate prefab data format
*/
public static validate(prefabData: PrefabData): { valid: boolean; errors?: string[] } {
const errors: string[] = [];
if (typeof prefabData.version !== 'number') {
errors.push('Invalid or missing version');
}
if (!prefabData.metadata) {
errors.push('Missing metadata');
} else {
if (!prefabData.metadata.name) {
errors.push('Missing metadata.name');
}
if (!Array.isArray(prefabData.metadata.componentTypes)) {
errors.push('Invalid metadata.componentTypes');
}
}
if (!prefabData.root) {
errors.push('Missing root entity');
} else {
this.validateEntity(prefabData.root, errors, 'root');
}
if (!Array.isArray(prefabData.componentTypeRegistry)) {
errors.push('Invalid componentTypeRegistry');
}
if (errors.length > 0) {
return { valid: false, errors };
}
return { valid: true };
}
/**
* 验证实体数据
* Validate entity data
*/
private static validateEntity(
entity: SerializedPrefabEntity,
errors: string[],
path: string
): void {
if (typeof entity.id !== 'number') {
errors.push(`${path}: Invalid or missing id`);
}
if (typeof entity.name !== 'string') {
errors.push(`${path}: Invalid or missing name`);
}
if (!Array.isArray(entity.components)) {
errors.push(`${path}: Invalid or missing components`);
}
if (!Array.isArray(entity.children)) {
errors.push(`${path}: Invalid or missing children`);
} else {
entity.children.forEach((child, index) => {
this.validateEntity(child as SerializedPrefabEntity, errors, `${path}.children[${index}]`);
});
}
}
}

View File

@@ -13,6 +13,7 @@ import { getSerializationMetadata } from './SerializationDecorators';
import { BinarySerializer } from '../../Utils/BinarySerializer';
import { HierarchySystem } from '../Systems/HierarchySystem';
import { HierarchyComponent } from '../Components/HierarchyComponent';
import { SerializationContext } from './SerializationContext';
/**
* 场景序列化格式
@@ -216,6 +217,14 @@ export class SceneSerializer {
/**
* 反序列化场景
*
* 使用两阶段反序列化:
* 1. 创建所有实体和组件,收集待解析的 EntityRef
* 2. 解析所有 EntityRef建立正确的对象引用
*
* Deserialize scene using two-phase approach:
* 1. Create all entities and components, collect pending EntityRefs
* 2. Resolve all EntityRefs, establish correct object references
*
* @param scene 目标场景
* @param saveData 序列化的数据JSON字符串或二进制Uint8Array
* @param options 反序列化选项
@@ -266,14 +275,20 @@ export class SceneSerializer {
// 获取层级系统
const hierarchySystem = scene.getSystem(HierarchySystem);
// 反序列化实体
// ========== 阶段 1创建实体和组件收集 EntityRef ==========
// Phase 1: Create entities and components, collect EntityRefs
const context = new SerializationContext();
context.setPreserveIds(opts.preserveIds || false);
// 反序列化实体(传入 context 收集 EntityRef
const { rootEntities, allEntities } = EntitySerializer.deserializeEntities(
serializedScene.entities,
componentRegistry,
idGenerator,
opts.preserveIds || false,
scene,
hierarchySystem
hierarchySystem,
context
);
// 将所有实体添加到场景(包括子实体)
@@ -287,6 +302,18 @@ export class SceneSerializer {
scene.querySystem.clearCache();
scene.clearSystemEntityCaches();
// ========== 阶段 2解析所有 EntityRef ==========
// Phase 2: Resolve all EntityRefs
const resolvedCount = context.resolveAllReferences();
const unresolvedCount = context.getUnresolvedCount();
if (unresolvedCount > 0) {
console.warn(
`[SceneSerializer] ${unresolvedCount} EntityRef(s) could not be resolved. ` +
`Resolved: ${resolvedCount}, Total pending: ${context.getPendingCount()}`
);
}
// 反序列化场景自定义数据
if (serializedScene.sceneData) {
this.deserializeSceneData(serializedScene.sceneData, scene.sceneData);

View File

@@ -0,0 +1,321 @@
import type { Entity } from '../Entity';
import type { Component } from '../Component';
/**
* 序列化的实体引用格式
*
* Serialized entity reference format.
*/
export interface SerializedEntityRef {
/**
* 运行时 ID向后兼容
*
* Runtime ID (backward compatible).
*/
id?: number | undefined;
/**
* 持久化 GUID新格式
*
* Persistent GUID (new format).
*/
guid?: string | undefined;
}
/**
* 待解析的实体引用记录
*
* Pending entity reference record.
*/
interface PendingEntityRef {
/**
* 持有引用的组件
*/
component: Component;
/**
* 属性名
*/
propertyKey: string;
/**
* 原始运行时 ID可选
*/
originalId: number | undefined;
/**
* 原始 GUID可选
*/
originalGuid: string | undefined;
}
/**
* 序列化上下文
*
* 用于管理两阶段序列化/反序列化过程中的状态。
* 第一阶段:创建所有实体和组件,收集待解析的引用。
* 第二阶段:解析所有实体引用,建立正确的对象关系。
*
* Serialization context for managing two-phase serialization/deserialization.
* Phase 1: Create all entities and components, collect pending references.
* Phase 2: Resolve all entity references, establish correct object relationships.
*
* @example
* ```typescript
* const context = new SerializationContext();
*
* // 第一阶段:反序列化实体
* for (const entityData of entities) {
* const entity = scene.createEntity(entityData.name);
* context.registerEntity(entity, entityData.id, entityData.guid);
*
* // 反序列化组件时,遇到 EntityRef 注册为待解析
* context.registerPendingRef(component, 'target', entityData.targetId, entityData.targetGuid);
* }
*
* // 第二阶段:解析所有引用
* context.resolveAllReferences();
* ```
*/
export class SerializationContext {
/**
* 运行时 ID 映射:原始 ID -> Entity
*
* Runtime ID mapping: original ID -> Entity.
*/
private _idRemapping: Map<number, Entity> = new Map();
/**
* GUID 映射persistentId -> Entity
*
* GUID mapping: persistentId -> Entity.
*/
private _guidLookup: Map<string, Entity> = new Map();
/**
* 待解析的实体引用列表
*
* Pending entity references to resolve.
*/
private _pendingRefs: PendingEntityRef[] = [];
/**
* 是否保留原始 ID
*
* Whether to preserve original IDs.
*/
private _preserveIds: boolean = false;
/**
* 设置是否保留原始 ID
*
* Set whether to preserve original IDs.
*/
public setPreserveIds(value: boolean): void {
this._preserveIds = value;
}
/**
* 获取是否保留原始 ID
*
* Get whether to preserve original IDs.
*/
public get preserveIds(): boolean {
return this._preserveIds;
}
/**
* 注册实体到上下文
*
* Register entity to context for later reference resolution.
*
* @param entity - 实体实例
* @param originalId - 原始运行时 ID可选用于 ID 映射)
* @param originalGuid - 原始 GUID可选用于 GUID 映射,默认使用 entity.persistentId
*/
public registerEntity(entity: Entity, originalId?: number, originalGuid?: string): void {
// 使用实体自身的 persistentId 或提供的 originalGuid
const guid = originalGuid ?? entity.persistentId;
this._guidLookup.set(guid, entity);
// 如果提供了原始 ID建立 ID 映射
if (originalId !== undefined) {
this._idRemapping.set(originalId, entity);
}
}
/**
* 根据原始 ID 获取实体
*
* Get entity by original runtime ID.
*
* @param originalId - 原始运行时 ID
* @returns 实体实例或 null
*/
public getEntityById(originalId: number): Entity | null {
return this._idRemapping.get(originalId) ?? null;
}
/**
* 根据 GUID 获取实体
*
* Get entity by GUID.
*
* @param guid - 持久化 GUID
* @returns 实体实例或 null
*/
public getEntityByGuid(guid: string): Entity | null {
return this._guidLookup.get(guid) ?? null;
}
/**
* 解析实体引用
*
* Resolve entity reference, preferring GUID over ID.
*
* @param ref - 序列化的实体引用
* @returns 实体实例或 null
*/
public resolveEntityRef(ref: SerializedEntityRef | null | undefined): Entity | null {
if (!ref) {
return null;
}
// 优先使用 GUID
if (ref.guid) {
const entity = this._guidLookup.get(ref.guid);
if (entity) {
return entity;
}
}
// 降级使用 ID
if (ref.id !== undefined) {
const entity = this._idRemapping.get(ref.id);
if (entity) {
return entity;
}
}
return null;
}
/**
* 注册待解析的实体引用
*
* Register a pending entity reference to be resolved later.
*
* @param component - 持有引用的组件
* @param propertyKey - 属性名
* @param originalId - 原始运行时 ID
* @param originalGuid - 原始 GUID
*/
public registerPendingRef(
component: Component,
propertyKey: string,
originalId?: number,
originalGuid?: string
): void {
this._pendingRefs.push({
component,
propertyKey,
originalId,
originalGuid
});
}
/**
* 解析所有待处理的实体引用
*
* Resolve all pending entity references.
* Should be called after all entities have been created.
*
* @returns 成功解析的引用数量
*/
public resolveAllReferences(): number {
let resolvedCount = 0;
for (const pending of this._pendingRefs) {
const entity = this.resolveEntityRef({
id: pending.originalId,
guid: pending.originalGuid
});
if (entity) {
// 使用类型断言设置属性值
(pending.component as unknown as Record<string, unknown>)[pending.propertyKey] = entity;
resolvedCount++;
}
// 如果无法解析,保持为 null已在反序列化时设置
}
return resolvedCount;
}
/**
* 获取未解析的引用数量
*
* Get count of unresolved references.
*/
public getUnresolvedCount(): number {
let count = 0;
for (const pending of this._pendingRefs) {
const entity = this.resolveEntityRef({
id: pending.originalId,
guid: pending.originalGuid
});
if (!entity) {
count++;
}
}
return count;
}
/**
* 获取待解析引用数量
*
* Get count of pending references.
*/
public getPendingCount(): number {
return this._pendingRefs.length;
}
/**
* 获取已注册实体数量
*
* Get count of registered entities.
*/
public getRegisteredEntityCount(): number {
return this._guidLookup.size;
}
/**
* 清除上下文状态
*
* Clear context state.
*/
public clear(): void {
this._idRemapping.clear();
this._guidLookup.clear();
this._pendingRefs = [];
}
/**
* 获取调试信息
*
* Get debug information.
*/
public getDebugInfo(): {
registeredEntities: number;
pendingRefs: number;
unresolvedRefs: number;
preserveIds: boolean;
} {
return {
registeredEntities: this._guidLookup.size,
pendingRefs: this._pendingRefs.length,
unresolvedRefs: this.getUnresolvedCount(),
preserveIds: this._preserveIds
};
}
}

View File

@@ -60,3 +60,18 @@ export type {
ComponentChange,
SceneDataChange
} from './IncrementalSerializer';
// 预制体序列化
export { PrefabSerializer, PREFAB_FORMAT_VERSION } from './PrefabSerializer';
export type {
SerializedPrefabEntity,
PrefabMetadata,
PrefabComponentTypeEntry,
PrefabData,
PrefabCreateOptions,
PrefabInstantiateOptions
} from './PrefabSerializer';
// 序列化上下文
export { SerializationContext } from './SerializationContext';
export type { SerializedEntityRef } from './SerializationContext';

View File

@@ -0,0 +1,90 @@
/**
* GUID 生成工具
*
* 提供跨平台的 UUID v4 生成功能,用于实体持久化标识。
* 优先使用 crypto.randomUUID(),降级使用 Math.random() 实现。
*
* GUID generation utility.
* Provides cross-platform UUID v4 generation for entity persistent identification.
* Uses crypto.randomUUID() when available, falls back to Math.random() implementation.
*/
/**
* 生成 UUID v4 格式的 GUID
*
* Generate a UUID v4 format GUID.
*
* @returns 36 字符的 UUID 字符串 (例如: "550e8400-e29b-41d4-a716-446655440000")
*
* @example
* ```typescript
* const id = generateGUID();
* console.log(id); // "550e8400-e29b-41d4-a716-446655440000"
* ```
*/
export function generateGUID(): string {
// 优先使用原生 crypto API浏览器和 Node.js 19+
if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
return crypto.randomUUID();
}
// 降级方案:使用 crypto.getRandomValues 或 Math.random
return generateGUIDFallback();
}
/**
* 降级 GUID 生成实现
*
* Fallback GUID generation using crypto.getRandomValues or Math.random.
*/
function generateGUIDFallback(): string {
// 尝试使用 crypto.getRandomValues
if (typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function') {
const bytes = new Uint8Array(16);
crypto.getRandomValues(bytes);
// 设置版本号 (version 4)
bytes[6] = (bytes[6]! & 0x0f) | 0x40;
// 设置变体 (variant 1)
bytes[8] = (bytes[8]! & 0x3f) | 0x80;
return formatUUID(bytes);
}
// 最终降级:使用 Math.random不推荐但可用
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
const r = (Math.random() * 16) | 0;
const v = c === 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
}
/**
* 格式化 16 字节数组为 UUID 字符串
*
* Format 16-byte array to UUID string.
*/
function formatUUID(bytes: Uint8Array): string {
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
}
/**
* 验证字符串是否为有效的 UUID 格式
*
* Validate if a string is a valid UUID format.
*
* @param value - 要验证的字符串
* @returns 如果是有效的 UUID 格式返回 true
*/
export function isValidGUID(value: string): boolean {
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
return uuidRegex.test(value);
}
/**
* 空 GUID 常量
*
* Empty GUID constant (all zeros).
*/
export const EMPTY_GUID = '00000000-0000-0000-0000-000000000000';

View File

@@ -8,3 +8,4 @@ export * from './Debug';
export * from './Logger';
export * from './BinarySerializer';
export * from './Profiler';
export * from './GUID';

View File

@@ -18,6 +18,15 @@ export { PluginManager } from './Core/PluginManager';
export { PluginState } from './Core/Plugin';
export type { IPlugin, IPluginMetadata } from './Core/Plugin';
// 运行时模式服务 | Runtime Mode Service
export {
RuntimeModeService,
RuntimeModeToken,
createEditorModeService,
createStandaloneModeService
} from './Core/RuntimeModeService';
export type { IRuntimeMode, RuntimeModeConfig } from './Core/RuntimeModeService';
// 内置插件
export * from './Plugins';