Skip to content

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.

fix(sdk): two contracts the docs stated and the types did not

esenginedc2b30a1792a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index dd0b06f5b..b92985784 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -29,6 +29,18 @@ published separately; it ships inside the editor.
### Changed
+- **The scene format version is an integer, and `withScratch` refuses an async
+ callback.** The format version was compared with `parseFloat`, which reads
+ "1.10" as 1.1 and sorts it BELOW "1.2", and reads "1.0.1" as 1 — so once the
+ format reached its tenth revision, a newer file would have been read as older
+ and migrated backwards. With only "1.0" ever written, nothing could have caught
+ it. It is now a single integer that counts up (`version: 1`); every file written
+ before this is format 1, and reading one is unchanged. `withScratch` frees its
+ scratch pointers in a `finally`, so an `async` callback — which returns at its
+ first `await` — resumed onto a heap where every pointer it held was already
+ freed. The docs said "must be synchronous"; the type now says it, and an async
+ callback is a compile error at the call site.
+
- **A blended draw now sorts by depth before material.** The sort key ranked
material above depth for every stage, so within one sorting layer three
semi-transparent sprites at different z on materials B, A, B did not necessarily
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 482621b98..b8ce93acd 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -5969,7 +5969,7 @@ ComponentDef<{}>
## SCENE_FORMAT_VERSION — const
```
-"1.0"
+1
```
## SCREEN_FIT_OFF — const
@@ -6121,7 +6121,7 @@ entities: SceneEntityData[]
generator: string | undefined
name: string
textureMetadata: Record<string, TextureMetadata> | undefined
-version: string
+version: string | number
```
## SceneEntityData — interface
@@ -6194,9 +6194,9 @@ static prototype: SceneManagerState
## SceneMigrationResult — interface
```
data: SceneData
-fromVersion: string
+fromVersion: number
migrated: boolean
-toVersion: string
+toVersion: number
```
## SceneOwner — const
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index b424b06e6..568a843c6 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -6139,7 +6139,7 @@ ComponentDef<{}>
## SCENE_FORMAT_VERSION — const
```
-"1.0"
+1
```
## SCREEN_FIT_OFF — const
@@ -6291,7 +6291,7 @@ entities: SceneEntityData[]
generator: string | undefined
name: string
textureMetadata: Record<string, TextureMetadata> | undefined
-version: string
+version: string | number
```
## SceneEntityData — interface
@@ -6364,9 +6364,9 @@ static prototype: SceneManagerState
## SceneMigrationResult — interface
```
data: SceneData
-fromVersion: string
+fromVersion: number
migrated: boolean
-toVersion: string
+toVersion: number
```
## SceneOwner — const
diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.md
index 2cddf679a..d0dbcef5f 100644
--- a/sdk/etc/index.node.api.md
+++ b/sdk/etc/index.node.api.md
@@ -5964,7 +5964,7 @@ ComponentDef<{}>
## SCENE_FORMAT_VERSION — const
```
-"1.0"
+1
```
## SCREEN_FIT_OFF — const
@@ -6116,7 +6116,7 @@ entities: SceneEntityData[]
generator: string | undefined
name: string
textureMetadata: Record<string, TextureMetadata> | undefined
-version: string
+version: string | number
```
## SceneEntityData — interface
@@ -6189,9 +6189,9 @@ static prototype: SceneManagerState
## SceneMigrationResult — interface
```
data: SceneData
-fromVersion: string
+fromVersion: number
migrated: boolean
-toVersion: string
+toVersion: number
```
## SceneOwner — const
diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.md
index 2ca1648a8..a4576d531 100644
--- a/sdk/etc/minigame.api.md
+++ b/sdk/etc/minigame.api.md
@@ -6209,7 +6209,7 @@ ComponentDef<{}>
## SCENE_FORMAT_VERSION — const
```
-"1.0"
+1
```
## SCREEN_FIT_OFF — const
@@ -6361,7 +6361,7 @@ entities: SceneEntityData[]
generator: string | undefined
name: string
textureMetadata: Record<string, TextureMetadata> | undefined
-version: string
+version: string | number
```
## SceneEntityData — interface
@@ -6434,9 +6434,9 @@ static prototype: SceneManagerState
## SceneMigrationResult — interface
```
data: SceneData
-fromVersion: string
+fromVersion: number
migrated: boolean
-toVersion: string
+toVersion: number
```
## SceneOwner — const
diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.md
index f199d4474..ff7f991aa 100644
--- a/sdk/etc/wechat.api.md
+++ b/sdk/etc/wechat.api.md
@@ -5971,7 +5971,7 @@ ComponentDef<{}>
## SCENE_FORMAT_VERSION — const
```
-"1.0"
+1
```
## SCREEN_FIT_OFF — const
@@ -6123,7 +6123,7 @@ entities: SceneEntityData[]
generator: string | undefined
name: string
textureMetadata: Record<string, TextureMetadata> | undefined
-version: string
+version: string | number
```
## SceneEntityData — interface
@@ -6196,9 +6196,9 @@ static prototype: SceneManagerState
## SceneMigrationResult — interface
```
data: SceneData
-fromVersion: string
+fromVersion: number
migrated: boolean
-toVersion: string
+toVersion: number
```
## SceneOwner — const
diff --git a/sdk/src/scene/scene.ts b/sdk/src/scene/scene.ts
index 1ee36d2ba..27478d813 100644
--- a/sdk/src/scene/scene.ts
+++ b/sdk/src/scene/scene.ts
@@ -55,7 +55,13 @@ export interface TextureMetadata {
}
export interface SceneData {
- version: string;
+ /**
+ * Format version: one integer that only counts up. Files written before it
+ * became an integer carry a `"major.minor"` string, which
+ * {@link migrateSceneData} normalizes — read it through
+ * {@link parseSceneFormatVersion}, never by comparing it directly.
+ */
+ version: number | string;
name: string;
/** Origin tag of the engine that wrote this scene (see provenance.ts). */
generator?: string;
@@ -285,22 +291,36 @@ export async function expandScenePrefabs(
// Scene Migration — versioned, idempotent, non-mutating (mirrors prefab/migrate)
// =============================================================================
-/** Current scene format version. Bump when adding a migration step below. */
-export const SCENE_FORMAT_VERSION = '1.0';
+/**
+ * Current scene format version — bump by one per migration step below.
+ *
+ * An integer, not semver: this number only has to answer "older, current, or
+ * newer", and dotted ones cannot. `parseFloat` sorts "1.10" below "1.2".
+ */
+export const SCENE_FORMAT_VERSION = 1;
export interface SceneMigrationResult {
/** A migrated *copy* — the input is never mutated. */
data: SceneData;
/** True if any legacy shape was upgraded (callers may prompt a re-save). */
migrated: boolean;
- fromVersion: string;
- toVersion: string;
+ fromVersion: number;
+ toVersion: number;
}
-const versionNum = (v: string): number => {
- const n = parseFloat(v);
- return Number.isFinite(n) ? n : 0;
-};
+/**
+ * The format version of a scene, however it was written. Everything from before
+ * the integer scheme is format 1, so its leading digits are the whole answer.
+ * Unreadable reads as 1, not 0: a scene with no version predates having one.
+ */
+export function parseSceneFormatVersion(v: unknown): number {
+ if (typeof v === 'number') return Number.isInteger(v) && v > 0 ? v : 1;
+ if (typeof v === 'string') {
+ const leading = /^\s*(\d+)/.exec(v);
+ if (leading) return Math.max(1, Number(leading[1]));
+ }
+ return 1;
+}
/**
* Component types retired by an engine upgrade. A scene authored before the
@@ -323,11 +343,11 @@ export function migrateSceneData(raw: SceneData): SceneMigrationResult {
if (!raw || typeof raw !== 'object' || !Array.isArray(raw.entities)) {
throw new Error('Scene data must have an "entities" array');
}
- const fromVersion = typeof raw.version === 'string' ? raw.version : '1.0';
- if (versionNum(fromVersion) > versionNum(SCENE_FORMAT_VERSION)) {
+ const fromVersion = parseSceneFormatVersion(raw.version);
+ if (fromVersion > SCENE_FORMAT_VERSION) {
throw new Error(
- `Scene format version "${fromVersion}" is newer than this engine supports ` +
- `("${SCENE_FORMAT_VERSION}"); upgrade the engine to load it.`,
+ `Scene format version ${fromVersion} is newer than this engine supports ` +
+ `(${SCENE_FORMAT_VERSION}); upgrade the engine to load it.`,
);
}
diff --git a/sdk/src/wasm/wasmScratch.ts b/sdk/src/wasm/wasmScratch.ts
index 7c17b161f..62ad45077 100644
--- a/sdk/src/wasm/wasmScratch.ts
+++ b/sdk/src/wasm/wasmScratch.ts
@@ -21,6 +21,13 @@ export interface WasmAllocator {
_free(ptr: number): void;
}
+/**
+ * The callback's return type, or `never` if it is async. An `async` callback
+ * returns at its first `await`, so the frees run while it is suspended and every
+ * pointer it holds dangles when it resumes — corrupted data, not a crash.
+ */
+type Sync<R> = R extends PromiseLike<unknown> ? never : R;
+
/**
* Run `fn` with a scratch allocator; free everything it allocated on exit,
* whether `fn` returns normally or throws. Frees in reverse allocation order.
@@ -34,7 +41,7 @@ export interface WasmAllocator {
*/
export function withScratch<R>(
mod: WasmAllocator,
- fn: (alloc: (size: number) => number) => R,
+ fn: (alloc: (size: number) => number) => Sync<R>,
): R {
const ptrs: number[] = [];
const alloc = (size: number): number => {
@@ -43,7 +50,7 @@ export function withScratch<R>(
return p;
};
try {
- return fn(alloc);
+ return fn(alloc) as R;
} finally {
for (let i = ptrs.length - 1; i >= 0; i--) {
mod._free(ptrs[i]!);
@@ -58,7 +65,7 @@ export function withScratch<R>(
export function withMalloc<R>(
mod: WasmAllocator,
size: number,
- fn: (ptr: number) => R,
+ fn: (ptr: number) => Sync<R>,
): R {
- return withScratch(mod, alloc => fn(alloc(size)));
+ return withScratch<R>(mod, alloc => fn(alloc(size)));
}
diff --git a/sdk/tests/prefab.test.ts b/sdk/tests/prefab.test.ts
index 0b067ee87..317c4e252 100644
--- a/sdk/tests/prefab.test.ts
+++ b/sdk/tests/prefab.test.ts
@@ -2,7 +2,7 @@
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { describe, it, expect, vi, beforeEach } from 'vitest';
import type { PrefabData, PrefabOverride, InstantiatePrefabOptions } from '../src/prefab';
-import type { SceneData } from '../src/scene/scene';
+import { SCENE_FORMAT_VERSION, type SceneData } from '../src/scene/scene';
import type { World } from '../src/ecs/world';
import type { Entity } from '../src/types';
@@ -88,7 +88,7 @@ describe('Prefab', () => {
await instantiatePrefab(world, prefab);
expect(capturedSceneData).not.toBeNull();
- expect(capturedSceneData!.version).toBe('1.0');
+ expect(capturedSceneData!.version).toBe(SCENE_FORMAT_VERSION);
expect(capturedSceneData!.name).toBe('TestPrefab');
expect(capturedSceneData!.entities).toHaveLength(2);
});
diff --git a/sdk/tests/scene-format-version.test.ts b/sdk/tests/scene-format-version.test.ts
new file mode 100644
index 000000000..55c04f1a0
--- /dev/null
+++ b/sdk/tests/scene-format-version.test.ts
@@ -0,0 +1,72 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file scene-format-version.test.ts
+ * @brief The format version answers one question — older, current, or newer —
+ * and a dotted version cannot answer it.
+ *
+ * `parseFloat` reads "1.10" as 1.1 and sorts it BELOW "1.2", and reads
+ * "1.0.1" as 1, dropping the patch. While only "1.0" is ever written
+ * every test passes either way — these are the cases that separate them,
+ * so the tenth revision of the format cannot count as older than the
+ * second.
+ */
+import { describe, it, expect } from 'vitest';
+import {
+ SCENE_FORMAT_VERSION,
+ parseSceneFormatVersion,
+ migrateSceneData,
+ type SceneData,
+} from '../src/scene/scene';
+
+const scene = (version: unknown): SceneData =>
+ ({ version, name: 'test', entities: [] } as unknown as SceneData);
+
+describe('scene format version', () => {
+ it('is an integer, so ordering is ordering', () => {
+ expect(Number.isInteger(SCENE_FORMAT_VERSION)).toBe(true);
+ expect(SCENE_FORMAT_VERSION).toBeGreaterThan(0);
+ });
+
+ it('orders the way parseFloat could not', () => {
+ expect(parseSceneFormatVersion(10)).toBeGreaterThan(parseSceneFormatVersion(2));
+ expect(parseSceneFormatVersion(10)).toBeGreaterThan(parseSceneFormatVersion(9));
+ // The old reading: "1.10" → 1.1 < "1.2" → 1.2. Both are format 1 now.
+ expect(parseSceneFormatVersion('1.10')).toBe(parseSceneFormatVersion('1.2'));
+ });
+
+ it('reads every legacy spelling as format 1', () => {
+ for (const legacy of ['1.0', '1', '1.0.1', '1.2', '1.10']) {
+ expect(parseSceneFormatVersion(legacy)).toBe(1);
+ }
+ });
+
+ it('treats a missing or unreadable version as the oldest format, not zero', () => {
+ for (const bad of [undefined, null, '', 'nonsense', {}, [], NaN, 0, -3, 1.5]) {
+ expect(parseSceneFormatVersion(bad)).toBe(1);
+ }
+ });
+
+ it('migrating stamps the integer and reports integers', () => {
+ const result = migrateSceneData(scene('1.0'));
+ expect(result.data.version).toBe(SCENE_FORMAT_VERSION);
+ expect(result.fromVersion).toBe(1);
+ expect(result.toVersion).toBe(SCENE_FORMAT_VERSION);
+ });
+
+ it('a legacy file still loads', () => {
+ expect(() => migrateSceneData(scene('1.0'))).not.toThrow();
+ expect(() => migrateSceneData(scene(1))).not.toThrow();
+ });
+
+ it('a file from a newer engine is refused', () => {
+ expect(() => migrateSceneData(scene(SCENE_FORMAT_VERSION + 1)))
+ .toThrow(/newer than this engine supports/);
+ });
+
+ it('a two-digit future version is refused, not mistaken for an old one', () => {
+ // The case the old comparison got backwards: parseFloat("1.10") < 1.2 read
+ // a tenth-revision file as older and would have "migrated" it.
+ expect(() => migrateSceneData(scene(10))).toThrow(/newer than this engine supports/);
+ });
+});