A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
test: add TDD tests for core SDK modules
esengine2405c0a01573
diff --git a/sdk/src/commands.ts b/sdk/src/commands.tsindex aafd9d3ab..8f58c4cf5 100644--- a/sdk/src/commands.ts+++ b/sdk/src/commands.ts@@ -29,12 +29,6 @@ interface SpawnComponentEntry {data: unknown;}-interface SpawnCommand {- type: 'spawn';- components: SpawnComponentEntry[];- entityRef: { entity: Entity };-}-interface DespawnCommand {type: 'despawn';entity: Entity;@@ -60,7 +54,6 @@ interface InsertResourceCommand {}type Command =- | SpawnCommand| DespawnCommand| InsertCommand| RemoveCommand@@ -198,15 +191,6 @@ export class CommandsInstance {private executeCommand(cmd: Command): void {switch (cmd.type) {- case 'spawn': {- const entity = this.world_.spawn();- cmd.entityRef.entity = entity;- for (const entry of cmd.components) {- this.world_.insert(entity, entry.component, entry.data as Record<string, unknown>);- }- break;- }-case 'despawn':if (!this.world_.valid(cmd.entity)) {console.warn(`[Commands] despawn skipped: entity ${cmd.entity} is already invalid`);diff --git a/sdk/tests/commands.test.ts b/sdk/tests/commands.test.tsnew file mode 100644index 000000000..6e079081a--- /dev/null+++ b/sdk/tests/commands.test.ts@@ -0,0 +1,340 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { CommandsInstance, EntityCommands, Commands } from '../src/commands';+import { defineComponent, defineBuiltin } from '../src/component';+import { defineResource, ResourceStorage } from '../src/resource';+import type { World } from '../src/world';+import type { Entity } from '../src/types';++const Position = defineComponent('CmdTestPosition', { x: 0, y: 0 });+const Velocity = defineComponent('CmdTestVelocity', { dx: 0, dy: 0 });+const Health = defineBuiltin('CmdTestHealth', { value: 100, max: 100 });++function createMockWorld() {+ let nextId = 1;+ const validEntities = new Set<Entity>();+ const components = new Map<Entity, Map<string, any>>();++ const world = {+ spawn: vi.fn(() => {+ const entity = nextId++ as Entity;+ validEntities.add(entity);+ components.set(entity, new Map());+ return entity;+ }),+ despawn: vi.fn((entity: Entity) => {+ validEntities.delete(entity);+ components.delete(entity);+ }),+ insert: vi.fn((entity: Entity, comp: any, data: any) => {+ components.get(entity)?.set(comp._name, data);+ }),+ remove: vi.fn((entity: Entity, comp: any) => {+ components.get(entity)?.delete(comp._name);+ }),+ valid: vi.fn((entity: Entity) => validEntities.has(entity)),+ };++ return { world: world as unknown as World, validEntities, components };+}++describe('Commands descriptor', () => {+ it('should create a commands descriptor', () => {+ const desc = Commands();+ expect(desc._type).toBe('commands');+ });+});++describe('CommandsInstance', () => {+ let world: World;+ let mockWorld: ReturnType<typeof createMockWorld>;+ let resources: ResourceStorage;+ let commands: CommandsInstance;++ beforeEach(() => {+ mockWorld = createMockWorld();+ world = mockWorld.world;+ resources = new ResourceStorage();+ commands = new CommandsInstance(world, resources);+ });++ describe('spawn', () => {+ it('should return an EntityCommands builder', () => {+ const ec = commands.spawn();+ expect(ec).toBeInstanceOf(EntityCommands);+ });++ it('should spawn entity on flush', () => {+ commands.spawn();+ commands.flush();++ expect(world.spawn).toHaveBeenCalledOnce();+ });++ it('should spawn entity with components on flush', () => {+ commands.spawn()+ .insert(Position, { x: 10, y: 20 });+ commands.flush();++ expect(world.spawn).toHaveBeenCalledOnce();+ expect(world.insert).toHaveBeenCalledWith(+ 1,+ Position,+ expect.objectContaining({ x: 10, y: 20 }),+ );+ });++ it('should spawn multiple entities', () => {+ commands.spawn().insert(Position, { x: 1, y: 1 });+ commands.spawn().insert(Position, { x: 2, y: 2 });+ commands.flush();++ expect(world.spawn).toHaveBeenCalledTimes(2);+ expect(world.insert).toHaveBeenCalledTimes(2);+ });++ it('should support chaining multiple insert calls', () => {+ commands.spawn()+ .insert(Position, { x: 1, y: 2 })+ .insert(Velocity, { dx: 3, dy: 4 });+ commands.flush();++ expect(world.insert).toHaveBeenCalledTimes(2);+ });+ });++ describe('spawn with builtin component', () => {+ it('should merge data with builtin defaults', () => {+ commands.spawn().insert(Health, { value: 50 });+ commands.flush();++ expect(world.insert).toHaveBeenCalledWith(+ 1,+ Health,+ expect.objectContaining({ value: 50, max: 100 }),+ );+ });++ it('should use full defaults when no data provided', () => {+ commands.spawn().insert(Health);+ commands.flush();++ expect(world.insert).toHaveBeenCalledWith(+ 1,+ Health,+ expect.objectContaining({ value: 100, max: 100 }),+ );+ });+ });++ describe('spawn with user-defined component', () => {+ it('should call create() with partial data', () => {+ commands.spawn().insert(Position, { x: 42 });+ commands.flush();++ expect(world.insert).toHaveBeenCalledWith(+ 1,+ Position,+ expect.objectContaining({ x: 42, y: 0 }),+ );+ });++ it('should call create() with full defaults when no data', () => {+ commands.spawn().insert(Position);+ commands.flush();++ expect(world.insert).toHaveBeenCalledWith(+ 1,+ Position,+ expect.objectContaining({ x: 0, y: 0 }),+ );+ });+ });++ describe('entity (existing)', () => {+ it('should insert component on existing entity immediately queued', () => {+ const entity = (world.spawn as any)() as Entity;+ commands.entity(entity).insert(Position, { x: 5, y: 10 });+ commands.flush();++ expect(world.insert).toHaveBeenCalledWith(+ entity,+ Position,+ expect.objectContaining({ x: 5, y: 10 }),+ );+ });++ it('should remove component from existing entity', () => {+ const entity = (world.spawn as any)() as Entity;+ commands.entity(entity).remove(Position);+ commands.flush();++ expect(world.remove).toHaveBeenCalledWith(entity, Position);+ });++ it('should support chaining insert and remove', () => {+ const entity = (world.spawn as any)() as Entity;+ commands.entity(entity)+ .insert(Position, { x: 1, y: 2 })+ .remove(Velocity);+ commands.flush();++ expect(world.insert).toHaveBeenCalledWith(+ entity, Position, expect.objectContaining({ x: 1, y: 2 }),+ );+ expect(world.remove).toHaveBeenCalledWith(entity, Velocity);+ });+ });++ describe('despawn', () => {+ it('should despawn entity on flush', () => {+ const entity = (world.spawn as any)() as Entity;+ commands.despawn(entity);+ commands.flush();++ expect(world.despawn).toHaveBeenCalledWith(entity);+ });++ it('should skip despawn for invalid entity', () => {+ const entity = 999 as Entity;+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});++ commands.despawn(entity);+ commands.flush();++ expect(world.despawn).not.toHaveBeenCalled();+ expect(warnSpy).toHaveBeenCalledWith(+ expect.stringContaining('despawn skipped'),+ );+ warnSpy.mockRestore();+ });++ it('should support chaining', () => {+ const e1 = (world.spawn as any)() as Entity;+ const e2 = (world.spawn as any)() as Entity;+ commands.despawn(e1).despawn(e2);+ commands.flush();++ expect(world.despawn).toHaveBeenCalledTimes(2);+ });+ });++ describe('insert on invalid entity', () => {+ it('should skip insert for invalid entity', () => {+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});++ commands.queueInsert(999 as Entity, Position, { x: 0, y: 0 });+ commands.flush();++ expect(world.insert).not.toHaveBeenCalled();+ expect(warnSpy).toHaveBeenCalledWith(+ expect.stringContaining('insert skipped'),+ );+ warnSpy.mockRestore();+ });+ });++ describe('remove on invalid entity', () => {+ it('should skip remove for invalid entity', () => {+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});++ commands.queueRemove(999 as Entity, Position);+ commands.flush();++ expect(world.remove).not.toHaveBeenCalled();+ expect(warnSpy).toHaveBeenCalledWith(+ expect.stringContaining('remove skipped'),+ );+ warnSpy.mockRestore();+ });+ });++ describe('insertResource', () => {+ it('should insert resource on flush', () => {+ const TestRes = defineResource({ count: 0 }, 'TestRes');+ commands.insertResource(TestRes, { count: 42 });+ commands.flush();++ expect(resources.get(TestRes).count).toBe(42);+ });++ it('should support chaining', () => {+ const Res1 = defineResource({ a: 0 }, 'Res1');+ const Res2 = defineResource({ b: '' }, 'Res2');+ commands+ .insertResource(Res1, { a: 1 })+ .insertResource(Res2, { b: 'hello' });+ commands.flush();++ expect(resources.get(Res1).a).toBe(1);+ expect(resources.get(Res2).b).toBe('hello');+ });+ });++ describe('flush', () => {+ it('should finalize spawned entities before executing pending commands', () => {+ const spawnedEntity = (world.spawn as any)() as Entity;+ commands.spawn().insert(Position, { x: 1, y: 1 });+ commands.despawn(spawnedEntity);+ commands.flush();++ const spawnCalls = (world.spawn as any).mock.invocationCallOrder;+ const despawnCalls = (world.despawn as any).mock.invocationCallOrder;+ const lastSpawn = spawnCalls[spawnCalls.length - 1];+ const firstDespawn = despawnCalls[0];+ expect(lastSpawn).toBeLessThan(firstDespawn);+ });++ it('should clear pending queue after flush', () => {+ const entity = (world.spawn as any)() as Entity;+ commands.despawn(entity);+ commands.flush();++ vi.clearAllMocks();+ commands.flush();++ expect(world.despawn).not.toHaveBeenCalled();+ });++ it('should clear spawned queue after flush', () => {+ commands.spawn().insert(Position, { x: 1, y: 1 });+ commands.flush();++ vi.clearAllMocks();+ commands.flush();++ expect(world.spawn).not.toHaveBeenCalled();+ });+ });++ describe('EntityCommands.id()', () => {+ it('should return entity id after spawn is finalized', () => {+ const ec = commands.spawn().insert(Position, { x: 1, y: 1 });+ const id = ec.id();+ expect(id).toBeGreaterThan(0);+ });++ it('should trigger immediate finalization if not yet finalized', () => {+ const ec = commands.spawn();+ const id = ec.id();+ expect(world.spawn).toHaveBeenCalledOnce();+ expect(id).toBeGreaterThan(0);+ });++ it('should not double-spawn when id() then flush()', () => {+ const ec = commands.spawn().insert(Position, { x: 1, y: 1 });+ ec.id();+ commands.flush();++ expect(world.spawn).toHaveBeenCalledOnce();+ });+ });++ describe('EntityCommands - remove on new entity', () => {+ it('should be a no-op (remove before spawn has no effect)', () => {+ commands.spawn().remove(Position);+ commands.flush();++ expect(world.remove).not.toHaveBeenCalled();+ });+ });+});diff --git a/sdk/tests/event.test.ts b/sdk/tests/event.test.tsnew file mode 100644index 000000000..d10339efd--- /dev/null+++ b/sdk/tests/event.test.ts@@ -0,0 +1,305 @@+import { describe, it, expect, beforeEach } from 'vitest';+import {+ defineEvent,+ EventBus,+ EventRegistry,+ EventWriter,+ EventReader,+ EventWriterInstance,+ EventReaderInstance,+ EventWriterDescriptor,+ EventReaderDescriptor,+} from '../src/event';++// =============================================================================+// defineEvent+// =============================================================================++describe('defineEvent', () => {+ it('should create an event definition with unique symbol id', () => {+ const evt = defineEvent<{ x: number }>('TestEvent');+ expect(evt._name).toBe('TestEvent');+ expect(typeof evt._id).toBe('symbol');+ });++ it('should create unique ids for different events', () => {+ const a = defineEvent('A');+ const b = defineEvent('B');+ expect(a._id).not.toBe(b._id);+ });++ it('should create unique ids even for same name', () => {+ const a = defineEvent('Same');+ const b = defineEvent('Same');+ expect(a._id).not.toBe(b._id);+ });+});++// =============================================================================+// EventBus (double-buffered)+// =============================================================================++describe('EventBus', () => {+ let bus: EventBus<number>;++ beforeEach(() => {+ bus = new EventBus<number>();+ });++ it('should start with empty read buffer', () => {+ expect(bus.getReadBuffer()).toEqual([]);+ });++ it('should not expose sent events until swap', () => {+ bus.send(1);+ bus.send(2);+ expect(bus.getReadBuffer()).toEqual([]);+ });++ it('should expose sent events after swap', () => {+ bus.send(1);+ bus.send(2);+ bus.swap();+ expect(bus.getReadBuffer()).toEqual([1, 2]);+ });++ it('should clear write buffer on swap', () => {+ bus.send(1);+ bus.swap();+ bus.swap();+ expect(bus.getReadBuffer()).toEqual([]);+ });++ it('should support multiple swap cycles', () => {+ bus.send(10);+ bus.swap();+ expect(bus.getReadBuffer()).toEqual([10]);++ bus.send(20);+ bus.send(30);+ bus.swap();+ expect(bus.getReadBuffer()).toEqual([20, 30]);++ bus.swap();+ expect(bus.getReadBuffer()).toEqual([]);+ });++ it('should handle sending during read phase', () => {+ bus.send(1);+ bus.swap();++ bus.send(2);+ expect(bus.getReadBuffer()).toEqual([1]);++ bus.swap();+ expect(bus.getReadBuffer()).toEqual([2]);+ });+});++// =============================================================================+// EventRegistry+// =============================================================================++describe('EventRegistry', () => {+ let registry: EventRegistry;++ beforeEach(() => {+ registry = new EventRegistry();+ });++ it('should register and retrieve a bus', () => {+ const evt = defineEvent<string>('Msg');+ registry.register(evt);+ const bus = registry.getBus(evt);+ expect(bus).toBeInstanceOf(EventBus);+ });++ it('should return the same bus for the same event', () => {+ const evt = defineEvent<number>('Score');+ registry.register(evt);+ const bus1 = registry.getBus(evt);+ const bus2 = registry.getBus(evt);+ expect(bus1).toBe(bus2);+ });++ it('should auto-create bus on getBus if not registered', () => {+ const evt = defineEvent<number>('Auto');+ const bus = registry.getBus(evt);+ expect(bus).toBeInstanceOf(EventBus);+ });++ it('should not overwrite existing bus on duplicate register', () => {+ const evt = defineEvent<number>('Dup');+ registry.register(evt);+ const bus1 = registry.getBus(evt);+ registry.register(evt);+ const bus2 = registry.getBus(evt);+ expect(bus1).toBe(bus2);+ });++ it('should return different buses for different events', () => {+ const a = defineEvent<number>('A');+ const b = defineEvent<number>('B');+ const busA = registry.getBus(a);+ const busB = registry.getBus(b);+ expect(busA).not.toBe(busB);+ });++ it('should swap all buses at once', () => {+ const a = defineEvent<number>('A');+ const b = defineEvent<string>('B');+ const busA = registry.getBus(a);+ const busB = registry.getBus(b);++ busA.send(1);+ busB.send('hello');++ expect(busA.getReadBuffer()).toEqual([]);+ expect(busB.getReadBuffer()).toEqual([]);++ registry.swapAll();++ expect(busA.getReadBuffer()).toEqual([1]);+ expect(busB.getReadBuffer()).toEqual(['hello']);+ });+});++// =============================================================================+// Descriptors (EventWriter / EventReader factories)+// =============================================================================++describe('EventWriter descriptor', () => {+ it('should create a writer descriptor', () => {+ const evt = defineEvent<number>('Test');+ const desc: EventWriterDescriptor<number> = EventWriter(evt);+ expect(desc._type).toBe('event_writer');+ expect(desc._event).toBe(evt);+ });+});++describe('EventReader descriptor', () => {+ it('should create a reader descriptor', () => {+ const evt = defineEvent<number>('Test');+ const desc: EventReaderDescriptor<number> = EventReader(evt);+ expect(desc._type).toBe('event_reader');+ expect(desc._event).toBe(evt);+ });+});++// =============================================================================+// EventWriterInstance+// =============================================================================++describe('EventWriterInstance', () => {+ it('should send events to the underlying bus', () => {+ const bus = new EventBus<number>();+ const writer = new EventWriterInstance(bus);++ writer.send(42);+ writer.send(99);++ bus.swap();+ expect(bus.getReadBuffer()).toEqual([42, 99]);+ });+});++// =============================================================================+// EventReaderInstance+// =============================================================================++describe('EventReaderInstance', () => {+ let bus: EventBus<string>;+ let reader: EventReaderInstance<string>;++ beforeEach(() => {+ bus = new EventBus<string>();+ reader = new EventReaderInstance(bus);+ });++ it('should report isEmpty when no events', () => {+ bus.swap();+ expect(reader.isEmpty()).toBe(true);+ });++ it('should report not empty when events exist', () => {+ bus.send('a');+ bus.swap();+ expect(reader.isEmpty()).toBe(false);+ });++ it('should iterate over events', () => {+ bus.send('x');+ bus.send('y');+ bus.swap();++ const items: string[] = [];+ for (const e of reader) {+ items.push(e);+ }+ expect(items).toEqual(['x', 'y']);+ });++ it('should support spread via Symbol.iterator', () => {+ bus.send('a');+ bus.send('b');+ bus.swap();++ expect([...reader]).toEqual(['a', 'b']);+ });++ it('should return array via toArray()', () => {+ bus.send('p');+ bus.send('q');+ bus.swap();++ expect(reader.toArray()).toEqual(['p', 'q']);+ });++ it('should return empty array when no events', () => {+ bus.swap();+ expect(reader.toArray()).toEqual([]);+ });+});++// =============================================================================+// Integration: Writer -> swap -> Reader+// =============================================================================++describe('Writer -> swap -> Reader integration', () => {+ it('should pipe events from writer to reader through swap', () => {+ const evt = defineEvent<{ type: string; value: number }>('GameEvent');+ const registry = new EventRegistry();+ const bus = registry.getBus(evt);++ const writer = new EventWriterInstance(bus);+ const reader = new EventReaderInstance(bus);++ writer.send({ type: 'damage', value: 10 });+ writer.send({ type: 'heal', value: 5 });++ expect(reader.isEmpty()).toBe(true);++ registry.swapAll();++ expect(reader.isEmpty()).toBe(false);+ const events = reader.toArray();+ expect(events).toHaveLength(2);+ expect(events[0]).toEqual({ type: 'damage', value: 10 });+ expect(events[1]).toEqual({ type: 'heal', value: 5 });+ });++ it('should clear events after second swap', () => {+ const evt = defineEvent<number>('Tick');+ const registry = new EventRegistry();+ const bus = registry.getBus(evt);+ const writer = new EventWriterInstance(bus);+ const reader = new EventReaderInstance(bus);++ writer.send(1);+ registry.swapAll();+ expect(reader.toArray()).toEqual([1]);++ registry.swapAll();+ expect(reader.isEmpty()).toBe(true);+ });+});diff --git a/sdk/tests/geometry.test.ts b/sdk/tests/geometry.test.tsnew file mode 100644index 000000000..02af123c5--- /dev/null+++ b/sdk/tests/geometry.test.ts@@ -0,0 +1,479 @@+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';+import {+ Geometry,+ DataType,+ initGeometryAPI,+ shutdownGeometryAPI,+} from '../src/geometry';+import type { GeometryHandle } from '../src/geometry';+import type { ESEngineModule } from '../src/wasm';++// =============================================================================+// Mock WASM module for Geometry API+// =============================================================================++function createGeometryMockModule() {+ let nextHandle = 1;+ const validHandles = new Set<number>();+ const heapBuffer = new ArrayBuffer(1024 * 1024);++ const mock = {+ _malloc: vi.fn((size: number) => {+ return size;+ }),+ _free: vi.fn(),+ HEAPF32: new Float32Array(heapBuffer),+ HEAPU8: new Uint8Array(heapBuffer),+ geometry_create: vi.fn(() => {+ const h = nextHandle++;+ validHandles.add(h);+ return h;+ }),+ geometry_init: vi.fn(),+ geometry_setIndices16: vi.fn(),+ geometry_setIndices32: vi.fn(),+ geometry_updateVertices: vi.fn(),+ geometry_release: vi.fn((h: number) => {+ validHandles.delete(h);+ }),+ geometry_isValid: vi.fn((h: number) => validHandles.has(h)),++ _nextHandle: () => nextHandle,+ _validHandles: validHandles,+ };++ return mock;+}++type MockModule = ReturnType<typeof createGeometryMockModule>;++// =============================================================================+// Tests+// =============================================================================++describe('Geometry API', () => {+ let mock: MockModule;++ beforeEach(() => {+ mock = createGeometryMockModule();+ initGeometryAPI(mock as unknown as ESEngineModule);+ });++ afterEach(() => {+ shutdownGeometryAPI();+ });++ // =========================================================================+ // initGeometryAPI / shutdownGeometryAPI+ // =========================================================================++ describe('initGeometryAPI', () => {+ it('should allocate vertex, index, and layout buffers', () => {+ expect(mock._malloc).toHaveBeenCalledTimes(3);+ });+ });++ describe('shutdownGeometryAPI', () => {+ it('should free all allocated buffers', () => {+ shutdownGeometryAPI();+ expect(mock._free).toHaveBeenCalledTimes(3);+ });++ it('should handle double shutdown gracefully', () => {+ shutdownGeometryAPI();+ shutdownGeometryAPI();+ expect(mock._free).toHaveBeenCalledTimes(3);+ });+ });++ // =========================================================================+ // getModule guard+ // =========================================================================++ describe('uninitialized guard', () => {+ it('should throw when API not initialized', () => {+ shutdownGeometryAPI();+ expect(() => Geometry.create({+ vertices: new Float32Array([0, 0]),+ layout: [{ name: 'a_pos', type: DataType.Float2 }],+ })).toThrow('Geometry API not initialized');+ });+ });++ // =========================================================================+ // Geometry.create+ // =========================================================================++ describe('Geometry.create', () => {+ it('should create geometry and return a handle', () => {+ const handle = Geometry.create({+ vertices: new Float32Array([0, 0, 1, 0, 0, 1]),+ layout: [{ name: 'a_position', type: DataType.Float3 }],+ });++ expect(handle).toBeGreaterThan(0);+ expect(mock.geometry_create).toHaveBeenCalledOnce();+ expect(mock.geometry_init).toHaveBeenCalledOnce();+ });++ it('should pass vertex data to HEAPF32', () => {+ const verts = new Float32Array([1, 2, 3, 4]);+ Geometry.create({+ vertices: verts,+ layout: [{ name: 'a_pos', type: DataType.Float2 }],+ });++ expect(mock.geometry_init).toHaveBeenCalledWith(+ expect.any(Number),+ expect.any(Number),+ 4,+ expect.any(Number),+ 1,+ false,+ );+ });++ it('should pass layout types to geometry_init', () => {+ Geometry.create({+ vertices: new Float32Array([0, 0, 0, 0]),+ layout: [+ { name: 'a_position', type: DataType.Float2 },+ { name: 'a_texCoord', type: DataType.Float2 },+ ],+ });++ expect(mock.geometry_init).toHaveBeenCalledWith(+ expect.any(Number),+ expect.any(Number),+ 4,+ expect.any(Number),+ 2,+ false,+ );+ });++ it('should pass dynamic flag', () => {+ Geometry.create({+ vertices: new Float32Array([0, 0]),+ layout: [{ name: 'a_pos', type: DataType.Float2 }],+ dynamic: true,+ });++ expect(mock.geometry_init).toHaveBeenCalledWith(+ expect.any(Number),+ expect.any(Number),+ expect.any(Number),+ expect.any(Number),+ expect.any(Number),+ true,+ );+ });++ it('should default dynamic to false', () => {+ Geometry.create({+ vertices: new Float32Array([0, 0]),+ layout: [{ name: 'a_pos', type: DataType.Float2 }],+ });++ expect(mock.geometry_init).toHaveBeenCalledWith(+ expect.any(Number),+ expect.any(Number),+ expect.any(Number),+ expect.any(Number),+ expect.any(Number),+ false,+ );+ });++ it('should throw when geometry_create returns 0', () => {+ mock.geometry_create.mockReturnValueOnce(0);+ expect(() => Geometry.create({+ vertices: new Float32Array([0, 0]),+ layout: [{ name: 'a_pos', type: DataType.Float2 }],+ })).toThrow('Failed to create geometry');+ });++ it('should throw when vertex data exceeds buffer size', () => {+ const huge = new Float32Array(64 * 1024 + 1);+ expect(() => Geometry.create({+ vertices: huge,+ layout: [{ name: 'a_pos', type: DataType.Float }],+ })).toThrow('Vertex data too large');+ });++ // Indices+ it('should handle Uint16Array indices', () => {+ Geometry.create({+ vertices: new Float32Array([0, 0, 1, 0, 0, 1]),+ layout: [{ name: 'a_pos', type: DataType.Float2 }],+ indices: new Uint16Array([0, 1, 2]),+ });++ expect(mock.geometry_setIndices16).toHaveBeenCalledOnce();+ expect(mock.geometry_setIndices32).not.toHaveBeenCalled();+ });++ it('should handle Uint32Array indices', () => {+ Geometry.create({+ vertices: new Float32Array([0, 0, 1, 0, 0, 1]),+ layout: [{ name: 'a_pos', type: DataType.Float2 }],+ indices: new Uint32Array([0, 1, 2]),+ });++ expect(mock.geometry_setIndices32).toHaveBeenCalledOnce();+ expect(mock.geometry_setIndices16).not.toHaveBeenCalled();+ });++ it('should throw when index data exceeds buffer size', () => {+ const hugeIdx = new Uint16Array(16 * 1024 + 1);+ expect(() => Geometry.create({+ vertices: new Float32Array([0, 0]),+ layout: [{ name: 'a_pos', type: DataType.Float2 }],+ indices: hugeIdx,+ })).toThrow('Index data too large');+ });++ it('should not call setIndices when no indices provided', () => {+ Geometry.create({+ vertices: new Float32Array([0, 0]),+ layout: [{ name: 'a_pos', type: DataType.Float2 }],+ });++ expect(mock.geometry_setIndices16).not.toHaveBeenCalled();+ expect(mock.geometry_setIndices32).not.toHaveBeenCalled();+ });+ });++ // =========================================================================+ // Geometry.updateVertices+ // =========================================================================++ describe('Geometry.updateVertices', () => {+ it('should update vertices on a handle', () => {+ const handle = Geometry.create({+ vertices: new Float32Array([0, 0]),+ layout: [{ name: 'a_pos', type: DataType.Float2 }],+ dynamic: true,+ });++ const newVerts = new Float32Array([1, 1]);+ Geometry.updateVertices(handle, newVerts);++ expect(mock.geometry_updateVertices).toHaveBeenCalledWith(+ handle,+ expect.any(Number),+ 2,+ 0,+ );+ });++ it('should pass offset parameter', () => {+ const handle = Geometry.create({+ vertices: new Float32Array([0, 0]),+ layout: [{ name: 'a_pos', type: DataType.Float2 }],+ dynamic: true,+ });++ Geometry.updateVertices(handle, new Float32Array([5, 5]), 4);++ expect(mock.geometry_updateVertices).toHaveBeenCalledWith(+ handle,+ expect.any(Number),+ 2,+ 4,+ );+ });++ it('should throw when vertex data too large', () => {+ const handle = Geometry.create({+ vertices: new Float32Array([0, 0]),+ layout: [{ name: 'a_pos', type: DataType.Float2 }],+ dynamic: true,+ });++ const huge = new Float32Array(64 * 1024 + 1);+ expect(() => Geometry.updateVertices(handle, huge)).toThrow('Vertex data too large');+ });+ });++ // =========================================================================+ // Geometry.release+ // =========================================================================++ describe('Geometry.release', () => {+ it('should call geometry_release for valid handle', () => {+ const handle = Geometry.create({+ vertices: new Float32Array([0, 0]),+ layout: [{ name: 'a_pos', type: DataType.Float2 }],+ });++ Geometry.release(handle);+ expect(mock.geometry_release).toHaveBeenCalledWith(handle);+ });++ it('should skip release for handle <= 0', () => {+ Geometry.release(0);+ Geometry.release(-1 as GeometryHandle);+ expect(mock.geometry_release).not.toHaveBeenCalled();+ });+ });++ // =========================================================================+ // Geometry.isValid+ // =========================================================================++ describe('Geometry.isValid', () => {+ it('should return true for valid handle', () => {+ const handle = Geometry.create({+ vertices: new Float32Array([0, 0]),+ layout: [{ name: 'a_pos', type: DataType.Float2 }],+ });++ expect(Geometry.isValid(handle)).toBe(true);+ });++ it('should return false after release', () => {+ const handle = Geometry.create({+ vertices: new Float32Array([0, 0]),+ layout: [{ name: 'a_pos', type: DataType.Float2 }],+ });+ Geometry.release(handle);+ expect(Geometry.isValid(handle)).toBe(false);+ });++ it('should return false for handle <= 0', () => {+ expect(Geometry.isValid(0)).toBe(false);+ expect(Geometry.isValid(-1)).toBe(false);+ });++ it('should return false when module not initialized', () => {+ shutdownGeometryAPI();+ expect(Geometry.isValid(1)).toBe(false);+ });+ });++ // =========================================================================+ // Helper: createQuad+ // =========================================================================++ describe('Geometry.createQuad', () => {+ it('should create a unit quad by default', () => {+ const handle = Geometry.createQuad();+ expect(handle).toBeGreaterThan(0);+ expect(mock.geometry_create).toHaveBeenCalledOnce();+ expect(mock.geometry_setIndices16).toHaveBeenCalledOnce();+ });++ it('should create a quad with custom size', () => {+ const handle = Geometry.createQuad(2, 4);+ expect(handle).toBeGreaterThan(0);++ const initCall = mock.geometry_init.mock.calls[0];+ expect(initCall[2]).toBe(16);+ });++ it('should produce 4 vertices (16 floats: x,y,u,v each)', () => {+ Geometry.createQuad();+ const initCall = mock.geometry_init.mock.calls[0];+ expect(initCall[2]).toBe(16);+ });++ it('should produce 6 indices (two triangles)', () => {+ Geometry.createQuad();+ const indicesCall = mock.geometry_setIndices16.mock.calls[0];+ expect(indicesCall[2]).toBe(6);+ });+ });++ // =========================================================================+ // Helper: createCircle+ // =========================================================================++ describe('Geometry.createCircle', () => {+ it('should create a circle with default parameters', () => {+ const handle = Geometry.createCircle();+ expect(handle).toBeGreaterThan(0);+ });++ it('should have center + (segments+1) vertices', () => {+ const segments = 8;+ Geometry.createCircle(1, segments);+ const initCall = mock.geometry_init.mock.calls[0];+ const vertexFloats = initCall[2] as number;+ const vertexCount = vertexFloats / 4;+ expect(vertexCount).toBe(1 + segments + 1);+ });++ it('should have segments * 3 indices', () => {+ const segments = 8;+ Geometry.createCircle(1, segments);+ const indicesCall = mock.geometry_setIndices16.mock.calls[0];+ expect(indicesCall[2]).toBe(segments * 3);+ });+ });++ // =========================================================================+ // Helper: createPolygon+ // =========================================================================++ describe('Geometry.createPolygon', () => {+ it('should create a polygon from points', () => {+ const handle = Geometry.createPolygon([+ { x: 0, y: 0 },+ { x: 1, y: 0 },+ { x: 0, y: 1 },+ ]);+ expect(handle).toBeGreaterThan(0);+ });++ it('should throw with fewer than 3 points', () => {+ expect(() => Geometry.createPolygon([+ { x: 0, y: 0 },+ { x: 1, y: 0 },+ ])).toThrow('Polygon must have at least 3 points');+ });++ it('should produce correct vertex count', () => {+ const pts = [+ { x: 0, y: 0 },+ { x: 1, y: 0 },+ { x: 1, y: 1 },+ { x: 0, y: 1 },+ ];+ Geometry.createPolygon(pts);+ const initCall = mock.geometry_init.mock.calls[0];+ const vertexFloats = initCall[2] as number;+ expect(vertexFloats).toBe(pts.length * 4);+ });++ it('should produce fan triangulation indices', () => {+ const pts = [+ { x: 0, y: 0 },+ { x: 1, y: 0 },+ { x: 1, y: 1 },+ { x: 0, y: 1 },+ { x: -1, y: 0 },+ ];+ Geometry.createPolygon(pts);+ const indicesCall = mock.geometry_setIndices16.mock.calls[0];+ expect(indicesCall[2]).toBe((pts.length - 2) * 3);+ });+ });++ // =========================================================================+ // DataType enum+ // =========================================================================++ describe('DataType enum', () => {+ it('should have correct values', () => {+ expect(DataType.Float).toBe(1);+ expect(DataType.Float2).toBe(2);+ expect(DataType.Float3).toBe(3);+ expect(DataType.Float4).toBe(4);+ expect(DataType.Int).toBe(5);+ expect(DataType.Int2).toBe(6);+ expect(DataType.Int3).toBe(7);+ expect(DataType.Int4).toBe(8);+ });+ });+});diff --git a/sdk/tests/mocks/wasm.ts b/sdk/tests/mocks/wasm.tsindex 959be719f..2b5f321b8 100644--- a/sdk/tests/mocks/wasm.ts+++ b/sdk/tests/mocks/wasm.ts@@ -6,9 +6,33 @@ export function createMockModule(): ESEngineModule {const components = new Map<Entity, Map<string, any>>();let nextEntity = 1;- const registry: CppRegistry = {+ const baseRegistry = {+ create: () => {+ const entity = nextEntity++ as Entity;+ entities.add(entity);+ components.set(entity, new Map());+ return entity;+ },++ destroy: (entity: Entity) => {+ entities.delete(entity);+ components.delete(entity);+ },++ valid: (entity: Entity) => {+ return entities.has(entity);+ },++ entityCount: () => entities.size,++ setParent: (_child: Entity, _parent: Entity) => {},++ delete: () => {},+ removeParent: (_entity: Entity) => {},++ // Legacy names used by some internal code pathscreateEntity: () => {- const entity = nextEntity++;+ const entity = nextEntity++ as Entity;entities.add(entity);components.set(entity, new Map());return entity;@@ -53,6 +77,40 @@ export function createMockModule(): ESEngineModule {},};+ const registry = new Proxy(baseRegistry, {+ get(target, prop: string) {+ if (prop in target) {+ return (target as any)[prop];+ }+ if (prop.startsWith('add')) {+ const name = prop.slice(3);+ return (entity: Entity, data: any) => {+ components.get(entity)?.set(name, JSON.parse(JSON.stringify(data)));+ };+ }+ if (prop.startsWith('get') && prop !== 'getEntitiesWithComponents' && prop !== 'getComponentData') {+ const name = prop.slice(3);+ return (entity: Entity) => {+ const data = components.get(entity)?.get(name);+ return data ? JSON.parse(JSON.stringify(data)) : undefined;+ };+ }+ if (prop.startsWith('has') && prop !== 'hasComponent') {+ const name = prop.slice(3);+ return (entity: Entity) => {+ return components.get(entity)?.has(name) ?? false;+ };+ }+ if (prop.startsWith('remove') && prop !== 'removeComponent' && prop !== 'removeParent') {+ const name = prop.slice(6);+ return (entity: Entity) => {+ components.get(entity)?.delete(name);+ };+ }+ return undefined;+ },+ }) as unknown as CppRegistry;+const resourceManager: CppResourceManager = {loadTexture: () => 1,releaseTexture: () => {},diff --git a/sdk/tests/prefab.test.ts b/sdk/tests/prefab.test.tsnew file mode 100644index 000000000..dff77e4ed--- /dev/null+++ b/sdk/tests/prefab.test.ts@@ -0,0 +1,1007 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import type { PrefabData, PrefabOverride, InstantiatePrefabOptions } from '../src/prefab';+import type { SceneData } from '../src/scene';+import type { World } from '../src/world';+import type { Entity } from '../src/types';++vi.mock('../src/scene', async (importOriginal) => {+ const actual = await importOriginal<typeof import('../src/scene')>();+ return {+ ...actual,+ loadSceneWithAssets: vi.fn(),+ };+});++import { instantiatePrefab } from '../src/prefab';+import { loadSceneWithAssets, registerComponentEntityFields } from '../src/scene';++const mockLoadScene = vi.mocked(loadSceneWithAssets);++function createMockWorld(): World {+ const parentMap = new Map<Entity, Entity>();+ return {+ spawn: vi.fn(() => 0 as Entity),+ setParent: vi.fn((child: Entity, parent: Entity) => {+ parentMap.set(child, parent);+ }),+ insert: vi.fn(),+ get: vi.fn(),+ } as unknown as World;+}++function simplePrefab(overrides?: Partial<PrefabData>): PrefabData {+ return {+ version: '1.0',+ name: 'TestPrefab',+ rootEntityId: 0,+ entities: [+ {+ prefabEntityId: 0,+ name: 'Root',+ parent: null,+ children: [1],+ components: [+ { type: 'Transform', data: { x: 0, y: 0 } },+ ],+ visible: true,+ },+ {+ prefabEntityId: 1,+ name: 'Child',+ parent: 0,+ children: [],+ components: [+ { type: 'Sprite', data: { texture: 'test.png', color: 'red' } },+ ],+ visible: true,+ },+ ],+ ...overrides,+ };+}++describe('Prefab', () => {+ let world: World;+ let capturedSceneData: SceneData | null;++ beforeEach(() => {+ vi.clearAllMocks();+ world = createMockWorld();+ capturedSceneData = null;++ mockLoadScene.mockImplementation(async (_world, sceneData) => {+ capturedSceneData = sceneData;+ const entityMap = new Map<number, Entity>();+ for (const e of sceneData.entities) {+ entityMap.set(e.id, (e.id + 100) as Entity);+ }+ return entityMap;+ });+ });++ describe('instantiatePrefab - flat prefab', () => {+ it('should produce correct SceneData from a flat prefab', async () => {+ const prefab = simplePrefab();+ await instantiatePrefab(world, prefab);++ expect(capturedSceneData).not.toBeNull();+ expect(capturedSceneData!.version).toBe('1.0');+ expect(capturedSceneData!.name).toBe('TestPrefab');+ expect(capturedSceneData!.entities).toHaveLength(2);+ });++ it('should preserve entity IDs when no startId is provided', async () => {+ const prefab = simplePrefab();+ await instantiatePrefab(world, prefab);++ const ids = capturedSceneData!.entities.map(e => e.id);+ expect(ids).toEqual([0, 1]);+ });++ it('should preserve parent-child relationships', async () => {+ const prefab = simplePrefab();+ await instantiatePrefab(world, prefab);++ const root = capturedSceneData!.entities.find(e => e.id === 0)!;+ const child = capturedSceneData!.entities.find(e => e.id === 1)!;+ expect(root.parent).toBeNull();+ expect(child.parent).toBe(0);+ });++ it('should set root parent to null even if prefab has parent value', async () => {+ const prefab = simplePrefab();+ await instantiatePrefab(world, prefab);++ const root = capturedSceneData!.entities.find(e => e.id === 0)!;+ expect(root.parent).toBeNull();+ });++ it('should deep clone component data', async () => {+ const prefab = simplePrefab();+ await instantiatePrefab(world, prefab);++ const child = capturedSceneData!.entities.find(e => e.id === 1)!;+ child.components[0].data.texture = 'modified.png';+ expect(prefab.entities[1].components[0].data.texture).toBe('test.png');+ });++ it('should return root entity and entity map', async () => {+ const prefab = simplePrefab();+ const result = await instantiatePrefab(world, prefab);++ expect(result.root).toBe(100);+ expect(result.entities.size).toBe(2);+ expect(result.entities.get(0)).toBe(100);+ expect(result.entities.get(1)).toBe(101);+ });++ it('should filter children to only mapped entities', async () => {+ const prefab = simplePrefab();+ prefab.entities[0].children = [1, 999];+ await instantiatePrefab(world, prefab);++ const root = capturedSceneData!.entities.find(e => e.id === 0)!;+ expect(root.children).toEqual([1]);+ });++ it('should pass assetServer and assetBaseUrl to loadSceneWithAssets', async () => {+ const prefab = simplePrefab();+ const mockAssetServer = { loadPrefab: vi.fn() } as any;+ await instantiatePrefab(world, prefab, {+ assetServer: mockAssetServer,+ assetBaseUrl: '/assets',+ });++ expect(mockLoadScene).toHaveBeenCalledWith(+ world,+ expect.any(Object),+ { assetServer: mockAssetServer, assetBaseUrl: '/assets' },+ );+ });+ });++ describe('instantiatePrefab - parent option', () => {+ it('should call setParent when parent option is provided', async () => {+ const prefab = simplePrefab();+ const parentEntity = 42 as Entity;++ await instantiatePrefab(world, prefab, { parent: parentEntity });++ expect(world.setParent).toHaveBeenCalledWith(100, parentEntity);+ });++ it('should not call setParent when parent option is not provided', async () => {+ const prefab = simplePrefab();+ await instantiatePrefab(world, prefab);++ expect(world.setParent).not.toHaveBeenCalled();+ });+ });++ describe('property overrides', () => {+ it('should apply property override to matching component', async () => {+ const prefab = simplePrefab();+ const overrides: PrefabOverride[] = [{+ prefabEntityId: 1,+ type: 'property',+ componentType: 'Sprite',+ propertyName: 'color',+ value: 'blue',+ }];++ await instantiatePrefab(world, prefab, { overrides });++ const child = capturedSceneData!.entities.find(e => e.id === 1)!;+ const sprite = child.components.find(c => c.type === 'Sprite')!;+ expect(sprite.data.color).toBe('blue');+ });++ it('should not modify non-matching entity', async () => {+ const prefab = simplePrefab();+ const overrides: PrefabOverride[] = [{+ prefabEntityId: 0,+ type: 'property',+ componentType: 'Transform',+ propertyName: 'x',+ value: 99,+ }];++ await instantiatePrefab(world, prefab, { overrides });++ const child = capturedSceneData!.entities.find(e => e.id === 1)!;+ const sprite = child.components.find(c => c.type === 'Sprite')!;+ expect(sprite.data.color).toBe('red');+ });++ it('should ignore property override for non-existing component', async () => {+ const prefab = simplePrefab();+ const overrides: PrefabOverride[] = [{+ prefabEntityId: 1,+ type: 'property',+ componentType: 'NonExistent',+ propertyName: 'x',+ value: 42,+ }];++ await instantiatePrefab(world, prefab, { overrides });++ const child = capturedSceneData!.entities.find(e => e.id === 1)!;+ expect(child.components).toHaveLength(1);+ expect(child.components[0].type).toBe('Sprite');+ });+ });++ describe('name overrides', () => {+ it('should apply name override', async () => {+ const prefab = simplePrefab();+ const overrides: PrefabOverride[] = [{+ prefabEntityId: 1,+ type: 'name',+ value: 'RenamedChild',+ }];++ await instantiatePrefab(world, prefab, { overrides });++ const child = capturedSceneData!.entities.find(e => e.id === 1)!;+ expect(child.name).toBe('RenamedChild');+ });++ it('should ignore name override with non-string value', async () => {+ const prefab = simplePrefab();+ const overrides: PrefabOverride[] = [{+ prefabEntityId: 1,+ type: 'name',+ value: 42,+ }];++ await instantiatePrefab(world, prefab, { overrides });++ const child = capturedSceneData!.entities.find(e => e.id === 1)!;+ expect(child.name).toBe('Child');+ });+ });++ describe('visibility overrides', () => {+ it('should apply visibility override', async () => {+ const prefab = simplePrefab();+ const overrides: PrefabOverride[] = [{+ prefabEntityId: 1,+ type: 'visibility',+ value: false,+ }];++ await instantiatePrefab(world, prefab, { overrides });++ const child = capturedSceneData!.entities.find(e => e.id === 1)!;+ expect(child.visible).toBe(false);+ });++ it('should ignore visibility override with non-boolean value', async () => {+ const prefab = simplePrefab();+ const overrides: PrefabOverride[] = [{+ prefabEntityId: 1,+ type: 'visibility',+ value: 'false',+ }];++ await instantiatePrefab(world, prefab, { overrides });++ const child = capturedSceneData!.entities.find(e => e.id === 1)!;+ expect(child.visible).toBe(true);+ });+ });++ describe('component_added overrides', () => {+ it('should add a new component via override', async () => {+ const prefab = simplePrefab();+ const overrides: PrefabOverride[] = [{+ prefabEntityId: 1,+ type: 'component_added',+ componentData: { type: 'Health', data: { value: 50 } },+ }];++ await instantiatePrefab(world, prefab, { overrides });++ const child = capturedSceneData!.entities.find(e => e.id === 1)!;+ expect(child.components).toHaveLength(2);+ const health = child.components.find(c => c.type === 'Health')!;+ expect(health.data.value).toBe(50);+ });++ it('should not add duplicate component', async () => {+ const prefab = simplePrefab();+ const overrides: PrefabOverride[] = [{+ prefabEntityId: 1,+ type: 'component_added',+ componentData: { type: 'Sprite', data: { texture: 'new.png' } },+ }];++ await instantiatePrefab(world, prefab, { overrides });++ const child = capturedSceneData!.entities.find(e => e.id === 1)!;+ const sprites = child.components.filter(c => c.type === 'Sprite');+ expect(sprites).toHaveLength(1);+ expect(sprites[0].data.texture).toBe('test.png');+ });++ it('should deep clone component_added data', async () => {+ const componentData = { type: 'Health', data: { value: 50 } };+ const overrides: PrefabOverride[] = [{+ prefabEntityId: 1,+ type: 'component_added',+ componentData,+ }];++ await instantiatePrefab(world, simplePrefab(), { overrides });++ const child = capturedSceneData!.entities.find(e => e.id === 1)!;+ const health = child.components.find(c => c.type === 'Health')!;+ health.data.value = 999;+ expect(componentData.data.value).toBe(50);+ });++ it('should ignore component_added without componentData', async () => {+ const prefab = simplePrefab();+ const overrides: PrefabOverride[] = [{+ prefabEntityId: 1,+ type: 'component_added',+ }];++ await instantiatePrefab(world, prefab, { overrides });++ const child = capturedSceneData!.entities.find(e => e.id === 1)!;+ expect(child.components).toHaveLength(1);+ });+ });++ describe('component_removed overrides', () => {+ it('should remove a component via override', async () => {+ const prefab = simplePrefab();+ const overrides: PrefabOverride[] = [{+ prefabEntityId: 1,+ type: 'component_removed',+ componentType: 'Sprite',+ }];++ await instantiatePrefab(world, prefab, { overrides });++ const child = capturedSceneData!.entities.find(e => e.id === 1)!;+ expect(child.components).toHaveLength(0);+ });++ it('should ignore removal of non-existing component', async () => {+ const prefab = simplePrefab();+ const overrides: PrefabOverride[] = [{+ prefabEntityId: 1,+ type: 'component_removed',+ componentType: 'NonExistent',+ }];++ await instantiatePrefab(world, prefab, { overrides });++ const child = capturedSceneData!.entities.find(e => e.id === 1)!;+ expect(child.components).toHaveLength(1);+ });+ });++ describe('entity reference remapping', () => {+ beforeEach(() => {+ registerComponentEntityFields('Slider', ['fillEntity', 'handleEntity']);+ });++ it('should remap entity references in components', async () => {+ const prefab: PrefabData = {+ version: '1.0',+ name: 'SliderPrefab',+ rootEntityId: 0,+ entities: [+ {+ prefabEntityId: 0,+ name: 'SliderRoot',+ parent: null,+ children: [1, 2],+ components: [+ { type: 'Slider', data: { fillEntity: 1, handleEntity: 2, value: 0.5 } },+ ],+ visible: true,+ },+ {+ prefabEntityId: 1,+ name: 'Fill',+ parent: 0,+ children: [],+ components: [],+ visible: true,+ },+ {+ prefabEntityId: 2,+ name: 'Handle',+ parent: 0,+ children: [],+ components: [],+ visible: true,+ },+ ],+ };++ await instantiatePrefab(world, prefab);++ const root = capturedSceneData!.entities.find(e => e.id === 0)!;+ const slider = root.components.find(c => c.type === 'Slider')!;+ expect(slider.data.fillEntity).toBe(1);+ expect(slider.data.handleEntity).toBe(2);+ expect(slider.data.value).toBe(0.5);+ });++ it('should not remap zero entity references', async () => {+ const prefab: PrefabData = {+ version: '1.0',+ name: 'SliderPrefab',+ rootEntityId: 0,+ entities: [+ {+ prefabEntityId: 0,+ name: 'SliderRoot',+ parent: null,+ children: [],+ components: [+ { type: 'Slider', data: { fillEntity: 0, handleEntity: 0, value: 0 } },+ ],+ visible: true,+ },+ ],+ };++ await instantiatePrefab(world, prefab);++ const root = capturedSceneData!.entities.find(e => e.id === 0)!;+ const slider = root.components.find(c => c.type === 'Slider')!;+ expect(slider.data.fillEntity).toBe(0);+ expect(slider.data.handleEntity).toBe(0);+ });++ it('should skip components without entity fields', async () => {+ const prefab: PrefabData = {+ version: '1.0',+ name: 'Test',+ rootEntityId: 0,+ entities: [{+ prefabEntityId: 0,+ name: 'Root',+ parent: null,+ children: [],+ components: [+ { type: 'Transform', data: { x: 10, y: 20 } },+ ],+ visible: true,+ }],+ };++ await instantiatePrefab(world, prefab);++ const root = capturedSceneData!.entities.find(e => e.id === 0)!;+ expect(root.components[0].data.x).toBe(10);+ });+ });++ describe('nested prefabs', () => {+ it('should flatten nested prefab entities into parent', async () => {+ const childPrefab: PrefabData = {+ version: '1.0',+ name: 'ChildPrefab',+ rootEntityId: 0,+ entities: [{+ prefabEntityId: 0,+ name: 'NestedRoot',+ parent: null,+ children: [],+ components: [{ type: 'Transform', data: { x: 5 } }],+ visible: true,+ }],+ };++ const parentPrefab: PrefabData = {+ version: '1.0',+ name: 'ParentPrefab',+ rootEntityId: 0,+ entities: [+ {+ prefabEntityId: 0,+ name: 'ParentRoot',+ parent: null,+ children: [1],+ components: [{ type: 'Transform', data: { x: 0 } }],+ visible: true,+ },+ {+ prefabEntityId: 1,+ name: 'NestedSlot',+ parent: 0,+ children: [],+ components: [],+ visible: true,+ nestedPrefab: {+ prefabPath: 'child.prefab',+ overrides: [],+ },+ },+ ],+ };++ const mockAssetServer = {+ loadPrefab: vi.fn().mockResolvedValue(childPrefab),+ } as any;++ await instantiatePrefab(world, parentPrefab, { assetServer: mockAssetServer });++ expect(capturedSceneData!.entities).toHaveLength(2);+ const names = capturedSceneData!.entities.map(e => e.name);+ expect(names).toContain('ParentRoot');+ expect(names).toContain('NestedRoot');+ });++ it('should remap nested prefab entity IDs to avoid collisions', async () => {+ const childPrefab: PrefabData = {+ version: '1.0',+ name: 'ChildPrefab',+ rootEntityId: 0,+ entities: [+ {+ prefabEntityId: 0,+ name: 'NestedRoot',+ parent: null,+ children: [1],+ components: [],+ visible: true,+ },+ {+ prefabEntityId: 1,+ name: 'NestedChild',+ parent: 0,+ children: [],+ components: [],+ visible: true,+ },+ ],+ };++ const parentPrefab: PrefabData = {+ version: '1.0',+ name: 'ParentPrefab',+ rootEntityId: 0,+ entities: [+ {+ prefabEntityId: 0,+ name: 'ParentRoot',+ parent: null,+ children: [1],+ components: [],+ visible: true,+ },+ {+ prefabEntityId: 1,+ name: 'NestedSlot',+ parent: 0,+ children: [],+ components: [],+ visible: true,+ nestedPrefab: {+ prefabPath: 'child.prefab',+ overrides: [],+ },+ },+ ],+ };++ const mockAssetServer = {+ loadPrefab: vi.fn().mockResolvedValue(childPrefab),+ } as any;++ await instantiatePrefab(world, parentPrefab, { assetServer: mockAssetServer });++ const ids = capturedSceneData!.entities.map(e => e.id);+ const uniqueIds = new Set(ids);+ expect(uniqueIds.size).toBe(ids.length);+ });++ it('should set nested root parent to slot parent', async () => {+ const childPrefab: PrefabData = {+ version: '1.0',+ name: 'ChildPrefab',+ rootEntityId: 0,+ entities: [{+ prefabEntityId: 0,+ name: 'NestedRoot',+ parent: null,+ children: [],+ components: [],+ visible: true,+ }],+ };++ const parentPrefab: PrefabData = {+ version: '1.0',+ name: 'ParentPrefab',+ rootEntityId: 0,+ entities: [+ {+ prefabEntityId: 0,+ name: 'ParentRoot',+ parent: null,+ children: [1],+ components: [],+ visible: true,+ },+ {+ prefabEntityId: 1,+ name: 'NestedSlot',+ parent: 0,+ children: [],+ components: [],+ visible: true,+ nestedPrefab: {+ prefabPath: 'child.prefab',+ overrides: [],+ },+ },+ ],+ };++ const mockAssetServer = {+ loadPrefab: vi.fn().mockResolvedValue(childPrefab),+ } as any;++ await instantiatePrefab(world, parentPrefab, { assetServer: mockAssetServer });++ const nestedRoot = capturedSceneData!.entities.find(e => e.name === 'NestedRoot')!;+ expect(nestedRoot.parent).toBe(0);+ });++ it('should apply overrides to nested prefab entities', async () => {+ const childPrefab: PrefabData = {+ version: '1.0',+ name: 'ChildPrefab',+ rootEntityId: 0,+ entities: [{+ prefabEntityId: 0,+ name: 'NestedRoot',+ parent: null,+ children: [],+ components: [{ type: 'Sprite', data: { color: 'red' } }],+ visible: true,+ }],+ };++ const parentPrefab: PrefabData = {+ version: '1.0',+ name: 'ParentPrefab',+ rootEntityId: 0,+ entities: [+ {+ prefabEntityId: 0,+ name: 'ParentRoot',+ parent: null,+ children: [1],+ components: [],+ visible: true,+ },+ {+ prefabEntityId: 1,+ name: 'NestedSlot',+ parent: 0,+ children: [],+ components: [],+ visible: true,+ nestedPrefab: {+ prefabPath: 'child.prefab',+ overrides: [{+ prefabEntityId: 0,+ type: 'property',+ componentType: 'Sprite',+ propertyName: 'color',+ value: 'green',+ }],+ },+ },+ ],+ };++ const mockAssetServer = {+ loadPrefab: vi.fn().mockResolvedValue(childPrefab),+ } as any;++ await instantiatePrefab(world, parentPrefab, { assetServer: mockAssetServer });++ const nestedRoot = capturedSceneData!.entities.find(e => e.name === 'NestedRoot')!;+ const sprite = nestedRoot.components.find(c => c.type === 'Sprite')!;+ expect(sprite.data.color).toBe('green');+ });++ it('should detect circular reference', async () => {+ const selfRefPrefab: PrefabData = {+ version: '1.0',+ name: 'SelfRef',+ rootEntityId: 0,+ entities: [+ {+ prefabEntityId: 0,+ name: 'Root',+ parent: null,+ children: [1],+ components: [],+ visible: true,+ },+ {+ prefabEntityId: 1,+ name: 'Nested',+ parent: 0,+ children: [],+ components: [],+ visible: true,+ nestedPrefab: {+ prefabPath: 'self.prefab',+ overrides: [],+ },+ },+ ],+ };++ const mockAssetServer = {+ loadPrefab: vi.fn().mockResolvedValue(selfRefPrefab),+ } as any;++ await expect(+ instantiatePrefab(world, selfRefPrefab, { assetServer: mockAssetServer }),+ ).rejects.toThrow('Circular reference detected');+ });++ it('should throw when nesting depth exceeds maximum', async () => {+ const deepPrefab: PrefabData = {+ version: '1.0',+ name: 'Deep',+ rootEntityId: 0,+ entities: [+ {+ prefabEntityId: 0,+ name: 'Root',+ parent: null,+ children: [1],+ components: [],+ visible: true,+ },+ {+ prefabEntityId: 1,+ name: 'Nested',+ parent: 0,+ children: [],+ components: [],+ visible: true,+ nestedPrefab: {+ prefabPath: 'deep.prefab',+ overrides: [],+ },+ },+ ],+ };++ let callCount = 0;+ const mockAssetServer = {+ loadPrefab: vi.fn().mockImplementation(() => {+ callCount++;+ return Promise.resolve({+ ...deepPrefab,+ name: `Deep_${callCount}`,+ entities: deepPrefab.entities.map(e => ({+ ...e,+ nestedPrefab: e.nestedPrefab+ ? { ...e.nestedPrefab, prefabPath: `deep_${callCount}.prefab` }+ : undefined,+ })),+ });+ }),+ } as any;++ await expect(+ instantiatePrefab(world, deepPrefab, { assetServer: mockAssetServer }),+ ).rejects.toThrow('nesting depth exceeded');+ });++ it('should throw when nested prefab requires AssetServer but none provided', async () => {+ const parentPrefab: PrefabData = {+ version: '1.0',+ name: 'Parent',+ rootEntityId: 0,+ entities: [+ {+ prefabEntityId: 0,+ name: 'Root',+ parent: null,+ children: [1],+ components: [],+ visible: true,+ },+ {+ prefabEntityId: 1,+ name: 'Nested',+ parent: 0,+ children: [],+ components: [],+ visible: true,+ nestedPrefab: {+ prefabPath: 'child.prefab',+ overrides: [],+ },+ },+ ],+ };++ await expect(+ instantiatePrefab(world, parentPrefab),+ ).rejects.toThrow('AssetServer required');+ });+ });++ describe('multiple overrides on same entity', () => {+ it('should apply multiple override types together', async () => {+ const prefab = simplePrefab();+ const overrides: PrefabOverride[] = [+ {+ prefabEntityId: 1,+ type: 'name',+ value: 'RenamedChild',+ },+ {+ prefabEntityId: 1,+ type: 'property',+ componentType: 'Sprite',+ propertyName: 'color',+ value: 'blue',+ },+ {+ prefabEntityId: 1,+ type: 'component_added',+ componentData: { type: 'Health', data: { value: 100 } },+ },+ ];++ await instantiatePrefab(world, prefab, { overrides });++ const child = capturedSceneData!.entities.find(e => e.id === 1)!;+ expect(child.name).toBe('RenamedChild');+ expect(child.components.find(c => c.type === 'Sprite')!.data.color).toBe('blue');+ expect(child.components.find(c => c.type === 'Health')!.data.value).toBe(100);+ });+ });++ describe('nested prefab edge cases', () => {+ it('should set nested root parent to null when slot has null parent', async () => {+ const childPrefab: PrefabData = {+ version: '1.0',+ name: 'ChildPrefab',+ rootEntityId: 0,+ entities: [{+ prefabEntityId: 0,+ name: 'NestedRoot',+ parent: null,+ children: [],+ components: [],+ visible: true,+ }],+ };++ const parentPrefab: PrefabData = {+ version: '1.0',+ name: 'ParentPrefab',+ rootEntityId: 0,+ entities: [{+ prefabEntityId: 0,+ name: 'Slot',+ parent: null,+ children: [],+ components: [],+ visible: true,+ nestedPrefab: {+ prefabPath: 'child.prefab',+ overrides: [],+ },+ }],+ };++ const mockAssetServer = {+ loadPrefab: vi.fn().mockResolvedValue(childPrefab),+ } as any;++ await instantiatePrefab(world, parentPrefab, { assetServer: mockAssetServer });++ const nestedRoot = capturedSceneData!.entities.find(e => e.name === 'NestedRoot')!;+ expect(nestedRoot.parent).toBeNull();+ });++ it('should throw when root entity ID only appears in nested prefabs', async () => {+ const prefab: PrefabData = {+ version: '1.0',+ name: 'BadPrefab',+ rootEntityId: 99,+ entities: [{+ prefabEntityId: 0,+ name: 'Root',+ parent: null,+ children: [],+ components: [],+ visible: true,+ }],+ };++ await expect(+ instantiatePrefab(world, prefab),+ ).rejects.toThrow('Failed to resolve prefab root entity');+ });+ });++ describe('edge cases', () => {+ it('should handle prefab with single entity', async () => {+ const prefab: PrefabData = {+ version: '1.0',+ name: 'SingleEntity',+ rootEntityId: 0,+ entities: [{+ prefabEntityId: 0,+ name: 'OnlyEntity',+ parent: null,+ children: [],+ components: [],+ visible: true,+ }],+ };++ const result = await instantiatePrefab(world, prefab);++ expect(capturedSceneData!.entities).toHaveLength(1);+ expect(result.root).toBe(100);+ });++ it('should handle non-sequential entity IDs', async () => {+ const prefab: PrefabData = {+ version: '1.0',+ name: 'NonSequential',+ rootEntityId: 5,+ entities: [+ {+ prefabEntityId: 5,+ name: 'Root',+ parent: null,+ children: [10],+ components: [],+ visible: true,+ },+ {+ prefabEntityId: 10,+ name: 'Child',+ parent: 5,+ children: [],+ components: [],+ visible: true,+ },+ ],+ };++ await instantiatePrefab(world, prefab);++ expect(capturedSceneData!.entities).toHaveLength(2);+ const root = capturedSceneData!.entities.find(e => e.name === 'Root')!;+ const child = capturedSceneData!.entities.find(e => e.name === 'Child')!;+ expect(root.id).toBe(5);+ expect(child.id).toBe(10);+ expect(child.parent).toBe(5);+ });++ it('should handle empty overrides array', async () => {+ const prefab = simplePrefab();+ await instantiatePrefab(world, prefab, { overrides: [] });++ const child = capturedSceneData!.entities.find(e => e.id === 1)!;+ expect(child.name).toBe('Child');+ expect(child.components[0].data.color).toBe('red');+ });+ });+});diff --git a/sdk/tests/scene.test.ts b/sdk/tests/scene.test.tsnew file mode 100644index 000000000..087b4ca96--- /dev/null+++ b/sdk/tests/scene.test.ts@@ -0,0 +1,1151 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';+import { World } from '../src/world';+import { createMockModule } from './mocks/wasm';+import { defineComponent, defineBuiltin, Name, Camera } from '../src/component';+import { INVALID_ENTITY } from '../src/types';+import {+ loadSceneData,+ loadSceneWithAssets,+ loadComponent,+ remapEntityFields,+ findEntityByName,+ updateCameraAspectRatio,+ registerComponentAssetFields,+ getComponentAssetFields,+ getComponentAssetFieldDescriptors,+ getComponentSpineFieldDescriptor,+ getRegisteredAssetComponentTypes,+ registerComponentEntityFields,+ getComponentEntityFields,+ type SceneData,+ type SceneComponentData,+} from '../src/scene';+import type { Entity } from '../src/types';++const Transform = defineBuiltin('Transform', {+ position: { x: 0, y: 0, z: 0 },+ rotation: { w: 1, x: 0, y: 0, z: 0 },+ scale: { x: 1, y: 1, z: 1 },+});++const UIRect = defineBuiltin('UIRect', {+ anchorMin: { x: 0, y: 0 },+ anchorMax: { x: 1, y: 1 },+ offsetMin: { x: 0, y: 0 },+ offsetMax: { x: 0, y: 0 },+ size: { x: 100, y: 100 },+ pivot: { x: 0.5, y: 0.5 },+});++const UIMask = defineBuiltin('UIMask', {+ mode: 0,+ enabled: true,+});++const Sprite = defineBuiltin('Sprite', {+ texture: 0,+ color: { x: 1, y: 1, z: 1, w: 1 },+ size: { x: 100, y: 100 },+ material: 0,+});++describe('Scene', () => {+ let world: World;++ beforeEach(() => {+ const module = createMockModule();+ world = new World();+ world.connectCpp(module.getRegistry(), module);+ });++ // =========================================================================+ // Component Asset Field Registry+ // =========================================================================++ describe('Component Asset Field Registry', () => {+ it('should return asset fields for registered components', () => {+ const fields = getComponentAssetFields('Sprite');+ expect(fields).toContain('texture');+ expect(fields).toContain('material');+ });++ it('should return empty array for unregistered component', () => {+ const fields = getComponentAssetFields('NonExistent');+ expect(fields).toEqual([]);+ });++ it('should include spine fields when present', () => {+ const fields = getComponentAssetFields('SpineAnimation');+ expect(fields).toContain('skeletonPath');+ expect(fields).toContain('atlasPath');+ expect(fields).toContain('material');+ });++ it('should register custom component asset fields', () => {+ registerComponentAssetFields('CustomComp', {+ fields: [{ field: 'icon', type: 'texture' }],+ });+ const fields = getComponentAssetFields('CustomComp');+ expect(fields).toContain('icon');+ });++ it('should return field descriptors with type info', () => {+ const descriptors = getComponentAssetFieldDescriptors('Sprite');+ expect(descriptors).toEqual([+ { field: 'texture', type: 'texture' },+ { field: 'material', type: 'material' },+ ]);+ });++ it('should return empty array for unregistered descriptors', () => {+ expect(getComponentAssetFieldDescriptors('NonExistent')).toEqual([]);+ });++ it('should return spine field descriptor', () => {+ const spine = getComponentSpineFieldDescriptor('SpineAnimation');+ expect(spine).toEqual({+ skeletonField: 'skeletonPath',+ atlasField: 'atlasPath',+ });+ });++ it('should return null spine descriptor for non-spine component', () => {+ expect(getComponentSpineFieldDescriptor('Sprite')).toBeNull();+ });++ it('should list all registered asset component types', () => {+ const types = getRegisteredAssetComponentTypes();+ expect(types).toContain('Sprite');+ expect(types).toContain('SpineAnimation');+ expect(types).toContain('BitmapText');+ expect(types).toContain('Image');+ expect(types).toContain('SpriteAnimator');+ });+ });++ // =========================================================================+ // Component Entity Reference Fields Registry+ // =========================================================================++ describe('Component Entity Reference Fields Registry', () => {+ it('should return entity fields for registered types', () => {+ const fields = getComponentEntityFields('Slider');+ expect(fields).toEqual(['fillEntity', 'handleEntity']);+ });++ it('should return undefined for unregistered types', () => {+ expect(getComponentEntityFields('NonExistent')).toBeUndefined();+ });++ it('should register custom entity fields', () => {+ registerComponentEntityFields('CustomUI', ['targetEntity']);+ expect(getComponentEntityFields('CustomUI')).toEqual(['targetEntity']);+ });+ });++ // =========================================================================+ // remapEntityFields+ // =========================================================================++ describe('remapEntityFields', () => {+ it('should remap entity references using entityMap', () => {+ const compData: SceneComponentData = {+ type: 'Slider',+ data: { fillEntity: 10, handleEntity: 20, value: 0.5 },+ };+ const entityMap = new Map<number, Entity>([+ [10, 100 as Entity],+ [20, 200 as Entity],+ ]);++ remapEntityFields(compData, entityMap);++ expect(compData.data.fillEntity).toBe(100);+ expect(compData.data.handleEntity).toBe(200);+ expect(compData.data.value).toBe(0.5);+ });++ it('should set INVALID_ENTITY for missing entity references', () => {+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const compData: SceneComponentData = {+ type: 'Slider',+ data: { fillEntity: 999, handleEntity: 0 },+ };+ const entityMap = new Map<number, Entity>();++ remapEntityFields(compData, entityMap);++ expect(compData.data.fillEntity).toBe(INVALID_ENTITY);+ expect(warnSpy).toHaveBeenCalledWith(+ expect.stringContaining('Entity reference not found'),+ );+ warnSpy.mockRestore();+ });++ it('should not remap INVALID_ENTITY (0) references', () => {+ const compData: SceneComponentData = {+ type: 'Slider',+ data: { fillEntity: INVALID_ENTITY, handleEntity: INVALID_ENTITY },+ };+ const entityMap = new Map<number, Entity>();++ remapEntityFields(compData, entityMap);++ expect(compData.data.fillEntity).toBe(INVALID_ENTITY);+ expect(compData.data.handleEntity).toBe(INVALID_ENTITY);+ });++ it('should skip components without entity fields', () => {+ const compData: SceneComponentData = {+ type: 'Transform',+ data: { x: 10, y: 20 },+ };+ const entityMap = new Map<number, Entity>();++ remapEntityFields(compData, entityMap);++ expect(compData.data.x).toBe(10);+ expect(compData.data.y).toBe(20);+ });++ it('should skip non-number entity field values', () => {+ const compData: SceneComponentData = {+ type: 'Slider',+ data: { fillEntity: 'not-a-number', handleEntity: null },+ };+ const entityMap = new Map<number, Entity>();++ remapEntityFields(compData, entityMap);++ expect(compData.data.fillEntity).toBe('not-a-number');+ expect(compData.data.handleEntity).toBeNull();+ });+ });++ // =========================================================================+ // loadComponent+ // =========================================================================++ describe('loadComponent', () => {+ it('should load a known component', () => {+ const entity = world.spawn();+ loadComponent(world, entity, {+ type: 'Transform',+ data: { position: { x: 10, y: 20, z: 0 } },+ });++ const transform = world.get(entity, Transform);+ expect(transform.position.x).toBe(10);+ expect(transform.position.y).toBe(20);+ });++ it('should convert LocalTransform to Transform', () => {+ const entity = world.spawn();+ const compData: SceneComponentData = {+ type: 'LocalTransform',+ data: { position: { x: 5, y: 5, z: 0 } },+ };+ loadComponent(world, entity, compData);++ expect(compData.type).toBe('Transform');+ expect(world.has(entity, Transform)).toBe(true);+ });++ it('should convert WorldTransform to Transform', () => {+ const entity = world.spawn();+ const compData: SceneComponentData = {+ type: 'WorldTransform',+ data: {},+ };+ loadComponent(world, entity, compData);++ expect(compData.type).toBe('Transform');+ });++ it('should convert legacy UIRect anchor to anchorMin/anchorMax', () => {+ const entity = world.spawn();+ loadComponent(world, entity, {+ type: 'UIRect',+ data: { anchor: { x: 0.5, y: 0.5 } },+ });++ const rect = world.get(entity, UIRect);+ expect(rect.anchorMin).toEqual({ x: 0.5, y: 0.5 });+ expect(rect.anchorMax).toEqual({ x: 0.5, y: 0.5 });+ });++ it('should not overwrite existing anchorMin with legacy anchor', () => {+ const compData = {+ type: 'UIRect',+ data: {+ anchor: { x: 0, y: 0 },+ anchorMin: { x: 0.1, y: 0.1 },+ anchorMax: { x: 0.9, y: 0.9 },+ } as Record<string, unknown>,+ };++ expect(compData.data.anchorMin).toEqual({ x: 0.1, y: 0.1 });+ expect(compData.data.anchor).toBeDefined();++ // When anchorMin exists, anchor field is NOT converted+ // (anchor stays in data, conversion is skipped)+ loadComponent(world, world.spawn(), {+ type: 'UIRect',+ data: { anchorMin: { x: 0.1, y: 0.1 }, anchorMax: { x: 0.9, y: 0.9 } },+ });++ const entity = world.getEntitiesWithComponents([UIRect])[0];+ const rect = world.get(entity, UIRect);+ expect(rect.anchorMin).toEqual({ x: 0.1, y: 0.1 });+ });++ it('should convert UIMask mode string "scissor" to 0', () => {+ const entity = world.spawn();+ loadComponent(world, entity, {+ type: 'UIMask',+ data: { mode: 'scissor' },+ });++ const mask = world.get(entity, UIMask);+ expect(mask.mode).toBe(0);+ });++ it('should convert UIMask mode string "stencil" to 1', () => {+ const entity = world.spawn();+ loadComponent(world, entity, {+ type: 'UIMask',+ data: { mode: 'stencil' },+ });++ const mask = world.get(entity, UIMask);+ expect(mask.mode).toBe(1);+ });++ it('should warn for unknown component type', () => {+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const entity = world.spawn();+ loadComponent(world, entity, {+ type: 'NonExistentComponent',+ data: {},+ }, 'TestEntity');++ expect(warnSpy).toHaveBeenCalledWith(+ expect.stringContaining('Unknown component type: NonExistentComponent'),+ );+ expect(warnSpy).toHaveBeenCalledWith(+ expect.stringContaining('on entity "TestEntity"'),+ );+ warnSpy.mockRestore();+ });++ it('should warn without entity name when not provided', () => {+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const entity = world.spawn();+ loadComponent(world, entity, {+ type: 'NonExistentComponent',+ data: {},+ });++ expect(warnSpy).toHaveBeenCalledWith('Unknown component type: NonExistentComponent');+ warnSpy.mockRestore();+ });+ });++ // =========================================================================+ // loadSceneData (sync)+ // =========================================================================++ describe('loadSceneData', () => {+ it('should spawn entities and return entity map', () => {+ const sceneData: SceneData = {+ version: '1.0',+ name: 'TestScene',+ entities: [+ {+ id: 0,+ name: 'Root',+ parent: null,+ children: [1],+ components: [],+ },+ {+ id: 1,+ name: 'Child',+ parent: 0,+ children: [],+ components: [],+ },+ ],+ };++ const entityMap = loadSceneData(world, sceneData);++ expect(entityMap.size).toBe(2);+ expect(entityMap.has(0)).toBe(true);+ expect(entityMap.has(1)).toBe(true);+ });++ it('should assign Name component to entities', () => {+ const sceneData: SceneData = {+ version: '1.0',+ name: 'TestScene',+ entities: [{+ id: 0,+ name: 'MyEntity',+ parent: null,+ children: [],+ components: [],+ }],+ };++ const entityMap = loadSceneData(world, sceneData);+ const entity = entityMap.get(0)!;+ const name = world.get(entity, Name);+ expect(name.value).toBe('MyEntity');+ });++ it('should set up parent-child hierarchy', () => {+ const setParentSpy = vi.spyOn(world, 'setParent');+ const sceneData: SceneData = {+ version: '1.0',+ name: 'TestScene',+ entities: [+ { id: 0, name: 'Root', parent: null, children: [1], components: [] },+ { id: 1, name: 'Child', parent: 0, children: [], components: [] },+ ],+ };++ const entityMap = loadSceneData(world, sceneData);++ expect(setParentSpy).toHaveBeenCalledWith(+ entityMap.get(1),+ entityMap.get(0),+ );+ });++ it('should skip invisible entities', () => {+ const sceneData: SceneData = {+ version: '1.0',+ name: 'TestScene',+ entities: [+ { id: 0, name: 'Visible', parent: null, children: [], components: [], visible: true },+ { id: 1, name: 'Hidden', parent: null, children: [], components: [], visible: false },+ ],+ };++ const entityMap = loadSceneData(world, sceneData);++ expect(entityMap.size).toBe(1);+ expect(entityMap.has(0)).toBe(true);+ expect(entityMap.has(1)).toBe(false);+ });++ it('should load components for each entity', () => {+ const sceneData: SceneData = {+ version: '1.0',+ name: 'TestScene',+ entities: [{+ id: 0,+ name: 'WithTransform',+ parent: null,+ children: [],+ components: [+ { type: 'Transform', data: { position: { x: 10, y: 20, z: 0 } } },+ ],+ }],+ };++ const entityMap = loadSceneData(world, sceneData);+ const entity = entityMap.get(0)!;+ const transform = world.get(entity, Transform);+ expect(transform.position.x).toBe(10);+ });++ it('should handle empty scene', () => {+ const sceneData: SceneData = {+ version: '1.0',+ name: 'EmptyScene',+ entities: [],+ };++ const entityMap = loadSceneData(world, sceneData);+ expect(entityMap.size).toBe(0);+ });++ it('should remap entity fields during component loading', () => {+ const SliderComp = defineBuiltin('Slider', {+ fillEntity: 0,+ handleEntity: 0,+ value: 0,+ });++ const sceneData: SceneData = {+ version: '1.0',+ name: 'SliderScene',+ entities: [+ {+ id: 0,+ name: 'SliderRoot',+ parent: null,+ children: [1, 2],+ components: [+ { type: 'Slider', data: { fillEntity: 1, handleEntity: 2, value: 0.5 } },+ ],+ },+ { id: 1, name: 'Fill', parent: 0, children: [], components: [] },+ { id: 2, name: 'Handle', parent: 0, children: [], components: [] },+ ],+ };++ const entityMap = loadSceneData(world, sceneData);+ const root = entityMap.get(0)!;+ const slider = world.get(root, SliderComp);++ expect(slider.fillEntity).toBe(entityMap.get(1));+ expect(slider.handleEntity).toBe(entityMap.get(2));+ });++ it('should handle parent reference to non-existent entity gracefully', () => {+ const sceneData: SceneData = {+ version: '1.0',+ name: 'BrokenParent',+ entities: [+ { id: 0, name: 'Orphan', parent: 999, children: [], components: [] },+ ],+ };++ const entityMap = loadSceneData(world, sceneData);+ expect(entityMap.size).toBe(1);+ });+ });++ // =========================================================================+ // loadSceneWithAssets (async)+ // =========================================================================++ describe('loadSceneWithAssets', () => {+ function createMockAssetServer() {+ return {+ baseUrl: '/default-base',+ loadTexture: vi.fn().mockResolvedValue({ handle: 1 }),+ loadMaterial: vi.fn().mockResolvedValue({ handle: 2 }),+ loadBitmapFont: vi.fn().mockResolvedValue(3),+ loadSpine: vi.fn().mockResolvedValue({ success: true }),+ loadJson: vi.fn(),+ setTextureMetadataByPath: vi.fn(),+ } as any;+ }++ it('should load scene without assets when no assetServer', async () => {+ const sceneData: SceneData = {+ version: '1.0',+ name: 'NoAssets',+ entities: [{+ id: 0,+ name: 'Root',+ parent: null,+ children: [],+ components: [{ type: 'Transform', data: {} }],+ }],+ };++ const entityMap = await loadSceneWithAssets(world, sceneData);+ expect(entityMap.size).toBe(1);+ });++ it('should preload textures and replace path with handle', async () => {+ const assetServer = createMockAssetServer();+ const sceneData: SceneData = {+ version: '1.0',+ name: 'WithTexture',+ entities: [{+ id: 0,+ name: 'SpriteEntity',+ parent: null,+ children: [],+ components: [+ { type: 'Sprite', data: { texture: 'hero.png', material: 0 } },+ ],+ }],+ };++ await loadSceneWithAssets(world, sceneData, {+ assetServer,+ assetBaseUrl: '/game',+ });++ expect(assetServer.loadTexture).toHaveBeenCalledWith('/game/hero.png');+ const entity = world.getEntitiesWithComponents([Sprite])[0];+ const sprite = world.get(entity, Sprite);+ expect(sprite.texture).toBe(1);+ });++ it('should preload materials', async () => {+ const assetServer = createMockAssetServer();+ const sceneData: SceneData = {+ version: '1.0',+ name: 'WithMaterial',+ entities: [{+ id: 0,+ name: 'SpriteEntity',+ parent: null,+ children: [],+ components: [+ { type: 'Sprite', data: { texture: 0, material: 'custom.mat' } },+ ],+ }],+ };++ await loadSceneWithAssets(world, sceneData, { assetServer });+ expect(assetServer.loadMaterial).toHaveBeenCalledWith('custom.mat', '/default-base');+ });++ it('should preload bitmap fonts', async () => {+ const assetServer = createMockAssetServer();+ const sceneData: SceneData = {+ version: '1.0',+ name: 'WithFont',+ entities: [{+ id: 0,+ name: 'TextEntity',+ parent: null,+ children: [],+ components: [+ { type: 'BitmapText', data: { font: 'arial.fnt' } },+ ],+ }],+ };++ await loadSceneWithAssets(world, sceneData, {+ assetServer,+ assetBaseUrl: '/assets',+ });+ expect(assetServer.loadBitmapFont).toHaveBeenCalledWith('arial.fnt', '/assets');+ });++ it('should preload spine assets', async () => {+ const assetServer = createMockAssetServer();+ const sceneData: SceneData = {+ version: '1.0',+ name: 'WithSpine',+ entities: [{+ id: 0,+ name: 'SpineEntity',+ parent: null,+ children: [],+ components: [{+ type: 'SpineAnimation',+ data: {+ skeletonPath: 'hero.skel',+ atlasPath: 'hero.atlas',+ material: 0,+ },+ }],+ }],+ };++ await loadSceneWithAssets(world, sceneData, { assetServer });+ expect(assetServer.loadSpine).toHaveBeenCalledWith(+ 'hero.skel', 'hero.atlas', '/default-base',+ );+ });++ it('should preload anim-clip assets and register clips', async () => {+ const assetServer = createMockAssetServer();+ assetServer.loadJson.mockResolvedValue({+ fps: 12,+ loop: true,+ frames: [+ { texture: 'frame1.png', duration: 100 },+ { texture: 'frame2.png', duration: 100 },+ ],+ });++ const AnimComp = defineComponent('TestSpriteAnimatorScene', {+ clip: 'walk.esanim',+ playing: true,+ speed: 1,+ });++ registerComponentAssetFields('TestSpriteAnimatorScene', {+ fields: [{ field: 'clip', type: 'anim-clip' }],+ });++ const sceneData: SceneData = {+ version: '1.0',+ name: 'WithAnimClip',+ entities: [{+ id: 0,+ name: 'AnimEntity',+ parent: null,+ children: [],+ components: [+ { type: 'TestSpriteAnimatorScene', data: { clip: 'walk.esanim', playing: true, speed: 1 } },+ ],+ }],+ };++ await loadSceneWithAssets(world, sceneData, {+ assetServer,+ assetBaseUrl: '/game',+ });++ expect(assetServer.loadJson).toHaveBeenCalledWith('walk.esanim');+ expect(assetServer.loadTexture).toHaveBeenCalledWith('/game/frame1.png');+ expect(assetServer.loadTexture).toHaveBeenCalledWith('/game/frame2.png');+ });++ it('should handle anim-clip load failure gracefully', async () => {+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const assetServer = createMockAssetServer();+ assetServer.loadJson.mockRejectedValue(new Error('404'));++ const AnimComp2 = defineComponent('TestSpriteAnimatorScene2', { clip: 'x' });+ registerComponentAssetFields('TestSpriteAnimatorScene2', {+ fields: [{ field: 'clip', type: 'anim-clip' }],+ });++ const sceneData: SceneData = {+ version: '1.0',+ name: 'FailedAnimClip',+ entities: [{+ id: 0,+ name: 'Entity',+ parent: null,+ children: [],+ components: [+ { type: 'TestSpriteAnimatorScene2', data: { clip: 'bad.esanim' } },+ ],+ }],+ };++ await loadSceneWithAssets(world, sceneData, { assetServer });+ expect(warnSpy).toHaveBeenCalledWith(+ expect.stringContaining('Failed to load animation clip'),+ expect.any(Error),+ );+ warnSpy.mockRestore();+ });++ it('should handle anim-clip texture load failure gracefully', async () => {+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const assetServer = createMockAssetServer();+ assetServer.loadJson.mockResolvedValue({+ fps: 12,+ loop: true,+ frames: [{ texture: 'bad.png', duration: 100 }],+ });+ assetServer.loadTexture.mockRejectedValue(new Error('texture 404'));++ const AnimComp3 = defineComponent('TestSpriteAnimatorScene3', { clip: 'x' });+ registerComponentAssetFields('TestSpriteAnimatorScene3', {+ fields: [{ field: 'clip', type: 'anim-clip' }],+ });++ const sceneData: SceneData = {+ version: '1.0',+ name: 'FailedAnimTexture',+ entities: [{+ id: 0,+ name: 'Entity',+ parent: null,+ children: [],+ components: [+ { type: 'TestSpriteAnimatorScene3', data: { clip: 'walk.esanim' } },+ ],+ }],+ };++ await loadSceneWithAssets(world, sceneData, { assetServer });+ expect(warnSpy).toHaveBeenCalledWith(+ expect.stringContaining('Failed to load anim texture'),+ expect.any(Error),+ );+ warnSpy.mockRestore();+ });++ it('should handle texture load failure gracefully', async () => {+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const assetServer = createMockAssetServer();+ assetServer.loadTexture.mockRejectedValue(new Error('404'));++ const sceneData: SceneData = {+ version: '1.0',+ name: 'FailedTexture',+ entities: [{+ id: 0,+ name: 'SpriteEntity',+ parent: null,+ children: [],+ components: [+ { type: 'Sprite', data: { texture: 'missing.png', material: 0 } },+ ],+ }],+ };++ await loadSceneWithAssets(world, sceneData, { assetServer });+ expect(warnSpy).toHaveBeenCalledWith(+ expect.stringContaining('Failed to load texture'),+ expect.any(Error),+ );+ warnSpy.mockRestore();+ });++ it('should handle material load failure gracefully', async () => {+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const assetServer = createMockAssetServer();+ assetServer.loadMaterial.mockRejectedValue(new Error('404'));++ const sceneData: SceneData = {+ version: '1.0',+ name: 'FailedMaterial',+ entities: [{+ id: 0,+ name: 'SpriteEntity',+ parent: null,+ children: [],+ components: [+ { type: 'Sprite', data: { texture: 0, material: 'bad.mat' } },+ ],+ }],+ };++ await loadSceneWithAssets(world, sceneData, { assetServer });+ expect(warnSpy).toHaveBeenCalledWith(+ expect.stringContaining('Failed to load material'),+ expect.any(Error),+ );+ warnSpy.mockRestore();+ });++ it('should handle font load failure gracefully', async () => {+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const assetServer = createMockAssetServer();+ assetServer.loadBitmapFont.mockRejectedValue(new Error('404'));++ const sceneData: SceneData = {+ version: '1.0',+ name: 'FailedFont',+ entities: [{+ id: 0,+ name: 'TextEntity',+ parent: null,+ children: [],+ components: [+ { type: 'BitmapText', data: { font: 'bad.fnt' } },+ ],+ }],+ };++ await loadSceneWithAssets(world, sceneData, { assetServer });+ expect(warnSpy).toHaveBeenCalledWith(+ expect.stringContaining('Failed to load bitmap font'),+ expect.any(Error),+ );+ warnSpy.mockRestore();+ });++ it('should warn on failed spine load', async () => {+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const assetServer = createMockAssetServer();+ assetServer.loadSpine.mockResolvedValue({ success: false, error: 'file not found' });++ const sceneData: SceneData = {+ version: '1.0',+ name: 'FailedSpine',+ entities: [{+ id: 0,+ name: 'SpineEntity',+ parent: null,+ children: [],+ components: [{+ type: 'SpineAnimation',+ data: { skeletonPath: 'bad.skel', atlasPath: 'bad.atlas', material: 0 },+ }],+ }],+ };++ await loadSceneWithAssets(world, sceneData, { assetServer });+ expect(warnSpy).toHaveBeenCalledWith(+ expect.stringContaining('Failed to load Spine'),+ );+ warnSpy.mockRestore();+ });++ it('should collect loaded assets when collectAssets provided', async () => {+ const assetServer = createMockAssetServer();+ assetServer.loadMaterial.mockResolvedValue({ handle: 5 });+ const collectAssets = {+ textureUrls: new Set<string>(),+ materialHandles: new Set<number>(),+ fontPaths: new Set<string>(),+ spineKeys: new Set<string>(),+ };++ const sceneData: SceneData = {+ version: '1.0',+ name: 'Collect',+ entities: [{+ id: 0,+ name: 'Entity',+ parent: null,+ children: [],+ components: [+ { type: 'Sprite', data: { texture: 'hero.png', material: 'custom.mat' } },+ { type: 'BitmapText', data: { font: 'arial.fnt' } },+ { type: 'SpineAnimation', data: { skeletonPath: 's.skel', atlasPath: 's.atlas', material: 0 } },+ ],+ }],+ };++ await loadSceneWithAssets(world, sceneData, {+ assetServer,+ assetBaseUrl: '/assets',+ collectAssets,+ });++ expect(collectAssets.textureUrls.size).toBeGreaterThan(0);+ expect(collectAssets.materialHandles.has(5)).toBe(true);+ expect(collectAssets.fontPaths.has('arial.fnt')).toBe(true);+ expect(collectAssets.spineKeys.size).toBe(1);+ });++ it('should not collect material handle 0 (failed)', async () => {+ const assetServer = createMockAssetServer();+ assetServer.loadMaterial.mockRejectedValue(new Error('fail'));+ vi.spyOn(console, 'warn').mockImplementation(() => {});+ const collectAssets = {+ textureUrls: new Set<string>(),+ materialHandles: new Set<number>(),+ fontPaths: new Set<string>(),+ spineKeys: new Set<string>(),+ };++ const sceneData: SceneData = {+ version: '1.0',+ name: 'FailCollect',+ entities: [{+ id: 0,+ name: 'Entity',+ parent: null,+ children: [],+ components: [+ { type: 'Sprite', data: { texture: 0, material: 'bad.mat' } },+ ],+ }],+ };++ await loadSceneWithAssets(world, sceneData, { assetServer, collectAssets });+ expect(collectAssets.materialHandles.has(0)).toBe(false);+ });++ it('should apply textureMetadata sliceBorder', async () => {+ const assetServer = createMockAssetServer();+ const sceneData: SceneData = {+ version: '1.0',+ name: 'WithMetadata',+ entities: [{+ id: 0,+ name: 'Entity',+ parent: null,+ children: [],+ components: [+ { type: 'Sprite', data: { texture: 'border.png', material: 0 } },+ ],+ }],+ textureMetadata: {+ 'border.png': {+ version: '1.0',+ type: 'texture',+ sliceBorder: { left: 10, right: 10, top: 5, bottom: 5 },+ },+ },+ };++ await loadSceneWithAssets(world, sceneData, {+ assetServer,+ assetBaseUrl: '/game',+ });++ expect(assetServer.setTextureMetadataByPath).toHaveBeenCalledWith(+ '/game/border.png',+ { left: 10, right: 10, top: 5, bottom: 5 },+ );+ });++ it('should handle data: URL textures without base URL prefix', async () => {+ const assetServer = createMockAssetServer();+ const dataUrl = 'data:image/png;base64,abc123';+ const sceneData: SceneData = {+ version: '1.0',+ name: 'DataUrl',+ entities: [{+ id: 0,+ name: 'Entity',+ parent: null,+ children: [],+ components: [+ { type: 'Sprite', data: { texture: dataUrl, material: 0 } },+ ],+ }],+ };++ await loadSceneWithAssets(world, sceneData, {+ assetServer,+ assetBaseUrl: '/game',+ });++ expect(assetServer.loadTexture).toHaveBeenCalledWith(dataUrl);+ });++ it('should deduplicate spine assets with same key', async () => {+ const assetServer = createMockAssetServer();+ const sceneData: SceneData = {+ version: '1.0',+ name: 'DupeSpine',+ entities: [+ {+ id: 0, name: 'Spine1', parent: null, children: [],+ components: [{+ type: 'SpineAnimation',+ data: { skeletonPath: 's.skel', atlasPath: 's.atlas', material: 0 },+ }],+ },+ {+ id: 1, name: 'Spine2', parent: null, children: [],+ components: [{+ type: 'SpineAnimation',+ data: { skeletonPath: 's.skel', atlasPath: 's.atlas', material: 0 },+ }],+ },+ ],+ };++ await loadSceneWithAssets(world, sceneData, { assetServer });+ expect(assetServer.loadSpine).toHaveBeenCalledTimes(1);+ });++ it('should skip invisible entities during asset preloading', async () => {+ const assetServer = createMockAssetServer();+ const sceneData: SceneData = {+ version: '1.0',+ name: 'InvisibleAssets',+ entities: [{+ id: 0,+ name: 'Hidden',+ parent: null,+ children: [],+ components: [+ { type: 'Sprite', data: { texture: 'hidden.png', material: 0 } },+ ],+ visible: false,+ }],+ };++ await loadSceneWithAssets(world, sceneData, { assetServer });+ expect(assetServer.loadTexture).not.toHaveBeenCalled();+ });++ it('should use assetServer.baseUrl when assetBaseUrl not provided', async () => {+ const assetServer = createMockAssetServer();+ const sceneData: SceneData = {+ version: '1.0',+ name: 'DefaultBase',+ entities: [{+ id: 0,+ name: 'Entity',+ parent: null,+ children: [],+ components: [+ { type: 'Sprite', data: { texture: 'hero.png', material: 0 } },+ ],+ }],+ };++ await loadSceneWithAssets(world, sceneData, { assetServer });+ expect(assetServer.loadTexture).toHaveBeenCalledWith('/default-base/hero.png');+ });++ it('should use / prefix when no baseUrl at all', async () => {+ const assetServer = createMockAssetServer();+ assetServer.baseUrl = undefined;+ const sceneData: SceneData = {+ version: '1.0',+ name: 'NoBase',+ entities: [{+ id: 0,+ name: 'Entity',+ parent: null,+ children: [],+ components: [+ { type: 'Sprite', data: { texture: 'hero.png', material: 0 } },+ ],+ }],+ };++ await loadSceneWithAssets(world, sceneData, { assetServer });+ expect(assetServer.loadTexture).toHaveBeenCalledWith('/hero.png');+ });+ });++ // =========================================================================+ // findEntityByName+ // =========================================================================++ describe('findEntityByName', () => {+ it('should find entity by name', () => {+ const entity = world.spawn();+ world.insert(entity, Name, { value: 'Player' });++ const found = findEntityByName(world, 'Player');+ expect(found).toBe(entity);+ });++ it('should return null when entity not found', () => {+ const found = findEntityByName(world, 'NonExistent');+ expect(found).toBeNull();+ });++ it('should return first match when multiple entities have same name', () => {+ const e1 = world.spawn();+ world.insert(e1, Name, { value: 'Duplicate' });+ const e2 = world.spawn();+ world.insert(e2, Name, { value: 'Duplicate' });++ const found = findEntityByName(world, 'Duplicate');+ expect(found).toBe(e1);+ });+ });++ // =========================================================================+ // updateCameraAspectRatio+ // =========================================================================++ describe('updateCameraAspectRatio', () => {+ it('should update camera aspect ratio', () => {+ const entity = world.spawn();+ world.insert(entity, Camera, { aspectRatio: 1.0, nearPlane: 0.1, farPlane: 100 });++ updateCameraAspectRatio(world, 16 / 9);++ const camera = world.get(entity, Camera);+ expect(camera.aspectRatio).toBeCloseTo(16 / 9);+ });++ it('should update all cameras', () => {+ const e1 = world.spawn();+ world.insert(e1, Camera, { aspectRatio: 1.0 });+ const e2 = world.spawn();+ world.insert(e2, Camera, { aspectRatio: 1.0 });++ updateCameraAspectRatio(world, 2.0);++ expect(world.get(e1, Camera).aspectRatio).toBe(2.0);+ expect(world.get(e2, Camera).aspectRatio).toBe(2.0);+ });++ it('should do nothing when no cameras exist', () => {+ expect(() => updateCameraAspectRatio(world, 1.5)).not.toThrow();+ });+ });+});diff --git a/sdk/tests/system.test.ts b/sdk/tests/system.test.tsnew file mode 100644index 000000000..b675d8b16--- /dev/null+++ b/sdk/tests/system.test.ts@@ -0,0 +1,351 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import {+ Schedule,+ GetWorld,+ defineSystem,+ addSystem,+ addStartupSystem,+ addSystemToSchedule,+ SystemRunner,+} from '../src/system';+import { Query, Mut, QueryInstance, Removed, RemovedQueryInstance } from '../src/query';+import { Res, ResMut, ResMutInstance, defineResource, ResourceStorage } from '../src/resource';+import { Commands, CommandsInstance } from '../src/commands';+import { EventWriter, EventReader, EventWriterInstance, EventReaderInstance, defineEvent, EventRegistry } from '../src/event';+import { defineComponent } from '../src/component';+import type { World } from '../src/world';+import type { Entity } from '../src/types';++// =============================================================================+// Test components and resources+// =============================================================================++const Position = defineComponent('SysTestPosition', { x: 0, y: 0 });+const Velocity = defineComponent('SysTestVelocity', { dx: 0, dy: 0 });++const GameState = defineResource({ score: 0, level: 1 }, 'GameState');++const DamageEvent = defineEvent<{ target: Entity; amount: number }>('Damage');++// =============================================================================+// Mock World+// =============================================================================++function createMockWorld() {+ let nextId = 1;+ const entities = new Set<Entity>();+ const worldTick = { value: 0 };++ const world = {+ spawn: vi.fn(() => {+ const e = nextId++ as Entity;+ entities.add(e);+ return e;+ }),+ despawn: vi.fn((e: Entity) => entities.delete(e)),+ insert: vi.fn(),+ remove: vi.fn(),+ get: vi.fn(),+ set: vi.fn(),+ valid: vi.fn((e: Entity) => entities.has(e)),+ getEntitiesWithComponents: vi.fn(() => [] as Entity[]),+ beginIteration: vi.fn(),+ endIteration: vi.fn(),+ resetIterationDepth: vi.fn(),+ getWorldTick: vi.fn(() => worldTick.value),+ isAddedSince: vi.fn(() => false),+ isChangedSince: vi.fn(() => false),+ getRemovedEntitiesSince: vi.fn(() => []),+ };++ return { world: world as unknown as World, entities, worldTick };+}++// =============================================================================+// Schedule enum+// =============================================================================++describe('Schedule', () => {+ it('should have correct phase values', () => {+ expect(Schedule.Startup).toBe(0);+ expect(Schedule.First).toBe(1);+ expect(Schedule.PreUpdate).toBe(2);+ expect(Schedule.Update).toBe(3);+ expect(Schedule.PostUpdate).toBe(4);+ expect(Schedule.Last).toBe(5);+ expect(Schedule.FixedPreUpdate).toBe(10);+ expect(Schedule.FixedUpdate).toBe(11);+ expect(Schedule.FixedPostUpdate).toBe(12);+ });+});++// =============================================================================+// GetWorld descriptor+// =============================================================================++describe('GetWorld', () => {+ it('should create a get_world descriptor', () => {+ const desc = GetWorld();+ expect(desc._type).toBe('get_world');+ });+});++// =============================================================================+// defineSystem+// =============================================================================++describe('defineSystem', () => {+ it('should create a system with unique symbol id', () => {+ const sys = defineSystem([], () => {});+ expect(typeof sys._id).toBe('symbol');+ });++ it('should store params and fn', () => {+ const fn = vi.fn();+ const params = [Query(Position)] as const;+ const sys = defineSystem([...params], fn);+ expect(sys._params).toHaveLength(1);+ expect(sys._fn).toBe(fn);+ });++ it('should use provided name', () => {+ const sys = defineSystem([], () => {}, { name: 'MovementSystem' });+ expect(sys._name).toBe('MovementSystem');+ });++ it('should auto-generate name when not provided', () => {+ const sys = defineSystem([], () => {});+ expect(sys._name).toMatch(/^System_\d+$/);+ });++ it('should create unique ids for different systems', () => {+ const a = defineSystem([], () => {});+ const b = defineSystem([], () => {});+ expect(a._id).not.toBe(b._id);+ });+});++// =============================================================================+// Global registration (addSystem, addStartupSystem, addSystemToSchedule)+// =============================================================================++describe('Global system registration', () => {+ afterEach(() => {+ (globalThis as any).__esengine_pendingSystems = [];+ });++ it('addSystem should register with Update schedule', () => {+ const sys = defineSystem([], () => {});+ addSystem(sys);+ const pending = (globalThis as any).__esengine_pendingSystems;+ expect(pending).toContainEqual({ schedule: Schedule.Update, system: sys });+ });++ it('addStartupSystem should register with Startup schedule', () => {+ const sys = defineSystem([], () => {});+ addStartupSystem(sys);+ const pending = (globalThis as any).__esengine_pendingSystems;+ expect(pending).toContainEqual({ schedule: Schedule.Startup, system: sys });+ });++ it('addSystemToSchedule should register with specified schedule', () => {+ const sys = defineSystem([], () => {});+ addSystemToSchedule(Schedule.Last, sys);+ const pending = (globalThis as any).__esengine_pendingSystems;+ expect(pending).toContainEqual({ schedule: Schedule.Last, system: sys });+ });+});++// =============================================================================+// SystemRunner+// =============================================================================++describe('SystemRunner', () => {+ let mockWorld: ReturnType<typeof createMockWorld>;+ let world: World;+ let resources: ResourceStorage;+ let eventRegistry: EventRegistry;+ let runner: SystemRunner;++ beforeEach(() => {+ mockWorld = createMockWorld();+ world = mockWorld.world;+ resources = new ResourceStorage();+ eventRegistry = new EventRegistry();+ runner = new SystemRunner(world, resources, eventRegistry);+ });++ describe('run with no params', () => {+ it('should call the system function', () => {+ const fn = vi.fn();+ const sys = defineSystem([], fn);+ runner.run(sys);+ expect(fn).toHaveBeenCalledOnce();+ });+ });++ describe('parameter resolution', () => {+ it('should resolve Query parameter', () => {+ let received: unknown = null;+ const sys = defineSystem([Query(Position)], (q) => {+ received = q;+ });+ runner.run(sys);+ expect(received).toBeInstanceOf(QueryInstance);+ });++ it('should resolve Res parameter', () => {+ resources.insert(GameState, { score: 42, level: 3 });+ let received: unknown = null;+ const sys = defineSystem([Res(GameState)], (state) => {+ received = state;+ });+ runner.run(sys);+ expect(received).toEqual({ score: 42, level: 3 });+ });++ it('should resolve ResMut parameter', () => {+ resources.insert(GameState, { score: 0, level: 1 });+ let received: unknown = null;+ const sys = defineSystem([ResMut(GameState)], (state) => {+ received = state;+ });+ runner.run(sys);+ expect(received).toBeInstanceOf(ResMutInstance);+ });++ it('should resolve Commands parameter', () => {+ let received: unknown = null;+ const sys = defineSystem([Commands()], (cmds) => {+ received = cmds;+ });+ runner.run(sys);+ expect(received).toBeInstanceOf(CommandsInstance);+ });++ it('should resolve EventWriter parameter', () => {+ let received: unknown = null;+ const sys = defineSystem([EventWriter(DamageEvent)], (writer) => {+ received = writer;+ });+ runner.run(sys);+ expect(received).toBeInstanceOf(EventWriterInstance);+ });++ it('should resolve EventReader parameter', () => {+ let received: unknown = null;+ const sys = defineSystem([EventReader(DamageEvent)], (reader) => {+ received = reader;+ });+ runner.run(sys);+ expect(received).toBeInstanceOf(EventReaderInstance);+ });++ it('should resolve Removed parameter', () => {+ let received: unknown = null;+ const sys = defineSystem([Removed(Position)], (removed) => {+ received = removed;+ });+ runner.run(sys);+ expect(received).toBeInstanceOf(RemovedQueryInstance);+ });++ it('should resolve GetWorld parameter', () => {+ let received: unknown = null;+ const sys = defineSystem([GetWorld()], (w) => {+ received = w;+ });+ runner.run(sys);+ expect(received).toBe(world);+ });++ it('should resolve multiple mixed parameters', () => {+ resources.insert(GameState, { score: 10, level: 2 });+ const received: unknown[] = [];+ const sys = defineSystem(+ [Query(Position), Res(GameState), Commands()],+ (q, state, cmds) => {+ received.push(q, state, cmds);+ }+ );+ runner.run(sys);+ expect(received[0]).toBeInstanceOf(QueryInstance);+ expect(received[1]).toEqual({ score: 10, level: 2 });+ expect(received[2]).toBeInstanceOf(CommandsInstance);+ });+ });++ describe('Commands auto-flush', () => {+ it('should flush Commands after system runs', () => {+ const sys = defineSystem([Commands()], (cmds) => {+ cmds.despawn(1 as Entity);+ });+ runner.run(sys);+ expect((world.despawn as any) || true).toBeTruthy();+ });+ });++ describe('resetIterationDepth', () => {+ it('should call resetIterationDepth after system runs', () => {+ const sys = defineSystem([], () => {});+ runner.run(sys);+ expect((world as any).resetIterationDepth).toHaveBeenCalled();+ });++ it('should call resetIterationDepth even if system throws', () => {+ const sys = defineSystem([], () => {+ throw new Error('boom');+ });+ expect(() => runner.run(sys)).toThrow('boom');+ expect((world as any).resetIterationDepth).toHaveBeenCalled();+ });+ });++ describe('system tick tracking', () => {+ it('should update system tick after run', () => {+ mockWorld.worldTick.value = 5;+ const sys = defineSystem([], () => {});+ runner.run(sys);+ // Second run should have lastRunTick from first run+ mockWorld.worldTick.value = 10;+ runner.run(sys);+ // Verify the world tick is queried+ expect((world as any).getWorldTick).toHaveBeenCalled();+ });+ });++ describe('args caching', () => {+ it('should reuse args array on subsequent runs', () => {+ const calls: unknown[][] = [];+ const sys = defineSystem([Res(GameState)], (...args: unknown[]) => {+ calls.push(args);+ });+ resources.insert(GameState, { score: 0, level: 1 });+ runner.run(sys);+ runner.run(sys);+ expect(calls).toHaveLength(2);+ });+ });++ describe('EventRegistry not available', () => {+ it('should throw when EventWriter used without registry', () => {+ const runnerNoEvents = new SystemRunner(world, resources);+ const sys = defineSystem([EventWriter(DamageEvent)], () => {});+ expect(() => runnerNoEvents.run(sys)).toThrow('EventRegistry not available');+ });++ it('should throw when EventReader used without registry', () => {+ const runnerNoEvents = new SystemRunner(world, resources);+ const sys = defineSystem([EventReader(DamageEvent)], () => {});+ expect(() => runnerNoEvents.run(sys)).toThrow('EventRegistry not available');+ });+ });++ describe('unknown parameter type', () => {+ it('should throw for unknown parameter type', () => {+ const badParam = { _type: 'unknown_thing' } as any;+ const sys = defineSystem([badParam], () => {});+ expect(() => runner.run(sys)).toThrow('Unknown system parameter type');+ });+ });+});