Feature/editor optimization (#251)
* refactor: 编辑器/运行时架构拆分与构建系统升级 * feat(core): 层级系统重构与UI变换矩阵修复 * refactor: 移除 ecs-components 聚合包并修复跨包组件查找问题 * fix(physics): 修复跨包组件类引用问题 * feat: 统一运行时架构与浏览器运行支持 * feat(asset): 实现浏览器运行时资产加载系统 * fix: 修复文档、CodeQL安全问题和CI类型检查错误 * fix: 修复文档、CodeQL安全问题和CI类型检查错误 * fix: 修复文档、CodeQL安全问题、CI类型检查和测试错误 * test: 补齐核心模块测试用例,修复CI构建配置 * fix: 修复测试用例中的类型错误和断言问题 * fix: 修复 turbo build:npm 任务的依赖顺序问题 * fix: 修复 CI 构建错误并优化构建性能
This commit is contained in:
@@ -1,691 +0,0 @@
|
||||
import {
|
||||
EntityBuilder,
|
||||
SceneBuilder,
|
||||
ComponentBuilder,
|
||||
ECSFluentAPI,
|
||||
EntityBatchOperator,
|
||||
createECSAPI,
|
||||
initializeECS,
|
||||
ECS
|
||||
} from '../../../src/ECS/Core/FluentAPI';
|
||||
import { Scene } from '../../../src/ECS/Scene';
|
||||
import { Entity } from '../../../src/ECS/Entity';
|
||||
import { Component } from '../../../src/ECS/Component';
|
||||
import { QuerySystem } from '../../../src/ECS/Core/QuerySystem';
|
||||
import { TypeSafeEventSystem } from '../../../src/ECS/Core/EventSystem';
|
||||
import { EntitySystem } from '../../../src/ECS/Systems/EntitySystem';
|
||||
import { Matcher } from '../../../src/ECS/Utils/Matcher';
|
||||
|
||||
// 测试组件
|
||||
class TestComponent extends Component {
|
||||
public value: number;
|
||||
|
||||
constructor(...args: unknown[]) {
|
||||
super();
|
||||
const [value = 0] = args as [number?];
|
||||
this.value = value;
|
||||
}
|
||||
}
|
||||
|
||||
class PositionComponent extends Component {
|
||||
public x: number;
|
||||
public y: number;
|
||||
|
||||
constructor(...args: unknown[]) {
|
||||
super();
|
||||
const [x = 0, y = 0] = args as [number?, number?];
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
}
|
||||
}
|
||||
|
||||
class VelocityComponent extends Component {
|
||||
public vx: number;
|
||||
public vy: number;
|
||||
|
||||
constructor(...args: unknown[]) {
|
||||
super();
|
||||
const [vx = 0, vy = 0] = args as [number?, number?];
|
||||
this.vx = vx;
|
||||
this.vy = vy;
|
||||
}
|
||||
}
|
||||
|
||||
// 测试系统
|
||||
class TestSystem extends EntitySystem {
|
||||
constructor() {
|
||||
super(Matcher.empty().all(TestComponent));
|
||||
}
|
||||
|
||||
protected override process(entities: Entity[]): void {
|
||||
// 测试系统
|
||||
}
|
||||
}
|
||||
|
||||
describe('FluentAPI - 流式API测试', () => {
|
||||
let scene: Scene;
|
||||
let querySystem: QuerySystem;
|
||||
let eventSystem: TypeSafeEventSystem;
|
||||
|
||||
beforeEach(() => {
|
||||
scene = new Scene();
|
||||
querySystem = new QuerySystem();
|
||||
eventSystem = new TypeSafeEventSystem();
|
||||
});
|
||||
|
||||
describe('EntityBuilder - 实体构建器', () => {
|
||||
let builder: EntityBuilder;
|
||||
|
||||
beforeEach(() => {
|
||||
builder = new EntityBuilder(scene, scene.componentStorageManager);
|
||||
});
|
||||
|
||||
test('应该能够创建实体构建器', () => {
|
||||
expect(builder).toBeInstanceOf(EntityBuilder);
|
||||
});
|
||||
|
||||
test('应该能够设置实体名称', () => {
|
||||
const entity = builder.named('TestEntity').build();
|
||||
expect(entity.name).toBe('TestEntity');
|
||||
});
|
||||
|
||||
test('应该能够设置实体标签', () => {
|
||||
const entity = builder.tagged(42).build();
|
||||
expect(entity.tag).toBe(42);
|
||||
});
|
||||
|
||||
test('应该能够添加组件', () => {
|
||||
const component = new TestComponent(100);
|
||||
const entity = builder.with(component).build();
|
||||
|
||||
expect(entity.hasComponent(TestComponent)).toBe(true);
|
||||
expect(entity.getComponent(TestComponent)).toBe(component);
|
||||
});
|
||||
|
||||
test('应该能够添加多个组件', () => {
|
||||
const comp1 = new TestComponent(100);
|
||||
const comp2 = new PositionComponent(10, 20);
|
||||
const comp3 = new VelocityComponent(1, 2);
|
||||
|
||||
const entity = builder.withComponents(comp1, comp2, comp3).build();
|
||||
|
||||
expect(entity.hasComponent(TestComponent)).toBe(true);
|
||||
expect(entity.hasComponent(PositionComponent)).toBe(true);
|
||||
expect(entity.hasComponent(VelocityComponent)).toBe(true);
|
||||
});
|
||||
|
||||
test('应该能够条件性添加组件', () => {
|
||||
const comp1 = new TestComponent(100);
|
||||
const comp2 = new PositionComponent(10, 20);
|
||||
|
||||
const entity = builder
|
||||
.withIf(true, comp1)
|
||||
.withIf(false, comp2)
|
||||
.build();
|
||||
|
||||
expect(entity.hasComponent(TestComponent)).toBe(true);
|
||||
expect(entity.hasComponent(PositionComponent)).toBe(false);
|
||||
});
|
||||
|
||||
test('应该能够使用工厂函数创建组件', () => {
|
||||
const entity = builder
|
||||
.withFactory(() => new TestComponent(200))
|
||||
.build();
|
||||
|
||||
expect(entity.hasComponent(TestComponent)).toBe(true);
|
||||
expect(entity.getComponent(TestComponent)!.value).toBe(200);
|
||||
});
|
||||
|
||||
test('应该能够配置组件属性', () => {
|
||||
const entity = builder
|
||||
.with(new TestComponent(100))
|
||||
.configure(TestComponent, (comp) => {
|
||||
comp.value = 300;
|
||||
})
|
||||
.build();
|
||||
|
||||
expect(entity.getComponent(TestComponent)!.value).toBe(300);
|
||||
});
|
||||
|
||||
test('配置不存在的组件应该安全处理', () => {
|
||||
expect(() => {
|
||||
builder.configure(TestComponent, (comp) => {
|
||||
comp.value = 300;
|
||||
}).build();
|
||||
}).not.toThrow();
|
||||
});
|
||||
|
||||
test('应该能够设置实体启用状态', () => {
|
||||
const entity1 = builder.enabled(true).build();
|
||||
const entity2 = new EntityBuilder(scene, scene.componentStorageManager).enabled(false).build();
|
||||
|
||||
expect(entity1.enabled).toBe(true);
|
||||
expect(entity2.enabled).toBe(false);
|
||||
});
|
||||
|
||||
test('应该能够设置实体活跃状态', () => {
|
||||
const entity1 = builder.active(true).build();
|
||||
const entity2 = new EntityBuilder(scene, scene.componentStorageManager).active(false).build();
|
||||
|
||||
expect(entity1.active).toBe(true);
|
||||
expect(entity2.active).toBe(false);
|
||||
});
|
||||
|
||||
test('应该能够添加子实体', () => {
|
||||
const childBuilder = new EntityBuilder(scene, scene.componentStorageManager)
|
||||
.named('Child')
|
||||
.with(new TestComponent(50));
|
||||
|
||||
const parent = builder
|
||||
.named('Parent')
|
||||
.withChild(childBuilder)
|
||||
.build();
|
||||
|
||||
expect(parent.children.length).toBe(1);
|
||||
expect(parent.children[0].name).toBe('Child');
|
||||
});
|
||||
|
||||
test('应该能够添加多个子实体', () => {
|
||||
const child1 = new EntityBuilder(scene, scene.componentStorageManager).named('Child1');
|
||||
const child2 = new EntityBuilder(scene, scene.componentStorageManager).named('Child2');
|
||||
const child3 = new EntityBuilder(scene, scene.componentStorageManager).named('Child3');
|
||||
|
||||
const parent = builder
|
||||
.named('Parent')
|
||||
.withChildren(child1, child2, child3)
|
||||
.build();
|
||||
|
||||
expect(parent.children.length).toBe(3);
|
||||
expect(parent.children[0].name).toBe('Child1');
|
||||
expect(parent.children[1].name).toBe('Child2');
|
||||
expect(parent.children[2].name).toBe('Child3');
|
||||
});
|
||||
|
||||
test('应该能够使用工厂函数创建子实体', () => {
|
||||
const parent = builder
|
||||
.named('Parent')
|
||||
.withChildFactory((parentEntity) => {
|
||||
return new EntityBuilder(scene, scene.componentStorageManager)
|
||||
.named(`Child_of_${parentEntity.name}`)
|
||||
.with(new TestComponent(100));
|
||||
})
|
||||
.build();
|
||||
|
||||
expect(parent.children.length).toBe(1);
|
||||
expect(parent.children[0].name).toBe('Child_of_Parent');
|
||||
});
|
||||
|
||||
test('应该能够条件性添加子实体', () => {
|
||||
const child1 = new EntityBuilder(scene, scene.componentStorageManager).named('Child1');
|
||||
const child2 = new EntityBuilder(scene, scene.componentStorageManager).named('Child2');
|
||||
|
||||
const parent = builder
|
||||
.named('Parent')
|
||||
.withChildIf(true, child1)
|
||||
.withChildIf(false, child2)
|
||||
.build();
|
||||
|
||||
expect(parent.children.length).toBe(1);
|
||||
expect(parent.children[0].name).toBe('Child1');
|
||||
});
|
||||
|
||||
test('应该能够构建实体并添加到场景', () => {
|
||||
const entity = builder
|
||||
.named('SpawnedEntity')
|
||||
.with(new TestComponent(100))
|
||||
.spawn();
|
||||
|
||||
expect(entity.name).toBe('SpawnedEntity');
|
||||
expect(entity.scene).toBe(scene);
|
||||
});
|
||||
|
||||
test('应该能够克隆构建器', () => {
|
||||
const originalBuilder = builder.named('Original').with(new TestComponent(100));
|
||||
const clonedBuilder = originalBuilder.clone();
|
||||
|
||||
expect(clonedBuilder).toBeInstanceOf(EntityBuilder);
|
||||
expect(clonedBuilder).not.toBe(originalBuilder);
|
||||
});
|
||||
|
||||
test('流式调用应该工作正常', () => {
|
||||
const entity = builder
|
||||
.named('ComplexEntity')
|
||||
.tagged(42)
|
||||
.with(new TestComponent(100))
|
||||
.with(new PositionComponent(10, 20))
|
||||
.enabled(true)
|
||||
.active(true)
|
||||
.configure(TestComponent, (comp) => {
|
||||
comp.value = 200;
|
||||
})
|
||||
.build();
|
||||
|
||||
expect(entity.name).toBe('ComplexEntity');
|
||||
expect(entity.tag).toBe(42);
|
||||
expect(entity.enabled).toBe(true);
|
||||
expect(entity.active).toBe(true);
|
||||
expect(entity.hasComponent(TestComponent)).toBe(true);
|
||||
expect(entity.hasComponent(PositionComponent)).toBe(true);
|
||||
expect(entity.getComponent(TestComponent)!.value).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
describe('SceneBuilder - 场景构建器', () => {
|
||||
let builder: SceneBuilder;
|
||||
|
||||
beforeEach(() => {
|
||||
builder = new SceneBuilder();
|
||||
});
|
||||
|
||||
test('应该能够创建场景构建器', () => {
|
||||
expect(builder).toBeInstanceOf(SceneBuilder);
|
||||
});
|
||||
|
||||
test('应该能够设置场景名称', () => {
|
||||
const scene = builder.named('TestScene').build();
|
||||
expect(scene.name).toBe('TestScene');
|
||||
});
|
||||
|
||||
test('应该能够添加实体', () => {
|
||||
const entity = new Entity('TestEntity', 1);
|
||||
const scene = builder.withEntity(entity).build();
|
||||
|
||||
expect(scene.entities.count).toBe(1);
|
||||
expect(scene.findEntity('TestEntity')).toBe(entity);
|
||||
});
|
||||
|
||||
test('应该能够使用实体构建器添加实体', () => {
|
||||
const scene = builder
|
||||
.withEntityBuilder((builder) => {
|
||||
return builder
|
||||
.named('BuilderEntity')
|
||||
.with(new TestComponent(100));
|
||||
})
|
||||
.build();
|
||||
|
||||
expect(scene.entities.count).toBe(1);
|
||||
expect(scene.findEntity('BuilderEntity')).not.toBeNull();
|
||||
});
|
||||
|
||||
test('应该能够批量添加实体', () => {
|
||||
const entity1 = new Entity('Entity1', 1);
|
||||
const entity2 = new Entity('Entity2', 2);
|
||||
const entity3 = new Entity('Entity3', 3);
|
||||
|
||||
const scene = builder
|
||||
.withEntities(entity1, entity2, entity3)
|
||||
.build();
|
||||
|
||||
expect(scene.entities.count).toBe(3);
|
||||
});
|
||||
|
||||
test('应该能够添加系统', () => {
|
||||
const system = new TestSystem();
|
||||
const scene = builder.withSystem(system).build();
|
||||
|
||||
expect(scene.systems.length).toBe(1);
|
||||
expect(scene.systems[0]).toBe(system);
|
||||
});
|
||||
|
||||
test('应该能够批量添加系统', () => {
|
||||
const system1 = new TestSystem();
|
||||
const system2 = new TestSystem();
|
||||
|
||||
const scene = builder
|
||||
.withSystems(system1, system2)
|
||||
.build();
|
||||
|
||||
expect(scene.systems.length).toBe(1);
|
||||
});
|
||||
|
||||
test('流式调用应该工作正常', () => {
|
||||
const entity = new Entity('TestEntity', 1);
|
||||
const system = new TestSystem();
|
||||
|
||||
const scene = builder
|
||||
.named('ComplexScene')
|
||||
.withEntity(entity)
|
||||
.withSystem(system)
|
||||
.withEntityBuilder((builder) => {
|
||||
return builder.named('BuilderEntity');
|
||||
})
|
||||
.build();
|
||||
|
||||
expect(scene.name).toBe('ComplexScene');
|
||||
expect(scene.entities.count).toBe(2);
|
||||
expect(scene.systems.length).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('ComponentBuilder - 组件构建器', () => {
|
||||
test('应该能够创建组件构建器', () => {
|
||||
const builder = new ComponentBuilder(TestComponent, 100);
|
||||
expect(builder).toBeInstanceOf(ComponentBuilder);
|
||||
});
|
||||
|
||||
test('应该能够设置组件属性', () => {
|
||||
const component = new ComponentBuilder(TestComponent, 100)
|
||||
.set('value', 200)
|
||||
.build();
|
||||
|
||||
expect(component.value).toBe(200);
|
||||
});
|
||||
|
||||
test('应该能够使用配置函数', () => {
|
||||
const component = new ComponentBuilder(PositionComponent, 10, 20)
|
||||
.configure((comp) => {
|
||||
comp.x = 30;
|
||||
comp.y = 40;
|
||||
})
|
||||
.build();
|
||||
|
||||
expect(component.x).toBe(30);
|
||||
expect(component.y).toBe(40);
|
||||
});
|
||||
|
||||
test('应该能够条件性设置属性', () => {
|
||||
const component = new ComponentBuilder(TestComponent, 100)
|
||||
.setIf(true, 'value', 200)
|
||||
.setIf(false, 'value', 300)
|
||||
.build();
|
||||
|
||||
expect(component.value).toBe(200);
|
||||
});
|
||||
|
||||
test('流式调用应该工作正常', () => {
|
||||
const component = new ComponentBuilder(PositionComponent, 0, 0)
|
||||
.set('x', 10)
|
||||
.set('y', 20)
|
||||
.setIf(true, 'x', 30)
|
||||
.configure((comp) => {
|
||||
comp.y = 40;
|
||||
})
|
||||
.build();
|
||||
|
||||
expect(component.x).toBe(30);
|
||||
expect(component.y).toBe(40);
|
||||
});
|
||||
});
|
||||
|
||||
describe('ECSFluentAPI - 主API', () => {
|
||||
let api: ECSFluentAPI;
|
||||
|
||||
beforeEach(() => {
|
||||
api = new ECSFluentAPI(scene, querySystem, eventSystem);
|
||||
});
|
||||
|
||||
test('应该能够创建ECS API', () => {
|
||||
expect(api).toBeInstanceOf(ECSFluentAPI);
|
||||
});
|
||||
|
||||
test('应该能够创建实体构建器', () => {
|
||||
const builder = api.createEntity();
|
||||
expect(builder).toBeInstanceOf(EntityBuilder);
|
||||
});
|
||||
|
||||
test('应该能够创建场景构建器', () => {
|
||||
const builder = api.createScene();
|
||||
expect(builder).toBeInstanceOf(SceneBuilder);
|
||||
});
|
||||
|
||||
test('应该能够创建组件构建器', () => {
|
||||
const builder = api.createComponent(TestComponent, 100);
|
||||
expect(builder).toBeInstanceOf(ComponentBuilder);
|
||||
});
|
||||
|
||||
test('应该能够创建查询构建器', () => {
|
||||
const builder = api.query();
|
||||
expect(builder).toBeDefined();
|
||||
});
|
||||
|
||||
test('应该能够查找实体', () => {
|
||||
const entity = scene.createEntity('TestEntity');
|
||||
entity.addComponent(new TestComponent(100));
|
||||
querySystem.setEntities([entity]);
|
||||
|
||||
const results = api.find(TestComponent);
|
||||
expect(results.length).toBe(1);
|
||||
expect(results[0]).toBe(entity);
|
||||
});
|
||||
|
||||
test('应该能够查找第一个匹配的实体', () => {
|
||||
const entity1 = scene.createEntity('Entity1');
|
||||
const entity2 = scene.createEntity('Entity2');
|
||||
entity1.addComponent(new TestComponent(100));
|
||||
entity2.addComponent(new TestComponent(200));
|
||||
querySystem.setEntities([entity1, entity2]);
|
||||
|
||||
const result = api.findFirst(TestComponent);
|
||||
expect(result).not.toBeNull();
|
||||
expect([entity1, entity2]).toContain(result);
|
||||
});
|
||||
|
||||
test('查找不存在的实体应该返回null', () => {
|
||||
const result = api.findFirst(TestComponent);
|
||||
expect(result).toBeNull();
|
||||
});
|
||||
|
||||
test('应该能够按名称查找实体', () => {
|
||||
const entity = scene.createEntity('TestEntity');
|
||||
|
||||
const result = api.findByName('TestEntity');
|
||||
expect(result).toBe(entity);
|
||||
});
|
||||
|
||||
test('应该能够按标签查找实体', () => {
|
||||
const entity1 = scene.createEntity('Entity1');
|
||||
const entity2 = scene.createEntity('Entity2');
|
||||
entity1.tag = 42;
|
||||
entity2.tag = 42;
|
||||
|
||||
const results = api.findByTag(42);
|
||||
expect(results.length).toBe(2);
|
||||
expect(results).toContain(entity1);
|
||||
expect(results).toContain(entity2);
|
||||
});
|
||||
|
||||
test('应该能够触发同步事件', () => {
|
||||
let eventReceived = false;
|
||||
let eventData: any = null;
|
||||
|
||||
api.on('test:event', (data) => {
|
||||
eventReceived = true;
|
||||
eventData = data;
|
||||
});
|
||||
|
||||
api.emit('test:event', { message: 'hello' });
|
||||
|
||||
expect(eventReceived).toBe(true);
|
||||
expect(eventData.message).toBe('hello');
|
||||
});
|
||||
|
||||
test('应该能够触发异步事件', async () => {
|
||||
let eventReceived = false;
|
||||
let eventData: any = null;
|
||||
|
||||
api.on('test:event', (data) => {
|
||||
eventReceived = true;
|
||||
eventData = data;
|
||||
});
|
||||
|
||||
await api.emitAsync('test:event', { message: 'hello' });
|
||||
|
||||
expect(eventReceived).toBe(true);
|
||||
expect(eventData.message).toBe('hello');
|
||||
});
|
||||
|
||||
test('应该能够一次性监听事件', () => {
|
||||
let callCount = 0;
|
||||
|
||||
api.once('test:event', () => {
|
||||
callCount++;
|
||||
});
|
||||
|
||||
api.emit('test:event', {});
|
||||
api.emit('test:event', {});
|
||||
|
||||
expect(callCount).toBe(1);
|
||||
});
|
||||
|
||||
test('应该能够移除事件监听器', () => {
|
||||
let callCount = 0;
|
||||
|
||||
const listenerId = api.on('test:event', () => {
|
||||
callCount++;
|
||||
});
|
||||
|
||||
api.emit('test:event', {});
|
||||
api.off('test:event', listenerId);
|
||||
api.emit('test:event', {});
|
||||
|
||||
expect(callCount).toBe(1);
|
||||
});
|
||||
|
||||
test('应该能够创建批量操作器', () => {
|
||||
const entity1 = new Entity('Entity1', 1);
|
||||
const entity2 = new Entity('Entity2', 2);
|
||||
|
||||
const batch = api.batch([entity1, entity2]);
|
||||
expect(batch).toBeInstanceOf(EntityBatchOperator);
|
||||
});
|
||||
|
||||
test('应该能够获取统计信息', () => {
|
||||
const stats = api.getStats();
|
||||
|
||||
expect(stats).toBeDefined();
|
||||
expect(stats.entityCount).toBeDefined();
|
||||
expect(stats.systemCount).toBeDefined();
|
||||
expect(stats.componentStats).toBeDefined();
|
||||
expect(stats.queryStats).toBeDefined();
|
||||
expect(stats.eventStats).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('EntityBatchOperator - 批量操作器', () => {
|
||||
let entity1: Entity;
|
||||
let entity2: Entity;
|
||||
let entity3: Entity;
|
||||
let batchOp: EntityBatchOperator;
|
||||
|
||||
beforeEach(() => {
|
||||
entity1 = scene.createEntity('Entity1');
|
||||
entity2 = scene.createEntity('Entity2');
|
||||
entity3 = scene.createEntity('Entity3');
|
||||
batchOp = new EntityBatchOperator([entity1, entity2, entity3]);
|
||||
});
|
||||
|
||||
test('应该能够创建批量操作器', () => {
|
||||
expect(batchOp).toBeInstanceOf(EntityBatchOperator);
|
||||
});
|
||||
|
||||
test('应该能够批量添加组件', () => {
|
||||
const component = new TestComponent(100);
|
||||
batchOp.addComponent(component);
|
||||
|
||||
expect(entity1.hasComponent(TestComponent)).toBe(true);
|
||||
expect(entity2.hasComponent(TestComponent)).toBe(true);
|
||||
expect(entity3.hasComponent(TestComponent)).toBe(true);
|
||||
});
|
||||
|
||||
test('应该能够批量移除组件', () => {
|
||||
entity1.addComponent(new TestComponent(100));
|
||||
entity2.addComponent(new TestComponent(200));
|
||||
entity3.addComponent(new TestComponent(300));
|
||||
|
||||
batchOp.removeComponent(TestComponent);
|
||||
|
||||
expect(entity1.hasComponent(TestComponent)).toBe(false);
|
||||
expect(entity2.hasComponent(TestComponent)).toBe(false);
|
||||
expect(entity3.hasComponent(TestComponent)).toBe(false);
|
||||
});
|
||||
|
||||
test('应该能够批量设置活跃状态', () => {
|
||||
batchOp.setActive(false);
|
||||
|
||||
expect(entity1.active).toBe(false);
|
||||
expect(entity2.active).toBe(false);
|
||||
expect(entity3.active).toBe(false);
|
||||
});
|
||||
|
||||
test('应该能够批量设置标签', () => {
|
||||
batchOp.setTag(42);
|
||||
|
||||
expect(entity1.tag).toBe(42);
|
||||
expect(entity2.tag).toBe(42);
|
||||
expect(entity3.tag).toBe(42);
|
||||
});
|
||||
|
||||
test('应该能够批量执行操作', () => {
|
||||
const names: string[] = [];
|
||||
const indices: number[] = [];
|
||||
|
||||
batchOp.forEach((entity, index) => {
|
||||
names.push(entity.name);
|
||||
indices.push(index);
|
||||
});
|
||||
|
||||
expect(names).toEqual(['Entity1', 'Entity2', 'Entity3']);
|
||||
expect(indices).toEqual([0, 1, 2]);
|
||||
});
|
||||
|
||||
test('应该能够过滤实体', () => {
|
||||
entity1.tag = 1;
|
||||
entity2.tag = 2;
|
||||
entity3.tag = 1;
|
||||
|
||||
const filtered = batchOp.filter(entity => entity.tag === 1);
|
||||
|
||||
expect(filtered.count()).toBe(2);
|
||||
expect(filtered.toArray()).toContain(entity1);
|
||||
expect(filtered.toArray()).toContain(entity3);
|
||||
});
|
||||
|
||||
test('应该能够获取实体数组', () => {
|
||||
const entities = batchOp.toArray();
|
||||
|
||||
expect(entities.length).toBe(3);
|
||||
expect(entities).toContain(entity1);
|
||||
expect(entities).toContain(entity2);
|
||||
expect(entities).toContain(entity3);
|
||||
});
|
||||
|
||||
test('应该能够获取实体数量', () => {
|
||||
expect(batchOp.count()).toBe(3);
|
||||
});
|
||||
|
||||
test('流式调用应该工作正常', () => {
|
||||
const result = batchOp
|
||||
.addComponent(new TestComponent(100))
|
||||
.setActive(false)
|
||||
.setTag(42)
|
||||
.forEach((entity) => {
|
||||
entity.name = entity.name + '_Modified';
|
||||
});
|
||||
|
||||
expect(result).toBe(batchOp);
|
||||
expect(entity1.hasComponent(TestComponent)).toBe(true);
|
||||
expect(entity1.active).toBe(false);
|
||||
expect(entity1.tag).toBe(42);
|
||||
expect(entity1.name).toBe('Entity1_Modified');
|
||||
});
|
||||
});
|
||||
|
||||
describe('工厂函数和全局API', () => {
|
||||
test('createECSAPI应该创建API实例', () => {
|
||||
const api = createECSAPI(scene, querySystem, eventSystem);
|
||||
expect(api).toBeInstanceOf(ECSFluentAPI);
|
||||
});
|
||||
|
||||
test('initializeECS应该初始化全局ECS', () => {
|
||||
initializeECS(scene, querySystem, eventSystem);
|
||||
expect(ECS).toBeInstanceOf(ECSFluentAPI);
|
||||
});
|
||||
|
||||
test('全局ECS应该可用', () => {
|
||||
initializeECS(scene, querySystem, eventSystem);
|
||||
|
||||
const builder = ECS.createEntity();
|
||||
expect(builder).toBeInstanceOf(EntityBuilder);
|
||||
});
|
||||
});
|
||||
});
|
||||
321
packages/core/tests/ECS/Core/FluentAPI/EntityBuilder.test.ts
Normal file
321
packages/core/tests/ECS/Core/FluentAPI/EntityBuilder.test.ts
Normal file
@@ -0,0 +1,321 @@
|
||||
import { EntityBuilder } from '../../../../src/ECS/Core/FluentAPI/EntityBuilder';
|
||||
import { Scene } from '../../../../src/ECS/Scene';
|
||||
import { Component } from '../../../../src/ECS/Component';
|
||||
import { HierarchySystem } from '../../../../src/ECS/Systems/HierarchySystem';
|
||||
import { ECSComponent } from '../../../../src/ECS/Decorators';
|
||||
|
||||
@ECSComponent('BuilderTestPosition')
|
||||
class PositionComponent extends Component {
|
||||
public x: number = 0;
|
||||
public y: number = 0;
|
||||
|
||||
constructor(x: number = 0, y: number = 0) {
|
||||
super();
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
}
|
||||
}
|
||||
|
||||
@ECSComponent('BuilderTestVelocity')
|
||||
class VelocityComponent extends Component {
|
||||
public vx: number = 0;
|
||||
public vy: number = 0;
|
||||
}
|
||||
|
||||
@ECSComponent('BuilderTestHealth')
|
||||
class HealthComponent extends Component {
|
||||
public current: number = 100;
|
||||
public max: number = 100;
|
||||
}
|
||||
|
||||
// Helper function to create EntityBuilder
|
||||
function createBuilder(scene: Scene): EntityBuilder {
|
||||
return new EntityBuilder(scene, scene.componentStorageManager);
|
||||
}
|
||||
|
||||
describe('EntityBuilder', () => {
|
||||
let scene: Scene;
|
||||
let hierarchySystem: HierarchySystem;
|
||||
|
||||
beforeEach(() => {
|
||||
scene = new Scene({ name: 'BuilderTestScene' });
|
||||
hierarchySystem = new HierarchySystem();
|
||||
scene.addSystem(hierarchySystem);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
scene.end();
|
||||
});
|
||||
|
||||
describe('basic building', () => {
|
||||
test('should create entity with name', () => {
|
||||
const builder = createBuilder(scene);
|
||||
const entity = builder.named('TestEntity').build();
|
||||
|
||||
expect(entity.name).toBe('TestEntity');
|
||||
});
|
||||
|
||||
test('should create entity with tag', () => {
|
||||
const builder = createBuilder(scene);
|
||||
const entity = builder.tagged(0x100).build();
|
||||
|
||||
expect(entity.tag).toBe(0x100);
|
||||
});
|
||||
|
||||
test('should support chaining name and tag', () => {
|
||||
const entity = createBuilder(scene)
|
||||
.named('ChainedEntity')
|
||||
.tagged(0x200)
|
||||
.build();
|
||||
|
||||
expect(entity.name).toBe('ChainedEntity');
|
||||
expect(entity.tag).toBe(0x200);
|
||||
});
|
||||
});
|
||||
|
||||
describe('component management', () => {
|
||||
test('should add single component with .with()', () => {
|
||||
const entity = createBuilder(scene)
|
||||
.with(new PositionComponent(10, 20))
|
||||
.build();
|
||||
|
||||
const pos = entity.getComponent(PositionComponent);
|
||||
expect(pos).not.toBeNull();
|
||||
expect(pos!.x).toBe(10);
|
||||
expect(pos!.y).toBe(20);
|
||||
});
|
||||
|
||||
test('should add multiple components with .withComponents()', () => {
|
||||
const entity = createBuilder(scene)
|
||||
.withComponents(
|
||||
new PositionComponent(5, 10),
|
||||
new VelocityComponent(),
|
||||
new HealthComponent()
|
||||
)
|
||||
.build();
|
||||
|
||||
expect(entity.hasComponent(PositionComponent)).toBe(true);
|
||||
expect(entity.hasComponent(VelocityComponent)).toBe(true);
|
||||
expect(entity.hasComponent(HealthComponent)).toBe(true);
|
||||
});
|
||||
|
||||
test('should conditionally add component with .withIf()', () => {
|
||||
const shouldAdd = true;
|
||||
const shouldNotAdd = false;
|
||||
|
||||
const entity = createBuilder(scene)
|
||||
.withIf(shouldAdd, new PositionComponent())
|
||||
.withIf(shouldNotAdd, new VelocityComponent())
|
||||
.build();
|
||||
|
||||
expect(entity.hasComponent(PositionComponent)).toBe(true);
|
||||
expect(entity.hasComponent(VelocityComponent)).toBe(false);
|
||||
});
|
||||
|
||||
test('should add component using factory with .withFactory()', () => {
|
||||
const entity = createBuilder(scene)
|
||||
.withFactory(() => new PositionComponent(100, 200))
|
||||
.build();
|
||||
|
||||
const pos = entity.getComponent(PositionComponent);
|
||||
expect(pos).not.toBeNull();
|
||||
expect(pos!.x).toBe(100);
|
||||
expect(pos!.y).toBe(200);
|
||||
});
|
||||
|
||||
test('should configure existing component with .configure()', () => {
|
||||
const entity = createBuilder(scene)
|
||||
.with(new PositionComponent(0, 0))
|
||||
.configure(PositionComponent, (pos: PositionComponent) => {
|
||||
pos.x = 999;
|
||||
pos.y = 888;
|
||||
})
|
||||
.build();
|
||||
|
||||
const pos = entity.getComponent(PositionComponent);
|
||||
expect(pos!.x).toBe(999);
|
||||
expect(pos!.y).toBe(888);
|
||||
});
|
||||
|
||||
test('.configure() should do nothing if component does not exist', () => {
|
||||
const entity = createBuilder(scene)
|
||||
.configure(PositionComponent, (pos: PositionComponent) => {
|
||||
pos.x = 100;
|
||||
})
|
||||
.build();
|
||||
|
||||
expect(entity.hasComponent(PositionComponent)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('entity state', () => {
|
||||
test('should set enabled state', () => {
|
||||
const disabledEntity = createBuilder(scene)
|
||||
.enabled(false)
|
||||
.build();
|
||||
|
||||
const enabledEntity = createBuilder(scene)
|
||||
.enabled(true)
|
||||
.build();
|
||||
|
||||
expect(disabledEntity.enabled).toBe(false);
|
||||
expect(enabledEntity.enabled).toBe(true);
|
||||
});
|
||||
|
||||
test('should set active state', () => {
|
||||
const inactiveEntity = createBuilder(scene)
|
||||
.active(false)
|
||||
.build();
|
||||
|
||||
const activeEntity = createBuilder(scene)
|
||||
.active(true)
|
||||
.build();
|
||||
|
||||
expect(inactiveEntity.active).toBe(false);
|
||||
expect(activeEntity.active).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('hierarchy building', () => {
|
||||
test('should call withChild method', () => {
|
||||
const childBuilder = createBuilder(scene).named('Child');
|
||||
const builder = createBuilder(scene)
|
||||
.named('Parent')
|
||||
.withChild(childBuilder);
|
||||
|
||||
// withChild returns the builder for chaining
|
||||
expect(builder).toBeInstanceOf(EntityBuilder);
|
||||
});
|
||||
|
||||
test('should call withChildren method', () => {
|
||||
const child1Builder = createBuilder(scene).named('Child1');
|
||||
const child2Builder = createBuilder(scene).named('Child2');
|
||||
|
||||
const builder = createBuilder(scene)
|
||||
.named('Parent')
|
||||
.withChildren(child1Builder, child2Builder);
|
||||
|
||||
// withChildren returns the builder for chaining
|
||||
expect(builder).toBeInstanceOf(EntityBuilder);
|
||||
});
|
||||
|
||||
test('should call withChildFactory method', () => {
|
||||
const builder = createBuilder(scene)
|
||||
.named('Parent')
|
||||
.with(new PositionComponent(100, 100))
|
||||
.withChildFactory((parentEntity) => {
|
||||
return createBuilder(scene)
|
||||
.named('ChildFromFactory')
|
||||
.with(new PositionComponent(10, 20));
|
||||
});
|
||||
|
||||
// withChildFactory returns the builder for chaining
|
||||
expect(builder).toBeInstanceOf(EntityBuilder);
|
||||
});
|
||||
|
||||
test('should call withChildIf method', () => {
|
||||
const shouldAdd = true;
|
||||
const shouldNotAdd = false;
|
||||
|
||||
const child1Builder = createBuilder(scene).named('Child1');
|
||||
const builder1 = createBuilder(scene)
|
||||
.named('Parent')
|
||||
.withChildIf(shouldAdd, child1Builder);
|
||||
|
||||
expect(builder1).toBeInstanceOf(EntityBuilder);
|
||||
|
||||
const child2Builder = createBuilder(scene).named('Child2');
|
||||
const builder2 = createBuilder(scene)
|
||||
.named('Parent2')
|
||||
.withChildIf(shouldNotAdd, child2Builder);
|
||||
|
||||
expect(builder2).toBeInstanceOf(EntityBuilder);
|
||||
});
|
||||
});
|
||||
|
||||
describe('spawning and cloning', () => {
|
||||
test('should spawn entity to scene with .spawn()', () => {
|
||||
const initialCount = scene.entities.count;
|
||||
|
||||
const entity = createBuilder(scene)
|
||||
.named('SpawnedEntity')
|
||||
.with(new PositionComponent())
|
||||
.spawn();
|
||||
|
||||
expect(scene.entities.count).toBe(initialCount + 1);
|
||||
expect(scene.findEntityById(entity.id)).toBe(entity);
|
||||
});
|
||||
|
||||
test('.build() should not add to scene automatically', () => {
|
||||
const initialCount = scene.entities.count;
|
||||
|
||||
createBuilder(scene)
|
||||
.named('BuiltEntity')
|
||||
.build();
|
||||
|
||||
expect(scene.entities.count).toBe(initialCount);
|
||||
});
|
||||
|
||||
test('should clone builder', () => {
|
||||
const builder = createBuilder(scene)
|
||||
.named('OriginalEntity')
|
||||
.tagged(0x50);
|
||||
|
||||
const clonedBuilder = builder.clone();
|
||||
|
||||
expect(clonedBuilder).not.toBe(builder);
|
||||
expect(clonedBuilder).toBeInstanceOf(EntityBuilder);
|
||||
});
|
||||
});
|
||||
|
||||
describe('complex building scenarios', () => {
|
||||
test('should build complete entity with all options', () => {
|
||||
const entity = createBuilder(scene)
|
||||
.named('CompleteEntity')
|
||||
.tagged(0x100)
|
||||
.with(new PositionComponent(50, 75))
|
||||
.with(new VelocityComponent())
|
||||
.withFactory(() => new HealthComponent())
|
||||
.configure(HealthComponent, (h: HealthComponent) => {
|
||||
h.current = 80;
|
||||
h.max = 100;
|
||||
})
|
||||
.enabled(true)
|
||||
.active(true)
|
||||
.build();
|
||||
|
||||
expect(entity.name).toBe('CompleteEntity');
|
||||
expect(entity.tag).toBe(0x100);
|
||||
expect(entity.enabled).toBe(true);
|
||||
expect(entity.active).toBe(true);
|
||||
|
||||
expect(entity.hasComponent(PositionComponent)).toBe(true);
|
||||
expect(entity.hasComponent(VelocityComponent)).toBe(true);
|
||||
expect(entity.hasComponent(HealthComponent)).toBe(true);
|
||||
|
||||
const health = entity.getComponent(HealthComponent);
|
||||
expect(health!.current).toBe(80);
|
||||
expect(health!.max).toBe(100);
|
||||
});
|
||||
|
||||
test('should support complex chaining', () => {
|
||||
const builder = createBuilder(scene)
|
||||
.named('Root')
|
||||
.with(new PositionComponent(1, 1));
|
||||
|
||||
// Add child builder chain
|
||||
const childBuilder = createBuilder(scene)
|
||||
.named('Child')
|
||||
.with(new PositionComponent(2, 2));
|
||||
|
||||
// Chain withChild
|
||||
builder.withChild(childBuilder);
|
||||
|
||||
// Build and spawn
|
||||
const root = builder.spawn();
|
||||
|
||||
expect(root.name).toBe('Root');
|
||||
expect(root.hasComponent(PositionComponent)).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,274 +0,0 @@
|
||||
import { describe, test, expect, beforeEach } from '@jest/globals';
|
||||
import { Scene } from '../../src/ECS/Scene';
|
||||
import { Component } from '../../src/ECS/Component';
|
||||
import { Entity } from '../../src/ECS/Entity';
|
||||
import { EntityRef, ECSComponent } from '../../src/ECS/Decorators';
|
||||
|
||||
@ECSComponent('ParentRef')
|
||||
class ParentComponent extends Component {
|
||||
@EntityRef() parent: Entity | null = null;
|
||||
}
|
||||
|
||||
@ECSComponent('TargetRef')
|
||||
class TargetComponent extends Component {
|
||||
@EntityRef() target: Entity | null = null;
|
||||
@EntityRef() ally: Entity | null = null;
|
||||
}
|
||||
|
||||
describe('EntityRef Integration Tests', () => {
|
||||
let scene: Scene;
|
||||
|
||||
beforeEach(() => {
|
||||
scene = new Scene({ name: 'TestScene' });
|
||||
});
|
||||
|
||||
describe('基础功能', () => {
|
||||
test('应该支持EntityRef装饰器', () => {
|
||||
const entity1 = scene.createEntity('Entity1');
|
||||
const entity2 = scene.createEntity('Entity2');
|
||||
const comp = entity1.addComponent(new ParentComponent());
|
||||
|
||||
comp.parent = entity2;
|
||||
|
||||
expect(comp.parent).toBe(entity2);
|
||||
});
|
||||
|
||||
test('Entity销毁时应该自动清理所有引用', () => {
|
||||
const parent = scene.createEntity('Parent');
|
||||
const child1 = scene.createEntity('Child1');
|
||||
const child2 = scene.createEntity('Child2');
|
||||
|
||||
const comp1 = child1.addComponent(new ParentComponent());
|
||||
const comp2 = child2.addComponent(new ParentComponent());
|
||||
|
||||
comp1.parent = parent;
|
||||
comp2.parent = parent;
|
||||
|
||||
expect(comp1.parent).toBe(parent);
|
||||
expect(comp2.parent).toBe(parent);
|
||||
|
||||
parent.destroy();
|
||||
|
||||
expect(comp1.parent).toBeNull();
|
||||
expect(comp2.parent).toBeNull();
|
||||
});
|
||||
|
||||
test('修改引用应该更新ReferenceTracker', () => {
|
||||
const entity1 = scene.createEntity('Entity1');
|
||||
const entity2 = scene.createEntity('Entity2');
|
||||
const entity3 = scene.createEntity('Entity3');
|
||||
const comp = entity1.addComponent(new ParentComponent());
|
||||
|
||||
comp.parent = entity2;
|
||||
expect(scene.referenceTracker.getReferencesTo(entity2.id)).toHaveLength(1);
|
||||
|
||||
comp.parent = entity3;
|
||||
expect(scene.referenceTracker.getReferencesTo(entity2.id)).toHaveLength(0);
|
||||
expect(scene.referenceTracker.getReferencesTo(entity3.id)).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('设置为null应该注销引用', () => {
|
||||
const entity1 = scene.createEntity('Entity1');
|
||||
const entity2 = scene.createEntity('Entity2');
|
||||
const comp = entity1.addComponent(new ParentComponent());
|
||||
|
||||
comp.parent = entity2;
|
||||
expect(scene.referenceTracker.getReferencesTo(entity2.id)).toHaveLength(1);
|
||||
|
||||
comp.parent = null;
|
||||
expect(scene.referenceTracker.getReferencesTo(entity2.id)).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Component生命周期', () => {
|
||||
test('移除Component应该清理其所有引用注册', () => {
|
||||
const entity1 = scene.createEntity('Entity1');
|
||||
const entity2 = scene.createEntity('Entity2');
|
||||
const comp = entity1.addComponent(new ParentComponent());
|
||||
|
||||
comp.parent = entity2;
|
||||
expect(scene.referenceTracker.getReferencesTo(entity2.id)).toHaveLength(1);
|
||||
|
||||
entity1.removeComponent(comp);
|
||||
expect(scene.referenceTracker.getReferencesTo(entity2.id)).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('移除Component应该清除entityId引用', () => {
|
||||
const entity1 = scene.createEntity('Entity1');
|
||||
const comp = entity1.addComponent(new ParentComponent());
|
||||
|
||||
expect(comp.entityId).toBe(entity1.id);
|
||||
|
||||
entity1.removeComponent(comp);
|
||||
expect(comp.entityId).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('多属性引用', () => {
|
||||
test('应该支持同一Component的多个EntityRef属性', () => {
|
||||
const entity1 = scene.createEntity('Entity1');
|
||||
const entity2 = scene.createEntity('Entity2');
|
||||
const entity3 = scene.createEntity('Entity3');
|
||||
const comp = entity1.addComponent(new TargetComponent());
|
||||
|
||||
comp.target = entity2;
|
||||
comp.ally = entity3;
|
||||
|
||||
expect(comp.target).toBe(entity2);
|
||||
expect(comp.ally).toBe(entity3);
|
||||
|
||||
entity2.destroy();
|
||||
|
||||
expect(comp.target).toBeNull();
|
||||
expect(comp.ally).toBe(entity3);
|
||||
|
||||
entity3.destroy();
|
||||
|
||||
expect(comp.ally).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('边界情况', () => {
|
||||
test('跨Scene引用应该失败', () => {
|
||||
const scene2 = new Scene({ name: 'TestScene2' });
|
||||
const entity1 = scene.createEntity('Entity1');
|
||||
const entity2 = scene2.createEntity('Entity2');
|
||||
const comp = entity1.addComponent(new ParentComponent());
|
||||
|
||||
comp.parent = entity2;
|
||||
|
||||
expect(comp.parent).toBeNull();
|
||||
});
|
||||
|
||||
test('引用已销毁的Entity应该失败', () => {
|
||||
const entity1 = scene.createEntity('Entity1');
|
||||
const entity2 = scene.createEntity('Entity2');
|
||||
const comp = entity1.addComponent(new ParentComponent());
|
||||
|
||||
entity2.destroy();
|
||||
comp.parent = entity2;
|
||||
|
||||
expect(comp.parent).toBeNull();
|
||||
});
|
||||
|
||||
test('重复设置相同值不应重复注册', () => {
|
||||
const entity1 = scene.createEntity('Entity1');
|
||||
const entity2 = scene.createEntity('Entity2');
|
||||
const comp = entity1.addComponent(new ParentComponent());
|
||||
|
||||
comp.parent = entity2;
|
||||
comp.parent = entity2;
|
||||
comp.parent = entity2;
|
||||
|
||||
expect(scene.referenceTracker.getReferencesTo(entity2.id)).toHaveLength(1);
|
||||
});
|
||||
|
||||
test('循环引用应该正常工作', () => {
|
||||
const entity1 = scene.createEntity('Entity1');
|
||||
const entity2 = scene.createEntity('Entity2');
|
||||
const comp1 = entity1.addComponent(new ParentComponent());
|
||||
const comp2 = entity2.addComponent(new ParentComponent());
|
||||
|
||||
comp1.parent = entity2;
|
||||
comp2.parent = entity1;
|
||||
|
||||
expect(comp1.parent).toBe(entity2);
|
||||
expect(comp2.parent).toBe(entity1);
|
||||
|
||||
entity1.destroy();
|
||||
|
||||
expect(comp2.parent).toBeNull();
|
||||
expect(entity2.isDestroyed).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('复杂场景', () => {
|
||||
test('父子实体销毁应该正确清理引用', () => {
|
||||
const parent = scene.createEntity('Parent');
|
||||
const child1 = scene.createEntity('Child1');
|
||||
const child2 = scene.createEntity('Child2');
|
||||
const observer = scene.createEntity('Observer');
|
||||
|
||||
parent.addChild(child1);
|
||||
parent.addChild(child2);
|
||||
|
||||
const observerComp = observer.addComponent(new TargetComponent());
|
||||
observerComp.target = parent;
|
||||
observerComp.ally = child1;
|
||||
|
||||
expect(observerComp.target).toBe(parent);
|
||||
expect(observerComp.ally).toBe(child1);
|
||||
|
||||
parent.destroy();
|
||||
|
||||
expect(observerComp.target).toBeNull();
|
||||
expect(observerComp.ally).toBeNull();
|
||||
expect(child1.isDestroyed).toBe(true);
|
||||
expect(child2.isDestroyed).toBe(true);
|
||||
});
|
||||
|
||||
test('大量引用场景', () => {
|
||||
const target = scene.createEntity('Target');
|
||||
const entities: Entity[] = [];
|
||||
const components: ParentComponent[] = [];
|
||||
|
||||
for (let i = 0; i < 100; i++) {
|
||||
const entity = scene.createEntity(`Entity${i}`);
|
||||
const comp = entity.addComponent(new ParentComponent());
|
||||
comp.parent = target;
|
||||
entities.push(entity);
|
||||
components.push(comp);
|
||||
}
|
||||
|
||||
expect(scene.referenceTracker.getReferencesTo(target.id)).toHaveLength(100);
|
||||
|
||||
target.destroy();
|
||||
|
||||
for (const comp of components) {
|
||||
expect(comp.parent).toBeNull();
|
||||
}
|
||||
|
||||
expect(scene.referenceTracker.getReferencesTo(target.id)).toHaveLength(0);
|
||||
});
|
||||
|
||||
test('批量销毁后引用应全部清理', () => {
|
||||
const entities: Entity[] = [];
|
||||
const components: TargetComponent[] = [];
|
||||
|
||||
for (let i = 0; i < 50; i++) {
|
||||
entities.push(scene.createEntity(`Entity${i}`));
|
||||
}
|
||||
|
||||
for (let i = 0; i < 50; i++) {
|
||||
const comp = entities[i].addComponent(new TargetComponent());
|
||||
if (i > 0) {
|
||||
comp.target = entities[i - 1];
|
||||
}
|
||||
if (i < 49) {
|
||||
comp.ally = entities[i + 1];
|
||||
}
|
||||
components.push(comp);
|
||||
}
|
||||
|
||||
scene.destroyAllEntities();
|
||||
|
||||
for (const comp of components) {
|
||||
expect(comp.target).toBeNull();
|
||||
expect(comp.ally).toBeNull();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('调试功能', () => {
|
||||
test('getDebugInfo应该返回引用信息', () => {
|
||||
const entity1 = scene.createEntity('Entity1');
|
||||
const entity2 = scene.createEntity('Entity2');
|
||||
const comp = entity1.addComponent(new ParentComponent());
|
||||
|
||||
comp.parent = entity2;
|
||||
|
||||
const debugInfo = scene.referenceTracker.getDebugInfo();
|
||||
expect(debugInfo).toHaveProperty(`entity_${entity2.id}`);
|
||||
});
|
||||
});
|
||||
});
|
||||
237
packages/core/tests/ECS/EntityTags.test.ts
Normal file
237
packages/core/tests/ECS/EntityTags.test.ts
Normal file
@@ -0,0 +1,237 @@
|
||||
import {
|
||||
EntityTags,
|
||||
hasEntityTag,
|
||||
addEntityTag,
|
||||
removeEntityTag,
|
||||
isFolder,
|
||||
isHidden,
|
||||
isLocked
|
||||
} from '../../src/ECS/EntityTags';
|
||||
|
||||
describe('EntityTags', () => {
|
||||
describe('tag constants', () => {
|
||||
test('should have correct NONE value', () => {
|
||||
expect(EntityTags.NONE).toBe(0x0000);
|
||||
});
|
||||
|
||||
test('should have correct FOLDER value', () => {
|
||||
expect(EntityTags.FOLDER).toBe(0x1000);
|
||||
});
|
||||
|
||||
test('should have correct HIDDEN value', () => {
|
||||
expect(EntityTags.HIDDEN).toBe(0x2000);
|
||||
});
|
||||
|
||||
test('should have correct LOCKED value', () => {
|
||||
expect(EntityTags.LOCKED).toBe(0x4000);
|
||||
});
|
||||
|
||||
test('should have correct EDITOR_ONLY value', () => {
|
||||
expect(EntityTags.EDITOR_ONLY).toBe(0x8000);
|
||||
});
|
||||
|
||||
test('should have correct PREFAB_INSTANCE value', () => {
|
||||
expect(EntityTags.PREFAB_INSTANCE).toBe(0x0100);
|
||||
});
|
||||
|
||||
test('should have correct PREFAB_ROOT value', () => {
|
||||
expect(EntityTags.PREFAB_ROOT).toBe(0x0200);
|
||||
});
|
||||
|
||||
test('all tags should have unique values', () => {
|
||||
const values = Object.values(EntityTags).filter((v) => typeof v === 'number');
|
||||
const uniqueValues = new Set(values);
|
||||
expect(uniqueValues.size).toBe(values.length);
|
||||
});
|
||||
});
|
||||
|
||||
describe('hasEntityTag', () => {
|
||||
test('should return true when tag is present', () => {
|
||||
const tag = EntityTags.FOLDER;
|
||||
expect(hasEntityTag(tag, EntityTags.FOLDER)).toBe(true);
|
||||
});
|
||||
|
||||
test('should return false when tag is not present', () => {
|
||||
const tag = EntityTags.FOLDER;
|
||||
expect(hasEntityTag(tag, EntityTags.HIDDEN)).toBe(false);
|
||||
});
|
||||
|
||||
test('should work with combined tags', () => {
|
||||
const combined = EntityTags.FOLDER | EntityTags.HIDDEN | EntityTags.LOCKED;
|
||||
|
||||
expect(hasEntityTag(combined, EntityTags.FOLDER)).toBe(true);
|
||||
expect(hasEntityTag(combined, EntityTags.HIDDEN)).toBe(true);
|
||||
expect(hasEntityTag(combined, EntityTags.LOCKED)).toBe(true);
|
||||
expect(hasEntityTag(combined, EntityTags.EDITOR_ONLY)).toBe(false);
|
||||
});
|
||||
|
||||
test('should return false for NONE tag', () => {
|
||||
const tag = EntityTags.NONE;
|
||||
expect(hasEntityTag(tag, EntityTags.FOLDER)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('addEntityTag', () => {
|
||||
test('should add tag to empty tags', () => {
|
||||
const result = addEntityTag(EntityTags.NONE, EntityTags.FOLDER);
|
||||
expect(result).toBe(EntityTags.FOLDER);
|
||||
});
|
||||
|
||||
test('should add tag to existing tags', () => {
|
||||
const existing = EntityTags.FOLDER as number;
|
||||
const result = addEntityTag(existing, EntityTags.HIDDEN);
|
||||
|
||||
expect(hasEntityTag(result, EntityTags.FOLDER)).toBe(true);
|
||||
expect(hasEntityTag(result, EntityTags.HIDDEN)).toBe(true);
|
||||
});
|
||||
|
||||
test('should not change value when adding same tag', () => {
|
||||
const existing = EntityTags.FOLDER as number;
|
||||
const result = addEntityTag(existing, EntityTags.FOLDER);
|
||||
|
||||
expect(result).toBe(EntityTags.FOLDER);
|
||||
});
|
||||
|
||||
test('should handle multiple tag additions', () => {
|
||||
let tag: number = EntityTags.NONE;
|
||||
tag = addEntityTag(tag, EntityTags.FOLDER);
|
||||
tag = addEntityTag(tag, EntityTags.HIDDEN);
|
||||
tag = addEntityTag(tag, EntityTags.LOCKED);
|
||||
|
||||
expect(hasEntityTag(tag, EntityTags.FOLDER)).toBe(true);
|
||||
expect(hasEntityTag(tag, EntityTags.HIDDEN)).toBe(true);
|
||||
expect(hasEntityTag(tag, EntityTags.LOCKED)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('removeEntityTag', () => {
|
||||
test('should remove tag from combined tags', () => {
|
||||
const combined = (EntityTags.FOLDER | EntityTags.HIDDEN) as number;
|
||||
const result = removeEntityTag(combined, EntityTags.HIDDEN);
|
||||
|
||||
expect(hasEntityTag(result, EntityTags.FOLDER)).toBe(true);
|
||||
expect(hasEntityTag(result, EntityTags.HIDDEN)).toBe(false);
|
||||
});
|
||||
|
||||
test('should return same value when removing non-existent tag', () => {
|
||||
const existing = EntityTags.FOLDER as number;
|
||||
const result = removeEntityTag(existing, EntityTags.HIDDEN);
|
||||
|
||||
expect(result).toBe(EntityTags.FOLDER);
|
||||
});
|
||||
|
||||
test('should return NONE when removing last tag', () => {
|
||||
const result = removeEntityTag(EntityTags.FOLDER, EntityTags.FOLDER);
|
||||
expect(result).toBe(EntityTags.NONE);
|
||||
});
|
||||
|
||||
test('should handle multiple tag removals', () => {
|
||||
let tag: number = EntityTags.FOLDER | EntityTags.HIDDEN | EntityTags.LOCKED;
|
||||
tag = removeEntityTag(tag, EntityTags.FOLDER);
|
||||
tag = removeEntityTag(tag, EntityTags.LOCKED);
|
||||
|
||||
expect(hasEntityTag(tag, EntityTags.FOLDER)).toBe(false);
|
||||
expect(hasEntityTag(tag, EntityTags.HIDDEN)).toBe(true);
|
||||
expect(hasEntityTag(tag, EntityTags.LOCKED)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isFolder', () => {
|
||||
test('should return true for folder tag', () => {
|
||||
expect(isFolder(EntityTags.FOLDER)).toBe(true);
|
||||
});
|
||||
|
||||
test('should return true for combined tags including folder', () => {
|
||||
const combined = EntityTags.FOLDER | EntityTags.HIDDEN;
|
||||
expect(isFolder(combined)).toBe(true);
|
||||
});
|
||||
|
||||
test('should return false for non-folder tag', () => {
|
||||
expect(isFolder(EntityTags.HIDDEN)).toBe(false);
|
||||
expect(isFolder(EntityTags.NONE)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isHidden', () => {
|
||||
test('should return true for hidden tag', () => {
|
||||
expect(isHidden(EntityTags.HIDDEN)).toBe(true);
|
||||
});
|
||||
|
||||
test('should return true for combined tags including hidden', () => {
|
||||
const combined = EntityTags.FOLDER | EntityTags.HIDDEN;
|
||||
expect(isHidden(combined)).toBe(true);
|
||||
});
|
||||
|
||||
test('should return false for non-hidden tag', () => {
|
||||
expect(isHidden(EntityTags.FOLDER)).toBe(false);
|
||||
expect(isHidden(EntityTags.NONE)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isLocked', () => {
|
||||
test('should return true for locked tag', () => {
|
||||
expect(isLocked(EntityTags.LOCKED)).toBe(true);
|
||||
});
|
||||
|
||||
test('should return true for combined tags including locked', () => {
|
||||
const combined = EntityTags.FOLDER | EntityTags.LOCKED;
|
||||
expect(isLocked(combined)).toBe(true);
|
||||
});
|
||||
|
||||
test('should return false for non-locked tag', () => {
|
||||
expect(isLocked(EntityTags.FOLDER)).toBe(false);
|
||||
expect(isLocked(EntityTags.NONE)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('tag combinations', () => {
|
||||
test('should correctly combine and identify multiple tags', () => {
|
||||
const tag = (EntityTags.FOLDER | EntityTags.HIDDEN | EntityTags.PREFAB_ROOT) as number;
|
||||
|
||||
expect(isFolder(tag)).toBe(true);
|
||||
expect(isHidden(tag)).toBe(true);
|
||||
expect(hasEntityTag(tag, EntityTags.PREFAB_ROOT)).toBe(true);
|
||||
expect(isLocked(tag)).toBe(false);
|
||||
});
|
||||
|
||||
test('should support complex add/remove operations', () => {
|
||||
let tag: number = EntityTags.NONE;
|
||||
|
||||
// Add tags
|
||||
tag = addEntityTag(tag, EntityTags.FOLDER);
|
||||
tag = addEntityTag(tag, EntityTags.HIDDEN);
|
||||
tag = addEntityTag(tag, EntityTags.LOCKED);
|
||||
tag = addEntityTag(tag, EntityTags.EDITOR_ONLY);
|
||||
|
||||
expect(isFolder(tag)).toBe(true);
|
||||
expect(isHidden(tag)).toBe(true);
|
||||
expect(isLocked(tag)).toBe(true);
|
||||
expect(hasEntityTag(tag, EntityTags.EDITOR_ONLY)).toBe(true);
|
||||
|
||||
// Remove some tags
|
||||
tag = removeEntityTag(tag, EntityTags.HIDDEN);
|
||||
tag = removeEntityTag(tag, EntityTags.LOCKED);
|
||||
|
||||
expect(isFolder(tag)).toBe(true);
|
||||
expect(isHidden(tag)).toBe(false);
|
||||
expect(isLocked(tag)).toBe(false);
|
||||
expect(hasEntityTag(tag, EntityTags.EDITOR_ONLY)).toBe(true);
|
||||
});
|
||||
|
||||
test('should work correctly with prefab tags', () => {
|
||||
const prefabInstanceTag = EntityTags.PREFAB_INSTANCE as number;
|
||||
const prefabRootTag = EntityTags.PREFAB_ROOT as number;
|
||||
|
||||
expect(hasEntityTag(prefabInstanceTag, EntityTags.PREFAB_INSTANCE)).toBe(true);
|
||||
expect(hasEntityTag(prefabInstanceTag, EntityTags.PREFAB_ROOT)).toBe(false);
|
||||
|
||||
expect(hasEntityTag(prefabRootTag, EntityTags.PREFAB_ROOT)).toBe(true);
|
||||
expect(hasEntityTag(prefabRootTag, EntityTags.PREFAB_INSTANCE)).toBe(false);
|
||||
|
||||
// Combine both
|
||||
const combined = (prefabInstanceTag | prefabRootTag) as number;
|
||||
expect(hasEntityTag(combined, EntityTags.PREFAB_INSTANCE)).toBe(true);
|
||||
expect(hasEntityTag(combined, EntityTags.PREFAB_ROOT)).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
648
packages/core/tests/ECS/Hierarchy.test.ts
Normal file
648
packages/core/tests/ECS/Hierarchy.test.ts
Normal file
@@ -0,0 +1,648 @@
|
||||
import { Scene, Entity, HierarchyComponent, HierarchySystem } from '../../src';
|
||||
|
||||
describe('HierarchySystem', () => {
|
||||
let scene: Scene;
|
||||
let hierarchySystem: HierarchySystem;
|
||||
|
||||
beforeEach(() => {
|
||||
scene = new Scene();
|
||||
scene.initialize();
|
||||
hierarchySystem = new HierarchySystem();
|
||||
scene.addSystem(hierarchySystem);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
scene.end();
|
||||
});
|
||||
|
||||
describe('setParent', () => {
|
||||
it('should set parent-child relationship', () => {
|
||||
const parent = scene.createEntity('Parent');
|
||||
const child = scene.createEntity('Child');
|
||||
|
||||
hierarchySystem.setParent(child, parent);
|
||||
|
||||
expect(hierarchySystem.getParent(child)).toBe(parent);
|
||||
expect(hierarchySystem.getChildren(parent)).toContain(child);
|
||||
expect(hierarchySystem.getChildCount(parent)).toBe(1);
|
||||
});
|
||||
|
||||
it('should auto-add HierarchyComponent if not present', () => {
|
||||
const parent = scene.createEntity('Parent');
|
||||
const child = scene.createEntity('Child');
|
||||
|
||||
expect(parent.getComponent(HierarchyComponent)).toBeNull();
|
||||
expect(child.getComponent(HierarchyComponent)).toBeNull();
|
||||
|
||||
hierarchySystem.setParent(child, parent);
|
||||
|
||||
expect(parent.getComponent(HierarchyComponent)).not.toBeNull();
|
||||
expect(child.getComponent(HierarchyComponent)).not.toBeNull();
|
||||
});
|
||||
|
||||
it('should move child to root when parent is null', () => {
|
||||
const parent = scene.createEntity('Parent');
|
||||
const child = scene.createEntity('Child');
|
||||
|
||||
hierarchySystem.setParent(child, parent);
|
||||
expect(hierarchySystem.getParent(child)).toBe(parent);
|
||||
|
||||
hierarchySystem.setParent(child, null);
|
||||
expect(hierarchySystem.getParent(child)).toBeNull();
|
||||
expect(hierarchySystem.getChildren(parent)).not.toContain(child);
|
||||
});
|
||||
|
||||
it('should transfer child to new parent', () => {
|
||||
const parent1 = scene.createEntity('Parent1');
|
||||
const parent2 = scene.createEntity('Parent2');
|
||||
const child = scene.createEntity('Child');
|
||||
|
||||
hierarchySystem.setParent(child, parent1);
|
||||
expect(hierarchySystem.getParent(child)).toBe(parent1);
|
||||
expect(hierarchySystem.getChildCount(parent1)).toBe(1);
|
||||
|
||||
hierarchySystem.setParent(child, parent2);
|
||||
expect(hierarchySystem.getParent(child)).toBe(parent2);
|
||||
expect(hierarchySystem.getChildCount(parent1)).toBe(0);
|
||||
expect(hierarchySystem.getChildCount(parent2)).toBe(1);
|
||||
});
|
||||
|
||||
it('should throw error on circular reference', () => {
|
||||
const parent = scene.createEntity('Parent');
|
||||
const child = scene.createEntity('Child');
|
||||
const grandchild = scene.createEntity('Grandchild');
|
||||
|
||||
hierarchySystem.setParent(child, parent);
|
||||
hierarchySystem.setParent(grandchild, child);
|
||||
|
||||
expect(() => {
|
||||
hierarchySystem.setParent(parent, grandchild);
|
||||
}).toThrow('Cannot set parent: would create circular reference');
|
||||
});
|
||||
|
||||
it('should not change if setting same parent', () => {
|
||||
const parent = scene.createEntity('Parent');
|
||||
const child = scene.createEntity('Child');
|
||||
|
||||
hierarchySystem.setParent(child, parent);
|
||||
const hierarchy = child.getComponent(HierarchyComponent)!;
|
||||
hierarchy.bCacheDirty = false;
|
||||
|
||||
hierarchySystem.setParent(child, parent);
|
||||
// Should not mark dirty since parent didn't change
|
||||
expect(hierarchy.bCacheDirty).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('insertChildAt', () => {
|
||||
it('should insert child at specific position', () => {
|
||||
const parent = scene.createEntity('Parent');
|
||||
const child1 = scene.createEntity('Child1');
|
||||
const child2 = scene.createEntity('Child2');
|
||||
const child3 = scene.createEntity('Child3');
|
||||
|
||||
hierarchySystem.setParent(child1, parent);
|
||||
hierarchySystem.setParent(child3, parent);
|
||||
hierarchySystem.insertChildAt(parent, child2, 1);
|
||||
|
||||
const children = hierarchySystem.getChildren(parent);
|
||||
expect(children[0]).toBe(child1);
|
||||
expect(children[1]).toBe(child2);
|
||||
expect(children[2]).toBe(child3);
|
||||
});
|
||||
|
||||
it('should append child when index is -1', () => {
|
||||
const parent = scene.createEntity('Parent');
|
||||
const child1 = scene.createEntity('Child1');
|
||||
const child2 = scene.createEntity('Child2');
|
||||
|
||||
hierarchySystem.setParent(child1, parent);
|
||||
hierarchySystem.insertChildAt(parent, child2, -1);
|
||||
|
||||
const children = hierarchySystem.getChildren(parent);
|
||||
expect(children[children.length - 1]).toBe(child2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('removeChild', () => {
|
||||
it('should remove child from parent', () => {
|
||||
const parent = scene.createEntity('Parent');
|
||||
const child = scene.createEntity('Child');
|
||||
|
||||
hierarchySystem.setParent(child, parent);
|
||||
expect(hierarchySystem.getChildCount(parent)).toBe(1);
|
||||
|
||||
const result = hierarchySystem.removeChild(parent, child);
|
||||
expect(result).toBe(true);
|
||||
expect(hierarchySystem.getChildCount(parent)).toBe(0);
|
||||
expect(hierarchySystem.getParent(child)).toBeNull();
|
||||
});
|
||||
|
||||
it('should return false if child is not a child of parent', () => {
|
||||
const parent1 = scene.createEntity('Parent1');
|
||||
const parent2 = scene.createEntity('Parent2');
|
||||
const child = scene.createEntity('Child');
|
||||
|
||||
hierarchySystem.setParent(child, parent1);
|
||||
|
||||
const result = hierarchySystem.removeChild(parent2, child);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('removeAllChildren', () => {
|
||||
it('should remove all children from parent', () => {
|
||||
const parent = scene.createEntity('Parent');
|
||||
const child1 = scene.createEntity('Child1');
|
||||
const child2 = scene.createEntity('Child2');
|
||||
const child3 = scene.createEntity('Child3');
|
||||
|
||||
hierarchySystem.setParent(child1, parent);
|
||||
hierarchySystem.setParent(child2, parent);
|
||||
hierarchySystem.setParent(child3, parent);
|
||||
expect(hierarchySystem.getChildCount(parent)).toBe(3);
|
||||
|
||||
hierarchySystem.removeAllChildren(parent);
|
||||
expect(hierarchySystem.getChildCount(parent)).toBe(0);
|
||||
expect(hierarchySystem.getParent(child1)).toBeNull();
|
||||
expect(hierarchySystem.getParent(child2)).toBeNull();
|
||||
expect(hierarchySystem.getParent(child3)).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('hierarchy queries', () => {
|
||||
it('should check if entity has children', () => {
|
||||
const parent = scene.createEntity('Parent');
|
||||
const child = scene.createEntity('Child');
|
||||
|
||||
expect(hierarchySystem.hasChildren(parent)).toBe(false);
|
||||
|
||||
hierarchySystem.setParent(child, parent);
|
||||
expect(hierarchySystem.hasChildren(parent)).toBe(true);
|
||||
});
|
||||
|
||||
it('should check isAncestorOf', () => {
|
||||
const grandparent = scene.createEntity('Grandparent');
|
||||
const parent = scene.createEntity('Parent');
|
||||
const child = scene.createEntity('Child');
|
||||
|
||||
hierarchySystem.setParent(parent, grandparent);
|
||||
hierarchySystem.setParent(child, parent);
|
||||
|
||||
expect(hierarchySystem.isAncestorOf(grandparent, child)).toBe(true);
|
||||
expect(hierarchySystem.isAncestorOf(parent, child)).toBe(true);
|
||||
expect(hierarchySystem.isAncestorOf(child, grandparent)).toBe(false);
|
||||
});
|
||||
|
||||
it('should check isDescendantOf', () => {
|
||||
const grandparent = scene.createEntity('Grandparent');
|
||||
const parent = scene.createEntity('Parent');
|
||||
const child = scene.createEntity('Child');
|
||||
|
||||
hierarchySystem.setParent(parent, grandparent);
|
||||
hierarchySystem.setParent(child, parent);
|
||||
|
||||
expect(hierarchySystem.isDescendantOf(child, grandparent)).toBe(true);
|
||||
expect(hierarchySystem.isDescendantOf(child, parent)).toBe(true);
|
||||
expect(hierarchySystem.isDescendantOf(grandparent, child)).toBe(false);
|
||||
});
|
||||
|
||||
it('should get root entity', () => {
|
||||
const root = scene.createEntity('Root');
|
||||
const child = scene.createEntity('Child');
|
||||
const grandchild = scene.createEntity('Grandchild');
|
||||
|
||||
hierarchySystem.setParent(child, root);
|
||||
hierarchySystem.setParent(grandchild, child);
|
||||
|
||||
expect(hierarchySystem.getRoot(grandchild)).toBe(root);
|
||||
expect(hierarchySystem.getRoot(child)).toBe(root);
|
||||
expect(hierarchySystem.getRoot(root)).toBe(root);
|
||||
});
|
||||
|
||||
it('should get depth correctly', () => {
|
||||
const root = scene.createEntity('Root');
|
||||
const child = scene.createEntity('Child');
|
||||
const grandchild = scene.createEntity('Grandchild');
|
||||
|
||||
root.addComponent(new HierarchyComponent());
|
||||
hierarchySystem.setParent(child, root);
|
||||
hierarchySystem.setParent(grandchild, child);
|
||||
|
||||
expect(hierarchySystem.getDepth(root)).toBe(0);
|
||||
expect(hierarchySystem.getDepth(child)).toBe(1);
|
||||
expect(hierarchySystem.getDepth(grandchild)).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('findChild', () => {
|
||||
it('should find child by name', () => {
|
||||
const parent = scene.createEntity('Parent');
|
||||
const child1 = scene.createEntity('Child1');
|
||||
const child2 = scene.createEntity('Target');
|
||||
|
||||
hierarchySystem.setParent(child1, parent);
|
||||
hierarchySystem.setParent(child2, parent);
|
||||
|
||||
const found = hierarchySystem.findChild(parent, 'Target');
|
||||
expect(found).toBe(child2);
|
||||
});
|
||||
|
||||
it('should find child recursively', () => {
|
||||
const root = scene.createEntity('Root');
|
||||
const child = scene.createEntity('Child');
|
||||
const grandchild = scene.createEntity('Target');
|
||||
|
||||
hierarchySystem.setParent(child, root);
|
||||
hierarchySystem.setParent(grandchild, child);
|
||||
|
||||
const found = hierarchySystem.findChild(root, 'Target', true);
|
||||
expect(found).toBe(grandchild);
|
||||
|
||||
const notFound = hierarchySystem.findChild(root, 'Target', false);
|
||||
expect(notFound).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('forEachChild', () => {
|
||||
it('should iterate over children', () => {
|
||||
const parent = scene.createEntity('Parent');
|
||||
const child1 = scene.createEntity('Child1');
|
||||
const child2 = scene.createEntity('Child2');
|
||||
|
||||
hierarchySystem.setParent(child1, parent);
|
||||
hierarchySystem.setParent(child2, parent);
|
||||
|
||||
const visited: Entity[] = [];
|
||||
hierarchySystem.forEachChild(parent, (child) => {
|
||||
visited.push(child);
|
||||
});
|
||||
|
||||
expect(visited).toContain(child1);
|
||||
expect(visited).toContain(child2);
|
||||
expect(visited.length).toBe(2);
|
||||
});
|
||||
|
||||
it('should iterate recursively', () => {
|
||||
const root = scene.createEntity('Root');
|
||||
const child = scene.createEntity('Child');
|
||||
const grandchild = scene.createEntity('Grandchild');
|
||||
|
||||
hierarchySystem.setParent(child, root);
|
||||
hierarchySystem.setParent(grandchild, child);
|
||||
|
||||
const visited: Entity[] = [];
|
||||
hierarchySystem.forEachChild(root, (entity) => {
|
||||
visited.push(entity);
|
||||
}, true);
|
||||
|
||||
expect(visited).toContain(child);
|
||||
expect(visited).toContain(grandchild);
|
||||
expect(visited.length).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getRootEntities', () => {
|
||||
it('should return all root entities', () => {
|
||||
const root1 = scene.createEntity('Root1');
|
||||
const root2 = scene.createEntity('Root2');
|
||||
const child = scene.createEntity('Child');
|
||||
|
||||
root1.addComponent(new HierarchyComponent());
|
||||
root2.addComponent(new HierarchyComponent());
|
||||
hierarchySystem.setParent(child, root1);
|
||||
|
||||
const roots = hierarchySystem.getRootEntities();
|
||||
expect(roots).toContain(root1);
|
||||
expect(roots).toContain(root2);
|
||||
expect(roots).not.toContain(child);
|
||||
});
|
||||
});
|
||||
|
||||
describe('activeInHierarchy', () => {
|
||||
it('should be inactive if parent is inactive', () => {
|
||||
const parent = scene.createEntity('Parent');
|
||||
const child = scene.createEntity('Child');
|
||||
|
||||
hierarchySystem.setParent(child, parent);
|
||||
|
||||
expect(hierarchySystem.isActiveInHierarchy(child)).toBe(true);
|
||||
|
||||
parent.active = false;
|
||||
// Mark cache dirty to recalculate
|
||||
const childHierarchy = child.getComponent(HierarchyComponent)!;
|
||||
childHierarchy.bCacheDirty = true;
|
||||
|
||||
expect(hierarchySystem.isActiveInHierarchy(child)).toBe(false);
|
||||
});
|
||||
|
||||
it('should be inactive if self is inactive', () => {
|
||||
const parent = scene.createEntity('Parent');
|
||||
const child = scene.createEntity('Child');
|
||||
|
||||
hierarchySystem.setParent(child, parent);
|
||||
child.active = false;
|
||||
|
||||
expect(hierarchySystem.isActiveInHierarchy(child)).toBe(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('HierarchyComponent', () => {
|
||||
it('should have correct default values', () => {
|
||||
const component = new HierarchyComponent();
|
||||
|
||||
expect(component.parentId).toBeNull();
|
||||
expect(component.childIds).toEqual([]);
|
||||
expect(component.depth).toBe(0);
|
||||
expect(component.bActiveInHierarchy).toBe(true);
|
||||
expect(component.bCacheDirty).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('HierarchySystem - Extended Tests', () => {
|
||||
let scene: Scene;
|
||||
let hierarchySystem: HierarchySystem;
|
||||
|
||||
beforeEach(() => {
|
||||
scene = new Scene();
|
||||
scene.initialize();
|
||||
hierarchySystem = new HierarchySystem();
|
||||
scene.addSystem(hierarchySystem);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
scene.end();
|
||||
});
|
||||
|
||||
describe('findChildrenByTag', () => {
|
||||
it('should find children by tag', () => {
|
||||
const parent = scene.createEntity('Parent');
|
||||
const child1 = scene.createEntity('Child1');
|
||||
const child2 = scene.createEntity('Child2');
|
||||
const child3 = scene.createEntity('Child3');
|
||||
|
||||
child1.tag = 0x01;
|
||||
child2.tag = 0x02;
|
||||
child3.tag = 0x01;
|
||||
|
||||
hierarchySystem.setParent(child1, parent);
|
||||
hierarchySystem.setParent(child2, parent);
|
||||
hierarchySystem.setParent(child3, parent);
|
||||
|
||||
const found = hierarchySystem.findChildrenByTag(parent, 0x01);
|
||||
expect(found.length).toBe(2);
|
||||
expect(found).toContain(child1);
|
||||
expect(found).toContain(child3);
|
||||
});
|
||||
|
||||
it('should find children by tag recursively', () => {
|
||||
const root = scene.createEntity('Root');
|
||||
const child = scene.createEntity('Child');
|
||||
const grandchild = scene.createEntity('Grandchild');
|
||||
|
||||
child.tag = 0x01;
|
||||
grandchild.tag = 0x01;
|
||||
|
||||
hierarchySystem.setParent(child, root);
|
||||
hierarchySystem.setParent(grandchild, child);
|
||||
|
||||
const foundNonRecursive = hierarchySystem.findChildrenByTag(root, 0x01, false);
|
||||
expect(foundNonRecursive.length).toBe(1);
|
||||
expect(foundNonRecursive[0]).toBe(child);
|
||||
|
||||
const foundRecursive = hierarchySystem.findChildrenByTag(root, 0x01, true);
|
||||
expect(foundRecursive.length).toBe(2);
|
||||
expect(foundRecursive).toContain(child);
|
||||
expect(foundRecursive).toContain(grandchild);
|
||||
});
|
||||
|
||||
it('should return empty array when no children match tag', () => {
|
||||
const parent = scene.createEntity('Parent');
|
||||
const child = scene.createEntity('Child');
|
||||
child.tag = 0x01;
|
||||
|
||||
hierarchySystem.setParent(child, parent);
|
||||
|
||||
const found = hierarchySystem.findChildrenByTag(parent, 0x02);
|
||||
expect(found).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('flattenHierarchy', () => {
|
||||
it('should flatten hierarchy with expanded nodes', () => {
|
||||
const root = scene.createEntity('Root');
|
||||
const child1 = scene.createEntity('Child1');
|
||||
const child2 = scene.createEntity('Child2');
|
||||
const grandchild = scene.createEntity('Grandchild');
|
||||
|
||||
root.addComponent(new HierarchyComponent());
|
||||
hierarchySystem.setParent(child1, root);
|
||||
hierarchySystem.setParent(child2, root);
|
||||
hierarchySystem.setParent(grandchild, child1);
|
||||
|
||||
const expandedIds = new Set([root.id, child1.id]);
|
||||
const flattened = hierarchySystem.flattenHierarchy(expandedIds);
|
||||
|
||||
expect(flattened.length).toBe(4);
|
||||
expect(flattened[0].entity).toBe(root);
|
||||
expect(flattened[0].depth).toBe(0);
|
||||
expect(flattened[0].bHasChildren).toBe(true);
|
||||
expect(flattened[0].bIsExpanded).toBe(true);
|
||||
});
|
||||
|
||||
it('should not include children of collapsed nodes', () => {
|
||||
const root = scene.createEntity('Root');
|
||||
const child = scene.createEntity('Child');
|
||||
const grandchild = scene.createEntity('Grandchild');
|
||||
|
||||
root.addComponent(new HierarchyComponent());
|
||||
hierarchySystem.setParent(child, root);
|
||||
hierarchySystem.setParent(grandchild, child);
|
||||
|
||||
// Root is expanded, but child is collapsed
|
||||
const expandedIds = new Set([root.id]);
|
||||
const flattened = hierarchySystem.flattenHierarchy(expandedIds);
|
||||
|
||||
expect(flattened.length).toBe(2);
|
||||
expect(flattened[0].entity).toBe(root);
|
||||
expect(flattened[1].entity).toBe(child);
|
||||
expect(flattened[1].bHasChildren).toBe(true);
|
||||
expect(flattened[1].bIsExpanded).toBe(false);
|
||||
});
|
||||
|
||||
it('should return empty array when no root entities', () => {
|
||||
const flattened = hierarchySystem.flattenHierarchy(new Set());
|
||||
expect(flattened).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateOrder', () => {
|
||||
it('should have negative update order for early processing', () => {
|
||||
expect(hierarchySystem.updateOrder).toBe(-1000);
|
||||
});
|
||||
});
|
||||
|
||||
describe('process - cache update', () => {
|
||||
it('should update dirty caches during process', () => {
|
||||
const parent = scene.createEntity('Parent');
|
||||
const child = scene.createEntity('Child');
|
||||
|
||||
hierarchySystem.setParent(child, parent);
|
||||
|
||||
// Cache should be dirty after setParent
|
||||
const childHierarchy = child.getComponent(HierarchyComponent)!;
|
||||
expect(childHierarchy.bCacheDirty).toBe(true);
|
||||
|
||||
// Update scene to process
|
||||
scene.update();
|
||||
|
||||
// Cache should be clean after process
|
||||
expect(childHierarchy.bCacheDirty).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('insertChildAt edge cases', () => {
|
||||
it('should handle circular reference prevention', () => {
|
||||
const parent = scene.createEntity('Parent');
|
||||
const child = scene.createEntity('Child');
|
||||
const grandchild = scene.createEntity('Grandchild');
|
||||
|
||||
hierarchySystem.setParent(child, parent);
|
||||
hierarchySystem.setParent(grandchild, child);
|
||||
|
||||
expect(() => {
|
||||
hierarchySystem.insertChildAt(grandchild, parent, 0);
|
||||
}).toThrow('Cannot set parent: would create circular reference');
|
||||
});
|
||||
|
||||
it('should move child within same parent to different position', () => {
|
||||
const parent = scene.createEntity('Parent');
|
||||
const child1 = scene.createEntity('Child1');
|
||||
const child2 = scene.createEntity('Child2');
|
||||
const child3 = scene.createEntity('Child3');
|
||||
|
||||
hierarchySystem.setParent(child1, parent);
|
||||
hierarchySystem.setParent(child2, parent);
|
||||
hierarchySystem.setParent(child3, parent);
|
||||
|
||||
// Move child3 to position 0
|
||||
hierarchySystem.insertChildAt(parent, child3, 0);
|
||||
|
||||
const children = hierarchySystem.getChildren(parent);
|
||||
expect(children[0]).toBe(child3);
|
||||
expect(children[1]).toBe(child1);
|
||||
expect(children[2]).toBe(child2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('removeChild edge cases', () => {
|
||||
it('should return false when parent has no HierarchyComponent', () => {
|
||||
const parent = scene.createEntity('Parent');
|
||||
const child = scene.createEntity('Child');
|
||||
|
||||
const result = hierarchySystem.removeChild(parent, child);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
it('should return false when child has no HierarchyComponent', () => {
|
||||
const parent = scene.createEntity('Parent');
|
||||
const child = scene.createEntity('Child');
|
||||
|
||||
parent.addComponent(new HierarchyComponent());
|
||||
|
||||
const result = hierarchySystem.removeChild(parent, child);
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('removeAllChildren edge cases', () => {
|
||||
it('should handle entity with no HierarchyComponent', () => {
|
||||
const parent = scene.createEntity('Parent');
|
||||
|
||||
expect(() => {
|
||||
hierarchySystem.removeAllChildren(parent);
|
||||
}).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('getChildren edge cases', () => {
|
||||
it('should return empty array when entity has no HierarchyComponent', () => {
|
||||
const entity = scene.createEntity('Entity');
|
||||
const children = hierarchySystem.getChildren(entity);
|
||||
expect(children).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getChildCount edge cases', () => {
|
||||
it('should return 0 when entity has no HierarchyComponent', () => {
|
||||
const entity = scene.createEntity('Entity');
|
||||
expect(hierarchySystem.getChildCount(entity)).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getDepth edge cases', () => {
|
||||
it('should return 0 when entity has no HierarchyComponent', () => {
|
||||
const entity = scene.createEntity('Entity');
|
||||
expect(hierarchySystem.getDepth(entity)).toBe(0);
|
||||
});
|
||||
|
||||
it('should use cached depth when cache is valid', () => {
|
||||
const parent = scene.createEntity('Parent');
|
||||
const child = scene.createEntity('Child');
|
||||
|
||||
parent.addComponent(new HierarchyComponent());
|
||||
hierarchySystem.setParent(child, parent);
|
||||
|
||||
// First call computes depth
|
||||
const depth1 = hierarchySystem.getDepth(child);
|
||||
expect(depth1).toBe(1);
|
||||
|
||||
// Mark cache as valid
|
||||
const childHierarchy = child.getComponent(HierarchyComponent)!;
|
||||
childHierarchy.bCacheDirty = false;
|
||||
|
||||
// Second call should use cache
|
||||
const depth2 = hierarchySystem.getDepth(child);
|
||||
expect(depth2).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isActiveInHierarchy edge cases', () => {
|
||||
it('should return entity.active when entity has no HierarchyComponent', () => {
|
||||
const entity = scene.createEntity('Entity');
|
||||
entity.active = true;
|
||||
expect(hierarchySystem.isActiveInHierarchy(entity)).toBe(true);
|
||||
|
||||
entity.active = false;
|
||||
expect(hierarchySystem.isActiveInHierarchy(entity)).toBe(false);
|
||||
});
|
||||
|
||||
it('should use cached value when cache is valid', () => {
|
||||
const parent = scene.createEntity('Parent');
|
||||
const child = scene.createEntity('Child');
|
||||
|
||||
hierarchySystem.setParent(child, parent);
|
||||
|
||||
// First call computes activeInHierarchy
|
||||
const active1 = hierarchySystem.isActiveInHierarchy(child);
|
||||
expect(active1).toBe(true);
|
||||
|
||||
// Mark cache as valid
|
||||
const childHierarchy = child.getComponent(HierarchyComponent)!;
|
||||
childHierarchy.bCacheDirty = false;
|
||||
|
||||
// Second call should use cache
|
||||
const active2 = hierarchySystem.isActiveInHierarchy(child);
|
||||
expect(active2).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('dispose', () => {
|
||||
it('should not throw when disposing', () => {
|
||||
expect(() => {
|
||||
hierarchySystem.dispose();
|
||||
}).not.toThrow();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -629,4 +629,201 @@ describe('Scene - 场景管理系统测试', () => {
|
||||
scene2.end();
|
||||
});
|
||||
});
|
||||
|
||||
describe('扩展测试 - 补齐覆盖率', () => {
|
||||
describe('实体标签查找', () => {
|
||||
test('findEntitiesByTag 应该返回具有指定标签的实体', () => {
|
||||
const entity1 = scene.createEntity('Entity1');
|
||||
entity1.tag = 0x01;
|
||||
|
||||
const entity2 = scene.createEntity('Entity2');
|
||||
entity2.tag = 0x02;
|
||||
|
||||
const entity3 = scene.createEntity('Entity3');
|
||||
entity3.tag = 0x01;
|
||||
|
||||
const found = scene.findEntitiesByTag(0x01);
|
||||
|
||||
expect(found.length).toBe(2);
|
||||
expect(found).toContain(entity1);
|
||||
expect(found).toContain(entity3);
|
||||
});
|
||||
|
||||
test('findEntitiesByTag 应该在没有匹配时返回空数组', () => {
|
||||
scene.createEntity('Entity1');
|
||||
|
||||
const found = scene.findEntitiesByTag(0xFF);
|
||||
|
||||
expect(found).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('批量实体操作', () => {
|
||||
test('destroyEntities 应该批量销毁实体', () => {
|
||||
const entities = scene.createEntities(5, 'Entity');
|
||||
expect(scene.entities.count).toBe(5);
|
||||
|
||||
const toDestroy = entities.slice(0, 3);
|
||||
scene.destroyEntities(toDestroy);
|
||||
|
||||
expect(scene.entities.count).toBe(2);
|
||||
});
|
||||
|
||||
test('destroyEntities 应该处理空数组', () => {
|
||||
scene.createEntities(3, 'Entity');
|
||||
|
||||
expect(() => {
|
||||
scene.destroyEntities([]);
|
||||
}).not.toThrow();
|
||||
|
||||
expect(scene.entities.count).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe('查询方法', () => {
|
||||
test('queryAny 应该返回具有任意一个组件的实体', () => {
|
||||
const entity1 = scene.createEntity('Entity1');
|
||||
entity1.addComponent(new PositionComponent());
|
||||
|
||||
const entity2 = scene.createEntity('Entity2');
|
||||
entity2.addComponent(new VelocityComponent());
|
||||
|
||||
const entity3 = scene.createEntity('Entity3');
|
||||
entity3.addComponent(new HealthComponent());
|
||||
|
||||
const result = scene.queryAny(PositionComponent, VelocityComponent);
|
||||
|
||||
expect(result.entities.length).toBe(2);
|
||||
});
|
||||
|
||||
test('queryNone 应该返回不包含指定组件的实体', () => {
|
||||
const entity1 = scene.createEntity('Entity1');
|
||||
entity1.addComponent(new PositionComponent());
|
||||
|
||||
const entity2 = scene.createEntity('Entity2');
|
||||
entity2.addComponent(new VelocityComponent());
|
||||
|
||||
const entity3 = scene.createEntity('Entity3');
|
||||
|
||||
const result = scene.queryNone(PositionComponent);
|
||||
|
||||
expect(result.entities.length).toBe(2);
|
||||
expect(result.entities).toContain(entity2);
|
||||
expect(result.entities).toContain(entity3);
|
||||
});
|
||||
|
||||
test('query 应该创建类型安全的查询构建器', () => {
|
||||
const builder = scene.query();
|
||||
expect(builder).toBeDefined();
|
||||
|
||||
const matcher = builder.withAll(PositionComponent).buildMatcher();
|
||||
expect(matcher).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('服务容器', () => {
|
||||
test('scene.services 应该返回服务容器', () => {
|
||||
expect(scene.services).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('系统错误处理', () => {
|
||||
test('频繁出错的系统应该被自动禁用', () => {
|
||||
const consoleSpy = jest.spyOn(console, 'error').mockImplementation(() => {});
|
||||
|
||||
class ErrorProneSystem extends EntitySystem {
|
||||
constructor() {
|
||||
super(Matcher.empty().all(PositionComponent));
|
||||
}
|
||||
|
||||
protected override process(): void {
|
||||
throw new Error('Intentional error');
|
||||
}
|
||||
}
|
||||
|
||||
const system = new ErrorProneSystem();
|
||||
scene.addEntityProcessor(system);
|
||||
|
||||
const entity = scene.createEntity('TestEntity');
|
||||
entity.addComponent(new PositionComponent(0, 0));
|
||||
|
||||
// 多次更新以触发错误阈值
|
||||
for (let i = 0; i < 15; i++) {
|
||||
scene.update();
|
||||
}
|
||||
|
||||
// 系统应该被禁用
|
||||
expect(system.enabled).toBe(false);
|
||||
|
||||
consoleSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
|
||||
describe('已废弃方法', () => {
|
||||
test('getEntityByName 应该作为 findEntity 的别名工作', () => {
|
||||
const entity = scene.createEntity('TestEntity');
|
||||
|
||||
const found = scene.getEntityByName('TestEntity');
|
||||
|
||||
expect(found).toBe(entity);
|
||||
});
|
||||
|
||||
test('getEntitiesByTag 应该作为 findEntitiesByTag 的别名工作', () => {
|
||||
const entity = scene.createEntity('Entity');
|
||||
entity.tag = 0x10;
|
||||
|
||||
const found = scene.getEntitiesByTag(0x10);
|
||||
|
||||
expect(found.length).toBe(1);
|
||||
expect(found[0]).toBe(entity);
|
||||
});
|
||||
});
|
||||
|
||||
describe('系统管理扩展', () => {
|
||||
test('getSystem 应该返回指定类型的系统', () => {
|
||||
const movementSystem = new MovementSystem();
|
||||
scene.addEntityProcessor(movementSystem);
|
||||
|
||||
const found = scene.getSystem(MovementSystem);
|
||||
|
||||
expect(found).toBe(movementSystem);
|
||||
});
|
||||
|
||||
test('getSystem 应该在系统不存在时返回 null', () => {
|
||||
const found = scene.getSystem(MovementSystem);
|
||||
|
||||
expect(found).toBeNull();
|
||||
});
|
||||
|
||||
test('markSystemsOrderDirty 应该标记系统顺序为脏', () => {
|
||||
const system1 = new MovementSystem();
|
||||
const system2 = new RenderSystem();
|
||||
|
||||
scene.addEntityProcessor(system1);
|
||||
scene.addEntityProcessor(system2);
|
||||
|
||||
// 访问 systems 以清除脏标记
|
||||
const _ = scene.systems;
|
||||
|
||||
// 标记为脏
|
||||
scene.markSystemsOrderDirty();
|
||||
|
||||
// 再次访问应该重新构建缓存
|
||||
const systems = scene.systems;
|
||||
expect(systems).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('延迟缓存清理', () => {
|
||||
test('addEntity 应该支持延迟缓存清理', () => {
|
||||
scene.createEntity('Entity1');
|
||||
const entity2 = new Entity('Entity2', scene.identifierPool.checkOut());
|
||||
|
||||
// 延迟缓存清理
|
||||
scene.addEntity(entity2, true);
|
||||
|
||||
expect(scene.entities.count).toBe(2);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
495
packages/core/tests/ECS/Serialization/EntitySerializer.test.ts
Normal file
495
packages/core/tests/ECS/Serialization/EntitySerializer.test.ts
Normal file
@@ -0,0 +1,495 @@
|
||||
import { EntitySerializer, SerializedEntity } from '../../../src/ECS/Serialization/EntitySerializer';
|
||||
import { Scene } from '../../../src/ECS/Scene';
|
||||
import { Entity } from '../../../src/ECS/Entity';
|
||||
import { Component } from '../../../src/ECS/Component';
|
||||
import { HierarchySystem } from '../../../src/ECS/Systems/HierarchySystem';
|
||||
import { HierarchyComponent } from '../../../src/ECS/Components/HierarchyComponent';
|
||||
import { ECSComponent } from '../../../src/ECS/Decorators';
|
||||
import { ComponentRegistry, ComponentType } from '../../../src/ECS/Core/ComponentStorage';
|
||||
import { Serializable, Serialize } from '../../../src/ECS/Serialization';
|
||||
|
||||
@ECSComponent('EntitySerTest_Position')
|
||||
@Serializable({ version: 1 })
|
||||
class PositionComponent extends Component {
|
||||
@Serialize()
|
||||
public x: number = 0;
|
||||
|
||||
@Serialize()
|
||||
public y: number = 0;
|
||||
|
||||
constructor(x: number = 0, y: number = 0) {
|
||||
super();
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
}
|
||||
}
|
||||
|
||||
@ECSComponent('EntitySerTest_Velocity')
|
||||
@Serializable({ version: 1 })
|
||||
class VelocityComponent extends Component {
|
||||
@Serialize()
|
||||
public vx: number = 0;
|
||||
|
||||
@Serialize()
|
||||
public vy: number = 0;
|
||||
}
|
||||
|
||||
describe('EntitySerializer', () => {
|
||||
let scene: Scene;
|
||||
let hierarchySystem: HierarchySystem;
|
||||
let componentRegistry: Map<string, ComponentType>;
|
||||
|
||||
beforeEach(() => {
|
||||
ComponentRegistry.reset();
|
||||
ComponentRegistry.register(PositionComponent);
|
||||
ComponentRegistry.register(VelocityComponent);
|
||||
ComponentRegistry.register(HierarchyComponent);
|
||||
|
||||
scene = new Scene({ name: 'EntitySerializerTestScene' });
|
||||
hierarchySystem = new HierarchySystem();
|
||||
scene.addSystem(hierarchySystem);
|
||||
|
||||
componentRegistry = ComponentRegistry.getAllComponentNames() as Map<string, ComponentType>;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
scene.end();
|
||||
});
|
||||
|
||||
describe('serialize', () => {
|
||||
test('should serialize basic entity properties', () => {
|
||||
const entity = scene.createEntity('TestEntity');
|
||||
entity.tag = 42;
|
||||
entity.active = false;
|
||||
entity.enabled = false;
|
||||
entity.updateOrder = 10;
|
||||
|
||||
const serialized = EntitySerializer.serialize(entity, false);
|
||||
|
||||
expect(serialized.id).toBe(entity.id);
|
||||
expect(serialized.name).toBe('TestEntity');
|
||||
expect(serialized.tag).toBe(42);
|
||||
expect(serialized.active).toBe(false);
|
||||
expect(serialized.enabled).toBe(false);
|
||||
expect(serialized.updateOrder).toBe(10);
|
||||
});
|
||||
|
||||
test('should serialize entity with components', () => {
|
||||
const entity = scene.createEntity('Entity');
|
||||
entity.addComponent(new PositionComponent(100, 200));
|
||||
entity.addComponent(new VelocityComponent());
|
||||
|
||||
const serialized = EntitySerializer.serialize(entity, false);
|
||||
|
||||
expect(serialized.components.length).toBe(2);
|
||||
});
|
||||
|
||||
test('should serialize entity without children when includeChildren is false', () => {
|
||||
const parent = scene.createEntity('Parent');
|
||||
const child = scene.createEntity('Child');
|
||||
hierarchySystem.setParent(child, parent);
|
||||
|
||||
const serialized = EntitySerializer.serialize(parent, false, hierarchySystem);
|
||||
|
||||
expect(serialized.children).toEqual([]);
|
||||
});
|
||||
|
||||
test('should serialize entity with children when includeChildren is true', () => {
|
||||
const parent = scene.createEntity('Parent');
|
||||
const child1 = scene.createEntity('Child1');
|
||||
const child2 = scene.createEntity('Child2');
|
||||
|
||||
hierarchySystem.setParent(child1, parent);
|
||||
hierarchySystem.setParent(child2, parent);
|
||||
|
||||
const serialized = EntitySerializer.serialize(parent, true, hierarchySystem);
|
||||
|
||||
expect(serialized.children.length).toBe(2);
|
||||
expect(serialized.children.some(c => c.name === 'Child1')).toBe(true);
|
||||
expect(serialized.children.some(c => c.name === 'Child2')).toBe(true);
|
||||
});
|
||||
|
||||
test('should serialize nested hierarchy', () => {
|
||||
const root = scene.createEntity('Root');
|
||||
const child = scene.createEntity('Child');
|
||||
const grandchild = scene.createEntity('Grandchild');
|
||||
|
||||
hierarchySystem.setParent(child, root);
|
||||
hierarchySystem.setParent(grandchild, child);
|
||||
|
||||
const serialized = EntitySerializer.serialize(root, true, hierarchySystem);
|
||||
|
||||
expect(serialized.children.length).toBe(1);
|
||||
expect(serialized.children[0].name).toBe('Child');
|
||||
expect(serialized.children[0].children.length).toBe(1);
|
||||
expect(serialized.children[0].children[0].name).toBe('Grandchild');
|
||||
});
|
||||
|
||||
test('should include parentId in serialized data', () => {
|
||||
const parent = scene.createEntity('Parent');
|
||||
const child = scene.createEntity('Child');
|
||||
hierarchySystem.setParent(child, parent);
|
||||
|
||||
const serializedChild = EntitySerializer.serialize(child, false, hierarchySystem);
|
||||
|
||||
expect(serializedChild.parentId).toBe(parent.id);
|
||||
});
|
||||
});
|
||||
|
||||
describe('deserialize', () => {
|
||||
test('should deserialize basic entity properties', () => {
|
||||
const serialized: SerializedEntity = {
|
||||
id: 999,
|
||||
name: 'DeserializedEntity',
|
||||
tag: 77,
|
||||
active: false,
|
||||
enabled: false,
|
||||
updateOrder: 5,
|
||||
components: [],
|
||||
children: []
|
||||
};
|
||||
|
||||
let nextId = 1;
|
||||
const entity = EntitySerializer.deserialize(
|
||||
serialized,
|
||||
componentRegistry,
|
||||
() => nextId++,
|
||||
false
|
||||
);
|
||||
|
||||
expect(entity.name).toBe('DeserializedEntity');
|
||||
expect(entity.tag).toBe(77);
|
||||
expect(entity.active).toBe(false);
|
||||
expect(entity.enabled).toBe(false);
|
||||
expect(entity.updateOrder).toBe(5);
|
||||
});
|
||||
|
||||
test('should preserve IDs when preserveIds is true', () => {
|
||||
const serialized: SerializedEntity = {
|
||||
id: 999,
|
||||
name: 'Entity',
|
||||
tag: 0,
|
||||
active: true,
|
||||
enabled: true,
|
||||
updateOrder: 0,
|
||||
components: [],
|
||||
children: []
|
||||
};
|
||||
|
||||
const entity = EntitySerializer.deserialize(
|
||||
serialized,
|
||||
componentRegistry,
|
||||
() => 1,
|
||||
true
|
||||
);
|
||||
|
||||
expect(entity.id).toBe(999);
|
||||
});
|
||||
|
||||
test('should generate new IDs when preserveIds is false', () => {
|
||||
const serialized: SerializedEntity = {
|
||||
id: 999,
|
||||
name: 'Entity',
|
||||
tag: 0,
|
||||
active: true,
|
||||
enabled: true,
|
||||
updateOrder: 0,
|
||||
components: [],
|
||||
children: []
|
||||
};
|
||||
|
||||
let nextId = 100;
|
||||
const entity = EntitySerializer.deserialize(
|
||||
serialized,
|
||||
componentRegistry,
|
||||
() => nextId++,
|
||||
false
|
||||
);
|
||||
|
||||
expect(entity.id).toBe(100);
|
||||
});
|
||||
|
||||
test('should deserialize components', () => {
|
||||
const serialized: SerializedEntity = {
|
||||
id: 1,
|
||||
name: 'Entity',
|
||||
tag: 0,
|
||||
active: true,
|
||||
enabled: true,
|
||||
updateOrder: 0,
|
||||
components: [
|
||||
{ type: 'EntitySerTest_Position', version: 1, data: { x: 100, y: 200 } }
|
||||
],
|
||||
children: []
|
||||
};
|
||||
|
||||
const entity = EntitySerializer.deserialize(
|
||||
serialized,
|
||||
componentRegistry,
|
||||
() => 1,
|
||||
true,
|
||||
scene
|
||||
);
|
||||
|
||||
expect(entity.hasComponent(PositionComponent)).toBe(true);
|
||||
const pos = entity.getComponent(PositionComponent)!;
|
||||
expect(pos.x).toBe(100);
|
||||
expect(pos.y).toBe(200);
|
||||
});
|
||||
|
||||
test('should deserialize children with hierarchy relationships', () => {
|
||||
const serialized: SerializedEntity = {
|
||||
id: 1,
|
||||
name: 'Parent',
|
||||
tag: 0,
|
||||
active: true,
|
||||
enabled: true,
|
||||
updateOrder: 0,
|
||||
components: [],
|
||||
children: [
|
||||
{
|
||||
id: 2,
|
||||
name: 'Child',
|
||||
tag: 0,
|
||||
active: true,
|
||||
enabled: true,
|
||||
updateOrder: 0,
|
||||
components: [],
|
||||
children: []
|
||||
}
|
||||
]
|
||||
};
|
||||
|
||||
let nextId = 10;
|
||||
const allEntities = new Map<number, Entity>();
|
||||
const entity = EntitySerializer.deserialize(
|
||||
serialized,
|
||||
componentRegistry,
|
||||
() => nextId++,
|
||||
false,
|
||||
scene,
|
||||
hierarchySystem,
|
||||
allEntities
|
||||
);
|
||||
|
||||
expect(allEntities.size).toBe(2);
|
||||
|
||||
// Add deserialized entities to scene so hierarchySystem can find them
|
||||
for (const [, e] of allEntities) {
|
||||
scene.addEntity(e);
|
||||
}
|
||||
|
||||
const children = hierarchySystem.getChildren(entity);
|
||||
expect(children.length).toBe(1);
|
||||
expect(children[0].name).toBe('Child');
|
||||
});
|
||||
});
|
||||
|
||||
describe('serializeEntities', () => {
|
||||
test('should serialize multiple entities', () => {
|
||||
const entity1 = scene.createEntity('Entity1');
|
||||
const entity2 = scene.createEntity('Entity2');
|
||||
|
||||
const serialized = EntitySerializer.serializeEntities([entity1, entity2], false);
|
||||
|
||||
expect(serialized.length).toBe(2);
|
||||
});
|
||||
|
||||
test('should only serialize root entities when includeChildren is true', () => {
|
||||
const root = scene.createEntity('Root');
|
||||
const child = scene.createEntity('Child');
|
||||
hierarchySystem.setParent(child, root);
|
||||
|
||||
const serialized = EntitySerializer.serializeEntities(
|
||||
[root, child],
|
||||
true,
|
||||
hierarchySystem
|
||||
);
|
||||
|
||||
// Should only have root (child is serialized inside root)
|
||||
expect(serialized.length).toBe(1);
|
||||
expect(serialized[0].name).toBe('Root');
|
||||
expect(serialized[0].children.length).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('deserializeEntities', () => {
|
||||
test('should deserialize multiple entities', () => {
|
||||
const serializedEntities: SerializedEntity[] = [
|
||||
{
|
||||
id: 1,
|
||||
name: 'Entity1',
|
||||
tag: 0,
|
||||
active: true,
|
||||
enabled: true,
|
||||
updateOrder: 0,
|
||||
components: [],
|
||||
children: []
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
name: 'Entity2',
|
||||
tag: 0,
|
||||
active: true,
|
||||
enabled: true,
|
||||
updateOrder: 0,
|
||||
components: [],
|
||||
children: []
|
||||
}
|
||||
];
|
||||
|
||||
let nextId = 100;
|
||||
const { rootEntities, allEntities } = EntitySerializer.deserializeEntities(
|
||||
serializedEntities,
|
||||
componentRegistry,
|
||||
() => nextId++,
|
||||
false,
|
||||
scene
|
||||
);
|
||||
|
||||
expect(rootEntities.length).toBe(2);
|
||||
expect(allEntities.size).toBe(2);
|
||||
});
|
||||
|
||||
test('should deserialize entities with nested hierarchy', () => {
|
||||
const serializedEntities: SerializedEntity[] = [
|
||||
{
|
||||
id: 1,
|
||||
name: 'Root',
|
||||
tag: 0,
|
||||
active: true,
|
||||
enabled: true,
|
||||
updateOrder: 0,
|
||||
components: [],
|
||||
children: [
|
||||
{
|
||||
id: 2,
|
||||
name: 'Child',
|
||||
tag: 0,
|
||||
active: true,
|
||||
enabled: true,
|
||||
updateOrder: 0,
|
||||
components: [],
|
||||
children: [
|
||||
{
|
||||
id: 3,
|
||||
name: 'Grandchild',
|
||||
tag: 0,
|
||||
active: true,
|
||||
enabled: true,
|
||||
updateOrder: 0,
|
||||
components: [],
|
||||
children: []
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
];
|
||||
|
||||
let nextId = 10;
|
||||
const { rootEntities, allEntities } = EntitySerializer.deserializeEntities(
|
||||
serializedEntities,
|
||||
componentRegistry,
|
||||
() => nextId++,
|
||||
false,
|
||||
scene,
|
||||
hierarchySystem
|
||||
);
|
||||
|
||||
expect(rootEntities.length).toBe(1);
|
||||
expect(allEntities.size).toBe(3);
|
||||
});
|
||||
});
|
||||
|
||||
describe('clone', () => {
|
||||
test('should clone entity with new ID', () => {
|
||||
const original = scene.createEntity('Original');
|
||||
original.tag = 99;
|
||||
original.addComponent(new PositionComponent(50, 100));
|
||||
|
||||
// Use serialize + deserialize with scene for proper cloning
|
||||
const serialized = EntitySerializer.serialize(original, false);
|
||||
let nextId = 1000;
|
||||
const cloned = EntitySerializer.deserialize(
|
||||
serialized,
|
||||
componentRegistry,
|
||||
() => nextId++,
|
||||
false,
|
||||
scene // Pass scene so components can be added
|
||||
);
|
||||
|
||||
expect(cloned.id).not.toBe(original.id);
|
||||
expect(cloned.name).toBe('Original');
|
||||
expect(cloned.tag).toBe(99);
|
||||
expect(cloned.hasComponent(PositionComponent)).toBe(true);
|
||||
|
||||
const clonedPos = cloned.getComponent(PositionComponent)!;
|
||||
expect(clonedPos.x).toBe(50);
|
||||
expect(clonedPos.y).toBe(100);
|
||||
});
|
||||
|
||||
test('should clone entity basic properties without components', () => {
|
||||
// Test the clone method directly with entity that has no components
|
||||
const original = scene.createEntity('Original');
|
||||
original.tag = 99;
|
||||
original.active = false;
|
||||
original.enabled = false;
|
||||
original.updateOrder = 5;
|
||||
|
||||
let nextId = 1000;
|
||||
const cloned = EntitySerializer.clone(
|
||||
original,
|
||||
componentRegistry,
|
||||
() => nextId++
|
||||
);
|
||||
|
||||
expect(cloned.id).not.toBe(original.id);
|
||||
expect(cloned.name).toBe('Original');
|
||||
expect(cloned.tag).toBe(99);
|
||||
expect(cloned.active).toBe(false);
|
||||
expect(cloned.enabled).toBe(false);
|
||||
expect(cloned.updateOrder).toBe(5);
|
||||
});
|
||||
|
||||
test('should clone entity with children hierarchy data', () => {
|
||||
const parent = scene.createEntity('Parent');
|
||||
const child = scene.createEntity('Child');
|
||||
hierarchySystem.setParent(child, parent);
|
||||
|
||||
// Serialize with children
|
||||
const serialized = EntitySerializer.serialize(parent, true, hierarchySystem);
|
||||
|
||||
// Verify the serialized data contains children
|
||||
expect(serialized.children.length).toBe(1);
|
||||
expect(serialized.children[0].name).toBe('Child');
|
||||
});
|
||||
});
|
||||
|
||||
describe('edge cases', () => {
|
||||
test('should handle entity with no components', () => {
|
||||
const entity = scene.createEntity('Empty');
|
||||
const serialized = EntitySerializer.serialize(entity, false);
|
||||
|
||||
expect(serialized.components).toEqual([]);
|
||||
});
|
||||
|
||||
test('should handle entity with no hierarchy component', () => {
|
||||
const entity = new Entity('Standalone', 999);
|
||||
const serialized = EntitySerializer.serialize(entity, true);
|
||||
|
||||
expect(serialized.children).toEqual([]);
|
||||
expect(serialized.parentId).toBeUndefined();
|
||||
});
|
||||
|
||||
test('should handle default values in serialization', () => {
|
||||
const entity = scene.createEntity('Default');
|
||||
|
||||
const serialized = EntitySerializer.serialize(entity, false);
|
||||
|
||||
expect(serialized.active).toBe(true);
|
||||
expect(serialized.enabled).toBe(true);
|
||||
expect(serialized.updateOrder).toBe(0);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,117 +0,0 @@
|
||||
/**
|
||||
* 父子实体序列化和反序列化测试
|
||||
*
|
||||
* 测试场景序列化和反序列化时父子实体关系的正确性
|
||||
*/
|
||||
|
||||
import { Scene } from '../../../src';
|
||||
|
||||
describe('父子实体序列化测试', () => {
|
||||
let scene: Scene;
|
||||
|
||||
beforeEach(() => {
|
||||
scene = new Scene({ name: 'TestScene' });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
scene.end();
|
||||
});
|
||||
|
||||
test('应该正确反序列化父子实体层次结构', () => {
|
||||
// 创建父实体
|
||||
const parent = scene.createEntity('parent');
|
||||
parent.tag = 100;
|
||||
|
||||
// 创建2个子实体
|
||||
const child1 = scene.createEntity('child1');
|
||||
child1.tag = 200;
|
||||
parent.addChild(child1);
|
||||
|
||||
const child2 = scene.createEntity('child2');
|
||||
child2.tag = 200;
|
||||
parent.addChild(child2);
|
||||
|
||||
// 创建1个顶层实体(对照组)
|
||||
const topLevel = scene.createEntity('topLevel');
|
||||
topLevel.tag = 200;
|
||||
|
||||
// 验证序列化前的状态
|
||||
expect(scene.querySystem.queryAll().entities.length).toBe(4);
|
||||
expect(scene.findEntitiesByTag(100).length).toBe(1);
|
||||
expect(scene.findEntitiesByTag(200).length).toBe(3);
|
||||
|
||||
// 序列化
|
||||
const serialized = scene.serialize({ format: 'json' });
|
||||
|
||||
// 创建新场景并反序列化
|
||||
const scene2 = new Scene({ name: 'LoadTestScene' });
|
||||
scene2.deserialize(serialized as string, {
|
||||
strategy: 'replace',
|
||||
preserveIds: true,
|
||||
});
|
||||
|
||||
// 验证所有实体都被正确恢复
|
||||
const allEntities = scene2.querySystem.queryAll().entities;
|
||||
expect(allEntities.length).toBe(4);
|
||||
expect(scene2.findEntitiesByTag(100).length).toBe(1);
|
||||
expect(scene2.findEntitiesByTag(200).length).toBe(3);
|
||||
|
||||
// 验证父子关系正确恢复
|
||||
const restoredParent = scene2.findEntity('parent');
|
||||
expect(restoredParent).not.toBeNull();
|
||||
expect(restoredParent!.children.length).toBe(2);
|
||||
|
||||
const restoredChild1 = scene2.findEntity('child1');
|
||||
const restoredChild2 = scene2.findEntity('child2');
|
||||
expect(restoredChild1).not.toBeNull();
|
||||
expect(restoredChild2).not.toBeNull();
|
||||
expect(restoredChild1!.parent).toBe(restoredParent);
|
||||
expect(restoredChild2!.parent).toBe(restoredParent);
|
||||
|
||||
scene2.end();
|
||||
});
|
||||
|
||||
test('应该正确反序列化多层级实体层次结构', () => {
|
||||
// 创建多层级实体结构:grandparent -> parent -> child
|
||||
const grandparent = scene.createEntity('grandparent');
|
||||
grandparent.tag = 1;
|
||||
|
||||
const parent = scene.createEntity('parent');
|
||||
parent.tag = 2;
|
||||
grandparent.addChild(parent);
|
||||
|
||||
const child = scene.createEntity('child');
|
||||
child.tag = 3;
|
||||
parent.addChild(child);
|
||||
|
||||
expect(scene.querySystem.queryAll().entities.length).toBe(3);
|
||||
|
||||
// 序列化
|
||||
const serialized = scene.serialize({ format: 'json' });
|
||||
|
||||
// 创建新场景并反序列化
|
||||
const scene2 = new Scene({ name: 'LoadTestScene' });
|
||||
scene2.deserialize(serialized as string, {
|
||||
strategy: 'replace',
|
||||
preserveIds: true,
|
||||
});
|
||||
|
||||
// 验证多层级结构正确恢复
|
||||
expect(scene2.querySystem.queryAll().entities.length).toBe(3);
|
||||
|
||||
const restoredGrandparent = scene2.findEntity('grandparent');
|
||||
const restoredParent = scene2.findEntity('parent');
|
||||
const restoredChild = scene2.findEntity('child');
|
||||
|
||||
expect(restoredGrandparent).not.toBeNull();
|
||||
expect(restoredParent).not.toBeNull();
|
||||
expect(restoredChild).not.toBeNull();
|
||||
|
||||
expect(restoredParent!.parent).toBe(restoredGrandparent);
|
||||
expect(restoredChild!.parent).toBe(restoredParent);
|
||||
expect(restoredGrandparent!.children.length).toBe(1);
|
||||
expect(restoredParent!.children.length).toBe(1);
|
||||
|
||||
scene2.end();
|
||||
});
|
||||
});
|
||||
439
packages/core/tests/ECS/Serialization/SceneSerializer.test.ts
Normal file
439
packages/core/tests/ECS/Serialization/SceneSerializer.test.ts
Normal file
@@ -0,0 +1,439 @@
|
||||
import { SceneSerializer } from '../../../src/ECS/Serialization/SceneSerializer';
|
||||
import { Scene } from '../../../src/ECS/Scene';
|
||||
import { Component } from '../../../src/ECS/Component';
|
||||
import { HierarchySystem } from '../../../src/ECS/Systems/HierarchySystem';
|
||||
import { ECSComponent } from '../../../src/ECS/Decorators';
|
||||
import { ComponentRegistry, ComponentType } from '../../../src/ECS/Core/ComponentStorage';
|
||||
import { Serializable, Serialize } from '../../../src/ECS/Serialization';
|
||||
|
||||
@ECSComponent('SceneSerTest_Position')
|
||||
@Serializable({ version: 1 })
|
||||
class PositionComponent extends Component {
|
||||
@Serialize()
|
||||
public x: number = 0;
|
||||
|
||||
@Serialize()
|
||||
public y: number = 0;
|
||||
|
||||
constructor(x: number = 0, y: number = 0) {
|
||||
super();
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
}
|
||||
}
|
||||
|
||||
@ECSComponent('SceneSerTest_Velocity')
|
||||
@Serializable({ version: 1 })
|
||||
class VelocityComponent extends Component {
|
||||
@Serialize()
|
||||
public vx: number = 0;
|
||||
|
||||
@Serialize()
|
||||
public vy: number = 0;
|
||||
}
|
||||
|
||||
describe('SceneSerializer', () => {
|
||||
let scene: Scene;
|
||||
let componentRegistry: Map<string, ComponentType>;
|
||||
|
||||
beforeEach(() => {
|
||||
ComponentRegistry.reset();
|
||||
ComponentRegistry.register(PositionComponent);
|
||||
ComponentRegistry.register(VelocityComponent);
|
||||
|
||||
scene = new Scene({ name: 'SceneSerializerTestScene' });
|
||||
|
||||
componentRegistry = ComponentRegistry.getAllComponentNames() as Map<string, ComponentType>;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
scene.end();
|
||||
});
|
||||
|
||||
describe('serialize', () => {
|
||||
test('should serialize scene to JSON string', () => {
|
||||
scene.createEntity('Entity1').addComponent(new PositionComponent(10, 20));
|
||||
scene.createEntity('Entity2').addComponent(new VelocityComponent());
|
||||
|
||||
const result = SceneSerializer.serialize(scene);
|
||||
|
||||
expect(typeof result).toBe('string');
|
||||
const parsed = JSON.parse(result as string);
|
||||
expect(parsed.name).toBe('SceneSerializerTestScene');
|
||||
expect(parsed.entities.length).toBe(2);
|
||||
});
|
||||
|
||||
test('should serialize scene to binary format', () => {
|
||||
scene.createEntity('Entity');
|
||||
|
||||
const result = SceneSerializer.serialize(scene, { format: 'binary' });
|
||||
|
||||
expect(result).toBeInstanceOf(Uint8Array);
|
||||
});
|
||||
|
||||
test('should include metadata when requested', () => {
|
||||
scene.createEntity('Entity');
|
||||
|
||||
const result = SceneSerializer.serialize(scene, { includeMetadata: true });
|
||||
const parsed = JSON.parse(result as string);
|
||||
|
||||
expect(parsed.metadata).toBeDefined();
|
||||
expect(parsed.metadata.entityCount).toBe(1);
|
||||
expect(parsed.timestamp).toBeDefined();
|
||||
});
|
||||
|
||||
test('should pretty print JSON when requested', () => {
|
||||
scene.createEntity('Entity');
|
||||
|
||||
const result = SceneSerializer.serialize(scene, { pretty: true });
|
||||
|
||||
expect(typeof result).toBe('string');
|
||||
expect((result as string).includes('\n')).toBe(true);
|
||||
expect((result as string).includes(' ')).toBe(true);
|
||||
});
|
||||
|
||||
test('should serialize scene data', () => {
|
||||
scene.sceneData.set('level', 5);
|
||||
scene.sceneData.set('config', { difficulty: 'hard' });
|
||||
|
||||
const result = SceneSerializer.serialize(scene);
|
||||
const parsed = JSON.parse(result as string);
|
||||
|
||||
expect(parsed.sceneData).toBeDefined();
|
||||
expect(parsed.sceneData.level).toBe(5);
|
||||
expect(parsed.sceneData.config.difficulty).toBe('hard');
|
||||
});
|
||||
|
||||
test('should serialize with component filter', () => {
|
||||
scene.createEntity('Entity1').addComponent(new PositionComponent());
|
||||
scene.createEntity('Entity2').addComponent(new VelocityComponent());
|
||||
|
||||
const result = SceneSerializer.serialize(scene, {
|
||||
components: [PositionComponent]
|
||||
});
|
||||
const parsed = JSON.parse(result as string);
|
||||
|
||||
// Only entities with PositionComponent should be included
|
||||
expect(parsed.entities.length).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('deserialize', () => {
|
||||
test('should deserialize scene from JSON string', () => {
|
||||
scene.createEntity('Entity1').addComponent(new PositionComponent(100, 200));
|
||||
|
||||
const serialized = SceneSerializer.serialize(scene);
|
||||
|
||||
const newScene = new Scene({ name: 'NewScene' });
|
||||
SceneSerializer.deserialize(newScene, serialized, { componentRegistry });
|
||||
|
||||
expect(newScene.entities.count).toBe(1);
|
||||
const entity = newScene.findEntity('Entity1');
|
||||
expect(entity).not.toBeNull();
|
||||
expect(entity!.hasComponent(PositionComponent)).toBe(true);
|
||||
|
||||
const pos = entity!.getComponent(PositionComponent)!;
|
||||
expect(pos.x).toBe(100);
|
||||
expect(pos.y).toBe(200);
|
||||
|
||||
newScene.end();
|
||||
});
|
||||
|
||||
test('should deserialize scene from binary format', () => {
|
||||
scene.createEntity('BinaryEntity').addComponent(new PositionComponent(50, 75));
|
||||
|
||||
const serialized = SceneSerializer.serialize(scene, { format: 'binary' });
|
||||
|
||||
const newScene = new Scene({ name: 'NewScene' });
|
||||
SceneSerializer.deserialize(newScene, serialized, { componentRegistry });
|
||||
|
||||
expect(newScene.entities.count).toBe(1);
|
||||
const entity = newScene.findEntity('BinaryEntity');
|
||||
expect(entity).not.toBeNull();
|
||||
|
||||
newScene.end();
|
||||
});
|
||||
|
||||
test('should replace existing entities with strategy replace', () => {
|
||||
scene.createEntity('Original');
|
||||
const serialized = SceneSerializer.serialize(scene);
|
||||
|
||||
const targetScene = new Scene({ name: 'Target' });
|
||||
targetScene.createEntity('Existing1');
|
||||
targetScene.createEntity('Existing2');
|
||||
expect(targetScene.entities.count).toBe(2);
|
||||
|
||||
SceneSerializer.deserialize(targetScene, serialized, {
|
||||
strategy: 'replace',
|
||||
componentRegistry
|
||||
});
|
||||
|
||||
expect(targetScene.entities.count).toBe(1);
|
||||
expect(targetScene.findEntity('Original')).not.toBeNull();
|
||||
expect(targetScene.findEntity('Existing1')).toBeNull();
|
||||
|
||||
targetScene.end();
|
||||
});
|
||||
|
||||
test('should merge with existing entities with strategy merge', () => {
|
||||
scene.createEntity('FromSave');
|
||||
const serialized = SceneSerializer.serialize(scene);
|
||||
|
||||
const targetScene = new Scene({ name: 'Target' });
|
||||
targetScene.createEntity('Existing');
|
||||
expect(targetScene.entities.count).toBe(1);
|
||||
|
||||
SceneSerializer.deserialize(targetScene, serialized, {
|
||||
strategy: 'merge',
|
||||
componentRegistry
|
||||
});
|
||||
|
||||
expect(targetScene.entities.count).toBe(2);
|
||||
expect(targetScene.findEntity('Existing')).not.toBeNull();
|
||||
expect(targetScene.findEntity('FromSave')).not.toBeNull();
|
||||
|
||||
targetScene.end();
|
||||
});
|
||||
|
||||
test('should restore scene data', () => {
|
||||
scene.sceneData.set('weather', 'sunny');
|
||||
scene.sceneData.set('time', 12.5);
|
||||
|
||||
const serialized = SceneSerializer.serialize(scene);
|
||||
|
||||
const newScene = new Scene({ name: 'NewScene' });
|
||||
SceneSerializer.deserialize(newScene, serialized, { componentRegistry });
|
||||
|
||||
expect(newScene.sceneData.get('weather')).toBe('sunny');
|
||||
expect(newScene.sceneData.get('time')).toBe(12.5);
|
||||
|
||||
newScene.end();
|
||||
});
|
||||
|
||||
test('should call migration function when versions differ', () => {
|
||||
scene.createEntity('Entity');
|
||||
const serialized = SceneSerializer.serialize(scene);
|
||||
|
||||
// Manually modify version
|
||||
const parsed = JSON.parse(serialized as string);
|
||||
parsed.version = 0;
|
||||
const modifiedSerialized = JSON.stringify(parsed);
|
||||
|
||||
const migrationFn = jest.fn((oldVersion, newVersion, data) => {
|
||||
expect(oldVersion).toBe(0);
|
||||
return data;
|
||||
});
|
||||
|
||||
const newScene = new Scene({ name: 'NewScene' });
|
||||
SceneSerializer.deserialize(newScene, modifiedSerialized, {
|
||||
componentRegistry,
|
||||
migration: migrationFn
|
||||
});
|
||||
|
||||
expect(migrationFn).toHaveBeenCalled();
|
||||
|
||||
newScene.end();
|
||||
});
|
||||
|
||||
test('should throw on invalid JSON', () => {
|
||||
const newScene = new Scene({ name: 'NewScene' });
|
||||
|
||||
expect(() => {
|
||||
SceneSerializer.deserialize(newScene, 'invalid json{{{', { componentRegistry });
|
||||
}).toThrow();
|
||||
|
||||
newScene.end();
|
||||
});
|
||||
});
|
||||
|
||||
describe('validate', () => {
|
||||
test('should validate correct save data', () => {
|
||||
scene.createEntity('Entity');
|
||||
const serialized = SceneSerializer.serialize(scene);
|
||||
|
||||
const result = SceneSerializer.validate(serialized as string);
|
||||
|
||||
expect(result.valid).toBe(true);
|
||||
expect(result.version).toBe(1);
|
||||
});
|
||||
|
||||
test('should return errors for missing version', () => {
|
||||
const invalid = JSON.stringify({ entities: [], componentTypeRegistry: [] });
|
||||
|
||||
const result = SceneSerializer.validate(invalid);
|
||||
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.errors).toContain('Missing version field');
|
||||
});
|
||||
|
||||
test('should return errors for missing entities', () => {
|
||||
const invalid = JSON.stringify({ version: 1, componentTypeRegistry: [] });
|
||||
|
||||
const result = SceneSerializer.validate(invalid);
|
||||
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.errors).toContain('Missing or invalid entities field');
|
||||
});
|
||||
|
||||
test('should return errors for missing componentTypeRegistry', () => {
|
||||
const invalid = JSON.stringify({ version: 1, entities: [] });
|
||||
|
||||
const result = SceneSerializer.validate(invalid);
|
||||
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.errors).toContain('Missing or invalid componentTypeRegistry field');
|
||||
});
|
||||
|
||||
test('should handle JSON parse errors', () => {
|
||||
const result = SceneSerializer.validate('not valid json');
|
||||
|
||||
expect(result.valid).toBe(false);
|
||||
expect(result.errors).toBeDefined();
|
||||
expect(result.errors![0]).toContain('JSON parse error');
|
||||
});
|
||||
});
|
||||
|
||||
describe('getInfo', () => {
|
||||
test('should return info from save data', () => {
|
||||
scene.name = 'InfoTestScene';
|
||||
scene.createEntity('Entity1');
|
||||
scene.createEntity('Entity2');
|
||||
scene.createEntity('Entity3');
|
||||
|
||||
const serialized = SceneSerializer.serialize(scene);
|
||||
const info = SceneSerializer.getInfo(serialized as string);
|
||||
|
||||
expect(info).not.toBeNull();
|
||||
expect(info!.name).toBe('InfoTestScene');
|
||||
expect(info!.entityCount).toBe(3);
|
||||
expect(info!.version).toBe(1);
|
||||
});
|
||||
|
||||
test('should return null for invalid data', () => {
|
||||
const info = SceneSerializer.getInfo('invalid');
|
||||
|
||||
expect(info).toBeNull();
|
||||
});
|
||||
|
||||
test('should include timestamp when present', () => {
|
||||
scene.createEntity('Entity');
|
||||
const serialized = SceneSerializer.serialize(scene, { includeMetadata: true });
|
||||
const info = SceneSerializer.getInfo(serialized as string);
|
||||
|
||||
expect(info!.timestamp).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('scene data serialization', () => {
|
||||
test('should serialize Date objects', () => {
|
||||
const date = new Date('2024-01-01T00:00:00Z');
|
||||
scene.sceneData.set('createdAt', date);
|
||||
|
||||
const serialized = SceneSerializer.serialize(scene);
|
||||
const parsed = JSON.parse(serialized as string);
|
||||
|
||||
expect(parsed.sceneData.createdAt.__type).toBe('Date');
|
||||
});
|
||||
|
||||
test('should deserialize Date objects', () => {
|
||||
const date = new Date('2024-01-01T00:00:00Z');
|
||||
scene.sceneData.set('createdAt', date);
|
||||
|
||||
const serialized = SceneSerializer.serialize(scene);
|
||||
|
||||
const newScene = new Scene({ name: 'NewScene' });
|
||||
SceneSerializer.deserialize(newScene, serialized, { componentRegistry });
|
||||
|
||||
const restoredDate = newScene.sceneData.get('createdAt');
|
||||
expect(restoredDate).toBeInstanceOf(Date);
|
||||
expect(restoredDate.getTime()).toBe(date.getTime());
|
||||
|
||||
newScene.end();
|
||||
});
|
||||
|
||||
test('should serialize Map objects', () => {
|
||||
const map = new Map([['key1', 'value1'], ['key2', 'value2']]);
|
||||
scene.sceneData.set('mapping', map);
|
||||
|
||||
const serialized = SceneSerializer.serialize(scene);
|
||||
const parsed = JSON.parse(serialized as string);
|
||||
|
||||
expect(parsed.sceneData.mapping.__type).toBe('Map');
|
||||
});
|
||||
|
||||
test('should deserialize Map objects', () => {
|
||||
const map = new Map([['key1', 'value1'], ['key2', 'value2']]);
|
||||
scene.sceneData.set('mapping', map);
|
||||
|
||||
const serialized = SceneSerializer.serialize(scene);
|
||||
|
||||
const newScene = new Scene({ name: 'NewScene' });
|
||||
SceneSerializer.deserialize(newScene, serialized, { componentRegistry });
|
||||
|
||||
const restoredMap = newScene.sceneData.get('mapping');
|
||||
expect(restoredMap).toBeInstanceOf(Map);
|
||||
expect(restoredMap.get('key1')).toBe('value1');
|
||||
expect(restoredMap.get('key2')).toBe('value2');
|
||||
|
||||
newScene.end();
|
||||
});
|
||||
|
||||
test('should serialize Set objects', () => {
|
||||
const set = new Set([1, 2, 3]);
|
||||
scene.sceneData.set('numbers', set);
|
||||
|
||||
const serialized = SceneSerializer.serialize(scene);
|
||||
const parsed = JSON.parse(serialized as string);
|
||||
|
||||
expect(parsed.sceneData.numbers.__type).toBe('Set');
|
||||
});
|
||||
|
||||
test('should deserialize Set objects', () => {
|
||||
const set = new Set([1, 2, 3]);
|
||||
scene.sceneData.set('numbers', set);
|
||||
|
||||
const serialized = SceneSerializer.serialize(scene);
|
||||
|
||||
const newScene = new Scene({ name: 'NewScene' });
|
||||
SceneSerializer.deserialize(newScene, serialized, { componentRegistry });
|
||||
|
||||
const restoredSet = newScene.sceneData.get('numbers');
|
||||
expect(restoredSet).toBeInstanceOf(Set);
|
||||
expect(restoredSet.has(1)).toBe(true);
|
||||
expect(restoredSet.has(2)).toBe(true);
|
||||
expect(restoredSet.has(3)).toBe(true);
|
||||
|
||||
newScene.end();
|
||||
});
|
||||
});
|
||||
|
||||
describe('hierarchy serialization', () => {
|
||||
test('should serialize and deserialize entity hierarchy', () => {
|
||||
const hierarchySystem = new HierarchySystem();
|
||||
scene.addSystem(hierarchySystem);
|
||||
|
||||
const root = scene.createEntity('Root');
|
||||
const child1 = scene.createEntity('Child1');
|
||||
const child2 = scene.createEntity('Child2');
|
||||
|
||||
hierarchySystem.setParent(child1, root);
|
||||
hierarchySystem.setParent(child2, root);
|
||||
|
||||
const serialized = SceneSerializer.serialize(scene);
|
||||
|
||||
const newScene = new Scene({ name: 'NewScene' });
|
||||
const newHierarchySystem = new HierarchySystem();
|
||||
newScene.addSystem(newHierarchySystem);
|
||||
|
||||
SceneSerializer.deserialize(newScene, serialized, { componentRegistry });
|
||||
|
||||
const newRoot = newScene.findEntity('Root');
|
||||
expect(newRoot).not.toBeNull();
|
||||
|
||||
const children = newHierarchySystem.getChildren(newRoot!);
|
||||
expect(children.length).toBe(2);
|
||||
|
||||
newScene.end();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,629 +0,0 @@
|
||||
/**
|
||||
* 序列化系统测试
|
||||
*/
|
||||
|
||||
import { Component } from '../../../src/ECS/Component';
|
||||
import { Scene } from '../../../src/ECS/Scene';
|
||||
import { Entity } from '../../../src/ECS/Entity';
|
||||
import {
|
||||
Serializable,
|
||||
Serialize,
|
||||
SerializeAsMap,
|
||||
SerializeAsSet,
|
||||
IgnoreSerialization,
|
||||
ComponentSerializer,
|
||||
EntitySerializer,
|
||||
SceneSerializer,
|
||||
VersionMigrationManager,
|
||||
MigrationBuilder
|
||||
} from '../../../src/ECS/Serialization';
|
||||
import { ECSComponent } from '../../../src/ECS/Decorators';
|
||||
import { ComponentRegistry } from '../../../src/ECS/Core/ComponentStorage';
|
||||
|
||||
// 测试组件定义
|
||||
@ECSComponent('Position')
|
||||
@Serializable({ version: 1 })
|
||||
class PositionComponent extends Component {
|
||||
@Serialize()
|
||||
public x: number = 0;
|
||||
|
||||
@Serialize()
|
||||
public y: number = 0;
|
||||
|
||||
constructor(x: number = 0, y: number = 0) {
|
||||
super();
|
||||
this.x = x;
|
||||
this.y = y;
|
||||
}
|
||||
}
|
||||
|
||||
@ECSComponent('Velocity')
|
||||
@Serializable({ version: 1 })
|
||||
class VelocityComponent extends Component {
|
||||
@Serialize()
|
||||
public dx: number = 0;
|
||||
|
||||
@Serialize()
|
||||
public dy: number = 0;
|
||||
}
|
||||
|
||||
@ECSComponent('Player')
|
||||
@Serializable({ version: 1 })
|
||||
class PlayerComponent extends Component {
|
||||
@Serialize()
|
||||
public name: string = '';
|
||||
|
||||
@Serialize()
|
||||
public level: number = 1;
|
||||
|
||||
@SerializeAsMap()
|
||||
public inventory: Map<string, number> = new Map();
|
||||
|
||||
@SerializeAsSet()
|
||||
public tags: Set<string> = new Set();
|
||||
|
||||
@IgnoreSerialization()
|
||||
public tempCache: any = null;
|
||||
}
|
||||
|
||||
@ECSComponent('Health')
|
||||
@Serializable({ version: 1 })
|
||||
class HealthComponent extends Component {
|
||||
@Serialize()
|
||||
public current: number = 100;
|
||||
|
||||
@Serialize()
|
||||
public max: number = 100;
|
||||
}
|
||||
|
||||
// 非可序列化组件
|
||||
class NonSerializableComponent extends Component {
|
||||
public data: any = null;
|
||||
}
|
||||
|
||||
describe('ECS Serialization System', () => {
|
||||
let scene: Scene;
|
||||
|
||||
beforeEach(() => {
|
||||
// 清空测试环境
|
||||
ComponentRegistry.reset();
|
||||
|
||||
// 重新注册测试组件(因为reset会清空所有注册)
|
||||
ComponentRegistry.register(PositionComponent);
|
||||
ComponentRegistry.register(VelocityComponent);
|
||||
ComponentRegistry.register(PlayerComponent);
|
||||
ComponentRegistry.register(HealthComponent);
|
||||
|
||||
// 创建测试场景
|
||||
scene = new Scene();
|
||||
});
|
||||
|
||||
describe('Component Serialization', () => {
|
||||
it('should serialize a simple component', () => {
|
||||
const position = new PositionComponent(100, 200);
|
||||
const serialized = ComponentSerializer.serialize(position);
|
||||
|
||||
expect(serialized).not.toBeNull();
|
||||
expect(serialized!.type).toBe('Position');
|
||||
expect(serialized!.version).toBe(1);
|
||||
expect(serialized!.data.x).toBe(100);
|
||||
expect(serialized!.data.y).toBe(200);
|
||||
});
|
||||
|
||||
it('should deserialize a simple component', () => {
|
||||
const serializedData = {
|
||||
type: 'Position',
|
||||
version: 1,
|
||||
data: { x: 150, y: 250 }
|
||||
};
|
||||
|
||||
const registry = ComponentRegistry.getAllComponentNames() as Map<string, any>;
|
||||
const component = ComponentSerializer.deserialize(serializedData, registry);
|
||||
|
||||
expect(component).not.toBeNull();
|
||||
expect(component).toBeInstanceOf(PositionComponent);
|
||||
expect((component as PositionComponent).x).toBe(150);
|
||||
expect((component as PositionComponent).y).toBe(250);
|
||||
});
|
||||
|
||||
it('should serialize Map fields', () => {
|
||||
const player = new PlayerComponent();
|
||||
player.name = 'Hero';
|
||||
player.level = 5;
|
||||
player.inventory.set('sword', 1);
|
||||
player.inventory.set('potion', 10);
|
||||
|
||||
const serialized = ComponentSerializer.serialize(player);
|
||||
|
||||
expect(serialized).not.toBeNull();
|
||||
expect(serialized!.data.inventory).toEqual([
|
||||
['sword', 1],
|
||||
['potion', 10]
|
||||
]);
|
||||
});
|
||||
|
||||
it('should deserialize Map fields', () => {
|
||||
const serializedData = {
|
||||
type: 'Player',
|
||||
version: 1,
|
||||
data: {
|
||||
name: 'Hero',
|
||||
level: 5,
|
||||
inventory: [
|
||||
['sword', 1],
|
||||
['potion', 10]
|
||||
],
|
||||
tags: ['warrior', 'hero']
|
||||
}
|
||||
};
|
||||
|
||||
const registry = ComponentRegistry.getAllComponentNames() as Map<string, any>;
|
||||
const component = ComponentSerializer.deserialize(
|
||||
serializedData,
|
||||
registry
|
||||
) as PlayerComponent;
|
||||
|
||||
expect(component).not.toBeNull();
|
||||
expect(component.inventory.get('sword')).toBe(1);
|
||||
expect(component.inventory.get('potion')).toBe(10);
|
||||
expect(component.tags.has('warrior')).toBe(true);
|
||||
expect(component.tags.has('hero')).toBe(true);
|
||||
});
|
||||
|
||||
it('should ignore fields marked with @IgnoreSerialization', () => {
|
||||
const player = new PlayerComponent();
|
||||
player.tempCache = { foo: 'bar' };
|
||||
|
||||
const serialized = ComponentSerializer.serialize(player);
|
||||
|
||||
expect(serialized).not.toBeNull();
|
||||
expect(serialized!.data.tempCache).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should return null for non-serializable components', () => {
|
||||
const nonSerializable = new NonSerializableComponent();
|
||||
const serialized = ComponentSerializer.serialize(nonSerializable);
|
||||
|
||||
expect(serialized).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('Entity Serialization', () => {
|
||||
it('should serialize an entity with components', () => {
|
||||
const entity = scene.createEntity('Player');
|
||||
entity.addComponent(new PositionComponent(50, 100));
|
||||
entity.addComponent(new VelocityComponent());
|
||||
entity.tag = 10;
|
||||
|
||||
const serialized = EntitySerializer.serialize(entity);
|
||||
|
||||
expect(serialized.id).toBe(entity.id);
|
||||
expect(serialized.name).toBe('Player');
|
||||
expect(serialized.tag).toBe(10);
|
||||
expect(serialized.components.length).toBe(2);
|
||||
});
|
||||
|
||||
it('should serialize entity hierarchy', () => {
|
||||
const parent = scene.createEntity('Parent');
|
||||
const child = scene.createEntity('Child');
|
||||
|
||||
parent.addComponent(new PositionComponent(0, 0));
|
||||
child.addComponent(new PositionComponent(10, 10));
|
||||
parent.addChild(child);
|
||||
|
||||
const serialized = EntitySerializer.serialize(parent);
|
||||
|
||||
expect(serialized.children.length).toBe(1);
|
||||
expect(serialized.children[0].id).toBe(child.id);
|
||||
expect(serialized.children[0].name).toBe('Child');
|
||||
});
|
||||
|
||||
it('should deserialize an entity', () => {
|
||||
const serializedEntity = {
|
||||
id: 1,
|
||||
name: 'TestEntity',
|
||||
tag: 5,
|
||||
active: true,
|
||||
enabled: true,
|
||||
updateOrder: 0,
|
||||
components: [
|
||||
{
|
||||
type: 'Position',
|
||||
version: 1,
|
||||
data: { x: 100, y: 200 }
|
||||
}
|
||||
],
|
||||
children: []
|
||||
};
|
||||
|
||||
const registry = ComponentRegistry.getAllComponentNames() as Map<string, any>;
|
||||
let idCounter = 10;
|
||||
const entity = EntitySerializer.deserialize(
|
||||
serializedEntity,
|
||||
registry,
|
||||
() => idCounter++,
|
||||
false,
|
||||
scene
|
||||
);
|
||||
|
||||
expect(entity.name).toBe('TestEntity');
|
||||
expect(entity.tag).toBe(5);
|
||||
expect(entity.components.length).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Scene Serialization', () => {
|
||||
let scene: Scene;
|
||||
|
||||
beforeEach(() => {
|
||||
scene = new Scene({ name: 'TestScene' });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
scene.end();
|
||||
});
|
||||
|
||||
it('should serialize a scene', () => {
|
||||
const entity1 = scene.createEntity('Entity1');
|
||||
entity1.addComponent(new PositionComponent(10, 20));
|
||||
|
||||
const entity2 = scene.createEntity('Entity2');
|
||||
entity2.addComponent(new PlayerComponent());
|
||||
|
||||
const saveData = scene.serialize({ format: 'json', pretty: true });
|
||||
|
||||
expect(saveData).toBeTruthy();
|
||||
expect(typeof saveData).toBe('string');
|
||||
|
||||
const parsed = JSON.parse(saveData as string);
|
||||
expect(parsed.name).toBe('TestScene');
|
||||
expect(parsed.version).toBe(1);
|
||||
expect(parsed.entities.length).toBe(2);
|
||||
});
|
||||
|
||||
it('should deserialize a scene with replace strategy', () => {
|
||||
// 创建初始实体
|
||||
const entity1 = scene.createEntity('Initial');
|
||||
entity1.addComponent(new PositionComponent(0, 0));
|
||||
|
||||
// 序列化
|
||||
const entity2 = scene.createEntity('ToSave');
|
||||
entity2.addComponent(new PositionComponent(100, 100));
|
||||
const saveData = scene.serialize();
|
||||
|
||||
// 清空并重新加载
|
||||
scene.deserialize(saveData, {
|
||||
strategy: 'replace',
|
||||
// componentRegistry会自动从ComponentRegistry获取
|
||||
});
|
||||
|
||||
expect(scene.entities.count).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('should filter components during serialization', () => {
|
||||
const entity = scene.createEntity('Mixed');
|
||||
entity.addComponent(new PositionComponent(1, 2));
|
||||
entity.addComponent(new PlayerComponent());
|
||||
entity.addComponent(new HealthComponent());
|
||||
|
||||
const saveData = scene.serialize({
|
||||
components: [PositionComponent, PlayerComponent],
|
||||
format: 'json'
|
||||
});
|
||||
|
||||
const parsed = JSON.parse(saveData as string);
|
||||
expect(parsed.entities.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('should preserve entity hierarchy', () => {
|
||||
const parent = scene.createEntity('Parent');
|
||||
const child = scene.createEntity('Child');
|
||||
parent.addChild(child);
|
||||
|
||||
parent.addComponent(new PositionComponent(0, 0));
|
||||
child.addComponent(new PositionComponent(10, 10));
|
||||
|
||||
const saveData = scene.serialize({ format: 'json' });
|
||||
const parsed = JSON.parse(saveData as string);
|
||||
|
||||
// 只有父实体在顶层
|
||||
expect(parsed.entities.length).toBe(1);
|
||||
expect(parsed.entities[0].children.length).toBe(1);
|
||||
});
|
||||
|
||||
it('should validate save data', () => {
|
||||
const entity = scene.createEntity('Test');
|
||||
entity.addComponent(new PositionComponent(5, 5));
|
||||
|
||||
const saveData = scene.serialize({ format: 'json' });
|
||||
const validation = SceneSerializer.validate(saveData as string);
|
||||
|
||||
expect(validation.valid).toBe(true);
|
||||
expect(validation.version).toBe(1);
|
||||
});
|
||||
|
||||
it('should get save data info', () => {
|
||||
const entity = scene.createEntity('InfoTest');
|
||||
entity.addComponent(new PositionComponent(1, 1));
|
||||
|
||||
const saveData = scene.serialize({ format: 'json' });
|
||||
const info = SceneSerializer.getInfo(saveData as string);
|
||||
|
||||
expect(info).not.toBeNull();
|
||||
expect(info!.name).toBe('TestScene');
|
||||
expect(info!.version).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Version Migration', () => {
|
||||
@ECSComponent('OldPlayer')
|
||||
@Serializable({ version: 1 })
|
||||
class OldPlayerV1 extends Component {
|
||||
@Serialize()
|
||||
public name: string = '';
|
||||
|
||||
@Serialize()
|
||||
public hp: number = 100;
|
||||
}
|
||||
|
||||
@ECSComponent('OldPlayer')
|
||||
@Serializable({ version: 2 })
|
||||
class OldPlayerV2 extends Component {
|
||||
@Serialize()
|
||||
public name: string = '';
|
||||
|
||||
@Serialize()
|
||||
public health: number = 100; // 重命名了字段
|
||||
|
||||
@Serialize()
|
||||
public maxHealth: number = 100; // 新增字段
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
VersionMigrationManager.clearMigrations();
|
||||
});
|
||||
|
||||
it('should migrate component from v1 to v2', () => {
|
||||
// 注册迁移
|
||||
VersionMigrationManager.registerComponentMigration(
|
||||
'OldPlayer',
|
||||
1,
|
||||
2,
|
||||
(data) => {
|
||||
return {
|
||||
name: data.name,
|
||||
health: data.hp,
|
||||
maxHealth: data.hp
|
||||
};
|
||||
}
|
||||
);
|
||||
|
||||
const v1Data = {
|
||||
type: 'OldPlayer',
|
||||
version: 1,
|
||||
data: { name: 'Hero', hp: 80 }
|
||||
};
|
||||
|
||||
const migrated = VersionMigrationManager.migrateComponent(v1Data, 2);
|
||||
|
||||
expect(migrated.version).toBe(2);
|
||||
expect(migrated.data.health).toBe(80);
|
||||
expect(migrated.data.maxHealth).toBe(80);
|
||||
expect(migrated.data.hp).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should use MigrationBuilder for component migration', () => {
|
||||
new MigrationBuilder()
|
||||
.forComponent('Player')
|
||||
.fromVersionToVersion(1, 2)
|
||||
.migrate((data: any) => {
|
||||
data.experience = 0;
|
||||
return data;
|
||||
});
|
||||
|
||||
expect(VersionMigrationManager.canMigrateComponent('Player', 1, 2)).toBe(true);
|
||||
});
|
||||
|
||||
it('should check migration path availability', () => {
|
||||
VersionMigrationManager.registerComponentMigration('Test', 1, 2, (d) => d);
|
||||
VersionMigrationManager.registerComponentMigration('Test', 2, 3, (d) => d);
|
||||
|
||||
expect(VersionMigrationManager.canMigrateComponent('Test', 1, 3)).toBe(true);
|
||||
expect(VersionMigrationManager.canMigrateComponent('Test', 1, 4)).toBe(false);
|
||||
});
|
||||
|
||||
it('should get migration path', () => {
|
||||
VersionMigrationManager.registerComponentMigration('PathTest', 1, 2, (d) => d);
|
||||
VersionMigrationManager.registerComponentMigration('PathTest', 2, 3, (d) => d);
|
||||
|
||||
const path = VersionMigrationManager.getComponentMigrationPath('PathTest');
|
||||
|
||||
expect(path).toEqual([1, 2]);
|
||||
});
|
||||
});
|
||||
|
||||
// ComponentTypeRegistry已被移除,现在使用ComponentRegistry自动管理组件类型
|
||||
|
||||
describe('Integration Tests', () => {
|
||||
it('should perform full save/load cycle', () => {
|
||||
const scene1 = new Scene({ name: 'SaveTest' });
|
||||
|
||||
// 创建复杂实体
|
||||
const player = scene1.createEntity('Player');
|
||||
const playerComp = new PlayerComponent();
|
||||
playerComp.name = 'TestHero';
|
||||
playerComp.level = 10;
|
||||
playerComp.inventory.set('sword', 1);
|
||||
playerComp.inventory.set('shield', 1);
|
||||
playerComp.tags.add('warrior');
|
||||
|
||||
player.addComponent(playerComp);
|
||||
player.addComponent(new PositionComponent(100, 200));
|
||||
player.addComponent(new HealthComponent());
|
||||
|
||||
// 创建子实体
|
||||
const weapon = scene1.createEntity('Weapon');
|
||||
weapon.addComponent(new PositionComponent(5, 0));
|
||||
player.addChild(weapon);
|
||||
|
||||
// 序列化
|
||||
const saveData = scene1.serialize();
|
||||
|
||||
// 新场景
|
||||
const scene2 = new Scene({ name: 'LoadTest' });
|
||||
|
||||
// 反序列化
|
||||
scene2.deserialize(saveData, {
|
||||
strategy: 'replace',
|
||||
// componentRegistry会自动从ComponentRegistry获取
|
||||
});
|
||||
|
||||
// 验证
|
||||
const loadedPlayer = scene2.findEntity('Player');
|
||||
expect(loadedPlayer).not.toBeNull();
|
||||
|
||||
const loadedPlayerComp = loadedPlayer!.getComponent(PlayerComponent as any) as PlayerComponent;
|
||||
expect(loadedPlayerComp).not.toBeNull();
|
||||
expect(loadedPlayerComp.name).toBe('TestHero');
|
||||
expect(loadedPlayerComp.level).toBe(10);
|
||||
expect(loadedPlayerComp.inventory.get('sword')).toBe(1);
|
||||
expect(loadedPlayerComp.tags.has('warrior')).toBe(true);
|
||||
|
||||
// 验证层级结构
|
||||
expect(loadedPlayer!.childCount).toBe(1);
|
||||
|
||||
scene1.end();
|
||||
scene2.end();
|
||||
});
|
||||
|
||||
it('should serialize and deserialize scene custom data', () => {
|
||||
const scene1 = new Scene({ name: 'SceneDataTest' });
|
||||
|
||||
// 设置场景自定义数据
|
||||
scene1.sceneData.set('weather', 'rainy');
|
||||
scene1.sceneData.set('timeOfDay', 14.5);
|
||||
scene1.sceneData.set('difficulty', 'hard');
|
||||
scene1.sceneData.set('checkpoint', { x: 100, y: 200 });
|
||||
scene1.sceneData.set('tags', new Set(['action', 'adventure']));
|
||||
scene1.sceneData.set('metadata', new Map([['author', 'test'], ['version', '1.0']]));
|
||||
|
||||
// 序列化
|
||||
const saveData = scene1.serialize();
|
||||
|
||||
// 新场景
|
||||
const scene2 = new Scene({ name: 'LoadTest' });
|
||||
|
||||
// 反序列化
|
||||
scene2.deserialize(saveData, {
|
||||
strategy: 'replace',
|
||||
// componentRegistry会自动从ComponentRegistry获取
|
||||
});
|
||||
|
||||
// 验证场景数据
|
||||
expect(scene2.sceneData.get('weather')).toBe('rainy');
|
||||
expect(scene2.sceneData.get('timeOfDay')).toBe(14.5);
|
||||
expect(scene2.sceneData.get('difficulty')).toBe('hard');
|
||||
expect(scene2.sceneData.get('checkpoint')).toEqual({ x: 100, y: 200 });
|
||||
|
||||
const tags = scene2.sceneData.get('tags');
|
||||
expect(tags).toBeInstanceOf(Set);
|
||||
expect(tags.has('action')).toBe(true);
|
||||
expect(tags.has('adventure')).toBe(true);
|
||||
|
||||
const metadata = scene2.sceneData.get('metadata');
|
||||
expect(metadata).toBeInstanceOf(Map);
|
||||
expect(metadata.get('author')).toBe('test');
|
||||
expect(metadata.get('version')).toBe('1.0');
|
||||
|
||||
scene1.end();
|
||||
scene2.end();
|
||||
});
|
||||
|
||||
it('should serialize and deserialize using binary format', () => {
|
||||
const scene1 = new Scene({ name: 'BinaryTest' });
|
||||
|
||||
// 创建测试数据
|
||||
const player = scene1.createEntity('Player');
|
||||
const playerComp = new PlayerComponent();
|
||||
playerComp.name = 'BinaryHero';
|
||||
playerComp.level = 5;
|
||||
playerComp.inventory.set('sword', 1);
|
||||
player.addComponent(playerComp);
|
||||
player.addComponent(new PositionComponent(100, 200));
|
||||
|
||||
scene1.sceneData.set('weather', 'sunny');
|
||||
scene1.sceneData.set('score', 9999);
|
||||
|
||||
// 二进制序列化
|
||||
const binaryData = scene1.serialize({ format: 'binary' });
|
||||
|
||||
// 验证是Uint8Array类型
|
||||
expect(binaryData instanceof Uint8Array).toBe(true);
|
||||
expect((binaryData as Uint8Array).length).toBeGreaterThan(0);
|
||||
|
||||
// 新场景反序列化二进制数据
|
||||
const scene2 = new Scene({ name: 'LoadTest' });
|
||||
scene2.deserialize(binaryData, {
|
||||
strategy: 'replace',
|
||||
// componentRegistry会自动从ComponentRegistry获取
|
||||
});
|
||||
|
||||
// 验证数据完整性
|
||||
const loadedPlayer = scene2.findEntity('Player');
|
||||
expect(loadedPlayer).not.toBeNull();
|
||||
|
||||
const loadedPlayerComp = loadedPlayer!.getComponent(PlayerComponent as any) as PlayerComponent;
|
||||
expect(loadedPlayerComp.name).toBe('BinaryHero');
|
||||
expect(loadedPlayerComp.level).toBe(5);
|
||||
expect(loadedPlayerComp.inventory.get('sword')).toBe(1);
|
||||
|
||||
const loadedPos = loadedPlayer!.getComponent(PositionComponent as any) as PositionComponent;
|
||||
expect(loadedPos.x).toBe(100);
|
||||
expect(loadedPos.y).toBe(200);
|
||||
|
||||
expect(scene2.sceneData.get('weather')).toBe('sunny');
|
||||
expect(scene2.sceneData.get('score')).toBe(9999);
|
||||
|
||||
scene1.end();
|
||||
scene2.end();
|
||||
});
|
||||
|
||||
it('should handle complex nested data in binary format', () => {
|
||||
const scene1 = new Scene({ name: 'NestedBinaryTest' });
|
||||
|
||||
// 复杂嵌套数据
|
||||
scene1.sceneData.set('config', {
|
||||
graphics: {
|
||||
quality: 'high',
|
||||
resolution: { width: 1920, height: 1080 }
|
||||
},
|
||||
audio: {
|
||||
masterVolume: 0.8,
|
||||
effects: new Map([['music', 0.7], ['sfx', 0.9]])
|
||||
},
|
||||
tags: new Set(['multiplayer', 'ranked']),
|
||||
timestamp: new Date('2024-01-01')
|
||||
});
|
||||
|
||||
// 二进制序列化
|
||||
const binaryData = scene1.serialize({ format: 'binary' });
|
||||
|
||||
// 反序列化
|
||||
const scene2 = new Scene({ name: 'LoadTest' });
|
||||
scene2.deserialize(binaryData, {
|
||||
// componentRegistry会自动从ComponentRegistry获取
|
||||
});
|
||||
|
||||
const config = scene2.sceneData.get('config');
|
||||
expect(config.graphics.quality).toBe('high');
|
||||
expect(config.graphics.resolution.width).toBe(1920);
|
||||
expect(config.audio.masterVolume).toBe(0.8);
|
||||
expect(config.audio.effects.get('music')).toBe(0.7);
|
||||
expect(config.tags.has('multiplayer')).toBe(true);
|
||||
expect(config.timestamp).toBeInstanceOf(Date);
|
||||
|
||||
scene1.end();
|
||||
scene2.end();
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user