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(assets): meshes with fewer than 65536 vertices are written with 16-bit indices
yhh778d777d001b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 409c6f45c..9e5ba91c1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,7 @@ published separately; it ships inside the editor.### Added+- **Smaller meshes on disk.** Newly imported meshes are about 9% smaller on disk. A mesh whose indices all fit in 16 bits is now written with 16-bit indices (`.esmesh` version 4), half the index bytes, and read back as 32-bit so nothing downstream changes: the renderer, the lightmap and decal bakers and static batching see the same indices as before. A mesh that needs 32 bits is written exactly as before, on the version every earlier reader knows, and files written before this change still load. Measured on the Bistro meshes (1143 files, 116 MB), re-encoding saves 10.4 MB; existing `.esmesh` files are not rewritten until the model is re-imported.- **Levels of detail generated at import.** Imported models can generate cheaper levels of detail automatically. Set **Generate LODs** to 1–3 levels in a model's import settings (or pass `--lods <n>` to `import-model`) and each mesh is collapsed into copies with about 50%, 20% and 7% of its triangles, written as `<mesh>_lod<n>.esmesh`, with a `LODGroup` on the entity that swaps them in as it shrinks on screen. The collapse bounds how far the surface may move and will not pull apart a UV seam or a hard edge; vertex colours and the lightmap UV come along unchanged. Skinned and morphing meshes, and meshes under a minimum triangle count, keep one level. Measured on the Bistro exterior (1143 meshes, 2.83M triangles), the 621 meshes large enough to get levels hold 1.35M, 0.44M and 0.10M triangles at levels 1, 2 and 3; the levels are extra files, so they make a large scene cheaper to draw rather than smaller to ship.- **Steadier highlights on curved and bevelled surfaces.** Lit models no longer sparkle on rails, bevels and rounded trim. Where a surface's normal turns faster than a pixel can resolve, the highlight is the sum of many normals the pixel cannot tell apart, and shading it with one made it flicker as the camera moved. The Model shader now widens a highlight by how fast the vertex normal turns across the pixel — a steady, slightly rougher highlight in place of a flickering sharp one — on WebGL2 and WebGPU alike. Measured on a street scene shifted by sub-pixel steps, frame-to-frame shimmer on rails and lamp trim fell by about 5–8%; a surface that is flat or smooth is not touched.- **A Neutral output transform.** The output transform has a Neutral option that keeps hue and saturation. The output transform is the one curve a finished frame goes through on its way to the display; None only encodes and ACES rolls highlights off a filmic shoulder, but ACES also desaturates as it goes, so a brightly lit red drifts toward cream. Neutral (Khronos PBR Neutral) rolls highlights off in the same way and leaves colour alone, so a sunlit red awning stays red. Pick it in Settings → Project → Rendering, or set `outputTransform: 'neutral'`; it applies to the viewport, Play and every export, on WebGL2 and WebGPU alike.diff --git a/sdk/src/asset/meshFormat.ts b/sdk/src/asset/meshFormat.tsindex 756d527ca..3fd9e92c8 100644--- a/sdk/src/asset/meshFormat.ts+++ b/sdk/src/asset/meshFormat.ts@@ -12,7 +12,22 @@/** Magic 'ESMH', little-endian. */const MAGIC = 0x484d5345;-const VERSION = 3;+const VERSION = 4;+/** The last version whose indices are always 32-bit. */+const VERSION_U32_INDICES = 3;+/** Flag bits at header offset 50, beside the morph-normals bit. */+const FLAG_MORPH_NORMALS = 1;+/** v4: the index section is 16-bit. Widened to 32-bit when read, so nothing downstream+ * of the decoder knows the file was narrower. */+const FLAG_U16_INDICES = 2;+/** Largest vertex index a 16-bit index can name. */+const MAX_U16_INDEX = 0xffff;++/** Whether every index fits in 16 bits — half the index bytes, for any mesh that small. */+function fitsU16(indices: Uint32Array): boolean {+ for (let i = 0; i < indices.length; i++) if (indices[i]! > MAX_U16_INDEX) return false;+ return true;+}/** v1 had no joint count; a file that predates skinning reads with the shorter one. */const HEADER_BYTES_V1 = 44;/** v2 ended at the joint count; a file that predates morph targets reads with that. */@@ -159,14 +174,18 @@ export function encodeMesh(data: MeshData): Uint8Array {const names = (data.morph?.names ?? []).map(n => new TextEncoder().encode(n));const nameBytes = morphNameBytes(names);const deltaFloats = data.morph?.deltas.length ?? 0;+ // Narrowed whenever it loses nothing: an index file is a tenth of a mesh, and the+ // meshes with more than 65536 vertices stay on the version every reader knows.+ const narrow = fitsU16(data.indices);+ const indexBytes = narrow ? 2 : 4;const size = HEADER_BYTES + data.channels.length * CHANNEL_BYTES- + data.vertexCount * data.vertexStride + data.indices.length * 4+ + data.vertexCount * data.vertexStride + data.indices.length * indexBytes+ jointCount * MATRIX_BYTES + nameBytes + deltaFloats * 4;const out = new Uint8Array(size);const view = new DataView(out.buffer);view.setUint32(0, MAGIC, true);- view.setUint16(4, VERSION, true);+ view.setUint16(4, narrow ? VERSION : VERSION_U32_INDICES, true);view.setUint16(6, data.channels.length, true);view.setUint32(8, data.vertexStride, true);view.setUint32(12, data.vertexCount, true);@@ -177,7 +196,7 @@ export function encodeMesh(data: MeshData): Uint8Array {}view.setUint32(44, jointCount, true);view.setUint16(48, names.length, true);- view.setUint16(50, data.morph?.hasNormals ? 1 : 0, true);+ view.setUint16(50, (data.morph?.hasNormals ? FLAG_MORPH_NORMALS : 0) | (narrow ? FLAG_U16_INDICES : 0), true);view.setUint32(52, nameBytes, true);let at = HEADER_BYTES;@@ -192,8 +211,12 @@ export function encodeMesh(data: MeshData): Uint8Array {out.set(data.vertices.subarray(0, data.vertexCount * data.vertexStride), at);at += data.vertexCount * data.vertexStride;- out.set(new Uint8Array(data.indices.buffer, data.indices.byteOffset, data.indices.length * 4), at);- at += data.indices.length * 4;+ if (narrow) {+ for (let i = 0; i < data.indices.length; i++) view.setUint16(at + i * 2, data.indices[i]!, true);+ } else {+ out.set(new Uint8Array(data.indices.buffer, data.indices.byteOffset, data.indices.length * 4), at);+ }+ at += data.indices.length * indexBytes;if (data.inverseBindMatrices) {// Written through the DataView: the section's start is only 4-byte// aligned, and a Float32Array view on it may not be constructible.@@ -249,7 +272,9 @@ export function decodeMesh(bytes: Uint8Array): MeshData {: version >= 2 ? HEADER_BYTES_V2 : HEADER_BYTES_V1;const jointCount = version >= 2 ? view.getUint32(44, true) : 0;const morphCount = version >= 3 ? view.getUint16(48, true) : 0;- const morphNormals = version >= 3 && view.getUint16(50, true) !== 0;+ const flags = version >= 3 ? view.getUint16(50, true) : 0;+ const morphNormals = (flags & FLAG_MORPH_NORMALS) !== 0;+ const indexBytes = version > VERSION_U32_INDICES && (flags & FLAG_U16_INDICES) !== 0 ? 2 : 4;const nameBytes = version >= 3 ? view.getUint32(52, true) : 0;const morphComponents = morphNormals ? 6 : 3;@@ -271,7 +296,7 @@ export function decodeMesh(bytes: Uint8Array): MeshData {const vertexBytes = vertexCount * vertexStride;const deltaFloats = morphCount * vertexCount * morphComponents;- const expected = at + vertexBytes + indexCount * 4 + jointCount * MATRIX_BYTES+ const expected = at + vertexBytes + indexCount * indexBytes + jointCount * MATRIX_BYTES+ nameBytes + deltaFloats * 4;if (bytes.byteLength < expected) {throw new Error(`.esmesh is truncated: ${bytes.byteLength} bytes, header describes ${expected}`);@@ -281,10 +306,14 @@ export function decodeMesh(bytes: Uint8Array): MeshData {// the file, and a Uint32Array view on an odd offset throws.const indices = new Uint32Array(indexCount);const indexBase = at + vertexBytes;- for (let i = 0; i < indexCount; i++) indices[i] = view.getUint32(indexBase + i * 4, true);+ if (indexBytes === 2) {+ for (let i = 0; i < indexCount; i++) indices[i] = view.getUint16(indexBase + i * 2, true);+ } else {+ for (let i = 0; i < indexCount; i++) indices[i] = view.getUint32(indexBase + i * 4, true);+ }const out: MeshData = { channels, vertexStride, vertexCount, vertices, indices, aabbMin, aabbMax };- const bindBase = indexBase + indexCount * 4;+ const bindBase = indexBase + indexCount * indexBytes;if (jointCount > 0) {const matrices = new Float32Array(jointCount * 16);for (let i = 0; i < matrices.length; i++) {diff --git a/sdk/tests/mesh-format-indices.test.ts b/sdk/tests/mesh-format-indices.test.tsnew file mode 100644index 000000000..815a368c9--- /dev/null+++ b/sdk/tests/mesh-format-indices.test.ts@@ -0,0 +1,67 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file A mesh small enough for 16-bit indices is written with them, and reads back the same.+ */+import { describe, it, expect } from 'vitest';+import { decodeMesh, encodeMesh, MeshChannel, MeshChannelType, packChannels, type MeshData } from '../src/asset/meshFormat';++const version = (bytes: Uint8Array) => new DataView(bytes.buffer, bytes.byteOffset).getUint16(4, true);++function mesh(vertexCount: number, indices: number[], extra: Partial<MeshData> = {}): MeshData {+ const { channels, vertexStride } = packChannels([+ { semantic: MeshChannel.Position, components: 3, type: MeshChannelType.Float32 },+ ]);+ const vertices = new Uint8Array(vertexCount * vertexStride);+ const view = new DataView(vertices.buffer);+ for (let v = 0; v < vertexCount; v++) view.setFloat32(v * vertexStride, v, true);+ return {+ channels, vertexStride, vertexCount, vertices, indices: Uint32Array.from(indices),+ aabbMin: [0, 0, 0], aabbMax: [vertexCount, 0, 0], ...extra,+ };+}++describe('.esmesh index width', () => {+ it('writes 16-bit indices when every index fits, and reads them back as 32-bit', () => {+ const src = mesh(5, [0, 1, 2, 2, 3, 4, 4, 0, 1]);+ const bytes = encodeMesh(src);+ expect(version(bytes)).toBe(4);+ const back = decodeMesh(bytes);+ expect(Array.from(back.indices)).toEqual(Array.from(src.indices));+ expect(back.vertexCount).toBe(5);+ // two bytes saved per index, nothing else moved+ const as32 = bytes.length + src.indices.length * 2;+ expect(as32 - bytes.length).toBe(18);+ });++ it('keeps 32-bit indices, on the version every reader knows, once one needs them', () => {+ const src = mesh(70000, [0, 69999, 65536, 1, 2, 3]);+ const bytes = encodeMesh(src);+ expect(version(bytes)).toBe(3);+ expect(Array.from(decodeMesh(bytes).indices)).toEqual(Array.from(src.indices));+ // the boundary: 65535 is the last index 16 bits can name+ expect(version(encodeMesh(mesh(65536, [0, 65535, 1])))).toBe(4);+ expect(version(encodeMesh(mesh(65537, [0, 65536, 1])))).toBe(3);+ });++ it('leaves what follows the indices where it was, with an odd index count', () => {+ const src = mesh(4, [0, 1, 2], {+ inverseBindMatrices: Float32Array.from({ length: 16 }, (_, i) => i),+ morph: { names: ['smile'], hasNormals: true, deltas: Float32Array.from({ length: 4 * 6 }, (_, i) => i / 2) },+ });+ const back = decodeMesh(encodeMesh(src));+ expect(Array.from(back.indices)).toEqual([0, 1, 2]);+ expect(Array.from(back.inverseBindMatrices!)).toEqual(Array.from(src.inverseBindMatrices!));+ expect(back.morph!.names).toEqual(['smile']);+ expect(back.morph!.hasNormals).toBe(true);+ expect(Array.from(back.morph!.deltas)).toEqual(Array.from(src.morph!.deltas));+ });++ it('reads a file that predates the flag as 32-bit', () => {+ const bytes = encodeMesh(mesh(70000, [0, 69999, 2]));+ expect(version(bytes)).toBe(3);+ expect(Array.from(decodeMesh(bytes).indices)).toEqual([0, 69999, 2]);+ // a big mesh whose indices all happen to be small still narrows: it is the indices that count+ expect(version(encodeMesh(mesh(70000, [0, 1, 2])))).toBe(4);+ });+});diff --git a/sdk/tests/mesh-format-morph.test.ts b/sdk/tests/mesh-format-morph.test.tsindex c45f64bf7..e3a2fe3ae 100644--- a/sdk/tests/mesh-format-morph.test.ts+++ b/sdk/tests/mesh-format-morph.test.ts@@ -90,10 +90,15 @@ describe('.esmesh morph targets', () => {const bytes = encodeMesh(mesh({}));// The same file as a v2 writer would have produced: a 48-byte header that// ends at the joint count, so the channel table starts eight bytes earlier.- const older = new Uint8Array(bytes.byteLength - 8);+ // Its indices are 32-bit — the width every version before the index flag wrote — so+ // they are widened by hand: this file is built to be what that writer produced.+ const tableAndVertices = bytes.subarray(56, 56 + 8 + 3 * POSITION_ONLY.vertexStride);+ const older = new Uint8Array(48 + tableAndVertices.length + 3 * 4);older.set(bytes.subarray(0, 48));- older.set(bytes.subarray(56), 48);- new DataView(older.buffer).setUint16(4, 2, true);+ older.set(tableAndVertices, 48);+ const olderView = new DataView(older.buffer);+ olderView.setUint16(4, 2, true);+ [0, 1, 2].forEach((v, i) => olderView.setUint32(48 + tableAndVertices.length + i * 4, v, true));const decoded = decodeMesh(older);expect(decoded.vertexCount).toBe(3);diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 41541206e..1acae2f01 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -2469,4 +2469,6 @@ export const NOTED = {{"note":"Lit models no longer sparkle on rails, bevels and rounded trim."},"feat(import): a model import can write simplified levels of detail and a LODGroup that swaps them in":{"note":"Imported models can generate cheaper levels of detail automatically."},+ "feat(assets): meshes with fewer than 65536 vertices are written with 16-bit indices":+ {"note":"Newly imported meshes are about 9% smaller on disk."},};