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
perf: optimize physics sync (37x), forEach (1.75x), world.has (2x)
esengine9e0972469a55
diff --git a/sdk/benchmarks/physics.bench.ts b/sdk/benchmarks/physics.bench.tsnew file mode 100644index 000000000..7761d444f--- /dev/null+++ b/sdk/benchmarks/physics.bench.ts@@ -0,0 +1,498 @@+import { describe, bench, beforeAll } from 'vitest';+import path from 'path';+import { World } from '../src/world';+import { defineBuiltin } from '../src/component';+import type { CppRegistry, ESEngineModule } from '../src/wasm';+import type { PhysicsWasmModule } from '../src/physics/PhysicsModuleLoader';+import { syncDynamicTransforms } from '../src/physics/PhysicsPlugin';+import type { Entity } from '../src/types';++let wasmModule: ESEngineModule;+let physicsMod: PhysicsWasmModule;++const WASM_DIR = path.resolve(__dirname, '../../desktop/public/wasm');++beforeAll(async () => {+ const engineJs = path.join(WASM_DIR, 'esengine.js');+ const engineMod = await import(engineJs);+ wasmModule = await engineMod.default({+ locateFile(p: string) { return path.join(WASM_DIR, p); },+ });++ const physicsJs = path.join(WASM_DIR, 'physics.js');+ const physicsFn = await import(physicsJs);+ physicsMod = await physicsFn.default({+ locateFile(p: string) { return path.join(WASM_DIR, p); },+ }) as PhysicsWasmModule;+ physicsMod._physics_init(0, -9.81, 1 / 30, 4, 30, 10, 3);+});++const Transform = defineBuiltin('Transform', {+ position: { x: 0, y: 0, z: 0 },+ rotation: { x: 0, y: 0, z: 0, w: 1 },+ scale: { x: 1, y: 1, z: 1 },+ worldPosition: { x: 0, y: 0, z: 0 },+ worldRotation: { x: 0, y: 0, z: 0, w: 1 },+ worldScale: { x: 1, y: 1, z: 1 },+});++const RigidBody = defineBuiltin('RigidBody', {+ bodyType: 2, gravityScale: 1, linearDamping: 0, angularDamping: 0,+ fixedRotation: false, bullet: false, enabled: true,+});++const PPU = 100;+const INV_PPU = 1 / PPU;++const TRANSFORM_DATA = {+ position: { x: 0, y: 0, z: 0 },+ rotation: { x: 0, y: 0, z: 0, w: 1 },+ scale: { x: 1, y: 1, z: 1 },+ worldPosition: { x: 0, y: 0, z: 0 },+ worldRotation: { x: 0, y: 0, z: 0, w: 1 },+ worldScale: { x: 1, y: 1, z: 1 },+};++const RIGIDBODY_DATA = {+ bodyType: 2, gravityScale: 1, linearDamping: 0.1, angularDamping: 0.05,+ fixedRotation: false, bullet: false, enabled: true,+};++function createBodies(count: number, reg: CppRegistry) {+ const ids: number[] = [];+ for (let i = 0; i < count; i++) {+ const e = reg.create!();+ (reg as any).addTransform(e, TRANSFORM_DATA);+ physicsMod._physics_createBody(e, 2, i * 0.5 * INV_PPU, i * 0.3 * INV_PPU, 0, 1, 0, 0, 0, 0);+ physicsMod._physics_addBoxShape(e, 0.5, 0.5, 0, 0, 0.05, 1, 0.3, 0, 0, 0x0001, 0xFFFF);+ ids.push(e as number);+ }+ return ids;+}++function destroyBodies(ids: number[]) {+ for (const e of ids) physicsMod._physics_destroyBody(e);+}++// =============================================================================+// _physics_step — Box2D simulation cost+// =============================================================================++describe('Physics - _physics_step (Box2D simulation)', () => {+ bench('step (0 bodies)', () => {+ physicsMod._physics_step(1 / 60);+ });++ bench('step (50 bodies)', () => {+ const reg = new wasmModule.Registry();+ const ids = createBodies(50, reg as unknown as CppRegistry);+ physicsMod._physics_step(1 / 60);+ destroyBodies(ids);+ reg.delete();+ });++ bench('step (200 bodies)', () => {+ const reg = new wasmModule.Registry();+ const ids = createBodies(200, reg as unknown as CppRegistry);+ physicsMod._physics_step(1 / 60);+ destroyBodies(ids);+ reg.delete();+ });++ bench('step (500 bodies)', () => {+ const reg = new wasmModule.Registry();+ const ids = createBodies(500, reg as unknown as CppRegistry);+ physicsMod._physics_step(1 / 60);+ destroyBodies(ids);+ reg.delete();+ });+});++// =============================================================================+// syncDynamicTransforms — read from physics, write to ECS+// =============================================================================++describe('Physics - syncDynamicTransforms', () => {+ bench('50 bodies', () => {+ const reg = new wasmModule.Registry();+ const ids = createBodies(50, reg as unknown as CppRegistry);+ physicsMod._physics_step(1 / 60);+ const world = new World();+ world.connectCpp(reg as unknown as CppRegistry, wasmModule);+ syncDynamicTransforms({ world } as any, physicsMod, PPU, new Set());+ destroyBodies(ids);+ reg.delete();+ });++ bench('200 bodies', () => {+ const reg = new wasmModule.Registry();+ const ids = createBodies(200, reg as unknown as CppRegistry);+ physicsMod._physics_step(1 / 60);+ const world = new World();+ world.connectCpp(reg as unknown as CppRegistry, wasmModule);+ syncDynamicTransforms({ world } as any, physicsMod, PPU, new Set());+ destroyBodies(ids);+ reg.delete();+ });++ bench('500 bodies', () => {+ const reg = new wasmModule.Registry();+ const ids = createBodies(500, reg as unknown as CppRegistry);+ physicsMod._physics_step(1 / 60);+ const world = new World();+ world.connectCpp(reg as unknown as CppRegistry, wasmModule);+ syncDynamicTransforms({ world } as any, physicsMod, PPU, new Set());+ destroyBodies(ids);+ reg.delete();+ });+});++// =============================================================================+// Body creation cost+// =============================================================================++describe('Physics - body creation (createBody + addBoxShape)', () => {+ bench('create + shape x50', () => {+ const reg = new wasmModule.Registry();+ const ids: number[] = [];+ for (let i = 0; i < 50; i++) {+ const e = (reg as any).create();+ physicsMod._physics_createBody(e, 2, i * INV_PPU, 0, 0, 1, 0, 0, 0, 0);+ physicsMod._physics_addBoxShape(e, 0.5, 0.5, 0, 0, 0.05, 1, 0.3, 0, 0, 0x0001, 0xFFFF);+ ids.push(e);+ }+ for (const e of ids) physicsMod._physics_destroyBody(e);+ reg.delete();+ });++ bench('create + shape x200', () => {+ const reg = new wasmModule.Registry();+ const ids: number[] = [];+ for (let i = 0; i < 200; i++) {+ const e = (reg as any).create();+ physicsMod._physics_createBody(e, 2, i * INV_PPU, 0, 0, 1, 0, 0, 0, 0);+ physicsMod._physics_addBoxShape(e, 0.5, 0.5, 0, 0, 0.05, 1, 0.3, 0, 0, 0x0001, 0xFFFF);+ ids.push(e);+ }+ for (const e of ids) physicsMod._physics_destroyBody(e);+ reg.delete();+ });+});++// =============================================================================+// collectEvents+// =============================================================================++describe('Physics - collectEvents', () => {+ bench('collectEvents (0 collisions)', () => {+ physicsMod._physics_collectEvents();+ physicsMod._physics_getCollisionEnterCount();+ physicsMod._physics_getCollisionExitCount();+ physicsMod._physics_getSensorEnterCount();+ physicsMod._physics_getSensorExitCount();+ });++ bench('step + collectEvents (50 stacked bodies)', () => {+ const reg = new wasmModule.Registry();+ const ids: number[] = [];+ for (let i = 0; i < 50; i++) {+ const e = (reg as any).create();+ physicsMod._physics_createBody(e, 2, 0, i * 1.1, 0, 1, 0, 0, 0, 0);+ physicsMod._physics_addBoxShape(e, 0.5, 0.5, 0, 0, 0, 1, 0.3, 0.1, 0, 0x0001, 0xFFFF);+ ids.push(e);+ }+ physicsMod._physics_step(1 / 60);+ physicsMod._physics_collectEvents();+ const enterCount = physicsMod._physics_getCollisionEnterCount();+ if (enterCount > 0) {+ const enterPtr = physicsMod._physics_getCollisionEnterBuffer() >> 2;+ for (let i = 0; i < enterCount; i++) {+ const base = enterPtr + i * 6;+ const _a = physicsMod.HEAPU32[base];+ const _b = physicsMod.HEAPU32[base + 1];+ }+ }+ for (const e of ids) physicsMod._physics_destroyBody(e);+ reg.delete();+ });+});++// =============================================================================+// Full physics frame — step + sync + events+// =============================================================================++describe('Physics - full frame (step + sync + events)', () => {+ bench('50 bodies', () => {+ const reg = new wasmModule.Registry();+ const ids = createBodies(50, reg as unknown as CppRegistry);+ const world = new World();+ world.connectCpp(reg as unknown as CppRegistry, wasmModule);+ physicsMod._physics_step(1 / 60);+ syncDynamicTransforms({ world } as any, physicsMod, PPU, new Set());+ physicsMod._physics_collectEvents();+ destroyBodies(ids);+ reg.delete();+ });++ bench('200 bodies', () => {+ const reg = new wasmModule.Registry();+ const ids = createBodies(200, reg as unknown as CppRegistry);+ const world = new World();+ world.connectCpp(reg as unknown as CppRegistry, wasmModule);+ physicsMod._physics_step(1 / 60);+ syncDynamicTransforms({ world } as any, physicsMod, PPU, new Set());+ physicsMod._physics_collectEvents();+ destroyBodies(ids);+ reg.delete();+ });++ bench('500 bodies', () => {+ const reg = new wasmModule.Registry();+ const ids = createBodies(500, reg as unknown as CppRegistry);+ const world = new World();+ world.connectCpp(reg as unknown as CppRegistry, wasmModule);+ physicsMod._physics_step(1 / 60);+ syncDynamicTransforms({ world } as any, physicsMod, PPU, new Set());+ physicsMod._physics_collectEvents();+ destroyBodies(ids);+ reg.delete();+ });+});++// =============================================================================+// addTransform writeback isolation (embind vs ptr)+// =============================================================================++describe('Physics - addTransform writeback (embind vs ptr)', () => {+ bench('registry.addTransform x200 (embind)', () => {+ const reg = new wasmModule.Registry();+ const entities: number[] = [];+ for (let i = 0; i < 200; i++) {+ const e = (reg as any).create();+ (reg as any).addTransform(e, TRANSFORM_DATA);+ entities.push(e);+ }+ for (const e of entities) (reg as any).addTransform(e, TRANSFORM_DATA);+ reg.delete();+ });++ bench('ptr setter x200 (resolvedSetter)', () => {+ const world = new World();+ const reg = new wasmModule.Registry();+ world.connectCpp(reg as unknown as CppRegistry, wasmModule);+ const entities: Entity[] = [];+ for (let i = 0; i < 200; i++) {+ const e = world.spawn();+ world.insert(e, Transform, TRANSFORM_DATA as any);+ entities.push(e);+ }+ const setter = world.resolveSetter(Transform)!;+ for (const e of entities) setter(e, TRANSFORM_DATA);+ reg.delete();+ });+});++// =============================================================================+// Entity query overhead+// =============================================================================++describe('Physics - entity sync query', () => {+ bench('getEntitiesWithComponents([RigidBody, Transform]) x10 (200 entities)', () => {+ const world = new World();+ const reg = new wasmModule.Registry();+ world.connectCpp(reg as unknown as CppRegistry, wasmModule);+ for (let i = 0; i < 200; i++) {+ const e = world.spawn();+ world.insert(e, Transform, TRANSFORM_DATA as any);+ world.insert(e, RigidBody, RIGIDBODY_DATA as any);+ }+ for (let i = 0; i < 10; i++) {+ world.getEntitiesWithComponents([RigidBody, Transform]);+ }+ reg.delete();+ });+});++// =============================================================================+// syncDynamicTransforms — isolated batch vs embind comparison+// =============================================================================++describe('Physics - syncDynamicTransforms (batch vs embind)', () => {+ let reg: CppRegistry;+ let worldBatch: World;+ let worldEmbind: World;++ function ensureSetup() {+ if (reg) return;+ reg = new wasmModule.Registry() as unknown as CppRegistry;+ createBodies(200, reg);+ physicsMod._physics_step(1 / 60);+ worldBatch = new World();+ worldBatch.connectCpp(reg, wasmModule);+ worldEmbind = new World();+ worldEmbind.connectCpp(reg);+ }++ bench('batch sync (200 bodies)', () => {+ ensureSetup();+ syncDynamicTransforms({ world: worldBatch } as any, physicsMod, PPU, new Set());+ });++ bench('embind sync (200 bodies)', () => {+ ensureSetup();+ syncDynamicTransforms({ world: worldEmbind } as any, physicsMod, PPU, new Set());+ });+});++// =============================================================================+// _physics_step — isolated: sleeping vs active bodies+// =============================================================================++describe('Physics - step cost: sleeping vs active (200 bodies)', () => {+ let sleepReg: CppRegistry | null = null;+ let sleepIds: number[] = [];+ let activeReg: CppRegistry | null = null;+ let activeIds: number[] = [];++ function ensureSleepSetup() {+ if (sleepReg) return;+ physicsMod._physics_shutdown();+ physicsMod._physics_init(0, -9.81, 1 / 60, 4, 30, 10, 3);+ sleepReg = new wasmModule.Registry() as unknown as CppRegistry;+ sleepIds = createBodies(200, sleepReg);+ for (let i = 0; i < 120; i++) physicsMod._physics_step(1 / 60);+ }++ function ensureActiveSetup() {+ if (activeReg) return;+ physicsMod._physics_shutdown();+ physicsMod._physics_init(0, -9.81, 1 / 60, 4, 30, 10, 3);+ activeReg = new wasmModule.Registry() as unknown as CppRegistry;+ activeIds = [];+ for (let i = 0; i < 200; i++) {+ const e = (activeReg as any).create();+ (activeReg as any).addTransform(e, TRANSFORM_DATA);+ physicsMod._physics_createBody(e, 2, (i % 20) * 0.5 * INV_PPU, Math.floor(i / 20) * 0.6 * INV_PPU, 0, 1, 0, 0, 0, 0);+ physicsMod._physics_addBoxShape(e, 0.25, 0.25, 0, 0, 0.02, 1, 0.3, 0.1, 0, 0x0001, 0xFFFF);+ activeIds.push(e);+ }+ physicsMod._physics_step(1 / 60);+ }++ bench('sleeping bodies (settled)', () => {+ ensureSleepSetup();+ physicsMod._physics_step(1 / 60);+ });++ bench('active bodies (perturbed each frame)', () => {+ ensureActiveSetup();+ for (let i = 0; i < activeIds.length; i += 10) {+ physicsMod._physics_setLinearVelocity(activeIds[i], (i % 3 - 1) * 0.5, 2);+ }+ physicsMod._physics_step(1 / 60);+ });+});++// =============================================================================+// _physics_step — subStepCount tuning (active bodies)+// =============================================================================++describe('Physics - step tuning: subStepCount (200 active bodies)', () => {+ let setupDone = false;+ let bodyIds: number[] = [];+ let curSubSteps = -1;++ function setupForSubSteps(subSteps: number) {+ if (curSubSteps === subSteps) return;+ physicsMod._physics_shutdown();+ physicsMod._physics_init(0, -9.81, 1 / 60, subSteps, 30, 10, 3);+ const reg = new wasmModule.Registry() as unknown as CppRegistry;+ bodyIds = [];+ for (let i = 0; i < 200; i++) {+ const e = (reg as any).create();+ (reg as any).addTransform(e, TRANSFORM_DATA);+ physicsMod._physics_createBody(e, 2, (i % 20) * 0.5 * INV_PPU, Math.floor(i / 20) * 0.6 * INV_PPU, 0, 1, 0, 0, 0, 0);+ physicsMod._physics_addBoxShape(e, 0.25, 0.25, 0, 0, 0.02, 1, 0.3, 0.1, 0, 0x0001, 0xFFFF);+ bodyIds.push(e);+ }+ physicsMod._physics_step(1 / 60);+ curSubSteps = subSteps;+ }++ function perturbAndStep() {+ for (let i = 0; i < bodyIds.length; i += 10) {+ physicsMod._physics_setLinearVelocity(bodyIds[i], (i % 3 - 1) * 0.5, 2);+ }+ physicsMod._physics_step(1 / 60);+ }++ bench('subSteps=1', () => { setupForSubSteps(1); perturbAndStep(); });+ bench('subSteps=2', () => { setupForSubSteps(2); perturbAndStep(); });+ bench('subSteps=4 (default)', () => { setupForSubSteps(4); perturbAndStep(); });+});++// =============================================================================+// Full physics frame — isolated (step + batch sync + events)+// =============================================================================++describe('Physics - full frame isolated (200 active bodies)', () => {+ let reg: CppRegistry;+ let world: World;+ let bodyIds: number[];+ let ready = false;++ function ensureSetup() {+ if (ready) return;+ physicsMod._physics_shutdown();+ physicsMod._physics_init(0, -9.81, 1 / 60, 4, 30, 10, 3);+ reg = new wasmModule.Registry() as unknown as CppRegistry;+ bodyIds = [];+ for (let i = 0; i < 200; i++) {+ const e = (reg as any).create();+ (reg as any).addTransform(e, TRANSFORM_DATA);+ physicsMod._physics_createBody(e, 2, (i % 20) * 0.5 * INV_PPU, Math.floor(i / 20) * 0.6 * INV_PPU, 0, 1, 0, 0, 0, 0);+ physicsMod._physics_addBoxShape(e, 0.25, 0.25, 0, 0, 0.02, 1, 0.3, 0.1, 0, 0x0001, 0xFFFF);+ bodyIds.push(e);+ }+ world = new World();+ world.connectCpp(reg, wasmModule);+ physicsMod._physics_step(1 / 60);+ ready = true;+ }++ bench('full frame (step + sync + events)', () => {+ ensureSetup();+ for (let i = 0; i < bodyIds.length; i += 10) {+ physicsMod._physics_setLinearVelocity(bodyIds[i], (i % 3 - 1) * 0.5, 2);+ }+ physicsMod._physics_step(1 / 60);+ syncDynamicTransforms({ world } as any, physicsMod, PPU, new Set());+ physicsMod._physics_collectEvents();+ });+});++// =============================================================================+// Trig cost baseline+// =============================================================================++describe('Physics - trig overhead (per-body math)', () => {+ bench('Math.cos + Math.sin x500 (angle→quat)', () => {+ let sumW = 0, sumZ = 0;+ for (let i = 0; i < 500; i++) {+ const half = i * 0.005;+ sumW += Math.cos(half);+ sumZ += Math.sin(half);+ }+ if (sumW + sumZ === -Infinity) throw new Error();+ });++ bench('Math.atan2 x500 (quat→angle)', () => {+ let sum = 0;+ for (let i = 0; i < 500; i++) {+ const w = Math.cos(i * 0.005);+ const z = Math.sin(i * 0.005);+ sum += Math.atan2(2 * w * z, 1 - 2 * z * z);+ }+ if (sum === -Infinity) throw new Error();+ });+});diff --git a/sdk/src/physics/PhysicsPlugin.ts b/sdk/src/physics/PhysicsPlugin.tsindex 104b2fe7e..ad564aab5 100644--- a/sdk/src/physics/PhysicsPlugin.ts+++ b/sdk/src/physics/PhysicsPlugin.ts@@ -431,6 +431,9 @@ const syncTransformBuf_ = {worldScale: { x: 1, y: 1, z: 1 },};+const PHYSICS_BODY_STRIDE = 4; // u32 entity + 3x f32 (x, y, angle)+const PHYSICS_BODY_BYTES = PHYSICS_BODY_STRIDE * 4;+/** @internal exported for testing */export function syncDynamicTransforms(app: App,@@ -443,21 +446,43 @@ export function syncDynamicTransforms(const ptr = module._physics_getDynamicBodyTransforms();const baseU32 = ptr >> 2;- const heap32 = module.HEAPU32;- const heapF = module.HEAPF32;+ const physU32 = module.HEAPU32;+ const physF32 = module.HEAPF32;const registry = app.world.getCppRegistry();if (!registry) return;- const addFn = registry.addTransform.bind(registry);++ const engineMod = app.world.getWasmModule();const hasParented = parentedBodies.size > 0;++ if (!hasParented && engineMod?.registry_batchSyncPhysicsTransforms) {+ const byteLen = count * PHYSICS_BODY_BYTES;+ const engineBuf = engineMod._malloc(byteLen);+ engineMod.HEAPU8.set(+ new Uint8Array(module.HEAPU8.buffer, ptr, byteLen),+ engineBuf,+ );+ engineMod.registry_batchSyncPhysicsTransforms(registry, engineBuf, count, ppu);+ engineMod._free(engineBuf);+ return;+ }++ const getTransformPtr = engineMod?.getTransformPtr+ ? (e: Entity) => engineMod!.getTransformPtr(registry!, e as number)+ : null;+ const engF32 = engineMod?.HEAPF32;+ const addFn = (!getTransformPtr || !engF32)+ ? registry.addTransform.bind(registry)+ : null;+const t = syncTransformBuf_;for (let i = 0; i < count; i++) {- const offset = baseU32 + i * 4;- const entityId = heap32[offset] as Entity;- let localX = heapF[offset + 1] * ppu;- let localY = heapF[offset + 2] * ppu;- let localAngle = heapF[offset + 3];+ const offset = baseU32 + i * PHYSICS_BODY_STRIDE;+ const entityId = physU32[offset] as Entity;+ let localX = physF32[offset + 1] * ppu;+ let localY = physF32[offset + 2] * ppu;+ let localAngle = physF32[offset + 3];if (hasParented && parentedBodies.has(entityId)) {const parentData = app.world.get(entityId, Parent) as ParentData;@@ -481,6 +506,35 @@ export function syncDynamicTransforms(const half = localAngle * 0.5;const cosH = Math.cos(half);const sinH = Math.sin(half);++ if (getTransformPtr && engF32) {+ const tPtr = getTransformPtr(entityId);+ if (tPtr) {+ const fi = tPtr >> 2;+ engF32[fi] = localX;+ engF32[fi + 1] = localY;+ engF32[fi + 2] = 0;+ engF32[fi + 3] = 0;+ engF32[fi + 4] = 0;+ engF32[fi + 5] = sinH;+ engF32[fi + 6] = cosH;+ engF32[fi + 7] = 1;+ engF32[fi + 8] = 1;+ engF32[fi + 9] = 1;+ engF32[fi + 10] = localX;+ engF32[fi + 11] = localY;+ engF32[fi + 12] = 0;+ engF32[fi + 13] = 0;+ engF32[fi + 14] = 0;+ engF32[fi + 15] = sinH;+ engF32[fi + 16] = cosH;+ engF32[fi + 17] = 1;+ engF32[fi + 18] = 1;+ engF32[fi + 19] = 1;+ continue;+ }+ }+t.position.x = localX;t.position.y = localY;t.rotation.w = cosH;@@ -494,7 +548,7 @@ export function syncDynamicTransforms(t.worldRotation.y = 0;t.worldRotation.z = sinH;- addFn(entityId, t);+ addFn!(entityId, t);}}diff --git a/sdk/src/query.ts b/sdk/src/query.tsindex 6721980ae..a25c75d0c 100644--- a/sdk/src/query.ts+++ b/sdk/src/query.ts@@ -303,9 +303,64 @@ export class QueryInstance<C extends readonly QueryArg[]> implements Iterable<Qu}forEach(callback: (entity: Entity, ...components: ComponentsData<C>) => void): void {- for (const [entity, ...components] of this) {- callback(entity, ...(components as ComponentsData<C>));+ const { _mutIndices } = this.descriptor_;+ const entities = this.world_.getEntitiesWithComponents(+ this.allRequired_,+ this.descriptor_._with,+ this.descriptor_._without,+ this.cacheKey_+ );+ const compCount = this.actualComponents_.length;+ const hasMut = _mutIndices.length > 0;+ const hasChangeFilters = this.descriptor_._addedFilters.length > 0 || this.descriptor_._changedFilters.length > 0;+ const result = this.result_;+ const mutData = this.mutData_;+ const mutCount = mutData.length;+ const mutSetters = this.mutSetters_;+ const world = this.world_;+ const getters = this.getters_;+ const actualComponents = this.actualComponents_;++ world.beginIteration();+ let prevEntity: Entity | null = null;+ for (let idx = 0; idx < entities.length; idx++) {+ const entity = entities[idx];+ if (hasChangeFilters && !this.passesChangeFilters_(entity)) continue;++ if (prevEntity !== null && hasMut) {+ for (let i = 0; i < mutCount; i++) {+ const mut = mutData[i];+ const setter = mutSetters[i];+ if (setter) setter(prevEntity, mut.data);+ else world.set(prevEntity, mut.component, mut.data);+ }+ }++ result[0] = entity;+ for (let i = 0; i < compCount; i++) {+ const getter = getters[i];+ result[i + 1] = getter ? getter(entity) : world.get(entity, actualComponents[i]);+ }++ if (hasMut) {+ for (let i = 0; i < mutCount; i++) {+ mutData[i].data = result[_mutIndices[i] + 1] as Record<string, unknown>;+ }+ prevEntity = entity;+ }++ (callback as Function).apply(null, result);+ }++ if (prevEntity !== null && hasMut) {+ for (let i = 0; i < mutCount; i++) {+ const mut = mutData[i];+ const setter = mutSetters[i];+ if (setter) setter(prevEntity, mut.data);+ else world.set(prevEntity, mut.component, mut.data);+ }}+ world.endIteration();}single(): QueryResult<C> | null {diff --git a/sdk/src/world.ts b/sdk/src/world.tsindex fd90264c3..3b6b32ad4 100644--- a/sdk/src/world.ts+++ b/sdk/src/world.ts@@ -162,14 +162,14 @@ const PTR_LAYOUTS: Record<string, PtrLayout> = {};function readPtrField(- f32: Float32Array, i32: Int32Array, u32: Uint32Array, u8: Uint8Array,+ f32: Float32Array, u32: Uint32Array, u8: Uint8Array,ptr: number, field: PtrFieldDesc,): unknown {const byteOff = ptr + field.offset;const idx = byteOff >> 2;switch (field.type) {case 'f32': return f32[idx];- case 'i32': return i32[idx];+ case 'i32': return u32[idx] | 0;case 'u32': return u32[idx];case 'bool': return u8[byteOff] !== 0;case 'u8': return u8[byteOff];@@ -181,14 +181,14 @@ function readPtrField(}function writePtrField(- f32: Float32Array, i32: Int32Array, u32: Uint32Array, u8: Uint8Array,+ f32: Float32Array, u32: Uint32Array, u8: Uint8Array,ptr: number, field: PtrFieldDesc, value: any,): void {const byteOff = ptr + field.offset;const idx = byteOff >> 2;switch (field.type) {case 'f32': f32[idx] = value; break;- case 'i32': i32[idx] = value; break;+ case 'i32': u32[idx] = value | 0; break;case 'u32': u32[idx] = value; break;case 'bool': u8[byteOff] = value ? 1 : 0; break;case 'u8': u8[byteOff] = value; break;@@ -295,6 +295,11 @@ export class World {return this.cppRegistry_;}+ /** @internal */+ getWasmModule(): ESEngineModule | null {+ return this.module_;+ }+// =========================================================================// Entity Management// =========================================================================@@ -499,8 +504,9 @@ export class World {}has(entity: Entity, component: AnyComponentDef): boolean {- if (isBuiltinComponent(component)) {- return this.hasBuiltin(entity, component);+ if (component._builtin) {+ if (!this.cppRegistry_) return false;+ return this.getBuiltinMethods((component as BuiltinComponentDef<any>)._cppName).has(entity);}return this.hasScript(entity, component as ComponentDef<any>);}@@ -811,7 +817,7 @@ export class World {if (!ptr) return;const d = data as any;for (let i = 0; i < fields.length; i++) {- writePtrField(mod.HEAPF32, mod.HEAP32, mod.HEAPU32, mod.HEAPU8, ptr, fields[i], d[fields[i].name]);+ writePtrField(mod.HEAPF32, mod.HEAPU32, mod.HEAPU8, ptr, fields[i], d[fields[i].name]);}};}@@ -828,7 +834,7 @@ export class World {if (!ptr) return null;const result: Record<string, unknown> = {};for (let i = 0; i < fields.length; i++) {- result[fields[i].name] = readPtrField(mod.HEAPF32, mod.HEAP32, mod.HEAPU32, mod.HEAPU8, ptr, fields[i]);+ result[fields[i].name] = readPtrField(mod.HEAPF32, mod.HEAPU32, mod.HEAPU8, ptr, fields[i]);}return result;};