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.

feat(import): a model import can write simplified levels of detail and a LODGroup that swaps them in

yhh21912c365d92
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f26620cb1..409c6f45c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -16,6 +16,7 @@ published separately; it ships inside the editor.
### Added
+- **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.
- **Static batching.** Static meshes that share a material can be drawn as one. Add `StaticBatch` to a mesh that will not move, and the meshes that share its material, texture, colour and layer are merged while the game runs into one mesh per area, so a level built from many different props costs a few draws instead of one per distinct mesh. The renderer already drew copies of the same mesh as one instanced draw; this is for different meshes. The marked entities stay as authored — scripts find them, colliders collide, the editor picks them — and only their drawing moves to the merged mesh. A mesh is left out, and the reason recorded, when it is skinned, morphing, a level-of-detail group, blended, moving (a dynamic body or a character), lit by a bake or a probe volume, or alone in its group. Merging copies each part's vertices, so it spends memory to save draws; `StaticBatching` reports each merged mesh's size and what drawing its parts cost before. In the editor the outliner's menu marks the selected meshes, a marked mesh's Details say whether it merged and why not, and the profiler lists every merged mesh and the meshes left out.
diff --git a/desktop b/desktop
index 320482486..5a40236f2 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit 320482486a70b9706b35367eca2e7c1d3e9fe6ed
+Subproject commit 5a40236f2ccde460164dc23ed94b4d13eddc581f
diff --git a/docs/astro/src/content/docs/assets/models.mdx b/docs/astro/src/content/docs/assets/models.mdx
index 8450c4a88..e2c4be6f9 100644
--- a/docs/astro/src/content/docs/assets/models.mdx
+++ b/docs/astro/src/content/docs/assets/models.mdx
@@ -99,6 +99,28 @@ Content Browser). Saving it re-imports the model.
`Scale` lands on the prefab root's `Transform`, never baked into the geometry — the
`.esmesh` stays faithful to the source, and the number stays visible and editable.
+## Generated levels of detail
+
+A mesh seen from far away does not need the triangles it has up close. Set
+**Generate LODs** in the model's import settings to 1, 2 or 3 levels and the
+import collapses each mesh into cheaper copies — about 50%, 20% and 7% of its
+triangles — written beside it as `<mesh>_lod1.esmesh`, `_lod2` and `_lod3`, and
+adds a [`LODGroup`](/performance/level-of-detail/) to the entity that draws it. The
+group swaps a level in as the object shrinks on screen (below 40%, 18% and 7% of
+the viewport height).
+
+The collapse keeps the shape within a small error of the mesh's own size and
+refuses to pull apart a UV seam or a hard edge, so a texture still lands where it
+did. Every surviving vertex is a copy of one the source had, so vertex colours and
+the lightmap UV come along. A level that would shed less than 15% of the level
+above is left out, and a mesh under **LOD Minimum Triangles** (256 by default)
+gets none. A skinned or morphing mesh keeps a single level.
+
+Levels are extra files: three of them add about three quarters of the original
+meshes' size to the project. They cost memory only when a view needs them — they
+are what makes a large scene cheaper to *draw*, not smaller to ship. The
+command-line import takes `--lods <0-3>`.
+
## Lightmap UVs
A baked lightmap is read through a **second** UV set, and it has to be one where
diff --git a/docs/astro/src/content/docs/zh-cn/assets/models.mdx b/docs/astro/src/content/docs/zh-cn/assets/models.mdx
index 52e459277..690dbff51 100644
--- a/docs/astro/src/content/docs/zh-cn/assets/models.mdx
+++ b/docs/astro/src/content/docs/zh-cn/assets/models.mdx
@@ -88,6 +88,22 @@ Transform 给,和导入的模型一样。
`Scale` 落在 prefab 根节点的 `Transform` 上,**不会烘进几何** —— `.esmesh` 保持与源一致,
而那个数字始终看得见、改得动。
+## 自动生成 LOD
+
+远处的网格用不着近处那么多三角形。在模型的导入设置里把 **Generate LODs** 设为 1、2 或 3 级,
+导入就会把每个网格简化成更便宜的副本 —— 大约保留 50%、20% 和 7% 的三角形 ——
+写成它旁边的 `<mesh>_lod1.esmesh`、`_lod2`、`_lod3`,并给绘制它的实体加一个
+[`LODGroup`](/zh-cn/performance/level-of-detail/)。物体在屏幕上缩小时,LODGroup 依次换上
+各级(分别在低于视口高度的 40%、18%、7% 时)。
+
+简化把形状误差控制在网格自身尺寸的很小比例内,并且不会拆开 UV 接缝和硬边,所以贴图仍落在原处。
+每个留下的顶点都是源网格某个顶点的拷贝,顶点色和 lightmap UV 随之保留。
+比上一级少不了 15% 的级别会被省掉;低于 **LOD Minimum Triangles**(默认 256)的网格不生成。
+蒙皮或带形变的网格只保留一级。
+
+各级是额外的文件:三级大约会让工程多出原网格四分之三的体积。它们只在某个视图需要时才占内存 ——
+它让大场景**画得更快**,而不是**发布得更小**。命令行导入用 `--lods <0-3>`。
+
## Lightmap UV
烘焙好的 lightmap 是通过**第二套** UV 读的,而且这套 UV 必须保证没有两个面落在同一批纹素上。
diff --git a/pipeline/bin/estella.mjs b/pipeline/bin/estella.mjs
index 2c49c6a7d..0f7ada7fd 100644
--- a/pipeline/bin/estella.mjs
+++ b/pipeline/bin/estella.mjs
@@ -15,7 +15,7 @@ const REPO = path.join(PIPELINE, '..');
const USAGE = `usage: node pipeline/bin/estella.mjs export <projectDir> [options]
node pipeline/bin/estella.mjs import-model <file.gltf|file.glb|file.fbx> [outDir]
[--project <dir>] [--scale <n>]
- [--specular-map color|orm] [--lightmap-uv]
+ [--specular-map color|orm] [--lightmap-uv] [--lods <0-3>]
node pipeline/bin/estella.mjs import-hdr <file.hdr> [outDir] [--face-size <n>]
node pipeline/bin/estella.mjs bake-scene <scene.esscene> [--check]
node pipeline/bin/estella.mjs package-openpaas <exportDir> --config <local.json> --out <game.sp>
@@ -64,6 +64,9 @@ metalness (Falcor-era scenes such as Bistro); the source's own \`.meta\` setting
is used when the flag is absent. DDS images are converted to PNG on the way in.
--lightmap-uv gives every mesh a lightmap UV set (Generate Lightmap UVs in the
editor), unwrapping one where the source's second set is too sparse to bake into.
+--lods <n> writes n cheaper levels of every mesh (about 50%, 20% and 7% of its
+triangles) as <mesh>_lod<n>.esmesh and a LODGroup that swaps them in (Generate
+LODs in the editor); skinned and morphing meshes keep one level.
import-hdr bakes an equirectangular panorama into the two things a renderer asks
an environment for: nine irradiance coefficients (in the \`.esenv\`) and one
@@ -105,6 +108,7 @@ function parseArgs(argv) {
const faceSize = rest.indexOf('--face-size');
const specular = rest.indexOf('--specular-map');
const lightmapUV = rest.includes('--lightmap-uv');
+ const lods = rest.indexOf('--lods');
const out = rest[0] && !rest[0].startsWith('--') ? path.resolve(rest[0]) : null;
return {
command, out, source: path.resolve(projectDir),
@@ -113,6 +117,7 @@ function parseArgs(argv) {
faceSize: faceSize >= 0 ? Number(rest[faceSize + 1]) || undefined : undefined,
specularMap: specular >= 0 ? rest[specular + 1] : undefined,
lightmapUV,
+ lodLevels: lods >= 0 ? Number(rest[lods + 1]) : undefined,
};
}
if (command !== 'export' || !projectDir) {
@@ -647,6 +652,20 @@ function lightmapUVFor(opts) {
}
}
+/** The flag, else the source's own `.meta` import settings: [levels, minimum triangles]. */
+function lodSettingsFor(opts) {
+ let importerMeta = {};
+ try {
+ importerMeta = JSON.parse(readFileSync(`${opts.source}.meta`, 'utf8')).importer ?? {};
+ } catch { /* no meta: the schema's defaults */ }
+ const levels = Number.isFinite(opts.lodLevels) ? opts.lodLevels : importerMeta.lodLevels;
+ const min = importerMeta.lodMinTriangles;
+ return {
+ levels: typeof levels === 'number' ? Math.min(3, Math.max(0, Math.floor(levels))) : 0,
+ minTriangles: typeof min === 'number' && min >= 0 ? min : 256,
+ };
+}
+
function findProjectRoot(from) {
for (let dir = from, prev = ''; dir !== prev; prev = dir, dir = path.dirname(dir)) {
if (PROJECT_FILES.some((name) => existsSync(path.join(dir, name)))) return dir;
@@ -737,6 +756,7 @@ if (opts.command === 'import-model' || opts.command === 'import-gltf') {
},
);
if (lightmapUVFor(opts)) warnings.push(...importer.applyLightmapUV(meshes));
+ warnings.push(...await importer.generateLods(meshes, lodSettingsFor(opts)));
for (const w of warnings) console.warn(` ! ${w}`);
if (!root && meshes.length > 0) {
console.warn(' ! no project found above the source — refs are bare file names'
@@ -769,6 +789,12 @@ if (opts.command === 'import-model' || opts.command === 'import-gltf') {
writeFileSync(outFile, importer.encodeImportedMesh(mesh));
await adopt(outFile);
report(outFile, `${mesh.vertexCount} vertices, ${mesh.triangleCount} triangles`);
+ for (const [i, lod] of (mesh.lods ?? []).entries()) {
+ const lodFile = path.join(dir, `${importer.lodName(mesh, i + 1)}.esmesh`);
+ writeFileSync(lodFile, importer.encodeGeneratedLod(lod));
+ await adopt(lodFile);
+ report(lodFile, `LOD ${i + 1}: ${lod.triangleCount} triangles`);
+ }
}
for (const texture of textures) {
const outFile = path.join(dir, texture.name);
diff --git a/pipeline/src/assets/meshSimplify.ts b/pipeline/src/assets/meshSimplify.ts
new file mode 100644
index 000000000..112ecdc2f
--- /dev/null
+++ b/pipeline/src/assets/meshSimplify.ts
@@ -0,0 +1,106 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file Mesh simplification — the cheaper stand-ins a `LODGroup` swaps in as an object shrinks.
+ *
+ * An import that can write the levels spares a creator the one job nobody does by
+ * hand: re-exporting every prop three times at three budgets. The collapse itself is
+ * meshoptimizer's quadric-error simplifier; what is written here is the part around
+ * it — what the simplifier is told about a vertex (its position, and the normal and
+ * UV that must not be collapsed across a seam), and what the result is made of.
+ *
+ * The result keeps the SOURCE vertices, not new ones: every surviving vertex is a
+ * byte-for-byte copy of one the original had, so every channel — colour, the
+ * lightmap UV, anything a later format adds — rides along without this file having
+ * to know it exists.
+ */
+import { MeshoptSimplifier } from 'meshoptimizer';
+import { MeshChannel, MeshChannelType, type MeshData } from 'esengine';
+
+/** What the collapse is allowed to cost, as a fraction of the mesh's own extent. */
+export interface SimplifyOptions {
+ /** Share of the triangles to keep, in (0, 1). The result may keep more where the
+ * error limit stops the collapse first — a level is never worse than its budget. */
+ ratio: number;
+ /** The most the surface may move, relative to the mesh's extent. */
+ maxError?: number;
+}
+
+export interface Simplified {
+ data: MeshData;
+ triangles: number;
+ /** What the collapse cost, relative to the mesh's extent. */
+ error: number;
+}
+
+/** Weights on what must survive besides the shape. A UV is wrapped art, so it counts
+ * full; a normal bends light and is allowed a little more give. */
+const NORMAL_WEIGHT = 0.5;
+const UV_WEIGHT = 1.0;
+
+const floatChannel = (data: MeshData, semantic: number, components: number) =>
+ data.channels.find((c) => c.semantic === semantic && c.components >= components
+ && c.type === MeshChannelType.Float32);
+
+/** Geometry a collapse would break: bones index into the vertices, morph deltas are
+ * addressed by them. Such a mesh keeps one level of detail. */
+export function canSimplify(data: MeshData): boolean {
+ if (data.morph) return false;
+ if (data.channels.some((c) => c.semantic === MeshChannel.Joints || c.semantic === MeshChannel.Weights)) return false;
+ return !!floatChannel(data, MeshChannel.Position, 3) && data.indices.length >= 3;
+}
+
+/**
+ * A cheaper copy of `data`, or null where it cannot be made cheaper (skinned, morphing,
+ * already smaller than the budget).
+ */
+export async function simplifyMesh(data: MeshData, options: SimplifyOptions): Promise<Simplified | null> {
+ if (!canSimplify(data)) return null;
+ await MeshoptSimplifier.ready;
+
+ const { vertexCount, vertexStride } = data;
+ const view = new DataView(data.vertices.buffer, data.vertices.byteOffset, data.vertices.byteLength);
+ const position = floatChannel(data, MeshChannel.Position, 3)!;
+ const normal = floatChannel(data, MeshChannel.Normal, 3);
+ const uv = floatChannel(data, MeshChannel.TexCoord0, 2);
+
+ const positions = new Float32Array(vertexCount * 3);
+ const attributeStride = (normal ? 3 : 0) + (uv ? 2 : 0);
+ const attributes = new Float32Array(vertexCount * attributeStride);
+ for (let v = 0; v < vertexCount; v++) {
+ const at = v * vertexStride;
+ for (let k = 0; k < 3; k++) positions[v * 3 + k] = view.getFloat32(at + position.offset + k * 4, true);
+ let a = v * attributeStride;
+ if (normal) for (let k = 0; k < 3; k++) attributes[a++] = view.getFloat32(at + normal.offset + k * 4, true);
+ if (uv) for (let k = 0; k < 2; k++) attributes[a++] = view.getFloat32(at + uv.offset + k * 4, true);
+ }
+ const weights = [...(normal ? [NORMAL_WEIGHT, NORMAL_WEIGHT, NORMAL_WEIGHT] : []),
+ ...(uv ? [UV_WEIGHT, UV_WEIGHT] : [])];
+
+ const triangles = data.indices.length / 3;
+ const targetTriangles = Math.max(1, Math.floor(triangles * options.ratio));
+ if (targetTriangles >= triangles) return null;
+ const [kept, error] = attributeStride > 0
+ ? MeshoptSimplifier.simplifyWithAttributes(data.indices, positions, 3, attributes, attributeStride, weights,
+ null, targetTriangles * 3, options.maxError ?? 0.05, ['LockBorder'])
+ : MeshoptSimplifier.simplify(data.indices, positions, 3, targetTriangles * 3, options.maxError ?? 0.05, ['LockBorder']);
+ if (kept.length === 0 || kept.length >= data.indices.length) return null;
+
+ // Only the vertices the survivors name are carried: a collapse leaves the rest behind.
+ const remap = new Int32Array(vertexCount).fill(-1);
+ let used = 0;
+ for (const i of kept) if (remap[i] < 0) remap[i] = used++;
+ const vertices = new Uint8Array(used * vertexStride);
+ for (let v = 0; v < vertexCount; v++) {
+ const to = remap[v];
+ if (to >= 0) vertices.set(data.vertices.subarray(v * vertexStride, (v + 1) * vertexStride), to * vertexStride);
+ }
+ const indices = new Uint32Array(kept.length);
+ for (let i = 0; i < kept.length; i++) indices[i] = remap[kept[i]!]!;
+
+ return {
+ data: { ...data, vertexCount: used, vertices, indices },
+ triangles: indices.length / 3,
+ error,
+ };
+}
diff --git a/pipeline/src/assets/modelImport.ts b/pipeline/src/assets/modelImport.ts
index 12cb425d7..21f6fecfb 100644
--- a/pipeline/src/assets/modelImport.ts
+++ b/pipeline/src/assets/modelImport.ts
@@ -16,6 +16,7 @@ import {
type MeshData, type MaterialAssetData, type PrefabData, type PrefabEntityData,
type PrefabComponentData as ComponentData,
} from 'esengine';
+import { canSimplify, simplifyMesh } from './meshSimplify';
import { SPARSE_LIGHTMAP_UV, OVERLAPPING_LIGHTMAP_UV } from '../../../sdk/src/lightmap/atlas';
/** One primitive's worth of geometry, named for the file it will be written to. */
@@ -32,6 +33,16 @@ export interface ImportedMesh {
skinJoints?: number[];
/** The weight each morph target starts at, where the source states them. */
morphWeights?: number[];
+ /** Cheaper stand-ins, finest first, written as `<name>_lod<n>.esmesh` (@ref generateLods). */
+ lods?: GeneratedLod[];
+}
+
+/** One cheaper level of a mesh, and the screen height below which it replaces the one above. */
+export interface GeneratedLod {
+ data: MeshData;
+ triangleCount: number;
+ /** Fraction of the viewport height — the unit a `LODGroup` threshold is in. */
+ size: number;
}
/** Where a material's image comes from: a product this import writes, or a file already on disk. */
@@ -410,6 +421,62 @@ export function applyLightmapUV(meshes: ImportedMesh[]): string[] {
return warnings;
}
+/** What a generated level keeps and where it takes over — each level is cheaper than the last. */
+const LOD_RATIOS = [0.5, 0.2, 0.07];
+const LOD_SIZES = [0.4, 0.18, 0.07];
+/** A level that sheds less than this share of the one above is not worth a draw swap. */
+const LOD_MIN_SAVING = 0.15;
+/** The collapse may move the surface this far, relative to the mesh's extent. */
+const LOD_ERROR = [0.01, 0.03, 0.08];
+
+export interface LodOptions {
+ /** How many levels to make below the original, 1–3. */
+ levels: number;
+ /** A mesh with fewer triangles than this has nothing worth swapping. */
+ minTriangles: number;
+}
+
+/** The file a mesh's level `n` is written to, by product name (no extension). */
+export function lodName(mesh: ImportedMesh, level: number): string {
+ return `${mesh.name}_lod${level}`;
+}
+
+/**
+ * Makes the cheaper stand-ins a `LODGroup` swaps in, and says what it left alone.
+ * Mutates in place, after any unwrap: a level is a collapse of the mesh as it will
+ * be written, lightmap UV included. Skinned and morphing meshes keep one level.
+ */
+export async function generateLods(meshes: ImportedMesh[], options: LodOptions): Promise<string[]> {
+ const warnings: string[] = [];
+ const levels = Math.min(LOD_RATIOS.length, Math.max(0, Math.floor(options.levels)));
+ if (levels === 0) return warnings;
+ for (const mesh of meshes) {
+ if (mesh.triangleCount < options.minTriangles) continue;
+ if (!canSimplify(mesh.data)) {
+ if (mesh.skinJoints?.length || mesh.data.morph) {
+ warnings.push(`${mesh.name}: skinned or morphing, so it keeps a single level of detail`);
+ }
+ continue;
+ }
+ const out: GeneratedLod[] = [];
+ let above = mesh.triangleCount;
+ for (let level = 0; level < levels; level++) {
+ // Collapse from the ORIGINAL each time: stacking collapses compounds their error.
+ const made = await simplifyMesh(mesh.data, { ratio: LOD_RATIOS[level]!, maxError: LOD_ERROR[level]! });
+ if (!made || made.triangles > above * (1 - LOD_MIN_SAVING)) break;
+ out.push({ data: made.data, triangleCount: made.triangles, size: LOD_SIZES[level]! });
+ above = made.triangles;
+ }
+ if (out.length > 0) mesh.lods = out;
+ }
+ return warnings;
+}
+
+/** The bytes to write for a generated level. */
+export function encodeGeneratedLod(lod: GeneratedLod): Uint8Array {
+ return encodeMesh(lod.data);
+}
+
/** The bytes to write for an imported mesh. */
export function encodeImportedMesh(mesh: ImportedMesh): Uint8Array {
return encodeMesh(mesh.data);
@@ -554,6 +621,18 @@ export function materialProducts(meshes: ImportedMesh[], stem: string,
return out;
}
+/** The `LODGroup` that points at a mesh's generated levels; none when it made none. */
+function lodComponent(mesh: ImportedMesh, refs: ProductRefs): ComponentData[] {
+ if (!mesh.lods || mesh.lods.length === 0) return [];
+ const prefix = refs.prefix ?? '';
+ const data: Record<string, unknown> = {};
+ mesh.lods.forEach((lod, i) => {
+ data[`lod${i + 1}`] = `${prefix}${lodName(mesh, i + 1)}.esmesh`;
+ data[`lod${i + 1}Size`] = lod.size;
+ });
+ return [{ type: 'LODGroup', data }];
+}
+
function meshComponent(mesh: ImportedMesh, stem: string, refs: ProductRefs): ComponentData {
const prefix = refs.prefix ?? '';
const texture = mesh.material?.baseColorTexture
@@ -675,7 +754,7 @@ export function assembleModelPrefab(name: string, meshes: ImportedMesh[],
// One primitive rides the node itself; several cannot, since a MeshRenderer
// draws one mesh — they become its children, at its own origin.
const own = drawn.length === 1 && drawn[0]
- ? [meshComponent(drawn[0], name, refs), ...skinComponent(drawn[0]),
+ ? [meshComponent(drawn[0], name, refs), ...lodComponent(drawn[0], refs), ...skinComponent(drawn[0]),
...morphComponent(drawn[0])] : [];
const self = entity(id, node.name, parent, [
transformComponent(node, rootScale), ...own,
@@ -689,7 +768,7 @@ export function assembleModelPrefab(name: string, meshes: ImportedMesh[],
self.children.push(childId);
entities.push(entity(childId, mesh.name, id,
[transformComponent(), meshComponent(mesh, name, refs),
- ...skinComponent(mesh), ...morphComponent(mesh)]));
+ ...lodComponent(mesh, refs), ...skinComponent(mesh), ...morphComponent(mesh)]));
});
}
for (const child of node.children) self.children.push(emitNode(child, id));
@@ -712,7 +791,8 @@ export function assembleModelPrefab(name: string, meshes: ImportedMesh[],
const id = `m${i}`;
root.children.push(id);
entities.push(entity(id, mesh.name, 'root',
- [transformComponent(), meshComponent(mesh, name, refs)]));
+ [transformComponent(), meshComponent(mesh, name, refs),
+ ...lodComponent(mesh, refs)]));
});
}
// The player rides the root, which is the entity a clip's childPaths are
diff --git a/pipeline/src/project/importSettings.ts b/pipeline/src/project/importSettings.ts
index f80aad9cc..dd04110fe 100644
--- a/pipeline/src/project/importSettings.ts
+++ b/pipeline/src/project/importSettings.ts
@@ -217,6 +217,20 @@ const MODEL: ImporterFieldSpec[] = [
+ 'because it splits vertices and most models are never baked; skinned meshes never get '
+ 'one, and a model that already carries the channel keeps its own.',
},
+ {
+ key: 'lodLevels', label: 'Generate LODs', type: 'enum', default: 0, category: 'Import',
+ options: [{ label: 'Off', value: 0 }, { label: '1 level', value: 1 },
+ { label: '2 levels', value: 2 }, { label: '3 levels', value: 3 }],
+ tooltip: 'Simplify each mesh into cheaper stand-ins (about 50%, 20% and 7% of its '
+ + 'triangles) and add a LODGroup that swaps them in as it shrinks on screen. Smaller '
+ + 'meshes load faster and distant ones draw faster. Skinned and morphing meshes keep one level.',
+ },
+ {
+ key: 'lodMinTriangles', label: 'LOD Minimum Triangles', type: 'number', default: 256, min: 0, step: 16,
+ category: 'Import', advanced: true,
+ tooltip: 'A mesh with fewer triangles than this gets no levels: there is too little to '
+ + 'take out for a swap to pay.',
+ },
{
key: 'specularMap', label: 'Specular Map', type: 'enum', default: 'color',
category: 'Import', advanced: true,
diff --git a/pipeline/tests/mesh-simplify.test.ts b/pipeline/tests/mesh-simplify.test.ts
new file mode 100644
index 000000000..c2b1fccd8
--- /dev/null
+++ b/pipeline/tests/mesh-simplify.test.ts
@@ -0,0 +1,137 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file A simplified mesh is a smaller copy of the same surface, made of the same vertices.
+ */
+import { describe, it, expect } from 'vitest';
+import { MeshChannel, MeshChannelType, type MeshData } from 'esengine';
+import { canSimplify, simplifyMesh } from '../src/assets/meshSimplify';
+import { assembleModelPrefab, generateLods, lodName, type ImportedMesh } from '../src/assets/modelImport';
+
+/** A UV sphere: position, normal, one UV set, and a packed colour — the channels a real mesh carries. */
+function sphere(rings: number, segments: number): MeshData {
+ const stride = 12 + 12 + 8 + 4;
+ const n = (rings + 1) * (segments + 1);
+ const vertices = new Uint8Array(n * stride);
+ const view = new DataView(vertices.buffer);
+ let v = 0;
+ for (let r = 0; r <= rings; r++) {
+ for (let s = 0; s <= segments; s++, v++) {
+ const phi = (r / rings) * Math.PI, theta = (s / segments) * Math.PI * 2;
+ const p = [Math.sin(phi) * Math.cos(theta), Math.cos(phi), Math.sin(phi) * Math.sin(theta)];
+ const at = v * stride;
+ p.forEach((c, k) => { view.setFloat32(at + k * 4, c * 50, true); view.setFloat32(at + 12 + k * 4, c, true); });
+ view.setFloat32(at + 24, s / segments, true);
+ view.setFloat32(at + 28, r / rings, true);
+ vertices.set([200, 100, 50, 255], at + 32);
+ }
+ }
+ const indices: number[] = [];
+ for (let r = 0; r < rings; r++) {
+ for (let s = 0; s < segments; s++) {
+ const a = r * (segments + 1) + s, b = a + segments + 1;
+ indices.push(a, b, a + 1, a + 1, b, b + 1);
+ }
+ }
+ return {
+ channels: [
+ { semantic: MeshChannel.Position, components: 3, type: MeshChannelType.Float32, offset: 0 },
+ { semantic: MeshChannel.Normal, components: 3, type: MeshChannelType.Float32, offset: 12 },
+ { semantic: MeshChannel.TexCoord0, components: 2, type: MeshChannelType.Float32, offset: 24 },
+ { semantic: MeshChannel.Color, components: 4, type: MeshChannelType.UNorm8, offset: 32 },
+ ],
+ vertexStride: stride, vertexCount: n, vertices, indices: Uint32Array.from(indices),
+ aabbMin: [-50, -50, -50], aabbMax: [50, 50, 50],
+ };
+}
+
+describe('simplifyMesh', () => {
+ it('keeps about the share of triangles it was asked for, and fewer vertices', async () => {
+ const src = sphere(32, 48);
+ const out = (await simplifyMesh(src, { ratio: 0.25, maxError: 0.5 }))!;
+ expect(out).not.toBeNull();
+ const asked = src.indices.length / 3 * 0.25;
+ expect(out.triangles).toBeLessThan(asked * 1.5);
+ expect(out.triangles).toBeGreaterThan(asked * 0.5);
+ expect(out.data.vertexCount).toBeLessThan(src.vertexCount);
+ expect(out.data.indices.length % 3).toBe(0);
+ });
+
+ it('refers only to vertices it carries, and carries every vertex it refers to unchanged', async () => {
+ const src = sphere(24, 36);
+ const out = (await simplifyMesh(src, { ratio: 0.3, maxError: 0.5 }))!;
+ expect(Math.max(...out.data.indices)).toBeLessThan(out.data.vertexCount);
+ expect(out.data.vertices.length).toBe(out.data.vertexCount * out.data.vertexStride);
+ // Each surviving vertex record is one the source had: colour, UV and normal came with it.
+ const records = new Set<string>();
+ for (let v = 0; v < src.vertexCount; v++) {
+ records.add(Buffer.from(src.vertices.subarray(v * src.vertexStride, (v + 1) * src.vertexStride)).toString('hex'));
+ }
+ for (let v = 0; v < out.data.vertexCount; v++) {
+ const rec = Buffer.from(out.data.vertices.subarray(v * out.data.vertexStride, (v + 1) * out.data.vertexStride)).toString('hex');
+ expect(records.has(rec)).toBe(true);
+ }
+ });
+
+ it('does not move the surface beyond what it was allowed', async () => {
+ const src = sphere(32, 48);
+ const out = (await simplifyMesh(src, { ratio: 0.2, maxError: 0.02 }))!;
+ const view = new DataView(out.data.vertices.buffer);
+ let worst = 0;
+ for (let v = 0; v < out.data.vertexCount; v++) {
+ const at = v * out.data.vertexStride;
+ const r = Math.hypot(view.getFloat32(at, true), view.getFloat32(at + 4, true), view.getFloat32(at + 8, true));
+ worst = Math.max(worst, Math.abs(r - 50));
+ }
+ expect(worst).toBeLessThan(0.5); // every vertex still sits on the sphere
+ expect(out.error).toBeLessThanOrEqual(0.02 + 1e-6);
+ });
+
+ it('leaves skinned and morphing geometry alone', async () => {
+ const src = sphere(8, 8);
+ const skinned: MeshData = {
+ ...src, channels: [...src.channels, { semantic: MeshChannel.Joints, components: 4, type: MeshChannelType.UInt16, offset: 36 }],
+ };
+ expect(canSimplify(skinned)).toBe(false);
+ expect(await simplifyMesh(skinned, { ratio: 0.5 })).toBeNull();
+ expect(canSimplify({ ...src, morph: { names: ['a'], hasNormals: false, deltas: new Float32Array(0) } })).toBe(false);
+ });
+
+ it('answers null when there is nothing to take out', async () => {
+ const src = sphere(4, 4);
+ expect(await simplifyMesh(src, { ratio: 1 })).toBeNull();
+ });
+});
+
+describe('generateLods', () => {
+ const imported = (name: string, data: MeshData): ImportedMesh =>
+ ({ name, data, vertexCount: data.vertexCount, triangleCount: data.indices.length / 3 });
+
+ it('writes levels that each shed triangles, and points a LODGroup at them', async () => {
+ const mesh = imported('rock', sphere(40, 60));
+ await generateLods([mesh], { levels: 3, minTriangles: 256 });
+ expect(mesh.lods!.length).toBe(3);
+ const counts = [mesh.triangleCount, ...mesh.lods!.map((l) => l.triangleCount)];
+ for (let i = 1; i < counts.length; i++) expect(counts[i]).toBeLessThan(counts[i - 1]!);
+ const sizes = mesh.lods!.map((l) => l.size);
+ expect([...sizes].sort((a, b) => b - a)).toEqual(sizes);
+
+ const prefab = assembleModelPrefab('rock', [mesh], { refs: { prefix: 'assets/' } });
+ const group = prefab.entities.flatMap((e) => e.components).find((c) => c.type === 'LODGroup')!;
+ expect(group.data.lod1).toBe(`assets/${lodName(mesh, 1)}.esmesh`);
+ expect(group.data.lod3).toBe('assets/rock_lod3.esmesh');
+ expect(group.data.lod1Size).toBe(sizes[0]);
+ });
+
+ it('leaves a small mesh and an off setting alone', async () => {
+ const small = imported('pebble', sphere(4, 4));
+ const big = imported('rock', sphere(40, 60));
+ await generateLods([small, big], { levels: 0, minTriangles: 256 });
+ expect(small.lods).toBeUndefined();
+ expect(big.lods).toBeUndefined();
+ await generateLods([small], { levels: 3, minTriangles: 256 });
+ expect(small.lods).toBeUndefined();
+ const prefab = assembleModelPrefab('pebble', [small]);
+ expect(prefab.entities.flatMap((e) => e.components).some((c) => c.type === 'LODGroup')).toBe(false);
+ });
+});
diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjs
index 74fc35ada..41541206e 100644
--- a/tools/releaseNotes.mjs
+++ b/tools/releaseNotes.mjs
@@ -2467,4 +2467,6 @@ export const NOTED = {
{"note":"The output transform has a Neutral option that keeps hue and saturation."},
"feat(render): model highlights widen with how fast the vertex normal turns, so they stop sparkling":
{"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."},
};