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
fix: preserve painted features during mesh simplification
yhh5f373997dc39
diff --git a/pipeline/src/assets/meshSimplify.ts b/pipeline/src/assets/meshSimplify.tsindex e6eb1b588..3f6b06a73 100644--- a/pipeline/src/assets/meshSimplify.ts+++ b/pipeline/src/assets/meshSimplify.ts@@ -1,28 +1,18 @@// 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.+ * @file meshSimplify.ts+ * @brief Simplify static meshes while preserving vertex channels and bounded surface error.*/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. */+/** Triangle budget and geometric error policy. */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. */+ /** Maximum surface error, relative to mesh extent unless flags include ErrorAbsolute. */maxError?: number;/** How freely the collapse may treat the surface. Far levels are looked at small, so they can give up a mesh's open borders, collapse across a seam* and drop specks that are no longer a shape (`Permissive`, `Prune`); a near level keeps its borders (`LockBorder`), where a gap would show. */@@ -34,7 +24,7 @@ export type SimplifierFlag = 'LockBorder' | 'Sparse' | 'ErrorAbsolute' | 'Prune'export interface Simplified {data: MeshData;triangles: number;- /** What the collapse cost, relative to the mesh's extent. */+ /** Measured error in the same units as maxError. */error: number;}@@ -50,7 +40,7 @@ const floatChannel = (data: MeshData, semantic: number, components: number) =>/** 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.morph || data.inverseBindMatrices) 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;}@@ -68,9 +58,12 @@ export async function simplifyMesh(data: MeshData, options: SimplifyOptions): Prconst position = floatChannel(data, MeshChannel.Position, 3)!;const normal = floatChannel(data, MeshChannel.Normal, 3);const uv = floatChannel(data, MeshChannel.TexCoord0, 2);+ const uv1 = floatChannel(data, MeshChannel.TexCoord1, 2);+ const color = data.channels.find(c => c.semantic === MeshChannel.Color && c.components >= 3+ && (c.type === MeshChannelType.Float32 || c.type === MeshChannelType.UNorm8));const positions = new Float32Array(vertexCount * 3);- const attributeStride = (normal ? 3 : 0) + (uv ? 2 : 0);+ const attributeStride = (normal ? 3 : 0) + (uv ? 2 : 0) + (uv1 ? 2 : 0) + (color?.components ?? 0);const attributes = new Float32Array(vertexCount * attributeStride);for (let v = 0; v < vertexCount; v++) {const at = v * vertexStride;@@ -78,9 +71,15 @@ export async function simplifyMesh(data: MeshData, options: SimplifyOptions): Prlet 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);+ if (uv1) for (let k = 0; k < 2; k++) attributes[a++] = view.getFloat32(at + uv1.offset + k * 4, true);+ if (color) for (let k = 0; k < color.components; k++) {+ attributes[a++] = color.type === MeshChannelType.UNorm8 ? view.getUint8(at + color.offset + k) / 255+ : view.getFloat32(at + color.offset + k * 4, true);+ }}const weights = [...(normal ? [NORMAL_WEIGHT, NORMAL_WEIGHT, NORMAL_WEIGHT] : []),- ...(uv ? [UV_WEIGHT, UV_WEIGHT] : [])];+ ...(uv ? [UV_WEIGHT, UV_WEIGHT] : []), ...(uv1 ? [UV_WEIGHT, UV_WEIGHT] : []),+ ...Array<number>(color?.components ?? 0).fill(1)];const triangles = data.indices.length / 3;const targetTriangles = Math.max(1, Math.floor(triangles * options.ratio));diff --git a/pipeline/tests/mesh-simplify.test.ts b/pipeline/tests/mesh-simplify.test.tsindex 5d228e985..e1a6e88d2 100644--- a/pipeline/tests/mesh-simplify.test.ts+++ b/pipeline/tests/mesh-simplify.test.ts@@ -1,7 +1,8 @@// 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.+ * @file mesh-simplify.test.ts+ * @brief Verify geometry, shading attributes and generated LOD references after simplification.*/import { describe, it, expect } from 'vitest';import { MeshChannel, MeshChannelType, type MeshData } from 'esengine';@@ -46,6 +47,54 @@ function sphere(rings: number, segments: number): MeshData {}describe('simplifyMesh', () => {+ it.each([+ { semantic: MeshChannel.Color, type: MeshChannelType.UNorm8, components: 4 },+ { semantic: MeshChannel.Color, type: MeshChannelType.Float32, components: 4 },+ { semantic: MeshChannel.TexCoord1, type: MeshChannelType.Float32, components: 2 },+ ])('preserves painted features in channel $semantic with storage $type', async ({ semantic, type, components }) => {+ const side = 20, stride = 12 + components * (type === MeshChannelType.UNorm8 ? 1 : 4);+ const vertices = new Uint8Array((side + 1) ** 2 * stride), view = new DataView(vertices.buffer);+ const indices: number[] = [];+ for (let y = 0; y <= side; y++) for (let x = 0; x <= side; x++) {+ const at = (y * (side + 1) + x) * stride;+ view.setFloat32(at, x, true); view.setFloat32(at + 4, y, true);+ const color = x >= 6 && x <= 14 && y >= 6 && y <= 14 ? [1, 0, 0, 1] : [1, 1, 1, 1];+ color.slice(0, components).forEach((value, c) => {+ if (type === MeshChannelType.UNorm8) view.setUint8(at + 12 + c, value * 255);+ else view.setFloat32(at + 12 + c * 4, value, true);+ });+ if (x < side && y < side) {+ const a = y * (side + 1) + x, b = a + side + 1;+ indices.push(a, a + 1, b, a + 1, b + 1, b);+ }+ }+ const mesh: MeshData = { vertices, vertexStride: stride, vertexCount: (side + 1) ** 2,+ indices: Uint32Array.from(indices), aabbMin: [0, 0, 0], aabbMax: [side, side, 0],+ channels: [{ semantic: MeshChannel.Position, type: MeshChannelType.Float32, components: 3, offset: 0 },+ { semantic, type, components, offset: 12 }] };+ const result = (await simplifyMesh(mesh, { ratio: 0.05, maxError: 0.001, flags: ['Permissive'] }))!;+ expect(result.triangles).toBeLessThan(indices.length / 3);+ const sampled = new DataView(result.data.vertices.buffer);+ for (const [x, y, expected] of [[8, 8, 0], [12, 8, 0], [8, 12, 0], [12, 12, 0], [2, 2, 1]]) {+ let green: number | undefined;+ for (let i = 0; i < result.data.indices.length; i += 3) {+ const points = Array.from(result.data.indices.subarray(i, i + 3)).map(index => ({+ x: sampled.getFloat32(index * stride, true), y: sampled.getFloat32(index * stride + 4, true),+ g: type === MeshChannelType.UNorm8 ? sampled.getUint8(index * stride + 13) / 255+ : sampled.getFloat32(index * stride + 16, true),+ }));+ const [a, b, c] = points;+ const area = (b.y - c.y) * (a.x - c.x) + (c.x - b.x) * (a.y - c.y);+ if (Math.abs(area) < 1e-9) continue;+ const u = ((b.y - c.y) * (x - c.x) + (c.x - b.x) * (y - c.y)) / area;+ const v = ((c.y - a.y) * (x - c.x) + (a.x - c.x) * (y - c.y)) / area;+ if (u >= -1e-6 && v >= -1e-6 && u + v <= 1 + 1e-6) { green = u * a.g + v * b.g + (1 - u - v) * c.g; break; }+ }+ expect(green).toBeDefined();+ expect(green).toBeCloseTo(expected, 2);+ }+ });+it('collapses further across borders and seams when the level is only seen small', async () => {const src = sphere(32, 48);const near = (await simplifyMesh(src, { ratio: 0.05, maxError: 0.5, flags: ['LockBorder'] }))!;@@ -101,6 +150,7 @@ describe('simplifyMesh', () => {...src, channels: [...src.channels, { semantic: MeshChannel.Joints, components: 4, type: MeshChannelType.UInt16, offset: 36 }],};expect(canSimplify(skinned)).toBe(false);+ expect(canSimplify({ ...src, inverseBindMatrices: new Float32Array(16) })).toBe(false);expect(await simplifyMesh(skinned, { ratio: 0.5 })).toBeNull();expect(canSimplify({ ...src, morph: { names: ['a'], hasNormals: false, deltas: new Float32Array(0) } })).toBe(false);});