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(render): a model can be unwrapped for the light that will be baked into it
esengineddc6d8efc6d9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 30a7efb7c..6527b656d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,35 @@ published separately; it ships inside the editor.### Added+- **A model can be given somewhere to receive baked light.** A bake is read+ through a second UV set, and it has to be one where no two surfaces share a+ texel — which the UV set the art is wrapped in deliberately is not: two arms+ share one arm's pixels, and given the same lightmap texels one arm's shadow+ falls on the other. Almost no model carries a second set, so until now the+ reading side shipped in 0.67 could be pointed at nothing.++ **Generate Lightmap UVs**, in a model's import settings, unwraps one. The+ surface is cut into nearly-flat charts, each is projected onto its own plane,+ and they are packed into the unit square at **one** world-to-texel ratio — so a+ wall is lit at the same resolution as the floor it meets, which is what stops a+ seam showing where they join. Vertices on a chart boundary are split, so the+ mesh comes back with more of them than the source had; nothing moves, and every+ shape, skin weight and vertex colour follows its vertex.++ Off by default, because most models are never baked and a split vertex costs+ memory whether or not anything reads the channel. Two never get one: a skinned+ mesh, because bones move it and a bake cannot follow; and a model that already+ carries a second set, because that layout is the author's and the art may be+ painted against it.++ What it must guarantee is one property rather than a resemblance, so that is+ what the gates check — every triangle rasterised into a grid of lumels, and not+ one of them covered twice. Four more hold the rest of it: a cube comes back as+ six charts with all eight corners split three ways, the UVs stay inside the unit+ square, every face is lit at the same resolution, and no vertex moves. A sixth+ runs the whole thing over a model out of the corpus, because a cube's charts are+ six flat quads and a real one's are neither.+- **A mesh can be read through the light that was baked into it.** Sixteen lightsreach one frame; the seventeenth is dropped by brightness, with a warning namingwhat was refused. That ceiling is not a quality setting — a room with thirtydiff --git a/desktop b/desktopindex 0b3dc59a5..e14811881 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 0b3dc59a5d3003058f45327df9740845b04fd0ba+Subproject commit e1481188131838c5d0d98a57529b4ec5f8c07d88diff --git a/docs/astro/src/content/docs/assets/models.mdx b/docs/astro/src/content/docs/assets/models.mdxindex 17907bd4d..8458818fb 100644--- a/docs/astro/src/content/docs/assets/models.mdx+++ b/docs/astro/src/content/docs/assets/models.mdx@@ -99,6 +99,37 @@ 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.+## Lightmap UVs++A baked lightmap is read through a **second** UV set, and it has to be one where+no two surfaces land on the same texels. The set the art is wrapped in is not:+two arms deliberately share one arm's pixels, which is what keeps a texture+small. Give them the same lightmap texels and one arm's shadow falls on the+other.++Turn on **Generate Lightmap UVs** in the model's import settings and the import+unwraps one: the surface is cut into nearly-flat charts, each is projected onto+its own plane, and they are packed into the unit square at **one** world-to-texel+ratio — so a wall is lit at the same resolution as the floor it meets. Vertices+on a chart boundary are split, so the mesh comes back with more of them than the+source had; nothing moves, and every shape, skin weight and vertex colour follows+its vertex.++It is off by default because most models are never baked, and a split vertex+costs memory whether or not anything reads the channel. Two models never get one:++- A **skinned** mesh, because bones move it and a bake cannot follow.+- A model that **already carries** a second UV set, because the layout is the+ author's and the art may be painted against it. Blender's *Smart UV Project*+ into a second UV map is exactly this, and it is usually better than what an+ importer can infer.++The import reports how much of the atlas the charts fill. A low number means the+charts are many and small: raise the chart angle and they merge, at the cost of+more stretch inside each one.++See [Baked light](/docs/graphics/lighting/#baked-light) for what reads the result.+## Re-importingAn import runs again when:diff --git a/docs/astro/src/content/docs/zh-cn/assets/models.mdx b/docs/astro/src/content/docs/zh-cn/assets/models.mdxindex b000bee17..3382b14fe 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,29 @@ Transform 给,和导入的模型一样。`Scale` 落在 prefab 根节点的 `Transform` 上,**不会烘进几何** —— `.esmesh` 保持与源一致,而那个数字始终看得见、改得动。+## Lightmap UV++烘焙好的 lightmap 是通过**第二套** UV 读的,而且这套 UV 必须保证没有两个面落在同一批纹素上。+美术包裹用的那套不保证:两条手臂**故意**共用一条手臂的像素,这正是纹理能做小的原因。+让它们共用 lightmap 纹素,一条手臂的阴影就会落到另一条上。++在模型的导入设置里打开 **Generate Lightmap UVs**,导入就会展开一套:曲面被切成一片片近似平坦的+chart,每片投影到自己的平面,再按**同一个**世界-纹素比打包进单位方块——于是一面墙和它连着的地板+被以同样的分辨率点亮。落在 chart 边界上的顶点会被分裂,所以网格回来时顶点比源文件多;+但没有任何东西移动,每个形状、蒙皮权重和顶点色都跟着自己的顶点走。++默认关闭,因为大多数模型永远不会被烘焙,而分裂出的顶点无论有没有人读那条通道都要占内存。+有两种模型永远拿不到:++- **蒙皮**网格,因为骨骼在动它,烘焙跟不上。+- **已经带**第二套 UV 的模型,因为那套布局是作者的,美术可能已经按它画好了。+ Blender 的 *Smart UV Project* 展到第二个 UV map 就是这件事,而且通常比导入器推断得更好。++导入会报告 chart 填满了图集的多少。数字偏低说明 chart 又多又小:把 chart 角度调大它们会合并,+代价是每片内部的拉伸变大。++读取端见[烘焙光照](/docs/zh-cn/graphics/lighting/#烘焙光照)。+## 重新导入以下情况会重新跑一次导入:diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex 14c142a0c..75b993e4a 100644--- a/docs/astro/src/data/apiStability.generated.json+++ b/docs/astro/src/data/apiStability.generated.json@@ -3,10 +3,10 @@"counts": {"public": 114,"beta": 101,- "experimental": 1881,+ "experimental": 1884,"deprecated": 3},- "total": 2096,+ "total": 2099,"subsystems": [{"id": "ecs",@@ -342,6 +342,17 @@"MeshRenderers"]},+ {+ "id": "lightmap",+ "title": "Baked lighting",+ "titleZh": "烘焙光照",+ "tier": "experimental",+ "why": "half a line: the engine reads a bake and nothing here produces one yet, so the shape of this will follow what a baker turns out to need",+ "whyZh": "只做了一半:引擎读得了烘焙图,而这里还产不出一张,所以这套接口的形状要跟着烘焙器最终需要什么走",+ "entry": [+ "unwrapLightmapUV"+ ]+ },{"id": "dragonbones","title": "DragonBones",diff --git a/pipeline/src/assets/modelImport.ts b/pipeline/src/assets/modelImport.tsindex aca9dafb0..a0861acfe 100644--- a/pipeline/src/assets/modelImport.ts+++ b/pipeline/src/assets/modelImport.ts@@ -11,7 +11,7 @@* second set of rules for what a model IS in this engine.*/import {- MeshChannel, encodeMesh, PREFAB_FORMAT_VERSION, TIMELINE_FORMAT_VERSION,+ MeshChannel, encodeMesh, unwrapLightmapUV, PREFAB_FORMAT_VERSION, TIMELINE_FORMAT_VERSION,MATERIAL_FORMAT_VERSION, BlendMode, CullMode,type MeshData, type MaterialAssetData, type PrefabData, type PrefabEntityData,type PrefabComponentData as ComponentData,@@ -286,6 +286,40 @@ export function animationProductName(stem: string, name: string): string {/* -- Products ----------------------------------------------------------- */+/**+ * Gives every mesh a bake can be read on a lightmap UV set, and says who it+ * skipped. Mutates in place: the caller holds the products it is about to write.+ * Skinned is skipped because bones move it and a bake cannot follow; one that+ * already carries the channel keeps a layout its art may be painted against.+ */+export function applyLightmapUV(meshes: ImportedMesh[]): string[] {+ const warnings: string[] = [];+ for (const mesh of meshes) {+ if (mesh.skinJoints && mesh.skinJoints.length > 0) {+ warnings.push(`${mesh.name}: skinned, so it gets no lightmap UV — bones move it and`+ + ' a bake cannot');+ continue;+ }+ if (mesh.data.channels.some((c) => c.semantic === MeshChannel.TexCoord1)) {+ warnings.push(`${mesh.name}: already carries a second UV set, which is kept`);+ continue;+ }+ try {+ const { mesh: unwrapped, charts, coverage } = unwrapLightmapUV(mesh.data);+ mesh.data = unwrapped;+ mesh.vertexCount = unwrapped.vertexCount;+ if (coverage < 0.15) {+ warnings.push(`${mesh.name}: ${charts} chart(s) fill only`+ + ` ${Math.round(coverage * 100)}% of its atlas — a wider chart angle packs`+ + ' tighter, at the cost of more stretch');+ }+ } catch (err) {+ warnings.push(`${mesh.name}: no lightmap UV (${(err as Error).message})`);+ }+ }+ return warnings;+}+/** The bytes to write for an imported mesh. */export function encodeImportedMesh(mesh: ImportedMesh): Uint8Array {return encodeMesh(mesh.data);diff --git a/pipeline/src/project/importSettings.ts b/pipeline/src/project/importSettings.tsindex d49a072ab..46823cdd0 100644--- a/pipeline/src/project/importSettings.ts+++ b/pipeline/src/project/importSettings.ts@@ -173,6 +173,13 @@ const MODEL: ImporterFieldSpec[] = [tooltip: 'Uniform scale on the imported prefab\u0027s root. A model is authored in metres '+ 'and a world unit is a design pixel, so a real-world model arrives a few pixels across.',},+ {+ key: 'lightmapUV', label: 'Generate Lightmap UVs', type: 'bool', default: false,+ category: 'Import',+ tooltip: 'Unwrap a second UV set so this model can receive baked light. Off by default '+ + '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.',+ },];const PANORAMA: ImporterFieldSpec[] = [diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 4522fed01..5245c0ec1 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 114 public · 94 beta · 1720 experimental · 3 deprecated+Symbols: 114 public · 94 beta · 1723 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -10120,6 +10120,13 @@ number | Vec2 | Vec3 | Vec4 | number[] | TextureRef() => void```+## UnwrapOptions — interface @experimental+```+atlasSize: number | undefined+maxChartAngleDegrees: number | undefined+paddingTexels: number | undefined+```+## UnwrapQueryArg — type @public```T extends MutWrapper<infer C> ? C :@@ -10128,6 +10135,13 @@ T extends MutWrapper<infer C> ? C :T```+## UnwrapResult — interface @experimental+```+charts: number+coverage: number+mesh: MeshData+```+## UploadedGpuFormat — type @experimental```CompressedTextureFormat | 'rgba8'@@ -14005,6 +14019,11 @@ UIVisibilityPlugin(id: string): void```+## unwrapLightmapUV — function @experimental+```+(mesh: MeshData, options?: UnwrapOptions): UnwrapResult+```+## updateAnimatorIK — function @experimental```(def: AnimatorControllerDef, index: number, patch: Partial<AnimatorIK>): AnimatorControllerDefdiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 6d1ae03b5..af201d59c 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 114 public · 99 beta · 1739 experimental · 3 deprecated+Symbols: 114 public · 99 beta · 1742 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -10313,6 +10313,13 @@ number | Vec2 | Vec3 | Vec4 | number[] | TextureRef() => void```+## UnwrapOptions — interface @experimental+```+atlasSize: number | undefined+maxChartAngleDegrees: number | undefined+paddingTexels: number | undefined+```+## UnwrapQueryArg — type @public```T extends MutWrapper<infer C> ? C :@@ -10321,6 +10328,13 @@ T extends MutWrapper<infer C> ? C :T```+## UnwrapResult — interface @experimental+```+charts: number+coverage: number+mesh: MeshData+```+## UploadedGpuFormat — type @experimental```CompressedTextureFormat | 'rgba8'@@ -14248,6 +14262,11 @@ UIVisibilityPlugin(id: string): void```+## unwrapLightmapUV — function @experimental+```+(mesh: MeshData, options?: UnwrapOptions): UnwrapResult+```+## updateAnimatorIK — function @experimental```(def: AnimatorControllerDef, index: number, patch: Partial<AnimatorIK>): AnimatorControllerDefdiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex cd44163a8..c7e0637f9 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.node<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 114 public · 96 beta · 1719 experimental · 3 deprecated+Symbols: 114 public · 96 beta · 1722 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -10115,6 +10115,13 @@ number | Vec2 | Vec3 | Vec4 | number[] | TextureRef() => void```+## UnwrapOptions — interface @experimental+```+atlasSize: number | undefined+maxChartAngleDegrees: number | undefined+paddingTexels: number | undefined+```+## UnwrapQueryArg — type @public```T extends MutWrapper<infer C> ? C :@@ -10123,6 +10130,13 @@ T extends MutWrapper<infer C> ? C :T```+## UnwrapResult — interface @experimental+```+charts: number+coverage: number+mesh: MeshData+```+## UploadedGpuFormat — type @experimental```CompressedTextureFormat | 'rgba8'@@ -14010,6 +14024,11 @@ UIVisibilityPlugin(id: string): void```+## unwrapLightmapUV — function @experimental+```+(mesh: MeshData, options?: UnwrapOptions): UnwrapResult+```+## updateAnimatorIK — function @experimental```(def: AnimatorControllerDef, index: number, patch: Partial<AnimatorIK>): AnimatorControllerDefdiff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 5281cff0c..5b569d1cd 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1,7 +1,7 @@# API surface — esengine/minigame<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 114 public · 94 beta · 1741 experimental · 3 deprecated+Symbols: 114 public · 94 beta · 1744 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -10363,6 +10363,13 @@ number | Vec2 | Vec3 | Vec4 | number[] | TextureRef() => void```+## UnwrapOptions — interface @experimental+```+atlasSize: number | undefined+maxChartAngleDegrees: number | undefined+paddingTexels: number | undefined+```+## UnwrapQueryArg — type @public```T extends MutWrapper<infer C> ? C :@@ -10371,6 +10378,13 @@ T extends MutWrapper<infer C> ? C :T```+## UnwrapResult — interface @experimental+```+charts: number+coverage: number+mesh: MeshData+```+## UploadedGpuFormat — type @experimental```CompressedTextureFormat | 'rgba8'@@ -14269,6 +14283,11 @@ UIVisibilityPlugin(id: string): void```+## unwrapLightmapUV — function @experimental+```+(mesh: MeshData, options?: UnwrapOptions): UnwrapResult+```+## updateAnimatorIK — function @experimental```(def: AnimatorControllerDef, index: number, patch: Partial<AnimatorIK>): AnimatorControllerDefdiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex c4d5a0577..2993d077d 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1,7 +1,7 @@# API surface — esengine/wechat<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 114 public · 94 beta · 1731 experimental · 3 deprecated+Symbols: 114 public · 94 beta · 1734 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -10122,6 +10122,13 @@ number | Vec2 | Vec3 | Vec4 | number[] | TextureRef() => void```+## UnwrapOptions — interface @experimental+```+atlasSize: number | undefined+maxChartAngleDegrees: number | undefined+paddingTexels: number | undefined+```+## UnwrapQueryArg — type @public```T extends MutWrapper<infer C> ? C :@@ -10130,6 +10137,13 @@ T extends MutWrapper<infer C> ? C :T```+## UnwrapResult — interface @experimental+```+charts: number+coverage: number+mesh: MeshData+```+## UploadedGpuFormat — type @experimental```CompressedTextureFormat | 'rgba8'@@ -14033,6 +14047,11 @@ UIVisibilityPlugin(id: string): void```+## unwrapLightmapUV — function @experimental+```+(mesh: MeshData, options?: UnwrapOptions): UnwrapResult+```+## updateAnimatorIK — function @experimental```(def: AnimatorControllerDef, index: number, patch: Partial<AnimatorIK>): AnimatorControllerDefdiff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex 14807b4be..d2330ff1a 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -133,6 +133,16 @@ export {encodeChannelTable, type MeshChannelDesc, type MeshData, type MeshMorphTargets,} from './asset/meshFormat';export type { MeshResult } from './asset/loaders/MeshAssetLoader';+/**+ * Gives a mesh the second UV set a baked lightmap is read through — no two+ * surfaces on one texel, which the UV set the art is wrapped in does not promise.+ * An import calls it; so would a tool that unwraps geometry it generated.+ *+ * @experimental Pre-1.0: the options will follow what a baker turns out to need.+ */+export {+ unwrapLightmapUV, type UnwrapOptions, type UnwrapResult,+} from './lightmap';/*** Stock geometry a `builtin:<id>` mesh ref names. Public because the editor's* pickers and Create menu are built from this list. `@beta`.diff --git a/sdk/src/lightmap/charts.ts b/sdk/src/lightmap/charts.tsnew file mode 100644index 000000000..84a65eef8--- /dev/null+++ b/sdk/src/lightmap/charts.ts@@ -0,0 +1,170 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file charts.ts+ * @brief Triangles in, flat pieces out — the first half of a lightmap unwrap.+ *+ * A bake is read through a UV set where no two surfaces share a texel, which the+ * UV set the art is wrapped in deliberately violates. Here the surface is cut+ * into charts that are nearly flat, and each is projected onto its own plane.+ */++/** One triangle of the source, by vertex index. */+export interface Tri {+ a: number;+ b: number;+ c: number;+}++export interface ChartSet {+ /** Chart index per triangle, parallel to the triangle list. */+ chartOf: Int32Array;+ /** How many charts the surface was cut into. */+ count: number;+ /** Orthonormal projection basis per chart: `[tx,ty,tz, bx,by,bz]`. */+ basis: Float32Array;+}++const dot = (a: Float32Array, i: number, b: Float32Array, j: number): number =>+ a[i] * b[j] + a[i + 1] * b[j + 1] + a[i + 2] * b[j + 2];++/**+ * Welds vertices by POSITION, returning a representative index per vertex.+ *+ * Adjacency has to be geometric: an importer already splits a vertex wherever a+ * normal or a UV is discontinuous, so two triangles sharing an edge of the model+ * usually share no vertex index at all. Quantising is what makes them meet.+ */+export function weldByPosition(positions: Float32Array, vertexCount: number,+ epsilon: number): Int32Array {+ const rep = new Int32Array(vertexCount);+ const grid = new Map<string, number>();+ const inv = 1 / Math.max(epsilon, 1e-9);+ for (let v = 0; v < vertexCount; v++) {+ const x = Math.round(positions[v * 3] * inv);+ const y = Math.round(positions[v * 3 + 1] * inv);+ const z = Math.round(positions[v * 3 + 2] * inv);+ const key = `${x},${y},${z}`;+ const seen = grid.get(key);+ if (seen === undefined) { grid.set(key, v); rep[v] = v; } else { rep[v] = seen; }+ }+ return rep;+}++/** Geometric normal of a triangle, unnormalised — its length is twice the area. */+function faceNormal(p: Float32Array, t: Tri, out: Float32Array, at: number): number {+ const ax = p[t.a * 3], ay = p[t.a * 3 + 1], az = p[t.a * 3 + 2];+ const ux = p[t.b * 3] - ax, uy = p[t.b * 3 + 1] - ay, uz = p[t.b * 3 + 2] - az;+ const vx = p[t.c * 3] - ax, vy = p[t.c * 3 + 1] - ay, vz = p[t.c * 3 + 2] - az;+ const nx = uy * vz - uz * vy, ny = uz * vx - ux * vz, nz = ux * vy - uy * vx;+ out[at] = nx; out[at + 1] = ny; out[at + 2] = nz;+ return Math.hypot(nx, ny, nz);+}++/** Triangles sharing each welded edge, as a map from edge key to triangle list. */+function edgeMap(tris: Tri[], rep: Int32Array): Map<number, number[]> {+ const edges = new Map<number, number[]>();+ const add = (u: number, v: number, t: number): void => {+ const lo = Math.min(u, v), hi = Math.max(u, v);+ // A pair key rather than a string: this runs once per edge of every model+ // imported, and 2^26 vertices is past what the format can index anyway.+ const key = lo * 67108864 + hi;+ const at = edges.get(key);+ if (at) at.push(t); else edges.set(key, [t]);+ };+ for (let i = 0; i < tris.length; i++) {+ const t = tris[i];+ add(rep[t.a], rep[t.b], i);+ add(rep[t.b], rep[t.c], i);+ add(rep[t.c], rep[t.a], i);+ }+ return edges;+}++/**+ * Cuts the surface into nearly-flat charts and gives each a projection basis.+ *+ * @param maxAngleCos Cosine of the widest angle two neighbours may differ by and+ * still be one chart. Flatter charts project with less stretch and pack+ * worse; this is the whole of that trade.+ */+export function buildCharts(positions: Float32Array, tris: Tri[], rep: Int32Array,+ maxAngleCos: number): ChartSet {+ const count = tris.length;+ const normals = new Float32Array(count * 3);+ const degenerate = new Uint8Array(count);+ for (let i = 0; i < count; i++) {+ const len = faceNormal(positions, tris[i], normals, i * 3);+ // A triangle with no area has no normal to grow a chart along, and no+ // texels to light either. It joins whatever claims it and is projected+ // with that chart's basis.+ if (len < 1e-12) { degenerate[i] = 1; continue; }+ normals[i * 3] /= len; normals[i * 3 + 1] /= len; normals[i * 3 + 2] /= len;+ }++ const edges = edgeMap(tris, rep);+ const neighboursOf = (t: number): number[] => {+ const tri = tris[t];+ const out: number[] = [];+ const push = (u: number, v: number): void => {+ const lo = Math.min(rep[u], rep[v]), hi = Math.max(rep[u], rep[v]);+ for (const other of edges.get(lo * 67108864 + hi) ?? []) {+ if (other !== t) out.push(other);+ }+ };+ push(tri.a, tri.b); push(tri.b, tri.c); push(tri.c, tri.a);+ return out;+ };++ const chartOf = new Int32Array(count).fill(-1);+ const seeds: number[] = [];+ let charts = 0;+ for (let start = 0; start < count; start++) {+ if (chartOf[start] >= 0) continue;+ const id = charts++;+ seeds.push(start);+ chartOf[start] = id;+ // Grown against the SEED's normal, not each neighbour's: comparing to the+ // neighbour lets a chart walk around a cylinder one small step at a time+ // and come back facing away from where it started.+ const queue = [start];+ while (queue.length > 0) {+ const t = queue.pop() as number;+ for (const n of neighboursOf(t)) {+ if (chartOf[n] >= 0) continue;+ if (!degenerate[n] && !degenerate[start]+ && dot(normals, start * 3, normals, n * 3) < maxAngleCos) continue;+ chartOf[n] = id;+ queue.push(n);+ }+ }+ }++ const basis = new Float32Array(charts * 6);+ const sum = new Float32Array(charts * 3);+ for (let i = 0; i < count; i++) {+ if (degenerate[i]) continue;+ const c = chartOf[i] * 3;+ sum[c] += normals[i * 3]; sum[c + 1] += normals[i * 3 + 1]; sum[c + 2] += normals[i * 3 + 2];+ }+ for (let c = 0; c < charts; c++) {+ let nx = sum[c * 3], ny = sum[c * 3 + 1], nz = sum[c * 3 + 2];+ let len = Math.hypot(nx, ny, nz);+ if (len < 1e-9) { nx = 0; ny = 0; nz = 1; len = 1; }+ nx /= len; ny /= len; nz /= len;+ // Any axis not parallel to the normal gives a tangent; the least of the+ // three components is the one that cannot be.+ const ax = Math.abs(nx), ay = Math.abs(ny), az = Math.abs(nz);+ const up = ax <= ay && ax <= az ? [1, 0, 0] : ay <= az ? [0, 1, 0] : [0, 0, 1];+ let tx = up[1] * nz - up[2] * ny;+ let ty = up[2] * nx - up[0] * nz;+ let tz = up[0] * ny - up[1] * nx;+ const tl = Math.hypot(tx, ty, tz) || 1;+ tx /= tl; ty /= tl; tz /= tl;+ basis[c * 6] = tx; basis[c * 6 + 1] = ty; basis[c * 6 + 2] = tz;+ basis[c * 6 + 3] = ny * tz - nz * ty;+ basis[c * 6 + 4] = nz * tx - nx * tz;+ basis[c * 6 + 5] = nx * ty - ny * tx;+ }+ return { chartOf, count: charts, basis };+}diff --git a/sdk/src/lightmap/index.ts b/sdk/src/lightmap/index.tsnew file mode 100644index 000000000..ebb7ac5f1--- /dev/null+++ b/sdk/src/lightmap/index.ts@@ -0,0 +1,3 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+export { unwrapLightmapUV, type UnwrapOptions, type UnwrapResult } from './unwrap';diff --git a/sdk/src/lightmap/pack.ts b/sdk/src/lightmap/pack.tsnew file mode 100644index 000000000..15cd20b55--- /dev/null+++ b/sdk/src/lightmap/pack.ts@@ -0,0 +1,91 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file pack.ts+ * @brief Rectangles into a square, bottom-left along a skyline.+ *+ * The charts arrive already scaled, because a lightmap wants ONE world-to-texel+ * ratio across the whole atlas: a chart shrunk to make it fit would be lit at a+ * different resolution from the wall beside it, and the seam shows.+ */++export interface PackedRect {+ x: number;+ y: number;+ /** Whether the rectangle was placed with its width and height exchanged. */+ rotated: boolean;+}++interface Segment {+ x: number;+ y: number;+ width: number;+}++/** Height the skyline reaches over `[x, x+width)`, or -1 if that runs off the end. */+function supportHeight(line: Segment[], from: number, x: number, width: number,+ extent: number): number {+ if (x + width > extent) return -1;+ let y = line[from].y;+ let left = width;+ for (let i = from; i < line.length && left > 0; i++) {+ y = Math.max(y, line[i].y);+ left -= line[i].width - (i === from ? x - line[i].x : 0);+ }+ return left > 0 ? -1 : y;+}++function place(line: Segment[], x: number, y: number, width: number, height: number): void {+ const top = y + height;+ const merged: Segment[] = [];+ for (const s of line) {+ if (s.x + s.width <= x || s.x >= x + width) { merged.push(s); continue; }+ if (s.x < x) merged.push({ x: s.x, y: s.y, width: x - s.x });+ if (s.x + s.width > x + width) {+ merged.push({ x: x + width, y: s.y, width: s.x + s.width - (x + width) });+ }+ }+ merged.push({ x, y: top, width });+ merged.sort((a, b) => a.x - b.x);+ line.length = 0;+ for (const s of merged) {+ const last = line[line.length - 1];+ if (last && last.y === s.y && last.x + last.width === s.x) last.width += s.width;+ else line.push(s);+ }+}++/**+ * Places every rectangle inside a square of side `extent`, or returns null.+ *+ * Null is the caller's signal to scale the whole set down and try again — which+ * is the only way to keep one ratio for all of them.+ */+export function packSkyline(sizes: ReadonlyArray<readonly [number, number]>,+ extent: number): PackedRect[] | null {+ const order = sizes.map((_, i) => i)+ .sort((a, b) => Math.max(sizes[b][0], sizes[b][1]) - Math.max(sizes[a][0], sizes[a][1]));+ const line: Segment[] = [{ x: 0, y: 0, width: extent }];+ const out: PackedRect[] = new Array(sizes.length);++ for (const i of order) {+ const [w, h] = sizes[i];+ let best: { x: number; y: number; rotated: boolean } | null = null;+ for (let s = 0; s < line.length; s++) {+ // Both orientations: a tall chart laid on its side often drops into a+ // gap the upright one has to start a new row for.+ for (const [rw, rh, rotated] of [[w, h, false], [h, w, true]] as const) {+ const y = supportHeight(line, s, line[s].x, rw, extent);+ if (y < 0 || y + rh > extent) continue;+ if (!best || y < best.y || (y === best.y && line[s].x < best.x)) {+ best = { x: line[s].x, y, rotated };+ }+ }+ }+ if (!best) return null;+ const [pw, ph] = best.rotated ? [h, w] : [w, h];+ place(line, best.x, best.y, pw, ph);+ out[i] = best;+ }+ return out;+}diff --git a/sdk/src/lightmap/unwrap.ts b/sdk/src/lightmap/unwrap.tsnew file mode 100644index 000000000..251799995--- /dev/null+++ b/sdk/src/lightmap/unwrap.ts@@ -0,0 +1,211 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * @file unwrap.ts+ * @brief A second UV set for a mesh that has none — the whole unwrap, in order.+ *+ * Cut into flat charts, project each onto its own plane, scale them all by ONE+ * ratio, pack, split the vertices the cuts run through. A bake is read through+ * the result, so what it must guarantee is that no two surfaces share a texel —+ * which is exactly what the UV set the art is wrapped in does not.+ */++import { MeshChannel, MeshChannelType, type MeshData, type MeshChannelDesc } from '../asset/meshFormat';+import { buildCharts, weldByPosition, type Tri } from './charts';+import { packSkyline } from './pack';++export interface UnwrapOptions {+ /** Widest angle two neighbouring faces may differ by and stay one chart. */+ maxChartAngleDegrees?: number;+ /** Texels of empty space kept around every chart, at {@link atlasSize}. Two is+ * the least that stops a bilinear tap reading the chart next door. */+ paddingTexels?: number;+ /** The atlas size the padding is reckoned against. Not stored anywhere: a UV+ * set is resolution-independent, and this only fixes what "two texels" means. */+ atlasSize?: number;+}++export interface UnwrapResult {+ /** The mesh with a `TexCoord1` channel. Has MORE vertices than the input+ * wherever a chart boundary runs through one — a vertex on a seam holds a+ * different lightmap UV for each side of it. */+ mesh: MeshData;+ charts: number;+ /** Fraction of the unit square the charts occupy. What is left is the price+ * of packing rectangles, and of the padding that keeps them apart. */+ coverage: number;+}++const DEFAULTS = { maxChartAngleDegrees: 60, paddingTexels: 2, atlasSize: 1024 };++function channelAt(channels: readonly MeshChannelDesc[], semantic: number): MeshChannelDesc | undefined {+ return channels.find((c) => c.semantic === semantic);+}++/** Positions as a tight `vertexCount * 3` array, whatever the source stride is. */+function readPositions(mesh: MeshData): Float32Array {+ const pos = channelAt(mesh.channels, MeshChannel.Position);+ if (!pos || pos.type !== MeshChannelType.Float32) {+ throw new Error('unwrapLightmapUV: the mesh carries no float Position channel');+ }+ const view = new DataView(mesh.vertices.buffer, mesh.vertices.byteOffset, mesh.vertices.byteLength);+ const out = new Float32Array(mesh.vertexCount * 3);+ for (let v = 0; v < mesh.vertexCount; v++) {+ const at = v * mesh.vertexStride + pos.offset;+ out[v * 3] = view.getFloat32(at, true);+ out[v * 3 + 1] = view.getFloat32(at + 4, true);+ out[v * 3 + 2] = pos.components >= 3 ? view.getFloat32(at + 8, true) : 0;+ }+ return out;+}++/** The diagonal of the bounds, as the scale a weld epsilon is relative to. */+function weldEpsilon(mesh: MeshData): number {+ const d = Math.hypot(mesh.aabbMax[0] - mesh.aabbMin[0],+ mesh.aabbMax[1] - mesh.aabbMin[1],+ mesh.aabbMax[2] - mesh.aabbMin[2]);+ return Math.max(d, 1e-6) * 1e-5;+}++/**+ * Gives `mesh` a lightmap UV set, splitting vertices where charts meet.+ *+ * Every per-vertex datum follows its vertex, morph deltas included, so the result+ * is the same mesh — drawn, skinned and shaped identically — that now also+ * carries somewhere to read a bake from.+ */+export function unwrapLightmapUV(mesh: MeshData, options: UnwrapOptions = {}): UnwrapResult {+ const opts = { ...DEFAULTS, ...options };+ const positions = readPositions(mesh);+ const tris: Tri[] = [];+ for (let i = 0; i + 2 < mesh.indices.length; i += 3) {+ tris.push({ a: mesh.indices[i], b: mesh.indices[i + 1], c: mesh.indices[i + 2] });+ }+ const rep = weldByPosition(positions, mesh.vertexCount, weldEpsilon(mesh));+ const maxCos = Math.cos((opts.maxChartAngleDegrees * Math.PI) / 180);+ const charts = buildCharts(positions, tris, rep, maxCos);++ // Project every corner into its chart's plane. Held per (triangle, corner)+ // rather than per vertex: a vertex on a seam belongs to more than one chart+ // and has a different answer in each.+ const cornerU = new Float32Array(tris.length * 3);+ const cornerV = new Float32Array(tris.length * 3);+ const lo = new Float32Array(charts.count * 2).fill(Infinity);+ const hi = new Float32Array(charts.count * 2).fill(-Infinity);+ for (let t = 0; t < tris.length; t++) {+ const c = charts.chartOf[t] * 6;+ const corners = [tris[t].a, tris[t].b, tris[t].c];+ for (let k = 0; k < 3; k++) {+ const p = corners[k] * 3;+ const u = positions[p] * charts.basis[c] + positions[p + 1] * charts.basis[c + 1]+ + positions[p + 2] * charts.basis[c + 2];+ const v = positions[p] * charts.basis[c + 3] + positions[p + 1] * charts.basis[c + 4]+ + positions[p + 2] * charts.basis[c + 5];+ cornerU[t * 3 + k] = u;+ cornerV[t * 3 + k] = v;+ const b = charts.chartOf[t] * 2;+ if (u < lo[b]) lo[b] = u;+ if (u > hi[b]) hi[b] = u;+ if (v < lo[b + 1]) lo[b + 1] = v;+ if (v > hi[b + 1]) hi[b + 1] = v;+ }+ }++ const extent: Array<readonly [number, number]> = [];+ for (let c = 0; c < charts.count; c++) {+ extent.push([Math.max(hi[c * 2] - lo[c * 2], 0), Math.max(hi[c * 2 + 1] - lo[c * 2 + 1], 0)]);+ }+ const pad = opts.paddingTexels / opts.atlasSize;++ // ONE ratio for every chart, found by shrinking until they fit. A chart+ // scaled on its own would be lit at a different resolution from the surface+ // it joins, and the seam is where that shows.+ let area = 0;+ for (const [w, h] of extent) area += w * h;+ let scale = area > 0 ? Math.sqrt(0.5 / area) : 1;+ let placed = null as ReturnType<typeof packSkyline>;+ for (let attempt = 0; attempt < 24 && !placed; attempt++) {+ const boxes = extent.map(([w, h]) => [w * scale + pad * 2, h * scale + pad * 2] as const);+ placed = packSkyline(boxes, 1);+ if (!placed) scale *= 0.8;+ }+ if (!placed) throw new Error('unwrapLightmapUV: charts do not fit even at 0.5% of their size');++ let covered = 0;+ for (let c = 0; c < charts.count; c++) covered += extent[c][0] * extent[c][1] * scale * scale;++ // Split: a vertex is one new vertex per chart that uses it.+ const remap = new Map<number, number>();+ const source: number[] = [];+ const uv: number[] = [];+ const indices = new Uint32Array(tris.length * 3);+ for (let t = 0; t < tris.length; t++) {+ const chart = charts.chartOf[t];+ const box = placed[chart];+ const corners = [tris[t].a, tris[t].b, tris[t].c];+ for (let k = 0; k < 3; k++) {+ const key = corners[k] * charts.count + chart;+ let out = remap.get(key);+ if (out === undefined) {+ out = source.length;+ remap.set(key, out);+ source.push(corners[k]);+ const du = (cornerU[t * 3 + k] - lo[chart * 2]) * scale;+ const dv = (cornerV[t * 3 + k] - lo[chart * 2 + 1]) * scale;+ uv.push(box.rotated ? box.x + pad + dv : box.x + pad + du,+ box.rotated ? box.y + pad + du : box.y + pad + dv);+ }+ indices[t * 3 + k] = out;+ }+ }++ return {+ mesh: rebuild(mesh, source, uv, indices),+ charts: charts.count,+ coverage: covered,+ };+}++/** The same mesh over a new vertex table, with the UV set appended to each. */+function rebuild(mesh: MeshData, source: number[], uv: number[], indices: Uint32Array): MeshData {+ const had = channelAt(mesh.channels, MeshChannel.TexCoord1);+ const stride = had ? mesh.vertexStride : mesh.vertexStride + 8;+ const at = had ? had.offset : mesh.vertexStride;+ const channels: MeshChannelDesc[] = had ? [...mesh.channels] : [+ ...mesh.channels,+ { semantic: MeshChannel.TexCoord1, components: 2, type: MeshChannelType.Float32, offset: at },+ ];++ const vertices = new Uint8Array(source.length * stride);+ const view = new DataView(vertices.buffer);+ for (let v = 0; v < source.length; v++) {+ vertices.set(mesh.vertices.subarray(source[v] * mesh.vertexStride,+ (source[v] + 1) * mesh.vertexStride), v * stride);+ view.setFloat32(v * stride + at, uv[v * 2], true);+ view.setFloat32(v * stride + at + 4, uv[v * 2 + 1], true);+ }++ let morph = mesh.morph;+ if (morph) {+ const per = morph.hasNormals ? 6 : 3;+ const targets = morph.names.length;+ const deltas = new Float32Array(targets * source.length * per);+ for (let t = 0; t < targets; t++) {+ for (let v = 0; v < source.length; v++) {+ const from = (t * mesh.vertexCount + source[v]) * per;+ deltas.set(morph.deltas.subarray(from, from + per), (t * source.length + v) * per);+ }+ }+ morph = { ...morph, deltas };+ }++ return {+ ...mesh,+ channels,+ vertexStride: stride,+ vertexCount: source.length,+ vertices,+ indices,+ morph,+ };+}diff --git a/sdk/tests/lightmap-unwrap.test.ts b/sdk/tests/lightmap-unwrap.test.tsnew file mode 100644index 000000000..4d9142536--- /dev/null+++ b/sdk/tests/lightmap-unwrap.test.ts@@ -0,0 +1,198 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+/**+ * The claim: a bake can be read through what this produces.+ *+ * That is one property and not a resemblance — NO TWO SURFACES SHARE A TEXEL —+ * so it is checked the way a bake would use it: rasterise every triangle into a+ * grid of lumels and look for one covered twice.+ */+import { describe, it, expect } from 'vitest';+import { readFileSync } from 'node:fs';+import path from 'node:path';+import { unwrapLightmapUV } from '../src/lightmap';+import { decodeMesh, MeshChannel, MeshChannelType, type MeshData, type MeshChannelDesc } from '../src/asset/meshFormat';++const chan = (m: MeshData, s: number): MeshChannelDesc =>+ m.channels.find((c) => c.semantic === s) as MeshChannelDesc;++function readVec(m: MeshData, semantic: number, v: number, n: number): number[] {+ const c = chan(m, semantic);+ const view = new DataView(m.vertices.buffer, m.vertices.byteOffset, m.vertices.byteLength);+ const at = v * m.vertexStride + c.offset;+ return Array.from({ length: n }, (_, i) => view.getFloat32(at + i * 4, true));+}++/** A unit cube: six faces at right angles, so a 60-degree chart angle must cut it+ * into six pieces and split all eight of its corners three ways. */+function cube(): MeshData {+ const corners = [+ [-1, -1, -1], [1, -1, -1], [1, 1, -1], [-1, 1, -1],+ [-1, -1, 1], [1, -1, 1], [1, 1, 1], [-1, 1, 1],+ ];+ const faces = [+ [0, 1, 2, 3], [5, 4, 7, 6], [4, 0, 3, 7],+ [1, 5, 6, 2], [4, 5, 1, 0], [3, 2, 6, 7],+ ];+ const stride = 12;+ const vertices = new Uint8Array(corners.length * stride);+ const view = new DataView(vertices.buffer);+ corners.forEach((p, i) => {+ for (let k = 0; k < 3; k++) view.setFloat32(i * stride + k * 4, p[k], true);+ });+ const indices: number[] = [];+ for (const [a, b, c, d] of faces) indices.push(a, b, c, a, c, d);+ return {+ channels: [{ semantic: MeshChannel.Position, components: 3, type: MeshChannelType.Float32, offset: 0 }],+ vertexStride: stride,+ vertexCount: corners.length,+ vertices,+ indices: Uint32Array.from(indices),+ aabbMin: [-1, -1, -1],+ aabbMax: [1, 1, 1],+ };+}++/**+ * How many times each lumel of an `n`-by-`n` atlas is covered.+ *+ * A texel centre inside two triangles is the failure a lightmap cannot survive:+ * one surface's light is written over the other's, and which one wins depends on+ * the order the bake happened to visit them in.+ */+function coverage(mesh: MeshData, n: number): { max: number; touched: number } {+ const count = new Uint16Array(n * n);+ const uvOf = (v: number): [number, number] => readVec(mesh, MeshChannel.TexCoord1, v, 2) as [number, number];+ for (let i = 0; i + 2 < mesh.indices.length; i += 3) {+ const p = [uvOf(mesh.indices[i]), uvOf(mesh.indices[i + 1]), uvOf(mesh.indices[i + 2])];+ const minX = Math.max(0, Math.floor(Math.min(...p.map((q) => q[0])) * n));+ const maxX = Math.min(n - 1, Math.ceil(Math.max(...p.map((q) => q[0])) * n));+ const minY = Math.max(0, Math.floor(Math.min(...p.map((q) => q[1])) * n));+ const maxY = Math.min(n - 1, Math.ceil(Math.max(...p.map((q) => q[1])) * n));+ const area = (p[1][0] - p[0][0]) * (p[2][1] - p[0][1]) - (p[2][0] - p[0][0]) * (p[1][1] - p[0][1]);+ if (Math.abs(area) < 1e-12) continue;+ for (let y = minY; y <= maxY; y++) {+ for (let x = minX; x <= maxX; x++) {+ const cx = (x + 0.5) / n, cy = (y + 0.5) / n;+ const w0 = ((p[1][0] - cx) * (p[2][1] - cy) - (p[2][0] - cx) * (p[1][1] - cy)) / area;+ const w1 = ((p[2][0] - cx) * (p[0][1] - cy) - (p[0][0] - cx) * (p[2][1] - cy)) / area;+ const w2 = 1 - w0 - w1;+ if (w0 >= 0 && w1 >= 0 && w2 >= 0) count[y * n + x]++;+ }+ }+ }+ let max = 0, touched = 0;+ for (const c of count) { if (c > max) max = c; if (c > 0) touched++; }+ return { max, touched };+}++/** World area of every triangle, by index, from the positions. */+function worldAreas(mesh: MeshData): number[] {+ const out: number[] = [];+ for (let i = 0; i + 2 < mesh.indices.length; i += 3) {+ const [a, b, c] = [0, 1, 2].map((k) => readVec(mesh, MeshChannel.Position, mesh.indices[i + k], 3));+ const u = [b[0] - a[0], b[1] - a[1], b[2] - a[2]];+ const v = [c[0] - a[0], c[1] - a[1], c[2] - a[2]];+ out.push(Math.hypot(u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]) / 2);+ }+ return out;+}++function uvAreas(mesh: MeshData): number[] {+ const out: number[] = [];+ for (let i = 0; i + 2 < mesh.indices.length; i += 3) {+ const [a, b, c] = [0, 1, 2].map((k) => readVec(mesh, MeshChannel.TexCoord1, mesh.indices[i + k], 2));+ out.push(Math.abs((b[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (b[1] - a[1])) / 2);+ }+ return out;+}++describe('a lightmap UV set', () => {+ it('gives a cube six charts and splits every corner three ways', () => {+ const { mesh, charts } = unwrapLightmapUV(cube());+ expect(charts).toBe(6);+ // Eight corners, each used by three faces that are three charts.+ expect(mesh.vertexCount).toBe(24);+ expect(mesh.indices.length).toBe(36);+ });++ it('never covers one lumel twice', () => {+ const { mesh } = unwrapLightmapUV(cube());+ const { max, touched } = coverage(mesh, 128);+ expect(touched).toBeGreaterThan(0);+ expect(max).toBe(1);+ });++ it('stays inside the unit square', () => {+ const { mesh } = unwrapLightmapUV(cube());+ for (let v = 0; v < mesh.vertexCount; v++) {+ const [u, w] = readVec(mesh, MeshChannel.TexCoord1, v, 2);+ expect(u).toBeGreaterThanOrEqual(0);+ expect(w).toBeGreaterThanOrEqual(0);+ expect(u).toBeLessThanOrEqual(1);+ expect(w).toBeLessThanOrEqual(1);+ }+ });++ it('lights every face at the same resolution', () => {+ // ONE world-to-texel ratio, which is what stops a wall being sharper than+ // the floor it meets. Per triangle the ratio is uv area over world area.+ const { mesh } = unwrapLightmapUV(cube());+ const ratios = uvAreas(mesh).map((uv, i) => uv / worldAreas(mesh)[i]);+ const lo = Math.min(...ratios), hi = Math.max(...ratios);+ expect(hi / lo).toBeLessThan(1.0001);+ });++ it('does not move a single vertex', () => {+ const before = cube();+ const { mesh } = unwrapLightmapUV(before);+ const tri = (m: MeshData, i: number): string =>+ [0, 1, 2].map((k) => readVec(m, MeshChannel.Position, m.indices[i + k], 3).join(',')).join('|');+ const was = new Set<string>();+ for (let i = 0; i + 2 < before.indices.length; i += 3) was.add(tri(before, i));+ for (let i = 0; i + 2 < mesh.indices.length; i += 3) expect(was.has(tri(mesh, i))).toBe(true);+ expect(mesh.indices.length).toBe(before.indices.length);+ });++ it('takes every shape the mesh can be blended into with it', () => {+ // A split vertex is the SAME vertex twice, so whatever moves the original+ // has to move both. Nothing else here reads the deltas, and a remap that+ // indexed the new table by its own position passed every other case.+ const base = cube();+ const per = 3;+ const deltas = new Float32Array(base.vertexCount * per);+ for (let v = 0; v < base.vertexCount; v++) deltas[v * per] = v + 1;+ const { mesh } = unwrapLightmapUV({+ ...base,+ morph: { names: ['Push'], hasNormals: false, deltas },+ });+ const moved = mesh.morph as NonNullable<MeshData['morph']>;+ expect(moved.deltas.length).toBe(mesh.vertexCount * per);+ // Looked up rather than derived: the corners are in winding order, and a+ // bit-pattern guess at their indices is a bug in this case, not the unwrap.+ const corners = new Map<string, number>();+ for (let v = 0; v < base.vertexCount; v++) {+ corners.set(readVec(base, MeshChannel.Position, v, 3).join(','), v);+ }+ for (let v = 0; v < mesh.vertexCount; v++) {+ const from = corners.get(readVec(mesh, MeshChannel.Position, v, 3).join(','));+ expect(from).toBeDefined();+ expect(moved.deltas[v * per]).toBe((from as number) + 1);+ }+ });++ it('carries a real model, not only a cube', () => {+ // A cube's charts are six flat quads; a model's are neither, and the packer+ // meets shapes a synthetic case never produces. Resolved from THIS file: a+ // relative path made the case skip itself in silence and pass for it.+ const file = path.resolve(__dirname,+ '../../examples/character-rig/assets/models/knight_4_0.esmesh');+ const source = decodeMesh(new Uint8Array(readFileSync(file)));+ expect(source.vertexCount).toBeGreaterThan(100);+ const { mesh, charts, coverage: filled } = unwrapLightmapUV(source);+ expect(charts).toBeGreaterThan(1);+ expect(mesh.vertexCount).toBeGreaterThanOrEqual(source.vertexCount);+ expect(filled).toBeGreaterThan(0.05);+ expect(coverage(mesh, 256).max).toBe(1);+ });+});diff --git a/tools/apiSubsystems.mjs b/tools/apiSubsystems.mjsindex e481fb798..bb4d9906d 100644--- a/tools/apiSubsystems.mjs+++ b/tools/apiSubsystems.mjs@@ -293,6 +293,16 @@ export const SUBSYSTEMS = [whyZh: '导入链路已经端到端认证,但游戏用来驱动模型的运行时面(几何体、逐子网格材质、关节实体)还没有被拿来定级',entry: ['MeshRenderer', 'MeshRendererAPI', 'MeshRenderers'],},+ {+ id: 'lightmap',+ title: 'Baked lighting',+ titleZh: '烘焙光照',+ source: ['lightmap'],+ tier: 'experimental',+ why: 'half a line: the engine reads a bake and nothing here produces one yet, so the shape of this will follow what a baker turns out to need',+ whyZh: '只做了一半:引擎读得了烘焙图,而这里还产不出一张,所以这套接口的形状要跟着烘焙器最终需要什么走',+ entry: ['unwrapLightmapUV'],+ },{id: 'dragonbones',title: 'DragonBones',diff --git a/tools/releaseNotes.mjs b/tools/releaseNotes.mjsindex 4cc384015..fee5e8195 100644--- a/tools/releaseNotes.mjs+++ b/tools/releaseNotes.mjs@@ -28,6 +28,11 @@ export const NOTES_FLOOR = 'v0.65.0';* the reader recognises anyway.*/export const NOTED = {+ 'feat(render): a model can be unwrapped for the light that will be baked into it':+ { note: 'A model can be given somewhere to receive baked light.' },+ 'feat(import): Generate Lightmap UVs reaches the mesh it decides':+ { note: 'A model can be given somewhere to receive baked light.' },+'feat(render): a mesh can be read through the light baked into it':{ note: 'A mesh can be read through the light that was baked into it.' },'fix(checks): the watcher check survives a loaded machine, and says what it saw':