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
feat: improve world query, app tick, and scene asset lifecycle
esengine308aacde33e3
diff --git a/sdk/src/app.ts b/sdk/src/app.tsindex bdba467c6..2704abb30 100644--- a/sdk/src/app.ts+++ b/sdk/src/app.ts@@ -147,7 +147,7 @@ export class App {// =========================================================================connectCpp(cppRegistry: CppRegistry, module?: ESEngineModule): this {- this.world_.connectCpp(cppRegistry);+ this.world_.connectCpp(cppRegistry, module);if (module) {this.module_ = module;@@ -293,6 +293,26 @@ export class App {// Run// =========================================================================+ tick(delta: number): void {+ if (!this.runner_) {+ this.runner_ = new SystemRunner(this.world_, this.resources_);+ if (!this.resources_.has(Time)) {+ this.resources_.insert(Time, { delta: 0, elapsed: 0, frameCount: 0 });+ }+ this.runSchedule(Schedule.Startup);+ }++ this.updateTime(delta);+ this.world_.resetQueryPool();+ this.frame_paused_ = false;++ this.runSchedule(Schedule.First);+ this.runSchedule(Schedule.PreUpdate);+ this.runSchedule(Schedule.Update);+ this.runSchedule(Schedule.PostUpdate);+ this.runSchedule(Schedule.Last);+ }+run(): void {if (this.running_) {return;@@ -340,7 +360,7 @@ export class App {fixedSteps++;}if (fixedSteps >= this.maxFixedSteps_) {- this.fixedAccumulator_ = 0;+ this.fixedAccumulator_ = this.fixedTimestep_;}this.runSchedule(Schedule.PreUpdate);@@ -726,6 +746,27 @@ interface CameraInfo {cameraY: number;}+const cameraInfoPool_: CameraInfo[] = [];++function acquireCameraInfo(index: number): CameraInfo {+ if (index < cameraInfoPool_.length) {+ return cameraInfoPool_[index];+ }+ const info: CameraInfo = {+ entity: 0,+ viewProjection: new Float32Array(16),+ viewportRect: { x: 0, y: 0, w: 0, h: 0 },+ clearFlags: 0,+ priority: 0,+ halfW: 0,+ halfH: 0,+ cameraX: 0,+ cameraY: 0,+ };+ cameraInfoPool_.push(info);+ return info;+}+function collectCameras(module: ESEngineModule,registry: CppRegistry,@@ -752,15 +793,9 @@ function collectCameras(for (const e of filtered) {const camera = registry.getCamera(e);- const transform = registry.getLocalTransform(e);+ const transform = registry.getTransform(e);- const vr = {- x: camera.viewportX,- y: camera.viewportY,- w: camera.viewportW,- h: camera.viewportH,- };- const aspect = (vr.w * width) / (vr.h * height);+ const aspect = (camera.viewportW * width) / (camera.viewportH * height);let projection: Float32Array;let camHalfW = 0;let camHalfH = 0;@@ -789,17 +824,20 @@ function collectCameras(}const view = invertTranslation(transform.position.x, transform.position.y, transform.position.z);- cameras.push({- entity: e,- viewProjection: new Float32Array(multiply(projection, view)),- viewportRect: vr,- clearFlags: camera.clearFlags,- priority: camera.priority,- halfW: camHalfW,- halfH: camHalfH,- cameraX: transform.position.x,- cameraY: transform.position.y,- });+ const cam = acquireCameraInfo(cameras.length);+ cam.entity = e;+ cam.viewProjection.set(multiply(projection, view));+ cam.viewportRect.x = camera.viewportX;+ cam.viewportRect.y = camera.viewportY;+ cam.viewportRect.w = camera.viewportW;+ cam.viewportRect.h = camera.viewportH;+ cam.clearFlags = camera.clearFlags;+ cam.priority = camera.priority;+ cam.halfW = camHalfW;+ cam.halfH = camHalfH;+ cam.cameraX = transform.position.x;+ cam.cameraY = transform.position.y;+ cameras.push(cam);}cameras.sort((a, b) => a.priority - b.priority);@@ -813,7 +851,7 @@ function computeViewProjection(module: ESEngineModule, registry: CppRegistry, wiconst e = cameraEntities[0];const camera = registry.getCamera(e);- const transform = registry.getLocalTransform(e);+ const transform = registry.getTransform(e);const aspect = width / height;let projection: Float32Array;diff --git a/sdk/src/asset/AssetServer.ts b/sdk/src/asset/AssetServer.tsindex bd1d42d3d..a0e1c5c17 100644--- a/sdk/src/asset/AssetServer.ts+++ b/sdk/src/asset/AssetServer.ts@@ -356,6 +356,16 @@ export class AssetServer {return this.loadedSpines_.has(`${skeletonPath}:${atlasPath}`);}+ releaseSpine(key: string): void {+ if (!this.loadedSpines_.has(key)) return;+ this.loadedSpines_.delete(key);+ const handle = this.spineSkeletons_.get(key);+ if (handle !== undefined && this.spineController_) {+ this.spineController_.unloadSkeleton(handle);+ this.spineSkeletons_.delete(key);+ }+ }+// =========================================================================// BitmapFont// =========================================================================diff --git a/sdk/src/material.ts b/sdk/src/material.tsindex 304bc400d..aca9e3b4e 100644--- a/sdk/src/material.ts+++ b/sdk/src/material.ts@@ -167,6 +167,7 @@ export const Material = {if (data) {data.uniforms.set(name, value);data.dirty_ = true;+ module?.invalidateMaterialCache(material);}},@@ -190,6 +191,7 @@ export const Material = {const data = materials.get(material);if (data) {data.blendMode = mode;+ module?.invalidateMaterialCache(material);}},@@ -212,6 +214,7 @@ export const Material = {const data = materials.get(material);if (data) {data.depthTest = enabled;+ module?.invalidateMaterialCache(material);}},@@ -231,6 +234,7 @@ export const Material = {*/release(material: MaterialHandle): void {materials.delete(material);+ module?.invalidateMaterialCache(material);},/**@@ -244,6 +248,7 @@ export const Material = {releaseAll(): void {materials.clear();+ module?.clearMaterialCache();},/**@@ -352,7 +357,7 @@ export const Material = {let materialCallbackRegistered = false;let uniformBuffer: number = 0;-const UNIFORM_BUFFER_SIZE = 4096;+const UNIFORM_BUFFER_SIZE = 16384;const encodedNameCache = new Map<string, Uint8Array>();let encoder: TextEncoder | null = null;@@ -374,7 +379,7 @@ function serializeUniforms(uniforms: Map<string, UniformValue>): { ptr: number;const heapF32 = module.HEAPF32;for (const [name, value] of uniforms) {- if (offset + 128 > UNIFORM_BUFFER_SIZE) break;+ if (isTextureRef(value)) continue;let nameBytes = encodedNameCache.get(name);if (!nameBytes) {@@ -384,6 +389,12 @@ function serializeUniforms(uniforms: Map<string, UniformValue>): { ptr: number;}const nameLen = nameBytes.length;const namePadded = Math.ceil(nameLen / 4) * 4;+ const requiredBytes = 4 + namePadded + 4 + 16;++ if (offset + requiredBytes > UNIFORM_BUFFER_SIZE) {+ console.warn(`[ESEngine] Material uniform buffer full (${offset}/${UNIFORM_BUFFER_SIZE} bytes), skipping remaining uniforms`);+ break;+ }heap32[(bufferPtr + offset) >> 2] = nameLen;offset += 4;diff --git a/sdk/src/prefab.ts b/sdk/src/prefab.tsindex de8f7050a..1dba15a4e 100644--- a/sdk/src/prefab.ts+++ b/sdk/src/prefab.ts@@ -159,8 +159,10 @@ async function flattenPrefab(}if (visited?.has(pe.nestedPrefab.prefabPath)) {- console.error(`[Prefab] Cycle detected: ${pe.nestedPrefab.prefabPath}`);- continue;+ throw new Error(+ `[Prefab] Circular reference detected: "${pe.nestedPrefab.prefabPath}" ` ++ `is already being instantiated in the current prefab chain`,+ );}visited?.add(pe.nestedPrefab.prefabPath);diff --git a/sdk/src/query.ts b/sdk/src/query.tsindex 3008471da..916b77ee1 100644--- a/sdk/src/query.ts+++ b/sdk/src/query.ts@@ -6,6 +6,7 @@import { Entity } from './types';import { AnyComponentDef, ComponentData, isBuiltinComponent } from './component';import type { World } from './world';+import { computeQueryCacheKey } from './world';// =============================================================================// Mutable Component Wrapper@@ -99,6 +100,7 @@ export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<Quprivate readonly allRequired_: AnyComponentDef[];private readonly result_: unknown[];private readonly mutData_: Array<{ component: AnyComponentDef; data: Record<string, unknown> }>;+ private readonly cacheKey_: string;constructor(world: World, descriptor: QueryDescriptor<C>) {this.world_ = world;@@ -112,19 +114,24 @@ export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<Qucomponent: this.actualComponents_[idx],data: null as unknown as Record<string, unknown>}));+ this.cacheKey_ = computeQueryCacheKey(+ this.allRequired_,+ descriptor._with,+ descriptor._without,+ );}*[Symbol.iterator](): Iterator<QueryResult<C>> {- const { _mutIndices, _without } = this.descriptor_;+ const { _mutIndices } = this.descriptor_;const actualComponents = this.actualComponents_;const entities = this.world_.getEntitiesWithComponents(this.allRequired_,this.descriptor_._with,- this.descriptor_._without+ this.descriptor_._without,+ this.cacheKey_);const compCount = actualComponents.length;const hasMut = _mutIndices.length > 0;- const hasWithout = _without.length > 0;const result = this.result_;const mutData = this.mutData_;const mutCount = mutData.length;@@ -137,19 +144,8 @@ export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<Quif (prevEntity !== null && hasMut) {for (let i = 0; i < mutCount; i++) {const mut = mutData[i];- this.world_.insert(prevEntity, mut.component, mut.data);- }- }-- if (hasWithout) {- let excluded = false;- for (let i = 0; i < _without.length; i++) {- if (this.world_.has(entity, _without[i])) {- excluded = true;- break;- }+ this.world_.set(prevEntity, mut.component, mut.data);}- if (excluded) continue;}result[0] = entity;@@ -171,7 +167,7 @@ export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<Quif (prevEntity !== null && hasMut) {for (let i = 0; i < mutCount; i++) {const mut = mutData[i];- this.world_.insert(prevEntity, mut.component, mut.data);+ this.world_.set(prevEntity, mut.component, mut.data);}}}@@ -195,11 +191,9 @@ export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<Qu}count(): number {- let n = 0;- for (const _ of this) {- n++;- }- return n;+ return this.world_.getEntitiesWithComponents(+ this.allRequired_, this.descriptor_._with, this.descriptor_._without+ ).length;}toArray(): QueryResult<C>[] {diff --git a/sdk/src/scene.ts b/sdk/src/scene.tsindex 55adff8f9..008c55733 100644--- a/sdk/src/scene.ts+++ b/sdk/src/scene.ts@@ -46,9 +46,17 @@ export interface SceneData {textureMetadata?: Record<string, TextureMetadata>;}+export interface LoadedSceneAssets {+ textureUrls: Set<string>;+ materialHandles: Set<number>;+ fontPaths: Set<string>;+ spineKeys: Set<string>;+}+export interface SceneLoadOptions {assetServer?: AssetServer;assetBaseUrl?: string;+ collectAssets?: LoadedSceneAssets;}// =============================================================================@@ -157,7 +165,7 @@ export function registerComponentEntityFields(COMPONENT_ENTITY_FIELDS.set(componentType, fields);}-function remapEntityFields(compData: SceneComponentData, entityMap: Map<number, Entity>): void {+export function remapEntityFields(compData: SceneComponentData, entityMap: Map<number, Entity>): void {const fields = COMPONENT_ENTITY_FIELDS.get(compData.type);if (!fields) return;const data = compData.data as Record<string, unknown>;@@ -165,6 +173,12 @@ function remapEntityFields(compData: SceneComponentData, entityMap: Map<number,const editorId = data[field];if (typeof editorId === 'number' && editorId !== INVALID_ENTITY) {const runtimeId = entityMap.get(editorId);+ if (runtimeId === undefined) {+ console.warn(+ `[Scene] Entity reference not found: ${compData.type}.${field} ` ++ `references entity ${editorId} which does not exist`,+ );+ }data[field] = runtimeId !== undefined ? runtimeId : INVALID_ENTITY;}}@@ -178,6 +192,7 @@ function spawnAndLoadEntities(world: World, sceneData: SceneData): Map<number, Econst entityMap = new Map<number, Entity>();for (const entityData of sceneData.entities) {+ if (entityData.visible === false) continue;const entity = world.spawn();entityMap.set(entityData.id, entity);world.insert(entity, Name, { value: entityData.name });@@ -219,7 +234,7 @@ export async function loadSceneWithAssets(const texturePathToUrl = new Map<string, string>();if (assetServer) {- await preloadSceneAssets(sceneData, assetServer, baseUrl, texturePathToUrl);+ await preloadSceneAssets(sceneData, assetServer, baseUrl, texturePathToUrl, options?.collectAssets);}const entityMap = spawnAndLoadEntities(world, sceneData);@@ -300,6 +315,7 @@ async function preloadSceneAssets(assetServer: AssetServer,baseUrl: string | undefined,texturePathToUrl: Map<string, string>,+ collectAssets?: LoadedSceneAssets,): Promise<void> {sceneData = JSON.parse(JSON.stringify(sceneData));@@ -356,6 +372,27 @@ async function preloadSceneAssets(await Promise.all([...loadPromises, ...spinePromises]);+ if (collectAssets) {+ for (const url of texturePathToUrl.values()) {+ collectAssets.textureUrls.add(url);+ }+ const materialHandles = assetHandles.get('material');+ if (materialHandles) {+ for (const handle of materialHandles.values()) {+ if (handle > 0) collectAssets.materialHandles.add(handle);+ }+ }+ const fontPaths = assetPaths.get('font');+ if (fontPaths) {+ for (const path of fontPaths) {+ collectAssets.fontPaths.add(path);+ }+ }+ for (const key of spineKeys) {+ collectAssets.spineKeys.add(key);+ }+ }+for (const entityData of sceneData.entities) {if (entityData.visible === false) continue;@@ -374,6 +411,9 @@ async function preloadSceneAssets(}export function loadComponent(world: World, entity: Entity, compData: SceneComponentData, entityName?: string): void {+ if (compData.type === 'LocalTransform' || compData.type === 'WorldTransform') {+ compData.type = 'Transform';+ }if (compData.type === 'UIRect') {const rectData = compData.data as Record<string, unknown>;if (rectData.anchor && !rectData.anchorMin) {@@ -382,6 +422,11 @@ export function loadComponent(world: World, entity: Entity, compData: SceneCompodelete rectData.anchor;}}+ if (compData.type === 'UIMask') {+ const maskData = compData.data as Record<string, unknown>;+ if (maskData.mode === 'scissor') maskData.mode = 0;+ else if (maskData.mode === 'stencil') maskData.mode = 1;+ }const comp = getComponent(compData.type);if (comp) {world.insert(entity, comp, compData.data);diff --git a/sdk/src/sceneManager.ts b/sdk/src/sceneManager.tsindex ad32496fb..c9457f9f9 100644--- a/sdk/src/sceneManager.ts+++ b/sdk/src/sceneManager.ts@@ -5,9 +5,9 @@import type { App } from './app';import type { Entity, Color } from './types';-import type { SceneData, SceneLoadOptions } from './scene';+import type { SceneData, SceneLoadOptions, LoadedSceneAssets } from './scene';import type { SystemDef } from './system';-import type { ShaderHandle } from './material';+import { Material, type ShaderHandle } from './material';import type { DrawCallback } from './customDraw';import { Schedule } from './system';import { loadSceneWithAssets } from './scene';@@ -79,6 +79,7 @@ class SceneInstance {readonly drawCallbacks = new Map<string, DrawCallback>();readonly postProcessPasses: string[] = [];readonly savedAlphas = new Map<Entity, { sprite?: number; spine?: number; bitmapText?: number }>();+ loadedAssets: LoadedSceneAssets | null = null;status: SceneStatus = 'loading';constructor(config: SceneConfig) {@@ -166,6 +167,7 @@ export class SceneManagerState {private activeScene_: string | null = null;private initialScene_: string | null = null;private transition_: TransitionState | null = null;+ private switching_ = false;private loadPromises_ = new Map<string, Promise<SceneContext>>();constructor(app: App) {@@ -189,8 +191,8 @@ export class SceneManagerState {}async switchTo(name: string, options?: TransitionOptions): Promise<void> {- if (this.transition_) {- console.warn(`[SceneManager] Transition already in progress, ignoring switchTo("${name}")`);+ if (this.transition_ || this.switching_) {+ console.warn(`[SceneManager] Scene switch already in progress, ignoring switchTo("${name}")`);return;}@@ -201,10 +203,15 @@ export class SceneManagerState {return;}- if (this.activeScene_ && this.activeScene_ !== name) {- await this.unload(this.activeScene_, options);+ this.switching_ = true;+ try {+ if (this.activeScene_ && this.activeScene_ !== name) {+ await this.unload(this.activeScene_, options);+ }+ await this.load(name);+ } finally {+ this.switching_ = false;}- await this.load(name);}private startFadeTransition(targetScene: string, options: TransitionOptions): Promise<void> {@@ -315,34 +322,7 @@ export class SceneManagerState {}}- if (sceneData) {- const loadOptions: SceneLoadOptions = {};- if (this.app_.hasResource(Assets)) {- loadOptions.assetServer = this.app_.getResource(Assets);- }- const entityMap = await loadSceneWithAssets(- this.app_.world, sceneData, loadOptions- );-- for (const entity of entityMap.values()) {- instance.entities.add(entity);- this.app_.world.insert(entity, SceneOwner, {- scene: name,- persistent: false,- });- }- }-- if (config.systems) {- for (const { schedule, system } of config.systems) {- const wrapped = wrapSceneSystem(this.app_, name, system);- this.app_.addSystemToSchedule(schedule, wrapped);- }- }-- if (config.setup) {- await config.setup(ctx);- }+ await this.loadSceneData_(instance, name, config, sceneData);instance.status = 'running';this.activeScene_ = name;@@ -394,34 +374,7 @@ export class SceneManagerState {}}- if (sceneData) {- const loadOptions: SceneLoadOptions = {};- if (this.app_.hasResource(Assets)) {- loadOptions.assetServer = this.app_.getResource(Assets);- }- const entityMap = await loadSceneWithAssets(- this.app_.world, sceneData, loadOptions- );-- for (const entity of entityMap.values()) {- instance.entities.add(entity);- this.app_.world.insert(entity, SceneOwner, {- scene: name,- persistent: false,- });- }- }-- if (config.systems) {- for (const { schedule, system } of config.systems) {- const wrapped = wrapSceneSystem(this.app_, name, system);- this.app_.addSystemToSchedule(schedule, wrapped);- }- }-- if (config.setup) {- await config.setup(ctx);- }+ await this.loadSceneData_(instance, name, config, sceneData);instance.status = 'running';this.additiveScenes_.add(name);@@ -475,6 +428,8 @@ export class SceneManagerState {}instance.postProcessPasses.length = 0;+ this.releaseSceneAssets_(instance);+this.scenes_.delete(name);this.contexts_.delete(name);this.additiveScenes_.delete(name);@@ -491,6 +446,77 @@ export class SceneManagerState {}}+ private async loadSceneData_(+ instance: SceneInstance,+ name: string,+ config: SceneConfig,+ sceneData: SceneData | undefined,+ ): Promise<void> {+ if (sceneData) {+ const collectAssets: LoadedSceneAssets = {+ textureUrls: new Set(),+ materialHandles: new Set(),+ fontPaths: new Set(),+ spineKeys: new Set(),+ };+ const loadOptions: SceneLoadOptions = { collectAssets };+ if (this.app_.hasResource(Assets)) {+ loadOptions.assetServer = this.app_.getResource(Assets);+ }+ const entityMap = await loadSceneWithAssets(+ this.app_.world, sceneData, loadOptions+ );+ instance.loadedAssets = collectAssets;++ for (const entity of entityMap.values()) {+ instance.entities.add(entity);+ this.app_.world.insert(entity, SceneOwner, {+ scene: name,+ persistent: false,+ });+ }+ }++ if (config.systems) {+ for (const { schedule, system } of config.systems) {+ const wrapped = wrapSceneSystem(this.app_, name, system);+ this.app_.addSystemToSchedule(schedule, wrapped);+ }+ }++ const ctx = this.contexts_.get(name)!;+ if (config.setup) {+ await config.setup(ctx);+ }+ }++ private releaseSceneAssets_(instance: SceneInstance): void {+ const assets = instance.loadedAssets;+ if (!assets) return;++ const assetServer = this.app_.hasResource(Assets)+ ? this.app_.getResource(Assets)+ : null;++ if (assetServer) {+ for (const url of assets.textureUrls) {+ assetServer.releaseTexture(url);+ }+ for (const path of assets.fontPaths) {+ assetServer.releaseFont(path);+ }+ for (const key of assets.spineKeys) {+ assetServer.releaseSpine(key);+ }+ }++ for (const handle of assets.materialHandles) {+ Material.release(handle);+ }++ instance.loadedAssets = null;+ }+pause(name: string): void {const instance = this.scenes_.get(name);if (!instance || instance.status !== 'running') return;@@ -524,21 +550,21 @@ export class SceneManagerState {if (world.has(entity, Sprite)) {const sprite = world.get(entity, Sprite);saved.sprite = sprite.color.a;- sprite.color = { ...sprite.color, a: 0 };+ sprite.color.a = 0;world.insert(entity, Sprite, sprite);hasSaved = true;}if (world.has(entity, SpineAnimation)) {const spine = world.get(entity, SpineAnimation);saved.spine = spine.color.a;- spine.color = { ...spine.color, a: 0 };+ spine.color.a = 0;world.insert(entity, SpineAnimation, spine);hasSaved = true;}if (world.has(entity, BitmapText)) {const bt = world.get(entity, BitmapText);saved.bitmapText = bt.color.a;- bt.color = { ...bt.color, a: 0 };+ bt.color.a = 0;world.insert(entity, BitmapText, bt);hasSaved = true;}@@ -564,17 +590,17 @@ export class SceneManagerState {if (saved.sprite !== undefined && world.has(entity, Sprite)) {const sprite = world.get(entity, Sprite);- sprite.color = { ...sprite.color, a: saved.sprite };+ sprite.color.a = saved.sprite;world.insert(entity, Sprite, sprite);}if (saved.spine !== undefined && world.has(entity, SpineAnimation)) {const spine = world.get(entity, SpineAnimation);- spine.color = { ...spine.color, a: saved.spine };+ spine.color.a = saved.spine;world.insert(entity, SpineAnimation, spine);}if (saved.bitmapText !== undefined && world.has(entity, BitmapText)) {const bt = world.get(entity, BitmapText);- bt.color = { ...bt.color, a: saved.bitmapText };+ bt.color.a = saved.bitmapText;world.insert(entity, BitmapText, bt);}}diff --git a/sdk/src/world.ts b/sdk/src/world.tsindex c2e58b985..4b1ef375b 100644--- a/sdk/src/world.ts+++ b/sdk/src/world.ts@@ -5,11 +5,24 @@import { Entity } from './types';import { AnyComponentDef, ComponentDef, ComponentData, BuiltinComponentDef, isBuiltinComponent, getAllRegisteredComponents, getComponentRegistry } from './component';-import type { CppRegistry } from './wasm';+import type { CppRegistry, ESEngineModule } from './wasm';import { validateComponentData, formatValidationErrors } from './validation';import { handleWasmError } from './wasmError';function convertForWasm(obj: Record<string, unknown>): Record<string, unknown> {+ let needsConversion = false;+ for (const key of Object.keys(obj)) {+ const val = obj[key];+ if (val !== null && val !== undefined && typeof val === 'object' && !Array.isArray(val)) {+ const rec = val as Record<string, unknown>;+ if ('r' in rec && 'g' in rec && 'b' in rec && 'a' in rec && !('x' in rec)) {+ needsConversion = true;+ break;+ }+ }+ }+ if (!needsConversion) return obj;+const result: Record<string, unknown> = {};for (const key of Object.keys(obj)) {const val = obj[key];@@ -18,7 +31,7 @@ function convertForWasm(obj: Record<string, unknown>): Record<string, unknown> {if ('r' in rec && 'g' in rec && 'b' in rec && 'a' in rec && !('x' in rec)) {result[key] = { x: rec.r, y: rec.g, z: rec.b, w: rec.a };} else {- result[key] = convertForWasm(rec);+ result[key] = val;}} else {result[key] = val;@@ -27,6 +40,48 @@ function convertForWasm(obj: Record<string, unknown>): Record<string, unknown> {return result;}+// =============================================================================+// Numeric Component IDs for Cache Keys+// =============================================================================++let nextCompNumId_ = 1;+const compNumIds_ = new WeakMap<object, number>();++function getCompNumId(comp: AnyComponentDef): number {+ let id = compNumIds_.get(comp);+ if (id === undefined) {+ id = nextCompNumId_++;+ compNumIds_.set(comp, id);+ }+ return id;+}++const _keyIds: number[] = [];++export function computeQueryCacheKey(+ components: AnyComponentDef[],+ withFilters: AnyComponentDef[] = [],+ withoutFilters: AnyComponentDef[] = [],+): string {+ _keyIds.length = 0;+ for (const c of components) _keyIds.push(getCompNumId(c));+ _keyIds.sort((a, b) => a - b);+ let key = _keyIds.join(',');+ if (withFilters.length > 0) {+ _keyIds.length = 0;+ for (const c of withFilters) _keyIds.push(getCompNumId(c));+ _keyIds.sort((a, b) => a - b);+ key += '|+' + _keyIds.join(',');+ }+ if (withoutFilters.length > 0) {+ _keyIds.length = 0;+ for (const c of withoutFilters) _keyIds.push(getCompNumId(c));+ _keyIds.sort((a, b) => a - b);+ key += '|-' + _keyIds.join(',');+ }+ return key;+}+// =============================================================================// World// =============================================================================@@ -40,7 +95,8 @@ interface BuiltinMethods {export class World {private cppRegistry_: CppRegistry | null = null;- private entities_ = new Set<Entity>();+ private module_: ESEngineModule | null = null;+ private entities_ = new Map<Entity, number>();private tsStorage_ = new Map<symbol, Map<Entity, unknown>>();private entityComponents_ = new Map<Entity, symbol[]>();private queryPool_: Entity[][] = [];@@ -50,14 +106,18 @@ export class World {private builtinMethodCache_ = new Map<string, BuiltinMethods>();private iterationDepth_ = 0;private nextEntityId_ = 0;+ private nextGeneration_ = 0;+ private despawnCallbacks_: Array<(entity: Entity) => void> = [];- connectCpp(cppRegistry: CppRegistry): void {+ connectCpp(cppRegistry: CppRegistry, module?: ESEngineModule): void {this.cppRegistry_ = cppRegistry;+ this.module_ = module ?? null;this.builtinMethodCache_.clear();}disconnectCpp(): void {this.cppRegistry_ = null;+ this.module_ = null;this.builtinMethodCache_.clear();}@@ -94,7 +154,15 @@ export class World {entity = (++this.nextEntityId_) as Entity;}- this.entities_.add(entity);+ let generation = 0;+ if (this.module_ && this.cppRegistry_) {+ try {+ generation = this.module_.registry_getGeneration(this.cppRegistry_, entity);+ } catch { /* fallback to 0 */ }+ } else {+ generation = ++this.nextGeneration_;+ }+ this.entities_.set(entity, generation);this.worldVersion_++;return entity;}@@ -107,6 +175,10 @@ export class World {);}+ for (const cb of this.despawnCallbacks_) {+ try { cb(entity); } catch {}+ }+if (this.cppRegistry_) {try {this.cppRegistry_.destroy(entity);@@ -126,6 +198,14 @@ export class World {}}+ onDespawn(callback: (entity: Entity) => void): () => void {+ this.despawnCallbacks_.push(callback);+ return () => {+ const idx = this.despawnCallbacks_.indexOf(callback);+ if (idx !== -1) this.despawnCallbacks_.splice(idx, 1);+ };+ }+valid(entity: Entity): boolean {if (this.cppRegistry_) {return this.cppRegistry_.valid(entity);@@ -148,6 +228,7 @@ export class World {endIteration(): void {this.iterationDepth_--;if (this.iterationDepth_ < 0) {+ console.warn('World.endIteration: mismatched begin/end calls');this.iterationDepth_ = 0;}}@@ -161,7 +242,7 @@ export class World {}getAllEntities(): Entity[] {- return Array.from(this.entities_);+ return Array.from(this.entities_.keys());}setParent(child: Entity, parent: Entity): void {@@ -195,6 +276,23 @@ export class World {return this.insertScript(entity, component as ComponentDef<any>, data) as ComponentData<C>;}+ set<C extends AnyComponentDef>(entity: Entity, component: C, data: ComponentData<C>): void {+ if (isBuiltinComponent(component)) {+ if (this.cppRegistry_) {+ try {+ this.getBuiltinMethods(component._cppName).add(+ entity,+ convertForWasm(data as Record<string, unknown>)+ );+ } catch (e) {+ handleWasmError(e, `set(${component._name}, entity=${entity})`);+ }+ }+ return;+ }+ this.getStorage(component as ComponentDef<any>).set(entity, data);+ }+get<C extends AnyComponentDef>(entity: Entity, component: C): ComponentData<C> {if (isBuiltinComponent(component)) {return this.getBuiltin(entity, component) as ComponentData<C>;@@ -292,15 +390,20 @@ export class World {}const merged = { ...component._default, ...filtered } as T;+ let isNew = true;if (this.cppRegistry_) {try {- this.getBuiltinMethods(component._cppName).add(entity, convertForWasm(merged as Record<string, unknown>));+ const methods = this.getBuiltinMethods(component._cppName);+ isNew = !methods.has(entity);+ methods.add(entity, convertForWasm(merged as Record<string, unknown>));} catch (e) {handleWasmError(e, `insertBuiltin(${component._name}, entity=${entity})`);}}- this.worldVersion_++;+ if (isNew) {+ this.worldVersion_++;+ }return merged;}@@ -365,8 +468,9 @@ export class World {}const value = component.create(filtered);- this.getStorage(component).set(entity, value);- this.worldVersion_++;+ const storage = this.getStorage(component);+ const isNew = !storage.has(entity);+ storage.set(entity, value);let ids = this.entityComponents_.get(entity);if (!ids) {ids = [];@@ -375,6 +479,9 @@ export class World {if (ids.indexOf(component._id) === -1) {ids.push(component._id);}+ if (isNew) {+ this.worldVersion_++;+ }return value;}@@ -422,16 +529,16 @@ export class World {}getComponentTypes(entity: Entity): string[] {- const types: string[] = [];+ const types = new Set<string>();for (const [name, methods] of this.builtinMethodCache_) {- try { if (methods.has(entity)) types.push(name); } catch {}+ try { if (methods.has(entity)) types.add(name); } catch {}}if (this.cppRegistry_) {for (const [name, comp] of getAllRegisteredComponents()) {- if (isBuiltinComponent(comp) && !types.includes(name)) {+ if (isBuiltinComponent(comp) && !types.has(name)) {try {const m = this.getBuiltinMethods(comp._cppName);- if (m.has(entity)) types.push(name);+ if (m.has(entity)) types.add(name);} catch {}}}@@ -442,31 +549,26 @@ export class World {for (const id of ids) {for (const [name, def] of registry) {if (def._id === id) {- types.push(name);+ types.add(name);break;}}}}- return types;+ return Array.from(types);}getEntitiesWithComponents(components: AnyComponentDef[],withFilters: AnyComponentDef[] = [],- withoutFilters: AnyComponentDef[] = []+ withoutFilters: AnyComponentDef[] = [],+ precomputedKey?: string): Entity[] {if (components.length === 0 && withFilters.length === 0 && withoutFilters.length === 0) {return this.getAllEntities();}- let cacheKey = components.map(c => c._name).sort().join(',');- if (withFilters.length > 0) {- cacheKey += '|+' + withFilters.map(c => c._name).sort().join(',');- }- if (withoutFilters.length > 0) {- cacheKey += '|-' + withoutFilters.map(c => c._name).sort().join(',');- }+ const cacheKey = precomputedKey ?? computeQueryCacheKey(components, withFilters, withoutFilters);const cached = this.queryCache_.get(cacheKey);if (cached && cached.version === this.worldVersion_) {return cached.result;@@ -492,17 +594,33 @@ export class World {const entities = this.queryPool_[this.queryPoolIdx_++];entities.length = 0;- const candidates = smallestPool ? smallestPool.keys() : this.entities_;+ const candidates = smallestPool ? smallestPool.keys() : this.entities_.keys();for (const entity of candidates) {- let hasAll = true;+ let match = true;for (const comp of components) {if (!this.has(entity, comp)) {- hasAll = false;+ match = false;break;}}- if (hasAll) {+ if (match) {+ for (const comp of withFilters) {+ if (!this.has(entity, comp)) {+ match = false;+ break;+ }+ }+ }+ if (match) {+ for (const comp of withoutFilters) {+ if (this.has(entity, comp)) {+ match = false;+ break;+ }+ }+ }+ if (match) {entities.push(entity);}}diff --git a/sdk/tests/validation.test.ts b/sdk/tests/validation.test.tsindex 43ecd6bb8..da6ca0ef6 100644--- a/sdk/tests/validation.test.ts+++ b/sdk/tests/validation.test.ts@@ -1,7 +1,6 @@import { describe, it, expect, beforeEach } from 'vitest';import { World } from '../src/world';import { defineComponent, defineTag } from '../src/component';-import { createMockModule } from './mocks/wasm';describe('Component Data Validation', () => {let world: World;@@ -21,8 +20,7 @@ describe('Component Data Validation', () => {});beforeEach(() => {- const module = createMockModule();- world = new World(module);+ world = new World();});describe('valid data', () => {@@ -284,7 +282,7 @@ describe('Component Data Validation', () => {describe('complex data types', () => {it('should validate nested objects', () => {- const Transform = defineComponent('Transform', {+ const Pose = defineComponent('Pose', {position: { x: 0, y: 0 },rotation: 0,});@@ -292,7 +290,7 @@ describe('Component Data Validation', () => {const entity = world.spawn();expect(() => {- world.insert(entity, Transform, {+ world.insert(entity, Pose, {position: { x: 10, y: 20 },rotation: 45,});diff --git a/sdk/tests/world.test.ts b/sdk/tests/world.test.tsindex 5f06109e5..180bc8241 100644--- a/sdk/tests/world.test.ts+++ b/sdk/tests/world.test.ts@@ -6,10 +6,10 @@ import { createMockModule } from './mocks/wasm';describe('World', () => {let world: World;- const Position = defineComponent('Position', { x: 0, y: 0 });- const Velocity = defineComponent('Velocity', { dx: 0, dy: 0 });- const Health = defineComponent('Health', { value: 100 });- const Player = defineTag('Player');+ const Position = defineComponent('TestPosition', { x: 0, y: 0 });+ const Velocity = defineComponent('TestVelocity', { dx: 0, dy: 0 });+ const Health = defineComponent('TestHealth', { value: 100 });+ const Player = defineTag('TestPlayer');beforeEach(() => {const module = createMockModule();