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(prefab): ?expand-virtual makes virtual instances whole, for a harness that expects every node at boot
yhhb8425677f301
diff --git a/sdk/src/prefab.ts b/sdk/src/prefab.tsindex 3651ad36b..b7c480ffa 100644--- a/sdk/src/prefab.ts+++ b/sdk/src/prefab.ts@@ -1,7 +1,7 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport type { DeferredRecord } from './prefab/deferred';-import { registerDeferredInstances } from './scene/deferredInstances';+import { expandVirtualRequested, registerDeferredInstances } from './scene/deferredInstances';import type { World } from './ecs/world';import type { Entity } from './types';import type { Assets } from './asset/Assets';@@ -94,7 +94,7 @@ export async function instantiatePrefab(allocateId: () => nextId++,loadPrefab: (path: string) => prefabCache.get(path) ?? null,visited: new Set<string>(),- ...(options?.expandDeferred ? {} : { deferred }),+ ...((options?.expandDeferred ?? expandVirtualRequested()) ? {} : { deferred }),};const { entities: processed, rootId } = flattenPrefab(diff --git a/sdk/src/scene/deferredInstances.ts b/sdk/src/scene/deferredInstances.tsindex bb2b4665d..e0f00edba 100644--- a/sdk/src/scene/deferredInstances.ts+++ b/sdk/src/scene/deferredInstances.ts@@ -14,6 +14,19 @@ import type { Entity } from '../types';const records = new WeakMap<World, Map<Entity, DeferredRecord>>();+/**+ * Whether the page was asked to make virtual instances whole (`?expand-virtual` in its address): a switch for looking at a game as+ * the editor shows it (an authoring preview, a pixel check of every page) and for ruling virtual instances in or out when something+ * is wrong. A page without an address (a test host, a device) answers no.+ */+export function expandVirtualRequested(): boolean {+ try {+ return new URLSearchParams((globalThis as { location?: { search?: string } }).location?.search ?? '').has('expand-virtual');+ } catch {+ return false;+ }+}+/** Remember the virtual instances a scene was loaded with: `entities` is the scene's id -> entity map the load answered. */export function registerDeferredInstances(world: World, list: readonly DeferredRecord[] | undefined, entities: ReadonlyMap<number, Entity>): void {if (!list || list.length === 0) return;diff --git a/sdk/src/scene/scene.ts b/sdk/src/scene/scene.tsindex 94fb0e264..7f3424906 100644--- a/sdk/src/scene/scene.ts+++ b/sdk/src/scene/scene.ts@@ -10,7 +10,7 @@ import { Entity, INVALID_ENTITY } from '../types';import { upgradeEntityComponents } from './legacyComponents';import { isPrefabEntry, type SceneEntry } from './sceneEntry';import { canDefer, cutToRoot, isDeferredInstance, rootOnly, rootOverrides, type DeferredRecord } from '../prefab/deferred';-import { registerDeferredInstances } from './deferredInstances';+import { expandVirtualRequested, registerDeferredInstances } from './deferredInstances';import { validateScene } from './validateScene';import { getComponent, Name, Camera, RuntimeOnly } from '../ecs/component';import { deepClone } from '../util/deepClone';@@ -311,7 +311,9 @@ const toSceneEntityData = (e: ProcessedEntity): SceneEntityData => ({export async function expandScenePrefabs(scene: SceneData,loadPrefab: PrefabAssetResolver,+ options?: { expandVirtual?: boolean },): Promise<SceneData> {+ const expandVirtual = options?.expandVirtual ?? expandVirtualRequested();const entries = scene.entities as SceneEntry[];// Allocate fresh ids for expanded internals above every id already in the// file, so they never collide with non-prefab entities or instance roots@@ -351,12 +353,12 @@ export async function expandScenePrefabs(continue;}// A virtual instance is made as its root alone (see prefab/deferred.ts); instances inside it are left to whoever opens it.- const virtual = isDeferredInstance(prefab, entry.overrides) && canDefer(entry.overrides, prefab)+ const virtual = !expandVirtual && isDeferredInstance(prefab, entry.overrides) && canDefer(entry.overrides, prefab)&& entry.added.length === 0 && entry.removed.length === 0;const stub = virtual ? rootOnly(prefab) : null;const { entities: expanded, unresolved: unresolvedAll } = expandEntry(stub ?? prefab, stub ? { ...entry, overrides: rootOverrides(prefab, entry.overrides) } : entry, allocateId,- (ref) => cache.get(ref) ?? null, deferred);+ (ref) => cache.get(ref) ?? null, expandVirtual ? undefined : deferred);const entities = virtual && !stub ? cutToRoot(expanded, entry.id) : expanded;const unresolved = virtual ? [] : unresolvedAll;if (virtual) deferred.push({ id: entry.id, prefab: entry.prefab, overrides: entry.overrides.map((o) => ({ ...o })) });diff --git a/sdk/tests/deferred-instances.test.ts b/sdk/tests/deferred-instances.test.tsindex aec2ea2fe..abd85443e 100644--- a/sdk/tests/deferred-instances.test.ts+++ b/sdk/tests/deferred-instances.test.ts@@ -79,6 +79,36 @@ describe('virtual prefab instances: loading a scene', () => {});});+describe('virtual prefab instances: the page can ask for them whole', () => {+ const withAddress = async (search: string | undefined, run: () => Promise<void>) => {+ const g = globalThis as { location?: unknown };+ const before = Object.getOwnPropertyDescriptor(globalThis, 'location');+ Object.defineProperty(globalThis, 'location', { value: search === undefined ? undefined : { search }, configurable: true, writable: true });+ try { await run(); } finally { if (before) Object.defineProperty(globalThis, 'location', before); else delete g.location; }+ };+ const prefabs = { shop: prefab('shop', ['x', 'y']) };+ it('?expand-virtual makes a marked instance whole, with nothing to open later', async () => {+ await withAddress('?headless&expand-virtual', async () => {+ const out = await expandScenePrefabs(sceneOf(entry(3, 'shop', [mark()])), loader(prefabs));+ expect(out.entities.map((e) => e.name)).toEqual(expect.arrayContaining(['shop', 'x', 'y']));+ expect(out.deferredInstances).toBeUndefined();+ });+ });+ it('without it, and on a page with no address, the instance stays virtual', async () => {+ await withAddress('?headless', async () => {+ expect((await expandScenePrefabs(sceneOf(entry(3, 'shop', [mark()])), loader(prefabs))).deferredInstances).toHaveLength(1);+ });+ await withAddress(undefined, async () => {+ expect((await expandScenePrefabs(sceneOf(entry(3, 'shop', [mark()])), loader(prefabs))).deferredInstances).toHaveLength(1);+ });+ });+ it('the option wins over the address', async () => {+ await withAddress('?expand-virtual', async () => {+ expect((await expandScenePrefabs(sceneOf(entry(3, 'shop', [mark()])), loader(prefabs), { expandVirtual: false })).deferredInstances).toHaveLength(1);+ });+ });+});+describe.skipIf(!HAS_WASM)('virtual prefab instances: in a world', () => {let engine: ESEngineModule;beforeAll(async () => { engine = await loadWasmModule(); });