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(render): a mesh can be read through the light baked into it

esengine122374a74796
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d8c3a8a92..30a7efb7c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,44 @@ published separately; it ships inside the editor.
## [Unreleased]
+### Added
+
+- **A mesh can be read through the light that was baked into it.** Sixteen lights
+ reach one frame; the seventeenth is dropped by brightness, with a warning naming
+ what was refused. That ceiling is not a quality setting — a room with thirty
+ lamps in it cannot be lit in real time at all — and a bake is the way past it:
+ light that never moves is computed once and stored as a texture, so a hundred
+ lamps cost what one costs, and what they cost is a sample.
+
+ A `MeshLightmap` says where an object's bake is: `lightmap` is the atlas, and
+ `scaleOffset` is the rectangle of it this object occupies. The rectangle rides
+ the **per-object** record beside the model matrix, and that is the reason it is
+ a component rather than part of the mesh — the same mesh placed twice is lit
+ twice, differently, and occupies two patches of one atlas.
+
+ It is read through the second UV set, which a model has been carrying since
+ 0.63 and which nothing read: the first UV set overlaps on purpose, and a bake
+ cannot, so `TEXCOORD_1` leaves `meshShaderReads`' exclusion list now that it
+ has a reader. A mesh without one draws exactly as before.
+
+ What the bake MEANS depends on whether the draw also takes real-time light, and
+ the two are worth telling apart: a lit surface adds it as the **indirect** term,
+ so a sun's contribution survives; an unlit one takes it as **all** of its light,
+ which is the case a bake is for — a scene whose lights all went into the atlas
+ pays for none of them. An object with no bake is not darkened by the difference:
+ the rectangle reads as zero, and the shader takes that as "none" rather than as
+ an atlas of black.
+
+ **There is no lightmapper yet** — nothing in the editor produces an atlas. This
+ is the reading side, and it went first on purpose: a bake authored by hand can
+ falsify it, where a baker built first would have nothing to say whether it baked
+ the right thing. Three pixel gates hold it, one claim each — which UV set was
+ read, that the bake adds to real-time light rather than replacing it, and that
+ one mesh drawn twice reads two different halves of one atlas.
+
+ Skinned meshes take no bake: bones move a character, and a bake cannot hold one
+ still long enough to light it.
+
## [0.66.0] - 2026-09-14
### Added
diff --git a/bench/residency/heavy.mjs b/bench/residency/heavy.mjs
index 284b5e786..1a03e2ca5 100755
--- a/bench/residency/heavy.mjs
+++ b/bench/residency/heavy.mjs
@@ -259,17 +259,17 @@ function main() {
+ ` — ${ready.compiles} compile(s) of ${ready.uniqueKeys} unique key(s)`
+ ` over ${ready.asks} ask(s) for ${ready.entities} renderable(s);`
+ ` ${ready.materialCompiles} material compile(s) of ${ready.materialAsks} ask(s)`
- + ` keys ${keySet(ready)}`);
+ + ` keys ${keySetText(ready)}`);
}
const both = prewarmed.get(arm);
if (both?.has('document') && both.has('entities')) {
const doc = both.get('document');
const live = both.get('entities');
- const same = doc.keysLo === live.keysLo && doc.keysHi === live.keysHi;
+ const same = sameKeys(doc, live);
failedTotal += same ? 0 : 1;
console.log(`\n ${same ? '✓' : '✗'} what a PREPARED cell knows it will need equals`
+ ` what its published entities ask for`
- + ` — ${keySet(doc)} from the document, ${keySet(live)} from the world`);
+ + ` — ${keySetText(doc)} from the document, ${keySetText(live)} from the world`);
const materials = doc.materialAsks === live.materialAsks;
failedTotal += materials ? 0 : 1;
console.log(` ${materials ? '✓' : '✗'} and the material-owned path is enumerated the`
@@ -759,15 +759,22 @@ function realization(window, arrival) {
}
}
-/** The variant keys a prewarm derived, as a set a reader can compare by eye. */
+const KEY_WORDS = ['keysLo', 'keysHi', 'keysLo2', 'keysHi2'];
+/** The variant keys a prewarm derived, as a set a reader can compare by eye. A
+ * bit per mesh variant, over as many words as the engine's variant space needs:
+ * reading only the first two would call two answers equal on the strength of
+ * the half of them that happens to be read. */
function keySet(r) {
const keys = [];
- for (let i = 0; i < 32; i++) {
- if (r.keysLo & (1 << i)) keys.push(i);
- if (r.keysHi & (1 << i)) keys.push(i + 32);
- }
- return `{${keys.join(', ')}}`;
+ KEY_WORDS.forEach((word, w) => {
+ for (let i = 0; i < 32; i++) if (r[word] & (1 << i)) keys.push(w * 32 + i);
+ });
+ return keys;
}
+/** Whether two prewarms need the same set — every word, for the reason above. */
+const sameKeys = (a, b) => KEY_WORDS.every((word) => a[word] === b[word]);
+/** Rendered for a log line. */
+const keySetText = (r) => `{${keySet(r).join(', ')}}`;
/** What one frame cost, by the domain that owns each system. */
function byDomain(frame) {
diff --git a/bench/residency/readiness.mjs b/bench/residency/readiness.mjs
index ffdc05085..fd808bd71 100644
--- a/bench/residency/readiness.mjs
+++ b/bench/residency/readiness.mjs
@@ -153,14 +153,21 @@ function drive(name, options) {
const digestOf = (r) => `${r.digestHi.toString(16)}${r.digestLo.toString(16).padStart(8, '0')}`;
-const keySet = (r) => {
+const KEY_WORDS = ['keysLo', 'keysHi', 'keysLo2', 'keysHi2'];
+/** The variant keys a prewarm derived, as a set a reader can compare by eye. A
+ * bit per mesh variant, over as many words as the engine's variant space needs:
+ * reading only the first two would call two answers equal on the strength of
+ * the half of them that happens to be read. */
+function keySet(r) {
const keys = [];
- for (let i = 0; i < 32; i++) {
- if (r.keysLo & (1 << i)) keys.push(i);
- if (r.keysHi & (1 << i)) keys.push(i + 32);
- }
+ KEY_WORDS.forEach((word, w) => {
+ for (let i = 0; i < 32; i++) if (r[word] & (1 << i)) keys.push(w * 32 + i);
+ });
return keys;
-};
+}
+/** Whether two prewarms need the same set — every word, for the reason above. */
+const sameKeys = (a, b) => KEY_WORDS.every((word) => a[word] === b[word]);
+
function main() {
if (!existsSync(SAMPLE)) {
@@ -237,7 +244,7 @@ function main() {
const plain = runs.get('plain').get('entities');
const shaded = runs.get('material').get('entities');
console.log('');
- check(plain.keysLo === shaded.keysLo && plain.keysHi === shaded.keysHi,
+ check(sameKeys(plain, shaded),
'the plain and material worlds need the SAME stock variants',
`{${keySet(plain).join(', ')}} against {${keySet(shaded).join(', ')}}`);
check(plain.materialAsks === 0 && shaded.materialAsks > 0,
diff --git a/desktop b/desktop
index 651e0ea27..19d869ebe 160000
--- a/desktop
+++ b/desktop
@@ -1 +1 @@
-Subproject commit 651e0ea271b8e5fe0243d0bbacabfadf8c9dc479
+Subproject commit 19d869ebe09cb3cc26e21bbda42c79ef567f34f7
diff --git a/docs/astro/src/content/docs/graphics/lighting.mdx b/docs/astro/src/content/docs/graphics/lighting.mdx
index a57a236a0..c9fa7ee05 100644
--- a/docs/astro/src/content/docs/graphics/lighting.mdx
+++ b/docs/astro/src/content/docs/graphics/lighting.mdx
@@ -347,6 +347,56 @@ saying something about its art direction; the fix is to turn shadows off (`shado
of 0 on a sun, or a smaller `radius` that takes a light out of view) on the ones whose
shadows nobody looks at.
+## Baked light
+
+Sixteen lights reach one frame. The seventeenth is dropped — by brightness, with a
+warning naming what was refused — and that ceiling is not a quality setting: a room
+with thirty lamps in it cannot be lit in real time here at all.
+
+A **bake** is the way past it. Light that never moves is computed once, offline, and
+stored as a texture; at run time the surface reads a texel instead of summing lights.
+A hundred lamps then cost exactly what one costs, and what they cost is a sample.
+
+The engine reads a bake through two things, and you give it both:
+
+- **A mesh with a second UV set.** The first UV set is how the art is wrapped, and it
+ overlaps on purpose — two arms share the texels of one arm. A bake cannot: each
+ surface needs its own patch, or one wall's light lands on another. Both importers
+ carry the channel through when a model has one (`TEXCOORD_1` in glTF, a second UV
+ layer in FBX), so this is a question for whoever authored the model.
+- **A `MeshLightmap` component.** `lightmap` is the atlas, and `scaleOffset` is the
+ rectangle of it this object occupies — `xy` scales the second UV set, `zw` offsets
+ it. `(1, 1, 0, 0)` reads the whole texture, which is what a bake of a single object
+ produces. The rectangle is per entity and not per mesh, because the same mesh placed
+ twice is lit twice, differently.
+
+What the bake MEANS depends on the renderer's `lit` flag, and the two are worth
+telling apart:
+
+| `lit` | With a `MeshLightmap` | Without |
+| --- | --- | --- |
+| on | Real-time light **plus** the bake, which carries the indirect term | Real-time light only |
+| off | The bake is **all** of the surface's light | Unlit — the texture as authored |
+
+The second row is the one a bake is for. A scene whose lights all went into the atlas
+draws with `lit` off and pays for no lights at all — on a phone, that is the difference
+between a lit room and a slideshow.
+
+An object whose geometry carries the channel but has no `MeshLightmap` draws exactly as
+it did before: the rectangle is zero, and the shader reads that as "no bake" rather than
+as an atlas of black.
+
+:::caution
+Estella has no lightmapper yet — nothing in the editor *produces* an atlas. The reading
+side is what shipped here, so a bake authored elsewhere (Blender's Cycles, a Substance
+bake, any renderer that writes a lightmap and its UV layout) can be brought in and read
+today. Baking from inside the editor is the next piece.
+:::
+
+Skinned meshes take no bake: bones move a character, and a bake cannot hold one still
+long enough to light it. A character in a baked room is lit in real time, by the lights
+that stayed behind.
+
## Linear color space
By default the engine renders **gamma-space** — colors blend as-authored, the way 2D
diff --git a/docs/astro/src/content/docs/zh-cn/graphics/lighting.mdx b/docs/astro/src/content/docs/zh-cn/graphics/lighting.mdx
index d819990f6..c1be44a46 100644
--- a/docs/astro/src/content/docs/zh-cn/graphics/lighting.mdx
+++ b/docs/astro/src/content/docs/zh-cn/graphics/lighting.mdx
@@ -270,6 +270,45 @@ cmds.spawn()
处理办法是把没人会看那道影子的光关掉阴影(太阳的 `shadowDistance` 设 0,或者用更小的 `radius`
让某个光离开视野)。
+## 烘焙光照
+
+一帧最多 16 盏灯。第 17 盏会被丢掉——按亮度取舍,并打出一条说明丢了谁的警告——这个天花板不是画质
+选项:一个摆了三十盏灯的房间,在这里根本无法实时点亮。
+
+**烘焙**是绕过它的办法。不会移动的光离线算一次,存成一张纹理;运行时表面读一个纹素,而不是把所有光
+加起来。于是一百盏灯的代价正好等于一盏,而这个代价是一次采样。
+
+引擎通过两样东西读一张烘焙图,两样都要你给:
+
+- **带第二套 UV 的网格。** 第一套 UV 是美术的包裹方式,它**故意**重叠——两条手臂共用一条手臂的
+ 纹素。烘焙不能这样:每个面都需要自己的一块,否则一面墙的光会落到另一面上。两个导入前端在模型带这
+ 条通道时都会把它带过来(glTF 的 `TEXCOORD_1`、FBX 的第二个 UV 层),所以这是问模型作者的问题。
+- **一个 `MeshLightmap` 组件。** `lightmap` 是图集,`scaleOffset` 是这个对象在图集里占的矩形——
+ `xy` 缩放第二套 UV,`zw` 偏移它。`(1, 1, 0, 0)` 读整张纹理,这正是单个对象烘焙出来的样子。矩形
+ 是**逐实体**而不是逐网格的,因为同一个网格摆两次,被照亮两次,而且照法不同。
+
+烘焙图**意味着什么**取决于渲染器的 `lit` 开关,这两种情形值得分开看:
+
+| `lit` | 有 `MeshLightmap` | 没有 |
+| --- | --- | --- |
+| 开 | 实时光**加上**烘焙图,后者承载间接光那一项 | 只有实时光 |
+| 关 | 烘焙图就是这个表面光照的**全部** | 不受光——纹理按作者所写 |
+
+第二行才是烘焙存在的理由。一个把所有灯都烘进图集的场景,`lit` 关着画,一盏灯的钱都不用付——在手机
+上,这是「一个点亮的房间」和「一张幻灯片」之间的差别。
+
+几何带着这条通道、却没有 `MeshLightmap` 的对象,画出来和以前一模一样:矩形是零,着色器把它读成
+「没有烘焙」,而不是读成一张全黑的图集。
+
+:::caution
+Estella 目前还**没有烘焙器**——编辑器里没有任何东西会*产出*一张图集。这里落地的是读取的那一端,所
+以别处烘出来的图(Blender 的 Cycles、Substance 的烘焙、任何写出 lightmap 与其 UV 布局的渲染器)
+今天就能拿进来读。在编辑器里烘焙是下一块。
+:::
+
+蒙皮网格不吃烘焙:骨骼在动角色,而烘焙抓不住一个动着的角色去照亮它。烘焙好的房间里的角色,由留下来
+的那些实时光点亮。
+
## 线性色彩空间
引擎默认以**伽马空间**渲染——颜色按作者所写直接混合,这是 2D 管线的经典方式。项目可以切换到
diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.ts
index 6181605a1..bfb418f0e 100644
--- a/docs/astro/src/data/componentDocs.ts
+++ b/docs/astro/src/data/componentDocs.ts
@@ -75,6 +75,7 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {
MeshRenderer: { category: 'graphics', summary: 'Geometry drawn as an entity — your own vertices or an imported mesh, with a material and a sorting layer.', doc: 'graphics/drawing', anchor: 'custom-meshes-meshrenderer', anchorZh: '自定义网格meshrenderer' },
MeshSkin: { category: 'graphics', summary: 'The joint entities that deform a MeshRenderer — an imported skin, in the order its bind matrices are in.', doc: 'assets/models', anchor: 'skinning', anchorZh: '蒙皮' },
MeshMorph: { category: 'graphics', summary: 'How far a MeshRenderer is blended towards each of the shapes its mesh carries — one weight per morph target.', doc: 'assets/models', anchor: 'morph-targets', anchorZh: 'morph-target' },
+ MeshLightmap: { category: 'graphics', summary: 'Where a MeshRenderer\'s baked light comes from — the atlas, and the rectangle of it this object occupies.', doc: 'graphics/lighting', anchor: 'baked-light', anchorZh: '烘焙光照' },
StreamedWorld: { category: 'world', summary: 'Declares the scene a streamed world and how big the cook cuts its cells.', doc: 'world/streaming', anchor: 'declaring-a-streamed-world', anchorZh: '声明一个流送世界' },
WorldPersistent: { category: 'world', summary: 'Keeps an entity\'s whole subtree out of the partition — it belongs to the persistent world.', doc: 'world/streaming', anchor: 'declaring-a-streamed-world', anchorZh: '声明一个流送世界' },
WorldStreamingSource: { category: 'world', summary: 'Asks for the places near it to exist; several sources are unioned.', doc: 'world/streaming', anchor: 'asking-for-places-streaming-sources', anchorZh: '请求地方存在流送源' },
diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.json
index 44b407e31..f2210ef90 100644
--- a/docs/astro/src/data/components.generated.json
+++ b/docs/astro/src/data/components.generated.json
@@ -2159,6 +2159,25 @@
}
]
},
+ {
+ "name": "MeshLightmap",
+ "source": "cpp",
+ "fields": [
+ {
+ "key": "lightmap",
+ "type": "Asset<texture>",
+ "default": "none",
+ "doc": "Baked lightmap atlas. Needs a mesh with a second UV set."
+ },
+ {
+ "key": "scaleOffset",
+ "type": "Vec4",
+ "default": "(1, 1, 0, 0)",
+ "doc": "Atlas rectangle: xy scales the second UV set, zw offsets it.",
+ "advanced": true
+ }
+ ]
+ },
{
"name": "MeshMorph",
"source": "cpp",
diff --git a/examples/effects-gallery/assets/materials/dissolve.esshader b/examples/effects-gallery/assets/materials/dissolve.esshader
index 86b8694b9..f1011a579 100644
--- a/examples/effects-gallery/assets/materials/dissolve.esshader
+++ b/examples/effects-gallery/assets/materials/dissolve.esshader
@@ -40,7 +40,7 @@ void main() {
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: 0a687499da49fe50
-// assembled-hash: ba69df3ba2801cfd
+// assembled-hash: 60636c76d066e1af
struct gl_PerVertex {
@builtin(position) gl_Position: vec4<f32>,
gl_PointSize: f32,
@@ -115,7 +115,7 @@ fn vs_main(@location(0) a_position: vec3<f32>, @location(1) a_color: vec4<f32>,
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: 0a687499da49fe50
-// assembled-hash: ba69df3ba2801cfd
+// assembled-hash: 60636c76d066e1af
struct MaterialConstants {
u_progress: f32,
u_edgeColor: vec4<f32>,
diff --git a/examples/effects-gallery/assets/materials/hit-flash.esshader b/examples/effects-gallery/assets/materials/hit-flash.esshader
index 66cd334cd..4d434aa56 100644
--- a/examples/effects-gallery/assets/materials/hit-flash.esshader
+++ b/examples/effects-gallery/assets/materials/hit-flash.esshader
@@ -25,7 +25,7 @@ void main() {
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: 674537b45fb865fb
-// assembled-hash: 3383afad4aba8b8c
+// assembled-hash: 72ca189990dafa80
struct gl_PerVertex {
@builtin(position) gl_Position: vec4<f32>,
gl_PointSize: f32,
@@ -98,7 +98,7 @@ fn vs_main(@location(0) a_position: vec3<f32>, @location(1) a_color: vec4<f32>,
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: 674537b45fb865fb
-// assembled-hash: 3383afad4aba8b8c
+// assembled-hash: 72ca189990dafa80
struct MaterialConstants {
u_flash: f32,
u_flashColor: vec4<f32>,
diff --git a/examples/effects-gallery/assets/materials/outline.esshader b/examples/effects-gallery/assets/materials/outline.esshader
index 121ae0c5d..8f5e71d1a 100644
--- a/examples/effects-gallery/assets/materials/outline.esshader
+++ b/examples/effects-gallery/assets/materials/outline.esshader
@@ -34,7 +34,7 @@ void main() {
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: 7ed4f4686c6bfd8d
-// assembled-hash: 3e8628fe75ffd27f
+// assembled-hash: e924eb284d528261
struct gl_PerVertex {
@builtin(position) gl_Position: vec4<f32>,
gl_PointSize: f32,
@@ -107,7 +107,7 @@ fn vs_main(@location(0) a_position: vec3<f32>, @location(1) a_color: vec4<f32>,
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: 7ed4f4686c6bfd8d
-// assembled-hash: 3e8628fe75ffd27f
+// assembled-hash: e924eb284d528261
struct MaterialConstants {
u_outlineColor: vec4<f32>,
u_outlineWidth: f32,
diff --git a/examples/effects-gallery/assets/materials/pixelate.esshader b/examples/effects-gallery/assets/materials/pixelate.esshader
index 96416a1e0..8a5021c14 100644
--- a/examples/effects-gallery/assets/materials/pixelate.esshader
+++ b/examples/effects-gallery/assets/materials/pixelate.esshader
@@ -23,7 +23,7 @@ void main() {
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: 0c2fb4b31599ec7a
-// assembled-hash: b9060e5c7b6dd67a
+// assembled-hash: 8d6d37a7023e822f
struct gl_PerVertex {
@builtin(position) gl_Position: vec4<f32>,
gl_PointSize: f32,
@@ -95,7 +95,7 @@ fn vs_main(@location(0) a_position: vec3<f32>, @location(1) a_color: vec4<f32>,
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: 0c2fb4b31599ec7a
-// assembled-hash: b9060e5c7b6dd67a
+// assembled-hash: 8d6d37a7023e822f
struct MaterialConstants {
u_pixels: f32,
}
diff --git a/examples/effects-gallery/assets/materials/uv-scroll.esshader b/examples/effects-gallery/assets/materials/uv-scroll.esshader
index ffd267c78..1789680f9 100644
--- a/examples/effects-gallery/assets/materials/uv-scroll.esshader
+++ b/examples/effects-gallery/assets/materials/uv-scroll.esshader
@@ -24,7 +24,7 @@ void main() {
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: 301c5b2b73d966f3
-// assembled-hash: 06c74bea06b6d589
+// assembled-hash: d2039f3013a5d165
struct gl_PerVertex {
@builtin(position) gl_Position: vec4<f32>,
gl_PointSize: f32,
@@ -96,7 +96,7 @@ fn vs_main(@location(0) a_position: vec3<f32>, @location(1) a_color: vec4<f32>,
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: 301c5b2b73d966f3
-// assembled-hash: 06c74bea06b6d589
+// assembled-hash: d2039f3013a5d165
struct TimeConstants {
u_time: vec4<f32>,
u_viewport: vec4<f32>,
diff --git a/fixtures/scenes/depth-layers/opaque.esshader b/fixtures/scenes/depth-layers/opaque.esshader
index 85babee8e..df8e73d64 100644
--- a/fixtures/scenes/depth-layers/opaque.esshader
+++ b/fixtures/scenes/depth-layers/opaque.esshader
@@ -24,7 +24,7 @@ void main() {
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: 930787555114ce9c
-// assembled-hash: be3675ce609a7d41
+// assembled-hash: 4fbd4cec4b7a3eab
struct gl_PerVertex {
@builtin(position) gl_Position: vec4<f32>,
gl_PointSize: f32,
@@ -90,7 +90,7 @@ fn vs_main(@location(0) a_position: vec3<f32>, @location(1) a_color: vec4<f32>,
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: 930787555114ce9c
-// assembled-hash: be3675ce609a7d41
+// assembled-hash: 4fbd4cec4b7a3eab
struct FrameConstants {
u_projection: mat4x4<f32>,
u_camera: vec4<f32>,
diff --git a/fixtures/scenes/lightmap-atlas-share.esscene b/fixtures/scenes/lightmap-atlas-share.esscene
new file mode 100644
index 000000000..0f67052f9
--- /dev/null
+++ b/fixtures/scenes/lightmap-atlas-share.esscene
@@ -0,0 +1,136 @@
+{
+ "version": 4,
+ "name": "LightmapAtlasShare",
+ "entities": [
+ {
+ "id": 0,
+ "name": "Camera",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 10
+ }
+ }
+ },
+ {
+ "type": "Camera",
+ "data": {
+ "projectionType": 1,
+ "orthoSize": 100,
+ "isActive": true,
+ "priority": 0
+ }
+ }
+ ]
+ },
+ {
+ "id": 1,
+ "name": "Left",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": -50,
+ "y": 0,
+ "z": 0
+ },
+ "scale": {
+ "x": 0.5,
+ "y": 0.5,
+ "z": 1
+ }
+ }
+ },
+ {
+ "type": "MeshRenderer",
+ "data": {
+ "color": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ },
+ "layer": 0,
+ "enabled": true,
+ "lit": false,
+ "mesh": "/scenes/lightmap-quad.esmesh"
+ }
+ },
+ {
+ "type": "MeshLightmap",
+ "data": {
+ "lightmap": "@uuid:bbbbbbbb-1111-2222-3333-555555555555",
+ "scaleOffset": {
+ "x": 0.5,
+ "y": 1,
+ "z": 0,
+ "w": 0
+ }
+ }
+ }
+ ]
+ },
+ {
+ "id": 2,
+ "name": "Right",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 50,
+ "y": 0,
+ "z": 0
+ },
+ "scale": {
+ "x": 0.5,
+ "y": 0.5,
+ "z": 1
+ }
+ }
+ },
+ {
+ "type": "MeshRenderer",
+ "data": {
+ "color": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ },
+ "layer": 0,
+ "enabled": true,
+ "lit": false,
+ "mesh": "/scenes/lightmap-quad.esmesh"
+ }
+ },
+ {
+ "type": "MeshLightmap",
+ "data": {
+ "lightmap": "@uuid:bbbbbbbb-1111-2222-3333-555555555555",
+ "scaleOffset": {
+ "x": 0.5,
+ "y": 1,
+ "z": 0.5,
+ "w": 0
+ }
+ }
+ }
+ ]
+ }
+ ]
+}
\ No newline at end of file
diff --git a/fixtures/scenes/lightmap-atlas-share.textures.json b/fixtures/scenes/lightmap-atlas-share.textures.json
new file mode 100644
index 000000000..867ac6dd6
--- /dev/null
+++ b/fixtures/scenes/lightmap-atlas-share.textures.json
@@ -0,0 +1,3 @@
+{
+ "bbbbbbbb-1111-2222-3333-555555555555": "/scenes/lightmap-atlas.png"
+}
\ No newline at end of file
diff --git a/fixtures/scenes/lightmap-atlas.png b/fixtures/scenes/lightmap-atlas.png
new file mode 100644
index 000000000..c80791256
Binary files /dev/null and b/fixtures/scenes/lightmap-atlas.png differ
diff --git a/fixtures/scenes/lightmap-mixed.esscene b/fixtures/scenes/lightmap-mixed.esscene
new file mode 100644
index 000000000..19026eb9f
--- /dev/null
+++ b/fixtures/scenes/lightmap-mixed.esscene
@@ -0,0 +1,161 @@
+{
+ "version": 4,
+ "name": "LightmapMixed",
+ "entities": [
+ {
+ "id": 0,
+ "name": "Camera",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 10
+ }
+ }
+ },
+ {
+ "type": "Camera",
+ "data": {
+ "projectionType": 1,
+ "orthoSize": 100,
+ "isActive": true,
+ "priority": 0
+ }
+ }
+ ]
+ },
+ {
+ "id": 3,
+ "name": "Sun",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 0
+ }
+ }
+ },
+ {
+ "type": "Light",
+ "data": {
+ "type": 1,
+ "color": {
+ "r": 0,
+ "g": 1,
+ "b": 0,
+ "a": 1
+ },
+ "intensity": 1,
+ "direction": {
+ "x": 0,
+ "y": 0
+ },
+ "enabled": true
+ }
+ }
+ ]
+ },
+ {
+ "id": 1,
+ "name": "Baked",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": -50,
+ "y": 0,
+ "z": 0
+ },
+ "scale": {
+ "x": 0.5,
+ "y": 0.5,
+ "z": 1
+ }
+ }
+ },
+ {
+ "type": "MeshRenderer",
+ "data": {
+ "color": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ },
+ "layer": 0,
+ "enabled": true,
+ "lit": true,
+ "mesh": "/scenes/lightmap-quad.esmesh"
+ }
+ },
+ {
+ "type": "MeshLightmap",
+ "data": {
+ "lightmap": "@uuid:bbbbbbbb-1111-2222-3333-555555555555",
+ "scaleOffset": {
+ "x": 1,
+ "y": 1,
+ "z": 0,
+ "w": 0
+ }
+ }
+ }
+ ]
+ },
+ {
+ "id": 2,
+ "name": "Unbaked",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 50,
+ "y": 0,
+ "z": 0
+ },
+ "scale": {
+ "x": 0.5,
+ "y": 0.5,
+ "z": 1
+ }
+ }
+ },
+ {
+ "type": "MeshRenderer",
+ "data": {
+ "color": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ },
+ "layer": 0,
+ "enabled": true,
+ "lit": true,
+ "mesh": "/scenes/lightmap-quad.esmesh"
+ }
+ }
+ ]
+ }
+ ]
+}
\ No newline at end of file
diff --git a/fixtures/scenes/lightmap-mixed.textures.json b/fixtures/scenes/lightmap-mixed.textures.json
new file mode 100644
index 000000000..867ac6dd6
--- /dev/null
+++ b/fixtures/scenes/lightmap-mixed.textures.json
@@ -0,0 +1,3 @@
+{
+ "bbbbbbbb-1111-2222-3333-555555555555": "/scenes/lightmap-atlas.png"
+}
\ No newline at end of file
diff --git a/fixtures/scenes/lightmap-quad.esmesh b/fixtures/scenes/lightmap-quad.esmesh
new file mode 100644
index 000000000..0a9dcd8a0
Binary files /dev/null and b/fixtures/scenes/lightmap-quad.esmesh differ
diff --git a/fixtures/scenes/lightmap-unlit.esscene b/fixtures/scenes/lightmap-unlit.esscene
new file mode 100644
index 000000000..4957b7aab
--- /dev/null
+++ b/fixtures/scenes/lightmap-unlit.esscene
@@ -0,0 +1,80 @@
+{
+ "version": 4,
+ "name": "LightmapUnlit",
+ "entities": [
+ {
+ "id": 0,
+ "name": "Camera",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 10
+ }
+ }
+ },
+ {
+ "type": "Camera",
+ "data": {
+ "projectionType": 1,
+ "orthoSize": 100,
+ "isActive": true,
+ "priority": 0
+ }
+ }
+ ]
+ },
+ {
+ "id": 1,
+ "name": "Baked",
+ "parent": null,
+ "children": [],
+ "visible": true,
+ "components": [
+ {
+ "type": "Transform",
+ "data": {
+ "position": {
+ "x": 0,
+ "y": 0,
+ "z": 0
+ }
+ }
+ },
+ {
+ "type": "MeshRenderer",
+ "data": {
+ "color": {
+ "r": 1,
+ "g": 1,
+ "b": 1,
+ "a": 1
+ },
+ "layer": 0,
+ "enabled": true,
+ "lit": false,
+ "mesh": "/scenes/lightmap-quad.esmesh"
+ }
+ },
+ {
+ "type": "MeshLightmap",
+ "data": {
+ "lightmap": "@uuid:bbbbbbbb-1111-2222-3333-555555555555",
+ "scaleOffset": {
+ "x": 1,
+ "y": 1,
+ "z": 0,
+ "w": 0
+ }
+ }
+ }
+ ]
+ }
+ ]
+}
\ No newline at end of file
diff --git a/fixtures/scenes/lightmap-unlit.textures.json b/fixtures/scenes/lightmap-unlit.textures.json
new file mode 100644
index 000000000..867ac6dd6
--- /dev/null
+++ b/fixtures/scenes/lightmap-unlit.textures.json
@@ -0,0 +1,3 @@
+{
+ "bbbbbbbb-1111-2222-3333-555555555555": "/scenes/lightmap-atlas.png"
+}
\ No newline at end of file
diff --git a/fixtures/scenes/mat-builtin-lit/lit.esshader b/fixtures/scenes/mat-builtin-lit/lit.esshader
index eebe32af6..cb423b9cf 100644
--- a/fixtures/scenes/mat-builtin-lit/lit.esshader
+++ b/fixtures/scenes/mat-builtin-lit/lit.esshader
@@ -27,7 +27,7 @@ void main() {
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: 5330079245724fa2
-// assembled-hash: 5d310bf3f48e5a0d
+// assembled-hash: 1e59361273df4851
struct gl_PerVertex {
@builtin(position) gl_Position: vec4<f32>,
gl_PointSize: f32,
@@ -52,7 +52,7 @@ struct VertexOutput {
@location(0) member: vec4<f32>,
@builtin(position) gl_Position: vec4<f32>,
@location(1) member_1: vec2<f32>,
- @location(4) member_2: vec2<f32>,
+ @location(5) member_2: vec2<f32>,
}
var<private> a_position_1: vec3<f32>;
@@ -108,7 +108,7 @@ fn vs_main(@location(0) a_position: vec3<f32>, @location(1) a_color: vec4<f32>,
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: 5330079245724fa2
-// assembled-hash: 5d310bf3f48e5a0d
+// assembled-hash: 1e59361273df4851
struct FrameConstants {
u_projection: mat4x4<f32>,
u_camera: vec4<f32>,
@@ -1036,7 +1036,7 @@ fn main_1() {
}
@fragment
-fn fs_main(@location(1) v_texCoord: vec2<f32>, @location(0) v_color: vec4<f32>, @location(4) v_worldPos: vec2<f32>) -> @location(0) vec4<f32> {
+fn fs_main(@location(1) v_texCoord: vec2<f32>, @location(0) v_color: vec4<f32>, @location(5) v_worldPos: vec2<f32>) -> @location(0) vec4<f32> {
v_texCoord_1 = v_texCoord;
v_color_1 = v_color;
v_worldPos_1 = v_worldPos;
diff --git a/fixtures/scenes/mat-dissolve/dissolve.esshader b/fixtures/scenes/mat-dissolve/dissolve.esshader
index 86b8694b9..f1011a579 100644
--- a/fixtures/scenes/mat-dissolve/dissolve.esshader
+++ b/fixtures/scenes/mat-dissolve/dissolve.esshader
@@ -40,7 +40,7 @@ void main() {
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: 0a687499da49fe50
-// assembled-hash: ba69df3ba2801cfd
+// assembled-hash: 60636c76d066e1af
struct gl_PerVertex {
@builtin(position) gl_Position: vec4<f32>,
gl_PointSize: f32,
@@ -115,7 +115,7 @@ fn vs_main(@location(0) a_position: vec3<f32>, @location(1) a_color: vec4<f32>,
// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.
// Regenerate after changing the GLSL stages above.
// source-hash: 0a687499da49fe50
-// assembled-hash: ba69df3ba2801cfd
+// assembled-hash: 60636c76d066e1af
struct MaterialConstants {
u_progress: f32,
u_edgeColor: vec4<f32>,
diff --git a/pipeline/src/runtime/gameHost.ts b/pipeline/src/runtime/gameHost.ts
index 3ea607395..feb5a258d 100644
--- a/pipeline/src/runtime/gameHost.ts
+++ b/pipeline/src/runtime/gameHost.ts
@@ -141,7 +141,7 @@ async function boot(): Promise<void> {
if (headless) {
let statsOn = false;
- const PREWARM_WORDS = 13;
+ const PREWARM_WORDS = 15;
const PREPARE_WORDS = 11;
/** Eleven words back from the production readying: whether a claim may be
@@ -165,10 +165,10 @@ async function boot(): Promise<void> {
return {
asks: o[0], compiles: o[1], uniqueKeys: o[2],
materialAsks: o[3], materialCompiles: o[4],
- keysLo: o[5], keysHi: o[6],
- digestLo: o[7], digestHi: o[8],
- programEpoch: o[9] + o[10] * 0x100000000,
- deviceGeneration: o[11] + o[12] * 0x100000000,
+ keysLo: o[5], keysHi: o[6], keysLo2: o[7], keysHi2: o[8],
+ digestLo: o[9], digestHi: o[10],
+ programEpoch: o[11] + o[12] * 0x100000000,
+ deviceGeneration: o[13] + o[14] * 0x100000000,
};
};
diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.md
index 2fdbf7151..4522fed01 100644
--- a/sdk/etc/index.api.md
+++ b/sdk/etc/index.api.md
@@ -5,7 +5,7 @@ Symbols: 114 public · 94 beta · 1720 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
-"7aee1689088373e3"
+"ca7cd852d3bc316f"
```
## ANCHOR_AXES — const @experimental
diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.md
index 4860978dc..6d1ae03b5 100644
--- a/sdk/etc/index.native.api.md
+++ b/sdk/etc/index.native.api.md
@@ -5,7 +5,7 @@ Symbols: 114 public · 99 beta · 1739 experimental · 3 deprecated
## ABI_LAYOUT_HASH — const @experimental
```
-"7aee1689088373e3"
+"ca7cd852d3bc316f"
```
## ANCHOR_AXES — const @experimental
diff --git a/sdk/etc/wasm.api.md b/sdk/etc/wasm.api.md
index 20c90a6bc..76e76f30f 100644
--- a/sdk/etc/wasm.api.md
+++ b/sdk/etc/wasm.api.md
@@ -31,6 +31,7 @@ addInteractable: (entity: Entity, component: Interactable) => void
addLODGroup: (entity: Entity, component: LODGroup) => void
addLight: (entity: Entity, component: Light) => void
addMeshCollider3D: (entity: Entity, component: MeshCollider3D) => void
+addMeshLightmap: (entity: Entity, component: MeshLightmap) => void
addMeshMorph: (entity: Entity, component: MeshMorph) => void
addMeshRenderer: (entity: Entity, component: MeshRenderer) => void
addMeshSkin: (entity: Entity, component: MeshSkin) => void
@@ -78,6 +79,7 @@ getInteractable: (entity: Entity) => Interactable
getLODGroup: (entity: Entity) => LODGroup
getLight: (entity: Entity) => Light
getMeshCollider3D: (entity: Entity) => MeshCollider3D
+getMeshLightmap: (entity: Entity) => MeshLightmap
getMeshMorph: (entity: Entity) => MeshMorph
getMeshRenderer: (entity: Entity) => MeshRenderer
getMeshSkin: (entity: Entity) => MeshSkin
@@ -121,6 +123,7 @@ hasInteractable: (entity: Entity) => boolean
hasLODGroup: (entity: Entity) => boolean
hasLight: (entity: Entity) => boolean
hasMeshCollider3D: (entity: Entity) => boolean
+hasMeshLightmap: (entity: Entity) => boolean
hasMeshMorph: (entity: Entity) => boolean
hasMeshRenderer: (entity: Entity) => boolean
hasMeshSkin: (entity: Entity) => boolean
@@ -165,6 +168,7 @@ removeInteractable: (entity: Entity) => void
removeLODGroup: (entity: Entity) => void
removeLight: (entity: Entity) => void
removeMeshCollider3D: (entity: Entity) => void
+removeMeshLightmap: (entity: Entity) => void
removeMeshMorph: (entity: Entity) => void
removeMeshRenderer: (entity: Entity) => void
removeMeshSkin: (entity: Entity) => void
diff --git a/sdk/src/ecs/bridge/ptrAccessors.generated.ts b/sdk/src/ecs/bridge/ptrAccessors.generated.ts
index 80bcd9e33..aaa08960a 100644
--- a/sdk/src/ecs/bridge/ptrAccessors.generated.ts
+++ b/sdk/src/ecs/bridge/ptrAccessors.generated.ts
@@ -937,6 +937,34 @@ export function createMeshCollider3DData(): MeshCollider3DPtrData {
};
}
+export interface MeshLightmapPtrData {
+ lightmap: number;
+ scaleOffset: Vec4;
+}
+
+export function fillMeshLightmap(
+ f32: Float32Array, u32: Uint32Array, u8: Uint8Array,
+ ptr: number, out: MeshLightmapPtrData,
+): void {
+ out.lightmap = u32[ptr >> 2];
+ const scaleOffset_ = out.scaleOffset; scaleOffset_.x = f32[(ptr + 4) >> 2]; scaleOffset_.y = f32[((ptr + 4) >> 2) + 1]; scaleOffset_.z = f32[((ptr + 4) >> 2) + 2]; scaleOffset_.w = f32[((ptr + 4) >> 2) + 3];
+}
+
+export function writeMeshLightmap(
+ f32: Float32Array, u32: Uint32Array, u8: Uint8Array,
+ ptr: number, data: MeshLightmapPtrData,
+): void {
+ u32[ptr >> 2] = data.lightmap;
+ f32[(ptr + 4) >> 2] = data.scaleOffset.x; f32[((ptr + 4) >> 2) + 1] = data.scaleOffset.y; f32[((ptr + 4) >> 2) + 2] = data.scaleOffset.z; f32[((ptr + 4) >> 2) + 3] = data.scaleOffset.w;
+}
+
+export function createMeshLightmapData(): MeshLightmapPtrData {
+ return {
+ lightmap: 0,
+ scaleOffset: { x: 0, y: 0, z: 0, w: 0 },
+ };
+}
+
export interface MeshRendererPtrData {
texture: number;
normalMap: number;
@@ -2325,6 +2353,7 @@ export const PTR_ACCESSORS: Record<string, PtrAccessor<any>> = {
LODGroup: { fill: fillLODGroup, write: writeLODGroup, create: createLODGroupData },
Light: { fill: fillLight, write: writeLight, create: createLightData },
MeshCollider3D: { fill: fillMeshCollider3D, write: writeMeshCollider3D, create: createMeshCollider3DData },
+ MeshLightmap: { fill: fillMeshLightmap, write: writeMeshLightmap, create: createMeshLightmapData },
MeshRenderer: { fill: fillMeshRenderer, write: writeMeshRenderer, create: createMeshRendererData },
ParticleEmitter: { fill: fillParticleEmitter, write: writeParticleEmitter, create: createParticleEmitterData },
ParticleForceField: { fill: fillParticleForceField, write: writeParticleForceField, create: createParticleForceFieldData },
diff --git a/sdk/src/ecs/component.generated.ts b/sdk/src/ecs/component.generated.ts
index 1fa507137..823cdabdf 100644
--- a/sdk/src/ecs/component.generated.ts
+++ b/sdk/src/ecs/component.generated.ts
@@ -15,7 +15,7 @@ import type { AlignContent, AlignItems, AlignSelf, BodyType, CanvasScaleMode, Cl
* getAbiLayoutHash(); BuiltinBridge.connect() compares them and refuses to
* run on mismatch, because mismatched offsets read the wrong heap bytes.
*/
-export const ABI_LAYOUT_HASH = '7aee1689088373e3';
+export const ABI_LAYOUT_HASH = 'ca7cd852d3bc316f';
/**
* One asset-valued field of a component: which field, and what kind of
@@ -525,6 +525,20 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
layer: { min: 0, max: 15, advanced: true },
},
},
+ MeshLightmap: {
+ defaults: {
+ lightmap: 0,
+ scaleOffset: { x: 1, y: 1, z: 0, w: 0 },
+ },
+ assetFields: [{ field: 'lightmap', type: 'texture' as AssetFieldType }],
+ entityFields: [],
+ colorFields: [],
+ animatableFields: [],
+ fields: {
+ lightmap: { tooltip: "Baked lightmap atlas. Needs a mesh with a second UV set." },
+ scaleOffset: { tooltip: "Atlas rectangle: xy scales the second UV set, zw offsets it.", advanced: true },
+ },
+ },
MeshMorph: {
defaults: {
weights: [],
@@ -1398,6 +1412,11 @@ export interface MeshCollider3DData {
enabled: boolean;
}
+export interface MeshLightmapData {
+ lightmap: number;
+ scaleOffset: Vec4;
+}
+
export interface MeshMorphData {
weights: number[];
}
diff --git a/sdk/src/wasm/ptrLayouts.generated.ts b/sdk/src/wasm/ptrLayouts.generated.ts
index e4326432a..719fbbb31 100644
--- a/sdk/src/wasm/ptrLayouts.generated.ts
+++ b/sdk/src/wasm/ptrLayouts.generated.ts
@@ -259,6 +259,13 @@ export const PTR_LAYOUTS: Record<string, PtrLayout> = {
{ name: 'enabled', type: 'bool', offset: 16 },
],
},
+ MeshLightmap: {
+ ptrFn: 'getMeshLightmapPtr',
+ fields: [
+ { name: 'lightmap', type: 'u32', offset: 0 },
+ { name: 'scaleOffset', type: 'vec4', offset: 4 },
+ ],
+ },
MeshRenderer: {
ptrFn: 'getMeshRendererPtr',
fields: [
diff --git a/sdk/src/wasm/wasm.generated.ts b/sdk/src/wasm/wasm.generated.ts
index 395001fa3..4bf908ac6 100644
--- a/sdk/src/wasm/wasm.generated.ts
+++ b/sdk/src/wasm/wasm.generated.ts
@@ -579,6 +579,11 @@ export interface MeshCollider3D {
enabled: boolean;
}
+export interface MeshLightmap {
+ lightmap: number;
+ scaleOffset: Vec4;
+}
+
export interface MeshMorph {
weights: VectorFloat;
}
@@ -972,6 +977,10 @@ export interface Registry {
getMeshCollider3D(entity: Entity): MeshCollider3D;
addMeshCollider3D(entity: Entity, component: MeshCollider3D): void;
removeMeshCollider3D(entity: Entity): void;
+ hasMeshLightmap(entity: Entity): boolean;
+ getMeshLightmap(entity: Entity): MeshLightmap;
+ addMeshLightmap(entity: Entity, component: MeshLightmap): void;
+ removeMeshLightmap(entity: Entity): void;
hasMeshMorph(entity: Entity): boolean;
getMeshMorph(entity: Entity): MeshMorph;
addMeshMorph(entity: Entity, component: MeshMorph): void;
@@ -1104,6 +1113,7 @@ export interface ESEngineModule {
LODGroup: new () => LODGroup;
Light: new () => Light;
MeshCollider3D: new () => MeshCollider3D;
+ MeshLightmap: new () => MeshLightmap;
MeshMorph: new () => MeshMorph;
MeshRenderer: new () => MeshRenderer;
MeshSkin: new () => MeshSkin;
diff --git a/src/esengine/aot/AotComponents.generated.cpp b/src/esengine/aot/AotComponents.generated.cpp
index 4424b8a9b..fefb50fee 100644
--- a/src/esengine/aot/AotComponents.generated.cpp
+++ b/src/esengine/aot/AotComponents.generated.cpp
@@ -152,6 +152,11 @@ ComponentAt engineComponentAt(ecs::Registry& registry, const char* name) {
return registry.tryGet<esengine::ecs::MeshCollider3D>(Entity::fromRaw(raw));
};
}
+ if (std::strcmp(name, "MeshLightmap") == 0) {
+ return [&registry](std::uint32_t raw) -> void* {
+ return registry.tryGet<esengine::ecs::MeshLightmap>(Entity::fromRaw(raw));
+ };
+ }
if (std::strcmp(name, "MeshMorph") == 0) {
return [&registry](std::uint32_t raw) -> void* {
return registry.tryGet<esengine::ecs::MeshMorph>(Entity::fromRaw(raw));
@@ -371,6 +376,11 @@ CandidatesOf engineComponentCandidates(ecs::Registry& registry, const char* name
return denseAsIds(registry.entitiesWith<esengine::ecs::MeshCollider3D>());
};
}
+ if (std::strcmp(name, "MeshLightmap") == 0) {
+ return [&registry]() -> Candidates {
+ return denseAsIds(registry.entitiesWith<esengine::ecs::MeshLightmap>());
+ };
+ }
if (std::strcmp(name, "MeshMorph") == 0) {
return [&registry]() -> Candidates {
return denseAsIds(registry.entitiesWith<esengine::ecs::MeshMorph>());
@@ -518,6 +528,7 @@ bool isEngineComponent(const char* name) {
if (std::strcmp(name, "LODGroup") == 0) return true;
if (std::strcmp(name, "Light") == 0) return true;
if (std::strcmp(name, "MeshCollider3D") == 0) return true;
+ if (std::strcmp(name, "MeshLightmap") == 0) return true;
if (std::strcmp(name, "MeshMorph") == 0) return true;
if (std::strcmp(name, "MeshRenderer") == 0) return true;
if (std::strcmp(name, "MeshSkin") == 0) return true;
diff --git a/src/esengine/aot/EngineDigest.generated.h b/src/esengine/aot/EngineDigest.generated.h
index 9293d59f8..ae4a0f873 100644
--- a/src/esengine/aot/EngineDigest.generated.h
+++ b/src/esengine/aot/EngineDigest.generated.h
@@ -6,7 +6,7 @@
/* One per address width, because the width is IN the digest: a host that
took the other one would refuse every module built for it. */
-#define ES_ENGINE_ABI_DIGEST_32 0xfddcefb604178b7fULL
-#define ES_ENGINE_ABI_DIGEST_64 0xcfe06bb8128f6f6bULL
+#define ES_ENGINE_ABI_DIGEST_32 0x5b011e67b82556a7ULL
+#define ES_ENGINE_ABI_DIGEST_64 0xb6ad0af24d9719e3ULL
#define ES_ENGINE_ABI_DIGEST \
(sizeof(es_addr_t) == 8 ? ES_ENGINE_ABI_DIGEST_64 : ES_ENGINE_ABI_DIGEST_32)
diff --git a/src/esengine/bindings/EditorAPI.generated.cpp b/src/esengine/bindings/EditorAPI.generated.cpp
index e72745a4b..b244ed71b 100644
--- a/src/esengine/bindings/EditorAPI.generated.cpp
+++ b/src/esengine/bindings/EditorAPI.generated.cpp
@@ -2,10 +2,10 @@
* @file EditorAPI.generated.cpp
* @brief Auto-generated editor API with string-dispatched component access
* @details Generated by EHT - DO NOT EDIT
- * @schema_hash 6b07b247cfa8569a
+ * @schema_hash 8de736341610664c
*/
-#define ES_EDITOR_API_SCHEMA_HASH "6b07b247cfa8569a"
+#define ES_EDITOR_API_SCHEMA_HASH "8de736341610664c"
#include <emscripten/bind.h>
#include <string>
@@ -82,6 +82,7 @@ std::vector<std::string> editor_getComponentNames() {
"LODGroup",
"Light",
"MeshCollider3D",
+ "MeshLightmap",
"MeshMorph",
"MeshRenderer",
"MeshSkin",
@@ -356,6 +357,14 @@ std::string editor_getComponentSchema(const std::string& name) {
{"key":"layer","type":"int","group":"MeshCollider3D"},
{"key":"enabled","type":"bool","group":"MeshCollider3D"}
])JSON";
+ } else if (name == "MeshLightmap") {
+ return R"JSON([
+ {"key":"lightmap","type":"asset","group":"MeshLightmap"},
+ {"key":"scaleOffset.x","type":"float","group":"MeshLightmap"},
+ {"key":"scaleOffset.y","type":"float","group":"MeshLightmap"},
+ {"key":"scaleOffset.z","type":"float","group":"MeshLightmap"},
+ {"key":"scaleOffset.w","type":"float","group":"MeshLightmap"}
+ ])JSON";
} else if (name == "MeshMorph") {
return R"JSON([
])JSON";
@@ -810,6 +819,9 @@ bool editor_addComponent(Registry& reg, u32 e, const std::string& name) {
} else if (name == "MeshCollider3D") {
if (!reg.has<esengine::ecs::MeshCollider3D>(entity)) reg.emplace<esengine::ecs::MeshCollider3D>(entity);
return true;
+ } else if (name == "MeshLightmap") {
+ if (!reg.has<esengine::ecs::MeshLightmap>(entity)) reg.emplace<esengine::ecs::MeshLightmap>(entity);
+ return true;
} else if (name == "MeshMorph") {
if (!reg.has<esengine::ecs::MeshMorph>(entity)) reg.emplace<esengine::ecs::MeshMorph>(entity);
return true;
@@ -931,6 +943,8 @@ bool editor_removeComponent(Registry& reg, u32 e, const std::string& name) {
if (reg.has<esengine::ecs::Light>(entity)) { reg.remove<esengine::ecs::Light>(entity); return true; }
} else if (name == "MeshCollider3D") {
if (reg.has<esengine::ecs::MeshCollider3D>(entity)) { reg.remove<esengine::ecs::MeshCollider3D>(entity); return true; }
+ } else if (name == "MeshLightmap") {
+ if (reg.has<esengine::ecs::MeshLightmap>(entity)) { reg.remove<esengine::ecs::MeshLightmap>(entity); return true; }
} else if (name == "MeshMorph") {
if (reg.has<esengine::ecs::MeshMorph>(entity)) { reg.remove<esengine::ecs::MeshMorph>(entity); return true; }
} else if (name == "MeshRenderer") {
@@ -1006,6 +1020,7 @@ bool editor_hasComponent(Registry& reg, u32 e, const std::string& name) {
if (name == "LODGroup") return reg.has<esengine::ecs::LODGroup>(entity);
if (name == "Light") return reg.has<esengine::ecs::Light>(entity);
if (name == "MeshCollider3D") return reg.has<esengine::ecs::MeshCollider3D>(entity);
+ if (name == "MeshLightmap") return reg.has<esengine::ecs::MeshLightmap>(entity);
if (name == "MeshMorph") return reg.has<esengine::ecs::MeshMorph>(entity);
if (name == "MeshRenderer") return reg.has<esengine::ecs::MeshRenderer>(entity);
if (name == "MeshSkin") return reg.has<esengine::ecs::MeshSkin>(entity);
@@ -1058,6 +1073,7 @@ std::vector<std::string> editor_getComponents(Registry& reg, u32 e) {
if (reg.has<esengine::ecs::LODGroup>(entity)) result.push_back("LODGroup");
if (reg.has<esengine::ecs::Light>(entity)) result.push_back("Light");
if (reg.has<esengine::ecs::MeshCollider3D>(entity)) result.push_back("MeshCollider3D");
+ if (reg.has<esengine::ecs::MeshLightmap>(entity)) result.push_back("MeshLightmap");
if (reg.has<esengine::ecs::MeshMorph>(entity)) result.push_back("MeshMorph");
if (reg.has<esengine::ecs::MeshRenderer>(entity)) result.push_back("MeshRenderer");
if (reg.has<esengine::ecs::MeshSkin>(entity)) result.push_back("MeshSkin");
@@ -1284,6 +1300,15 @@ bool editor_setFloat(Registry& reg, u32 e, const std::string& comp, const std::s
else if (field == "restitution") { c.restitution = value; }
else { return false; }
return true;
+ } else if (comp == "MeshLightmap") {
+ if (!reg.has<esengine::ecs::MeshLightmap>(entity)) return false;
+ auto& c = reg.get<esengine::ecs::MeshLightmap>(entity);
+ if (field == "scaleOffset.x") { c.scaleOffset.x = value; }
+ else if (field == "scaleOffset.y") { c.scaleOffset.y = value; }
+ else if (field == "scaleOffset.z") { c.scaleOffset.z = value; }
+ else if (field == "scaleOffset.w") { c.scaleOffset.w = value; }
+ else { return false; }
+ return true;
} else if (comp == "MeshRenderer") {
if (!reg.has<esengine::ecs::MeshRenderer>(entity)) return false;
auto& c = reg.get<esengine::ecs::MeshRenderer>(entity);
@@ -1766,6 +1791,13 @@ f32 editor_getFloat(Registry& reg, u32 e, const std::string& comp, const std::st
const auto& c = reg.get<esengine::ecs::MeshCollider3D>(entity);
if (field == "friction") { return c.friction; }
else if (field == "restitution") { return c.restitution; }
+ } else if (comp == "MeshLightmap") {
+ if (!reg.has<esengine::ecs::MeshLightmap>(entity)) return 0.0f;
+ const auto& c = reg.get<esengine::ecs::MeshLightmap>(entity);
+ if (field == "scaleOffset.x") { return c.scaleOffset.x; }
+ else if (field == "scaleOffset.y") { return c.scaleOffset.y; }
+ else if (field == "scaleOffset.z") { return c.scaleOffset.z; }
+ else if (field == "scaleOffset.w") { return c.scaleOffset.w; }
} else if (comp == "MeshRenderer") {
if (!reg.has<esengine::ecs::MeshRenderer>(entity)) return 0.0f;
const auto& c = reg.get<esengine::ecs::MeshRenderer>(entity);
@@ -2132,6 +2164,12 @@ bool editor_setInt(Registry& reg, u32 e, const std::string& comp, const std::str
else if (field == "layer") { c.layer = static_cast<u32>(value); }
else { return false; }
return true;
+ } else if (comp == "MeshLightmap") {
+ if (!reg.has<esengine::ecs::MeshLightmap>(entity)) return false;
+ auto& c = reg.get<esengine::ecs::MeshLightmap>(entity);
+ if (field == "lightmap") { c.lightmap = resource::TextureHandle(static_cast<u32>(value)); }
+ else { return false; }
+ return true;
} else if (comp == "MeshRenderer") {
if (!reg.has<esengine::ecs::MeshRenderer>(entity)) return false;
auto& c = reg.get<esengine::ecs::MeshRenderer>(entity);
@@ -2365,6 +2403,10 @@ i32 editor_getInt(Registry& reg, u32 e, const std::string& comp, const std::stri
const auto& c = reg.get<esengine::ecs::MeshCollider3D>(entity);
if (field == "mesh") { return static_cast<i32>(c.mesh.id()); }
else if (field == "layer") { return static_cast<i32>(c.layer); }
+ } else if (comp == "MeshLightmap") {
+ if (!reg.has<esengine::ecs::MeshLightmap>(entity)) return 0;
+ const auto& c = reg.get<esengine::ecs::MeshLightmap>(entity);
+ if (field == "lightmap") { return static_cast<i32>(c.lightmap.id()); }
} else if (comp == "MeshRenderer") {
if (!reg.has<esengine::ecs::MeshRenderer>(entity)) return 0;
const auto& c = reg.get<esengine::ecs::MeshRenderer>(entity);
diff --git a/src/esengine/bindings/RendererBindings.cpp b/src/esengine/bindings/RendererBindings.cpp
index e552d9bad..607241936 100644
--- a/src/esengine/bindings/RendererBindings.cpp
+++ b/src/esengine/bindings/RendererBindings.cpp
@@ -872,30 +872,33 @@ void engine_prepareMeshPrograms(u32 rowsPtr, u32 count, u32 outPtr) {
}
#ifdef ES_ENABLE_TEST_PROBES
-/** Eleven words: five counts, the 64-bit stock key set, the requirement digest
- * that also covers the material programs, and the epoch the digest was taken
- * under — a digest without its epoch cannot say whether it is still true. */
+/** Fifteen words: five counts, the stock key set (a bit per mesh variant, so two
+ * 64-bit words), the requirement digest that also covers the material programs,
+ * and the epoch the digest was taken under — a digest without its epoch cannot
+ * say whether it is still true. */
static void writePrewarm(u32* out, const RenderPrewarmResult& r) {
out[0] = r.asks;
out[1] = r.compiles;
out[2] = r.uniqueKeys;
out[3] = r.materialAsks;
out[4] = r.materialCompiles;
- out[5] = static_cast<u32>(r.keys & 0xFFFFFFFFull);
- out[6] = static_cast<u32>(r.keys >> 32);
+ for (u32 w = 0; w < 2; ++w) {
+ out[5 + w * 2] = static_cast<u32>(r.keys[w] & 0xFFFFFFFFull);
+ out[6 + w * 2] = static_cast<u32>(r.keys[w] >> 32);
+ }
const u64 digest = r.requirementDigest();
- out[7] = static_cast<u32>(digest & 0xFFFFFFFFull);
- out[8] = static_cast<u32>(digest >> 32);
+ out[9] = static_cast<u32>(digest & 0xFFFFFFFFull);
+ out[10] = static_cast<u32>(digest >> 32);
const auto* rc = ctx().tryGet<RenderContext>();
const u64 epoch = rc ? rc->programEpoch() : 0;
- out[9] = static_cast<u32>(epoch & 0xFFFFFFFFull);
- out[10] = static_cast<u32>(epoch >> 32);
+ out[11] = static_cast<u32>(epoch & 0xFFFFFFFFull);
+ out[12] = static_cast<u32>(epoch >> 32);
// Not a third truth in the stamp: the guard that says the two above were
// read on one device. A generation that moved mid-derivation invalidates the
// whole readying rather than being recorded alongside it.
const u64 generation = g_device ? g_device->deviceGeneration() : 0;
- out[11] = static_cast<u32>(generation & 0xFFFFFFFFull);
- out[12] = static_cast<u32>(generation >> 32);
+ out[13] = static_cast<u32>(generation & 0xFFFFFFFFull);
+ out[14] = static_cast<u32>(generation >> 32);
}
void engine_prewarmMeshVariants(ecs::Registry& registry, u32 entitiesPtr, u32 count, u32 outPtr) {
diff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cpp
index c32bc3e1a..8a24bc5d1 100644
--- a/src/esengine/bindings/WebBindings.generated.cpp
+++ b/src/esengine/bindings/WebBindings.generated.cpp
@@ -684,6 +684,29 @@ MeshCollider3DJS meshcollider3dToJS(const esengine::ecs::MeshCollider3D& c) {
return js;
}
+struct MeshLightmapJS {
+ u32 lightmap;
+ glm::vec4 scaleOffset;
+};
+
+void meshlightmapApplyJS(esengine::ecs::MeshLightmap& c, const MeshLightmapJS& js) {
+ c.lightmap = resource::TextureHandle(js.lightmap);
+ c.scaleOffset = js.scaleOffset;
+}
+
+esengine::ecs::MeshLightmap meshlightmapFromJS(const MeshLightmapJS& js) {
+ esengine::ecs::MeshLightmap c;
+ meshlightmapApplyJS(c, js);
+ return c;
+}
+
+MeshLightmapJS meshlightmapToJS(const esengine::ecs::MeshLightmap& c) {
+ MeshLightmapJS js;
+ js.lightmap = c.lightmap.id();
+ js.scaleOffset = c.scaleOffset;
+ return js;
+}
+
struct MeshRendererJS {
u32 texture;
u32 normalMap;
@@ -1642,6 +1665,10 @@ EMSCRIPTEN_BINDINGS(esengine_components) {
.field("layer", &MeshCollider3DJS::layer)
.field("enabled", &MeshCollider3DJS::enabled);
+ value_object<MeshLightmapJS>("MeshLightmap")
+ .field("lightmap", &MeshLightmapJS::lightmap)
+ .field("scaleOffset", &MeshLightmapJS::scaleOffset);
+
value_object<esengine::ecs::MeshMorph>("MeshMorph")
.field("weights", &esengine::ecs::MeshMorph::weights);
@@ -2357,6 +2384,30 @@ EMSCRIPTEN_BINDINGS(esengine_registry) {
r.remove<esengine::ecs::MeshCollider3D>(entity);
}))
+ // MeshLightmap
+ .function("hasMeshLightmap", optional_override([](Registry& r, u32 e) {
+ return r.has<esengine::ecs::MeshLightmap>(static_cast<Entity>(e));
+ }))
+ .function("getMeshLightmap", optional_override([](Registry& r, u32 e) {
+ auto entity = static_cast<Entity>(e);
+ if (!r.valid(entity) || !r.has<esengine::ecs::MeshLightmap>(entity)) return MeshLightmapJS{};
+ return meshlightmapToJS(r.get<esengine::ecs::MeshLightmap>(entity));
+ }))
+ .function("addMeshLightmap", optional_override([](Registry& r, u32 e, const MeshLightmapJS& js) {
+ auto entity = static_cast<Entity>(e);
+ if (!r.valid(entity)) return;
+ if (auto* existing = r.tryGet<esengine::ecs::MeshLightmap>(entity)) {
+ meshlightmapApplyJS(*existing, js);
+ return;
+ }
+ r.emplaceOrReplace<esengine::ecs::MeshLightmap>(entity, meshlightmapFromJS(js));
+ }))
+ .function("removeMeshLightmap", optional_override([](Registry& r, u32 e) {
+ auto entity = static_cast<Entity>(e);
+ if (!r.valid(entity) || !r.has<esengine::ecs::MeshLightmap>(entity)) return;
+ r.remove<esengine::ecs::MeshLightmap>(entity);
+ }))
+
// MeshMorph
.function("hasMeshMorph", optional_override([](Registry& r, u32 e) {
return r.has<esengine::ecs::MeshMorph>(static_cast<Entity>(e));
@@ -2956,6 +3007,7 @@ emscripten::val esengineGetBuiltinComponentNames() {
arr.set(i++, val(std::string("LODGroup")));
arr.set(i++, val(std::string("Light")));
arr.set(i++, val(std::string("MeshCollider3D")));
+ arr.set(i++, val(std::string("MeshLightmap")));
arr.set(i++, val(std::string("MeshMorph")));
arr.set(i++, val(std::string("MeshRenderer")));
arr.set(i++, val(std::string("MeshSkin")));
@@ -3142,6 +3194,8 @@ static_assert(offsetof(esengine::ecs::MeshCollider3D, friction) == 4, "ABI offse
static_assert(offsetof(esengine::ecs::MeshCollider3D, restitution) == 8, "ABI offset drift: esengine::ecs::MeshCollider3D.restitution (EHT expected 8)");
static_assert(offsetof(esengine::ecs::MeshCollider3D, layer) == 12, "ABI offset drift: esengine::ecs::MeshCollider3D.layer (EHT expected 12)");
static_assert(offsetof(esengine::ecs::MeshCollider3D, enabled) == 16, "ABI offset drift: esengine::ecs::MeshCollider3D.enabled (EHT expected 16)");
+static_assert(offsetof(esengine::ecs::MeshLightmap, lightmap) == 0, "ABI offset drift: esengine::ecs::MeshLightmap.lightmap (EHT expected 0)");
+static_assert(offsetof(esengine::ecs::MeshLightmap, scaleOffset) == 4, "ABI offset drift: esengine::ecs::MeshLightmap.scaleOffset (EHT expected 4)");
static_assert(offsetof(esengine::ecs::MeshRenderer, texture) == 0, "ABI offset drift: esengine::ecs::MeshRenderer.texture (EHT expected 0)");
static_assert(offsetof(esengine::ecs::MeshRenderer, normalMap) == 4, "ABI offset drift: esengine::ecs::MeshRenderer.normalMap (EHT expected 4)");
static_assert(offsetof(esengine::ecs::MeshRenderer, color) == 8, "ABI offset drift: esengine::ecs::MeshRenderer.color (EHT expected 8)");
@@ -3379,7 +3433,7 @@ static_assert(offsetof(esengine::ecs::Velocity, angular) == 12, "ABI offset drif
// ABI Hash -- runtime handshake against the SDK bundle
// =============================================================================
-static const char* kEsAbiLayoutHash = "7aee1689088373e3";
+static const char* kEsAbiLayoutHash = "ca7cd852d3bc316f";
std::string esengineGetAbiLayoutHash() {
return std::string(kEsAbiLayoutHash);
diff --git a/src/esengine/data/shaders/mesh.esshader b/src/esengine/data/shaders/mesh.esshader
index 7ff338934..37a0ceb3a 100644
--- a/src/esengine/data/shaders/mesh.esshader
+++ b/src/esengine/data/shaders/mesh.esshader
@@ -27,6 +27,12 @@
// channel — which is why this rides LIT rather than a vertex attribute.
#pragma feature NORMAL_MAP
+// Baked light: the second UV set a bake is laid out in, and the rectangle of the
+// atlas THIS object occupies. A feature rather than a number in a block — unlike
+// the morph weights below — because a vertex attribute a shader does not declare
+// may not appear in the layout it is drawn through, which WebGPU rejects.
+#pragma feature MESH_LIGHTMAP
+
// The shadow-map pass: the same geometry, from the light, writing depth as colour
// instead of shading. A feature and not a second shader, because what has to be
// identical between the two passes is the VERTEX stage — a skinned occluder must
@@ -49,6 +55,9 @@ layout(location = 3) in vec3 a_normal;
layout(location = 5) in uvec4 a_joints;
layout(location = 6) in vec4 a_weights;
#endif
+#ifdef MESH_LIGHTMAP
+layout(location = 7) in vec2 a_texCoord1;
+#endif
// 8.. and not 3..: a channel's semantic IS its location, so adding normals to a
// mesh must not move the per-object record (see MESH_INSTANCE_FIRST_LOCATION).
@@ -59,6 +68,12 @@ layout(location = 6) in vec4 a_weights;
layout(location = 8) in vec4 a_model0;
layout(location = 9) in vec4 a_model1;
layout(location = 10) in vec4 a_model2;
+#ifdef MESH_LIGHTMAP
+// Appended to the record, so the tint and the normal matrix keep the offsets
+// they had. Never on a skinned draw: bones move a character, and a character is
+// what a bake cannot hold still long enough to light.
+layout(location = 11) in vec4 a_lightmapRect;
+#endif
#endif
layout(location = 12) in vec4 a_instTint;
#if defined(MESH_NORMALS) && !defined(SKINNED)
@@ -111,6 +126,16 @@ void applyMorph(inout vec3 position, inout vec3 normal) {
out vec2 v_texCoord;
out vec4 v_color;
+#ifdef MESH_LIGHTMAP
+// xy = where in the atlas; z = whether this draw has a bake at all.
+//
+// The third component and not a fallback texture, because the two branches below
+// want DIFFERENT values for "no bake": the lit one adds the bake and wants black,
+// the unlit one multiplies by it and wants white. An unbound unit holds one
+// colour, so it can be right for one of them and never for both — and the engine
+// fills an unused unit with white, which is exactly the half that would be wrong.
+out highp vec3 v_lightmap;
+#endif
#ifdef LIT
out highp vec3 v_worldNormal;
// The full position, not just the plane's: a tangent frame is derived from how
@@ -153,6 +178,10 @@ void main() {
gl_Position = u_projection * world;
v_texCoord = a_texCoord;
v_color = a_color * a_instTint;
+#ifdef MESH_LIGHTMAP
+ v_lightmap = vec3(a_texCoord1 * a_lightmapRect.xy + a_lightmapRect.zw,
+ a_lightmapRect.x > 0.0 ? 1.0 : 0.0);
+#endif
#ifdef SHADOW_DEPTH
v_shadowClip = gl_Position;
#endif
@@ -175,6 +204,9 @@ precision mediump float;
in vec2 v_texCoord;
in vec4 v_color;
+#ifdef MESH_LIGHTMAP
+in highp vec3 v_lightmap;
+#endif
#ifdef LIT
in highp vec3 v_worldNormal;
in highp vec3 v_worldPos;
@@ -187,6 +219,9 @@ uniform sampler2D u_texture;
#ifdef NORMAL_MAP
uniform sampler2D u_normalMap;
#endif
+#ifdef MESH_LIGHTMAP
+uniform sampler2D u_lightmap;
+#endif
out vec4 fragColor;
@@ -199,6 +234,9 @@ void main() {
0.0, 1.0)), 1.0);
#else
vec4 base = texture(u_texture, v_texCoord) * v_color;
+#ifdef MESH_LIGHTMAP
+ vec3 baked = texture(u_lightmap, v_lightmap.xy).rgb;
+#endif
#ifdef LIT
highp vec3 N = normalize(v_worldNormal);
#ifdef NORMAL_MAP
@@ -208,12 +246,26 @@ void main() {
// point in space, and xy is not one. Specular stays ON — switching it off is
// not a cheaper PBR, it is a different surface, and a mesh whose material
// says nothing must still be lit the way the same mesh out of a glTF is.
- fragColor = vec4(applyLightingPBR(base.rgb, N, v_worldPos, viewDirection(v_worldPos),
- 0.0, 1.0, 1.0, 1.0), base.a);
+ vec3 shaded = applyLightingPBR(base.rgb, N, v_worldPos, viewDirection(v_worldPos),
+ 0.0, 1.0, 1.0, 1.0);
+#ifdef MESH_LIGHTMAP
+ // The INDIRECT term. A real-time light says what reaches this point straight
+ // from a source, and the bake says what reached it off everything else — so
+ // the two are added, and a surface that has both is not lit twice.
+ shaded += base.rgb * baked * v_lightmap.z;
+#endif
+ fragColor = vec4(shaded, base.a);
+#else
+#ifdef MESH_LIGHTMAP
+ // Unlit AND lightmapped: the bake is the whole of this surface's light, not
+ // an addition to a direct term it has none of. This is the case a bake is
+ // FOR — a scene whose lights all went into the atlas pays for none of them.
+ fragColor = vec4(base.rgb * mix(vec3(1.0), baked, v_lightmap.z), base.a);
#else
fragColor = base;
#endif
#endif
+#endif
}
#pragma end
@@ -250,6 +302,12 @@ struct VSIn {
@location(8) a_model0 : vec4f,
@location(9) a_model1 : vec4f,
@location(10) a_model2 : vec4f,
+#ifdef MESH_LIGHTMAP
+ @location(11) a_lightmapRect : vec4f,
+#endif
+#endif
+#ifdef MESH_LIGHTMAP
+ @location(7) a_texCoord1 : vec2f,
#endif
@location(12) a_instTint : vec4f,
// What the GLSL twin reads as gl_VertexID: a morph delta is addressed by it.
@@ -274,6 +332,9 @@ struct VSOut {
// The clip position, not the depth it divides down to — see the GLSL twin.
@location(4) v_shadowClip : vec4f,
#endif
+#ifdef MESH_LIGHTMAP
+ @location(5) v_lightmap : vec3f,
+#endif
};
@vertex fn vs_main(v : VSIn) -> VSOut {
@@ -314,6 +375,10 @@ struct VSOut {
out.pos = frame.projection * world;
out.v_texCoord = v.a_texCoord;
out.v_color = v.a_color * v.a_instTint;
+#ifdef MESH_LIGHTMAP
+ out.v_lightmap = vec3f(v.a_texCoord1 * v.a_lightmapRect.xy + v.a_lightmapRect.zw,
+ select(0.0, 1.0, v.a_lightmapRect.x > 0.0));
+#endif
#ifdef SHADOW_DEPTH
out.v_shadowClip = out.pos;
#endif
@@ -354,6 +419,11 @@ struct VSOut {
@group(1) @binding(3) var t3 : texture_2d<f32>;
@group(1) @binding(11) var s3 : sampler;
#endif
+#ifdef MESH_LIGHTMAP
+// The baked atlas, on the last slot a draw's own stream can claim.
+@group(1) @binding(5) var t5 : texture_2d<f32>;
+@group(1) @binding(13) var s5 : sampler;
+#endif
// The 2D shadow mask, on the top slot. Unconditional, because the injected
// lighting reads it for every Lit shader rather than behind a feature.
@group(1) @binding(7) var t7 : texture_2d<f32>;
@@ -370,6 +440,9 @@ struct VSOut {
#ifdef SHADOW_DEPTH
@location(4) v_shadowClip : vec4f,
#endif
+#ifdef MESH_LIGHTMAP
+ @location(5) v_lightmap : vec3f,
+#endif
};
@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
@@ -381,6 +454,9 @@ struct VSOut {
0.0, 1.0)), 1.0);
#else
let base = textureSampleLevel(t0, s0, v.v_texCoord, 0.0) * v.v_color;
+#ifdef MESH_LIGHTMAP
+ let baked = textureSampleLevel(t5, s5, v.v_lightmap.xy, 0.0).rgb;
+#endif
#ifdef LIT
var N = normalize(v.v_worldNormal);
#ifdef NORMAL_MAP
@@ -390,11 +466,21 @@ struct VSOut {
// point in space, and xy is not one. Specular stays ON — switching it off is
// not a cheaper PBR, it is a different surface, and a mesh whose material
// says nothing must still be lit the way the same mesh out of a glTF is.
- return vec4f(applyLightingPBR(base.rgb, N, v.v_worldPos, viewDirection(v.v_worldPos),
- 0.0, 1.0, 1.0, 1.0), base.a);
+ var shaded = applyLightingPBR(base.rgb, N, v.v_worldPos, viewDirection(v.v_worldPos),
+ 0.0, 1.0, 1.0, 1.0);
+#ifdef MESH_LIGHTMAP
+ // The INDIRECT term — see the GLSL twin.
+ shaded = shaded + base.rgb * baked * v.v_lightmap.z;
+#endif
+ return vec4f(shaded, base.a);
+#else
+#ifdef MESH_LIGHTMAP
+ // Unlit AND lightmapped: the bake is the whole of this surface's light.
+ return vec4f(base.rgb * mix(vec3f(1.0), baked, vec3f(v.v_lightmap.z)), base.a);
#else
return base;
#endif
#endif
+#endif
}
#pragma end
diff --git a/src/esengine/ecs/components/MeshRenderer.hpp b/src/esengine/ecs/components/MeshRenderer.hpp
index 0a72454b1..7ac7901ab 100644
--- a/src/esengine/ecs/components/MeshRenderer.hpp
+++ b/src/esengine/ecs/components/MeshRenderer.hpp
@@ -165,4 +165,32 @@ struct MeshMorph {
MeshMorph() = default;
};
+// =============================================================================
+// MeshLightmap Component
+// =============================================================================
+
+/**
+ * @brief Where a @ref MeshRenderer's BAKED light comes from: the atlas, and the
+ * rectangle of it this object occupies.
+ *
+ * @details Per ENTITY and not part of the mesh because of the rectangle: one mesh
+ * placed twice is lit twice, in two patches of one atlas. Needs a mesh
+ * carrying TexCoord1 — one without draws as before.
+ */
+ES_COMPONENT()
+struct MeshLightmap {
+ /** @brief The baked atlas. Invalid = this object has no bake, which is not
+ * the same as a black one: it keeps the light it gets in real time. */
+ ES_PROPERTY(asset = texture, tooltip="Baked lightmap atlas. Needs a mesh with a second UV set.")
+ resource::TextureHandle lightmap;
+
+ /** @brief Where in the atlas: xy scales the mesh's second UV, zw offsets it.
+ * (1,1,0,0) reads the whole texture, which is what a bake of a single
+ * object produces. */
+ ES_PROPERTY(advanced, tooltip="Atlas rectangle: xy scales the second UV set, zw offsets it.")
+ glm::vec4 scaleOffset{1.0f, 1.0f, 0.0f, 0.0f};
+
+ MeshLightmap() = default;
+};
+
} // namespace esengine::ecs
diff --git a/src/esengine/renderer/RenderTypePlugin.hpp b/src/esengine/renderer/RenderTypePlugin.hpp
index 3a456f04b..8453e3943 100644
--- a/src/esengine/renderer/RenderTypePlugin.hpp
+++ b/src/esengine/renderer/RenderTypePlugin.hpp
@@ -23,6 +23,7 @@
#include <cmath>
#include <algorithm>
+#include <array>
#include <unordered_set>
#include <vector>
@@ -130,6 +131,10 @@ struct MeshProgramFacts {
bool lit = false;
u32 normalTextureId = 0;
bool skinned = false;
+ /** Whether the GEOMETRY can be read through a bake — it carries the second UV
+ * set, and is not posed by bones. Whether it HAS one is the atlas rectangle
+ * in its record, which is a number rather than a program. */
+ bool lightmapped = false;
u32 materialId = 0;
};
@@ -142,8 +147,18 @@ struct RenderPrewarmResult {
u32 uniqueKeys = 0;
u32 materialAsks = 0;
u32 materialCompiles = 0;
- /** Which keys, not how many: an equality claim needs the set. 64 variants. */
- u64 keys = 0;
+ /** Which keys, not how many: an equality claim needs the set. One bit per
+ * MESH_VARIANTS, so it is two words rather than one. */
+ std::array<u64, MESH_VARIANTS / 64> keys{};
+
+ /** @brief Whether this key is already in the set; adds it if not. */
+ bool addKey(u32 variant) {
+ u64& word = keys[variant / 64];
+ const u64 bit = 1ull << (variant % 64);
+ if (word & bit) return false;
+ word |= bit;
+ return true;
+ }
/** The material programs the content needs, by identity rather than count.
* A material world whose shading changed must not digest the same as the
* one before it, and `materialAsks` alone cannot say that. */
@@ -179,7 +194,7 @@ struct RenderPrewarmResult {
h *= 1099511628211ull;
}
};
- mix(keys);
+ for (u64 word : keys) mix(word);
for (u64 k : sorted) mix(k);
return h;
}
@@ -190,7 +205,7 @@ struct RenderPrewarmResult {
uniqueKeys += other.uniqueKeys;
materialAsks += other.materialAsks;
materialCompiles += other.materialCompiles;
- keys |= other.keys;
+ for (usize w = 0; w < keys.size(); ++w) keys[w] |= other.keys[w];
// A union, so combining two plugins' answers cannot depend on the order
// they ran in — the digest above rests on that.
for (u64 k : other.materialKeys) addMaterialKey(k);
diff --git a/src/esengine/renderer/draw/BatchBuilder.cpp b/src/esengine/renderer/draw/BatchBuilder.cpp
index 9767959fb..2b5cada1b 100644
--- a/src/esengine/renderer/draw/BatchBuilder.cpp
+++ b/src/esengine/renderer/draw/BatchBuilder.cpp
@@ -148,6 +148,14 @@ void pushBatchDraw(DrawList& drawList, const ClipState& clips,
cmd.texture_ids[4] = key.morphTextureId;
cmd.texture_count = 5;
}
+ // The baked atlas, on the last slot below the frame's two masks. A draw whose
+ // geometry can read one but has none binds nothing here: the fill is white,
+ // and its record's rectangle is what says the bake does not apply.
+ if (key.lightmapTextureId != 0 && cmd.texture_count >= 1 && key.layoutId != LayoutId::Batch) {
+ for (u8 slot = cmd.texture_count; slot < 5; ++slot) cmd.texture_ids[slot] = key.textureId;
+ cmd.texture_ids[5] = key.lightmapTextureId;
+ cmd.texture_count = 6;
+ }
cmd.entity = key.entity;
cmd.type = key.type;
cmd.layer = layer;
diff --git a/src/esengine/renderer/draw/BatchBuilder.hpp b/src/esengine/renderer/draw/BatchBuilder.hpp
index e00a7378e..e69a9f771 100644
--- a/src/esengine/renderer/draw/BatchBuilder.hpp
+++ b/src/esengine/renderer/draw/BatchBuilder.hpp
@@ -140,6 +140,10 @@ struct BatchDrawKey {
// (1-based, 0 = none) and the mesh's own delta texture behind it.
u32 morphIndex = 0;
u32 morphTextureId = 0;
+ /// The baked atlas this draw reads, on the last slot a draw's own stream has.
+ /// Part of the key and not only of the command: two objects sharing a mesh but
+ /// baked into different atlases are two draws.
+ u32 lightmapTextureId = 0;
};
/**
diff --git a/src/esengine/renderer/plugins/MeshPlugin.cpp b/src/esengine/renderer/plugins/MeshPlugin.cpp
index 52e595ca0..6d4cb9fd0 100644
--- a/src/esengine/renderer/plugins/MeshPlugin.cpp
+++ b/src/esengine/renderer/plugins/MeshPlugin.cpp
@@ -95,6 +95,7 @@ MeshProgramFacts meshFactsFromDocument(RenderFrameContext& ctx, const MeshDocume
}
}
facts.skinned = resident && skinnedBy(*resident, row.jointCount, warnedBones) > 0;
+ facts.lightmapped = resident && resident->hasLightmapUV;
return facts;
}
@@ -245,9 +246,10 @@ void reportLodAuthoring(const LodLevels& levels, bool& warned) {
}
u32 meshVariant(bool normals, bool lit, bool normalMapped, bool skinned, bool depthOnly,
- bool envMapped) {
+ bool envMapped, bool lightmapped) {
return (normals ? 1u : 0u) | (lit ? 2u : 0u) | (normalMapped ? 4u : 0u)
- | (skinned ? 8u : 0u) | (depthOnly ? 16u : 0u) | (envMapped ? 32u : 0u);
+ | (skinned ? 8u : 0u) | (depthOnly ? 16u : 0u) | (envMapped ? 32u : 0u)
+ | (lightmapped ? 64u : 0u);
}
/**
@@ -264,9 +266,12 @@ struct MeshDrawKeys {
};
u32 meshVariantFrom(const MeshProgramFacts& facts, bool envMapped, bool shadowDepth) {
+ // `lightmapped` survives the shadow pass, unlike the three describing
+ // shading: it declares two vertex attributes, and a layout may not carry one
+ // the program ignores. The depth fragment simply never reads the atlas.
return meshVariant(facts.hasNormals, facts.lit && !shadowDepth,
facts.normalTextureId != 0 && !shadowDepth, facts.skinned, shadowDepth,
- envMapped);
+ envMapped, facts.lightmapped);
}
/** @brief The facts a LIVE entity answers with: its components and its mesh. */
@@ -284,6 +289,7 @@ MeshProgramFacts meshFactsFromEntity(RenderFrameContext& ctx, ecs::Registry& reg
}
}
facts.skinned = resident && skinJointCount(registry, entity, *resident, warnedBones) > 0;
+ facts.lightmapped = resident && resident->hasLightmapUV;
return facts;
}
@@ -331,6 +337,7 @@ u32 MeshPlugin::meshProgram(RenderFrameContext& ctx, u32 variant) {
const bool normals = (variant & 1u) != 0, lit = (variant & 2u) != 0;
const bool normalMapped = (variant & 4u) != 0, skinned = (variant & 8u) != 0;
const bool depthOnly = (variant & 16u) != 0, envMapped = (variant & 32u) != 0;
+ const bool lightmapped = (variant & 64u) != 0;
if (mesh_compiled_[variant]) return mesh_programs_[variant];
mesh_compiled_[variant] = true;
// Counted because the cost of this function is entirely the times it does
@@ -345,6 +352,7 @@ u32 MeshPlugin::meshProgram(RenderFrameContext& ctx, u32 variant) {
if (lit) features.emplace_back("LIT");
if (normalMapped) features.emplace_back("NORMAL_MAP");
if (skinned) features.emplace_back("SKINNED");
+ if (lightmapped) features.emplace_back("MESH_LIGHTMAP");
if (depthOnly) features.emplace_back("SHADOW_DEPTH");
// Resident geometry owns its texture slots, so it is the vertex source that can
// carry a shadow map and a reflection — the batch stream's are a per-vertex
@@ -400,7 +408,7 @@ RenderPrewarmResult MeshPlugin::prewarmFacts(RenderFrameContext& ctx,
if (shadowDepth && (!shadowPasses || !residentGeometry)) continue;
const u32 variant = meshVariantFrom(facts[i], envMapped, shadowDepth);
++out.asks;
- if ((out.keys & (1ull << variant)) == 0) { out.keys |= 1ull << variant; ++out.uniqueKeys; }
+ if (out.addKey(variant)) ++out.uniqueKeys;
if (!mesh_compiled_[variant]) ++out.compiles;
meshProgram(ctx, variant);
}
@@ -650,9 +658,11 @@ void MeshPlugin::collect(RenderCollectContext& collect_ctx) {
const u32 residentShader = meshProgram(ctx, keys.variant);
tick(3);
if (resident->isDrawable() && residentShader != 0) {
- const u32 stride = skinned ? MESH_INSTANCE_STRIDE_SKINNED
- : resident->hasNormals ? MESH_INSTANCE_STRIDE_LIT
- : MESH_INSTANCE_STRIDE;
+ // The shape the mesh was REALIZED in, not a second derivation:
+ // the record is read through that layout, so the fact that built
+ // it must pack it. (It already excludes a skinned mesh.)
+ const bool lightmapped = resident->hasLightmapUV;
+ const u32 stride = meshInstanceStride(skinned, resident->hasNormals, lightmapped);
u32 instOffset = buffers.allocVertices(LayoutId::MeshInstance, stride);
auto* dst = buffers.vertexData(LayoutId::MeshInstance) + instOffset;
u32 tintRGBA = packColor(mesh.color);
@@ -687,6 +697,19 @@ void MeshPlugin::collect(RenderCollectContext& collect_ctx) {
std::memcpy(dst + 52 + row * 12, &nrm[row][0], 12);
}
}
+ if (lightmapped) {
+ // A zero scale where this object has no bake — the shader
+ // reads it as "none" rather than as an atlas of black, which
+ // an unlit surface would wear as darkness it never had.
+ glm::vec4 rect{0.0f};
+ if (const auto* baked = registry.tryGet<ecs::MeshLightmap>(entity)) {
+ if (Texture* atlas = ctx.resources.getTexture(baked->lightmap)) {
+ rect = baked->scaleOffset;
+ key.lightmapTextureId = atlas->getId();
+ }
+ }
+ std::memcpy(dst + meshInstanceLightmapOffset(resident->hasNormals), &rect, 16);
+ }
}
// A material's default program is built for the BATCH vertex
diff --git a/src/esengine/renderer/plugins/MeshPlugin.hpp b/src/esengine/renderer/plugins/MeshPlugin.hpp
index fd33bc06b..9da16db5c 100644
--- a/src/esengine/renderer/plugins/MeshPlugin.hpp
+++ b/src/esengine/renderer/plugins/MeshPlugin.hpp
@@ -42,14 +42,14 @@ private:
u32 last_compiled_variant_ = 0;
std::vector<BatchVertex> scratch_; ///< Reused per mesh; amortizes the transform buffer.
/// Resident-geometry programs, indexed by {has normals, lit, normal-mapped,
- /// skinned, depth-only, environment-mapped}: what the geometry carries and what
- /// the draw asked for are separate questions. Compiled on first use.
- std::array<u32, 64> mesh_programs_{};
- std::array<bool, 64> mesh_compiled_{};
+ /// skinned, depth-only, environment-mapped, lightmapped}: what the geometry
+ /// carries and what the draw asked for are separate. Compiled on first use.
+ std::array<u32, MESH_VARIANTS> mesh_programs_{};
+ std::array<bool, MESH_VARIANTS> mesh_compiled_{};
/// The shader RESOURCES behind those ids, kept because init() runs again
/// after a device rebuild: with no handle to release, each rebuild left a
/// dead shader in the pool and one more program the host never freed.
- std::array<resource::ShaderHandle, 64> mesh_shaders_{};
+ std::array<resource::ShaderHandle, MESH_VARIANTS> mesh_shaders_{};
/// One entity's bone matrices while they are being built; reused per draw.
std::vector<glm::mat4> pose_scratch_;
u32 meshProgram(RenderFrameContext& ctx, u32 variant);
diff --git a/src/esengine/renderer/rhi/GfxEnums.hpp b/src/esengine/renderer/rhi/GfxEnums.hpp
index fb48718c1..97fd893e5 100644
--- a/src/esengine/renderer/rhi/GfxEnums.hpp
+++ b/src/esengine/renderer/rhi/GfxEnums.hpp
@@ -105,6 +105,10 @@ static constexpr u32 MESH_INSTANCE_STRIDE_LIT = 88;
/// skinned mesh's own transform is ignored (glTF says so) because its joints are
/// already placed in the world — and the pose itself is a uniform block.
static constexpr u32 MESH_INSTANCE_STRIDE_SKINNED = 4;
+/// What a lightmapped object APPENDS: the atlas rectangle its second UV set is
+/// read through (xy scale, zw offset). Per object, because the same mesh placed
+/// twice is lit twice and occupies two patches of one atlas.
+static constexpr u32 MESH_INSTANCE_LIGHTMAP_BYTES = 16;
/// Bone matrices one skinned draw may carry. 64 mat4 is 4KB, inside the 16KB a
/// WebGL2 uniform block is guaranteed; a mesh wanting more is drawn static.
static constexpr u32 MESH_MAX_BONES = 64;
@@ -119,12 +123,34 @@ static constexpr u32 MORPH_TEXTURE_WIDTH = 2048;
/// Beyond it the geometry draws unmorphed — a texture the device refuses is a
/// mesh that does not draw at all.
static constexpr u32 MORPH_MAX_TEXELS = MORPH_TEXTURE_WIDTH * MORPH_TEXTURE_WIDTH;
-/// The attributes that record occupies (4 matrix rows + the tint).
-static constexpr u32 MESH_INSTANCE_ATTRIBUTES = 5;
+/// The attributes that record occupies (4 matrix rows + the tint + the atlas
+/// rectangle) — the budget check, so the widest record is the one measured.
+static constexpr u32 MESH_INSTANCE_ATTRIBUTES = 6;
+/// Programs the resident-mesh shader has: one per combination of {normals, lit,
+/// normal-mapped, skinned, depth-only, env-mapped, lightmapped}. Seven bits, not
+/// one: the geometry, the draw, the frame and the pass each answer a different.
+static constexpr u32 MESH_VARIANTS = 128;
/// Where those attributes start. FIXED, not "after the mesh's channels": a mesh
/// that gains normals would otherwise move them, and every mesh shader with it.
static constexpr u32 MESH_INSTANCE_FIRST_LOCATION = 8;
+/**
+ * @brief How many bytes one object's record is, for the shape it is drawn in.
+ * @details One author for a number three places need — the layout, the
+ * allocation and the packer — so a part added to the record cannot
+ * reach two of them and miss the third.
+ */
+constexpr u32 meshInstanceStride(bool skinned, bool hasNormals, bool lightmapped) {
+ if (skinned) return MESH_INSTANCE_STRIDE_SKINNED;
+ return (hasNormals ? MESH_INSTANCE_STRIDE_LIT : MESH_INSTANCE_STRIDE)
+ + (lightmapped ? MESH_INSTANCE_LIGHTMAP_BYTES : 0);
+}
+
+/** @brief Where the atlas rectangle sits: appended, so nothing before it moves. */
+constexpr u32 meshInstanceLightmapOffset(bool hasNormals) {
+ return hasNormals ? MESH_INSTANCE_STRIDE_LIT : MESH_INSTANCE_STRIDE;
+}
+
/**
* @brief What a mesh vertex channel MEANS, and the attribute location it binds to.
* @details One vocabulary for the file format, the layout and the shaders: a
@@ -140,20 +166,21 @@ enum class MeshChannel : u8 {
Tangent = 4,
Joints = 5,
Weights = 6,
- /// A second UV set. Location 7 is the last one before the per-object record
- /// at MESH_INSTANCE_FIRST_LOCATION, which is why that constant is fixed.
+ /// A second UV set — what a bake is read through, laid out so no two of a
+ /// model's surfaces overlap. Location 7 is the last before the per-object
+ /// record at MESH_INSTANCE_FIRST_LOCATION, which is why that is fixed.
TexCoord1 = 7,
};
/**
* @brief Whether the mesh shaders READ a channel, as opposed to the file carrying it.
* @details An attribute nothing reads spends a slot and a fetch per vertex, so a
- * channel kept for its information stays out of the LAYOUT. Binding it
- * anyway was tried on both backends and neither refused: a cost, not a
- * correctness fix. check-mesh-shader-inputs holds this both ways.
+ * channel kept for its information stays out of the LAYOUT. TexCoord1
+ * left this list when a bake gave it a reader.
+ * check-mesh-shader-inputs holds this both ways.
*/
constexpr bool meshShaderReads(MeshChannel c) {
- return c != MeshChannel::Tangent && c != MeshChannel::TexCoord1;
+ return c != MeshChannel::Tangent;
}
/**
diff --git a/src/esengine/renderer/rhi/Shader.cpp b/src/esengine/renderer/rhi/Shader.cpp
index d94a24dd9..41961b19a 100644
--- a/src/esengine/renderer/rhi/Shader.cpp
+++ b/src/esengine/renderer/rhi/Shader.cpp
@@ -272,7 +272,7 @@ bool Shader::compile(const std::string& vertexSrc, const std::string& fragmentSr
// forgot the unit would sample slot 0 silently. GLSL ES 300 has no layout(binding).
if (hasUniform(SHADOW_MAP_SAMPLER) || hasUniform(ENV_MAP_SAMPLER)
|| hasUniform(SHADOW_2D_SAMPLER) || hasUniform(SHAPE_2D_SAMPLER)
- || hasUniform(MORPH_DELTA_SAMPLER)) {
+ || hasUniform(MORPH_DELTA_SAMPLER) || hasUniform(LIGHTMAP_SAMPLER)) {
bind();
if (hasUniform(SHADOW_MAP_SAMPLER)) {
setUniform(SHADOW_MAP_SAMPLER, static_cast<i32>(SHADOW_MAP_TEXTURE_UNIT));
@@ -290,6 +290,9 @@ bool Shader::compile(const std::string& vertexSrc, const std::string& fragmentSr
if (hasUniform(MORPH_DELTA_SAMPLER)) {
setUniform(MORPH_DELTA_SAMPLER, static_cast<i32>(MORPH_DELTA_TEXTURE_UNIT));
}
+ if (hasUniform(LIGHTMAP_SAMPLER)) {
+ setUniform(LIGHTMAP_SAMPLER, static_cast<i32>(LIGHTMAP_TEXTURE_UNIT));
+ }
unbind();
}
diff --git a/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp b/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp
index 57bdb944d..990ea2479 100644
--- a/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp
+++ b/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp
@@ -382,6 +382,12 @@ inline constexpr const char* MESH = R"esshader(#pragma shader "Mesh"
+#pragma feature MESH_LIGHTMAP
+
+
+
+
+
#pragma feature SHADOW_DEPTH
@@ -400,6 +406,9 @@ layout(location = 3) in vec3 a_normal;
layout(location = 5) in uvec4 a_joints;
layout(location = 6) in vec4 a_weights;
#endif
+#ifdef MESH_LIGHTMAP
+layout(location = 7) in vec2 a_texCoord1;
+#endif
@@ -410,6 +419,12 @@ layout(location = 6) in vec4 a_weights;
layout(location = 8) in vec4 a_model0;
layout(location = 9) in vec4 a_model1;
layout(location = 10) in vec4 a_model2;
+#ifdef MESH_LIGHTMAP
+
+
+
+layout(location = 11) in vec4 a_lightmapRect;
+#endif
#endif
layout(location = 12) in vec4 a_instTint;
#if defined(MESH_NORMALS) && !defined(SKINNED)
@@ -462,6 +477,16 @@ void applyMorph(inout vec3 position, inout vec3 normal) {
out vec2 v_texCoord;
out vec4 v_color;
+#ifdef MESH_LIGHTMAP
+
+
+
+
+
+
+
+out highp vec3 v_lightmap;
+#endif
#ifdef LIT
out highp vec3 v_worldNormal;
@@ -504,6 +529,10 @@ void main() {
gl_Position = u_projection * world;
v_texCoord = a_texCoord;
v_color = a_color * a_instTint;
+#ifdef MESH_LIGHTMAP
+ v_lightmap = vec3(a_texCoord1 * a_lightmapRect.xy + a_lightmapRect.zw,
+ a_lightmapRect.x > 0.0 ? 1.0 : 0.0);
+#endif
#ifdef SHADOW_DEPTH
v_shadowClip = gl_Position;
#endif
@@ -526,6 +555,9 @@ precision mediump float;
in vec2 v_texCoord;
in vec4 v_color;
+#ifdef MESH_LIGHTMAP
+in highp vec3 v_lightmap;
+#endif
#ifdef LIT
in highp vec3 v_worldNormal;
in highp vec3 v_worldPos;
@@ -538,6 +570,9 @@ uniform sampler2D u_texture;
#ifdef NORMAL_MAP
uniform sampler2D u_normalMap;
#endif
+#ifdef MESH_LIGHTMAP
+uniform sampler2D u_lightmap;
+#endif
out vec4 fragColor;
@@ -550,6 +585,9 @@ void main() {
0.0, 1.0)), 1.0);
#else
vec4 base = texture(u_texture, v_texCoord) * v_color;
+#ifdef MESH_LIGHTMAP
+ vec3 baked = texture(u_lightmap, v_lightmap.xy).rgb;
+#endif
#ifdef LIT
highp vec3 N = normalize(v_worldNormal);
#ifdef NORMAL_MAP
@@ -559,12 +597,26 @@ void main() {
- fragColor = vec4(applyLightingPBR(base.rgb, N, v_worldPos, viewDirection(v_worldPos),
- 0.0, 1.0, 1.0, 1.0), base.a);
+ vec3 shaded = applyLightingPBR(base.rgb, N, v_worldPos, viewDirection(v_worldPos),
+ 0.0, 1.0, 1.0, 1.0);
+#ifdef MESH_LIGHTMAP
+
+
+
+ shaded += base.rgb * baked * v_lightmap.z;
+#endif
+ fragColor = vec4(shaded, base.a);
+#else
+#ifdef MESH_LIGHTMAP
+
+
+
+ fragColor = vec4(base.rgb * mix(vec3(1.0), baked, v_lightmap.z), base.a);
#else
fragColor = base;
#endif
#endif
+#endif
}
#pragma end
@@ -601,6 +653,12 @@ struct VSIn {
@location(8) a_model0 : vec4f,
@location(9) a_model1 : vec4f,
@location(10) a_model2 : vec4f,
+#ifdef MESH_LIGHTMAP
+ @location(11) a_lightmapRect : vec4f,
+#endif
+#endif
+#ifdef MESH_LIGHTMAP
+ @location(7) a_texCoord1 : vec2f,
#endif
@location(12) a_instTint : vec4f,
@@ -625,6 +683,9 @@ struct VSOut {
@location(4) v_shadowClip : vec4f,
#endif
+#ifdef MESH_LIGHTMAP
+ @location(5) v_lightmap : vec3f,
+#endif
};
@vertex fn vs_main(v : VSIn) -> VSOut {
@@ -665,6 +726,10 @@ struct VSOut {
out.pos = frame.projection * world;
out.v_texCoord = v.a_texCoord;
out.v_color = v.a_color * v.a_instTint;
+#ifdef MESH_LIGHTMAP
+ out.v_lightmap = vec3f(v.a_texCoord1 * v.a_lightmapRect.xy + v.a_lightmapRect.zw,
+ select(0.0, 1.0, v.a_lightmapRect.x > 0.0));
+#endif
#ifdef SHADOW_DEPTH
out.v_shadowClip = out.pos;
#endif
@@ -705,6 +770,11 @@ struct VSOut {
@group(1) @binding(3) var t3 : texture_2d<f32>;
@group(1) @binding(11) var s3 : sampler;
#endif
+#ifdef MESH_LIGHTMAP
+
+@group(1) @binding(5) var t5 : texture_2d<f32>;
+@group(1) @binding(13) var s5 : sampler;
+#endif
@group(1) @binding(7) var t7 : texture_2d<f32>;
@@ -721,6 +791,9 @@ struct VSOut {
#ifdef SHADOW_DEPTH
@location(4) v_shadowClip : vec4f,
#endif
+#ifdef MESH_LIGHTMAP
+ @location(5) v_lightmap : vec3f,
+#endif
};
@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {
@@ -732,6 +805,9 @@ struct VSOut {
0.0, 1.0)), 1.0);
#else
let base = textureSampleLevel(t0, s0, v.v_texCoord, 0.0) * v.v_color;
+#ifdef MESH_LIGHTMAP
+ let baked = textureSampleLevel(t5, s5, v.v_lightmap.xy, 0.0).rgb;
+#endif
#ifdef LIT
var N = normalize(v.v_worldNormal);
#ifdef NORMAL_MAP
@@ -741,12 +817,22 @@ struct VSOut {
- return vec4f(applyLightingPBR(base.rgb, N, v.v_worldPos, viewDirection(v.v_worldPos),
- 0.0, 1.0, 1.0, 1.0), base.a);
+ var shaded = applyLightingPBR(base.rgb, N, v.v_worldPos, viewDirection(v.v_worldPos),
+ 0.0, 1.0, 1.0, 1.0);
+#ifdef MESH_LIGHTMAP
+
+ shaded = shaded + base.rgb * baked * v.v_lightmap.z;
+#endif
+ return vec4f(shaded, base.a);
+#else
+#ifdef MESH_LIGHTMAP
+
+ return vec4f(base.rgb * mix(vec3f(1.0), baked, vec3f(v.v_lightmap.z)), base.a);
#else
return base;
#endif
#endif
+#endif
}
#pragma end
)esshader";
diff --git a/src/esengine/renderer/store/LightConstants.hpp b/src/esengine/renderer/store/LightConstants.hpp
index d9e5c7b0e..8f87ec3c9 100644
--- a/src/esengine/renderer/store/LightConstants.hpp
+++ b/src/esengine/renderer/store/LightConstants.hpp
@@ -37,6 +37,16 @@ inline constexpr u32 SHADOW_MAP_TEXTURE_UNIT = 2;
inline constexpr const char* ENV_MAP_SAMPLER = "u_envMap";
inline constexpr u32 ENV_MAP_TEXTURE_UNIT = 3;
+/**
+ * @brief The baked-light atlas, and the unit a lightmapped mesh samples it from.
+ * @details Unit 5 and not 4: the morph deltas hold that one and 6/7 are the
+ * frame's 2D masks, so this is the last a draw's own stream can claim.
+ * A lit fragment ADDS the bake as its indirect term; an unlit one takes
+ * it as the whole of its light.
+ */
+inline constexpr const char* LIGHTMAP_SAMPLER = "u_lightmap";
+inline constexpr u32 LIGHTMAP_TEXTURE_UNIT = 5;
+
/**
* @brief Max simultaneous 2D lights packed into the UBO. The injected fragment loop is a fixed
* bound; inactive slots are zeroed (intensity 0) so they contribute nothing. Must match
diff --git a/src/esengine/resource/Mesh.hpp b/src/esengine/resource/Mesh.hpp
index 44a3c0b02..e8b3e34a8 100644
--- a/src/esengine/resource/Mesh.hpp
+++ b/src/esengine/resource/Mesh.hpp
@@ -79,6 +79,11 @@ public:
* and which shader variant draws it. */
bool hasNormals = false;
+ /** Whether the vertices carry a second UV set — the one a bake is read
+ * through. Beside hasNormals and for the same reason: an optional channel
+ * the geometry owns decides the record's shape and the variant. */
+ bool hasLightmapUV = false;
+
/** Local-space bounds of the vertices, for the frustum cull. */
glm::vec3 localMin{0.0f, 0.0f, 0.0f};
glm::vec3 localMax{0.0f, 0.0f, 0.0f};
diff --git a/src/esengine/resource/ResourceManager.cpp b/src/esengine/resource/ResourceManager.cpp
index 41c81cf6d..77aab7246 100644
--- a/src/esengine/resource/ResourceManager.cpp
+++ b/src/esengine/resource/ResourceManager.cpp
@@ -544,15 +544,20 @@ bool ResourceManager::realizeMesh(Mesh& mesh, ConstSpan<u8> vertexBytes, ConstSp
}
bool hasNormals = false;
bool skinned = false;
+ bool lightmapUV = false;
for (const GfxVertexAttribute& c : channels) {
if (c.location == static_cast<u32>(MeshChannel::Normal)) hasNormals = true;
if (c.location == static_cast<u32>(MeshChannel::Joints)) skinned = true;
+ if (c.location == static_cast<u32>(MeshChannel::TexCoord1)) lightmapUV = true;
}
skinned = skinned && !inverseBind.empty();
+ // Bones move a character and a bake cannot hold one still, so a skinned mesh
+ // reads no atlas however many UV sets it carries — and its record stays the
+ // tint alone.
+ const bool lightmapped = lightmapUV && !skinned;
layout.strides[0] = vertexStride;
- layout.strides[1] = skinned ? MESH_INSTANCE_STRIDE_SKINNED
- : hasNormals ? MESH_INSTANCE_STRIDE_LIT : MESH_INSTANCE_STRIDE;
+ layout.strides[1] = meshInstanceStride(skinned, hasNormals, lightmapped);
layout.instanceStep[1] = true;
u32 next = bound;
// Only where the shader will read them: a layout may not declare an attribute
@@ -572,6 +577,10 @@ bool ResourceManager::realizeMesh(Mesh& mesh, ConstSpan<u8> vertexBytes, ConstSp
GfxDataType::Float, false, 52 + row * 12u, 1};
}
}
+ if (lightmapped) {
+ layout.attributes[next++] = {MESH_INSTANCE_FIRST_LOCATION + 3, 4, GfxDataType::Float,
+ false, meshInstanceLightmapOffset(hasNormals), 1};
+ }
layout.attributeCount = next;
// The old records go only once the new ones stand: a rematerialization that
@@ -606,6 +615,7 @@ bool ResourceManager::realizeMesh(Mesh& mesh, ConstSpan<u8> vertexBytes, ConstSp
mesh.indexCount = static_cast<u32>(indices.size());
mesh.realizationGeneration = device_->deviceGeneration();
mesh.hasNormals = hasNormals;
+ mesh.hasLightmapUV = lightmapped;
mesh.localMin = localMin;
mesh.localMax = localMax;
mesh.inverseBind.clear();
diff --git a/src/esengine/resource/ShaderParser.cpp b/src/esengine/resource/ShaderParser.cpp
index 85579996f..14367b0e7 100644
--- a/src/esengine/resource/ShaderParser.cpp
+++ b/src/esengine/resource/ShaderParser.cpp
@@ -114,6 +114,12 @@ std::string wgslCanonicalVSOut(bool lit) {
"#ifdef MESH_NORMALS\n"
" @location(3) v_worldNormal : vec3f,\n"
" @location(4) v_worldXYZ : vec3f,\n"
+ "#endif\n"
+ // mesh.esshader's twin of the same varying, carried through a material's
+ // variant so the LAYOUT matches. What a material's fragment makes of it
+ // is the material's, as all of its shading is.
+ "#ifdef MESH_LIGHTMAP\n"
+ " @location(5) v_lightmap : vec3f,\n"
"#endif\n";
src += "};\n";
return src;
@@ -161,6 +167,9 @@ std::string canonicalVertexStageWGSL(bool lit) {
"#ifdef MESH_NORMALS\n"
" @location(3) a_normal : vec3f,\n"
"#endif\n"
+ "#ifdef MESH_LIGHTMAP\n"
+ " @location(7) a_texCoord1 : vec2f,\n"
+ "#endif\n"
"#ifdef SKINNED\n"
" @location(5) a_joints : vec4u,\n"
" @location(6) a_weights : vec4f,\n"
@@ -170,6 +179,9 @@ std::string canonicalVertexStageWGSL(bool lit) {
" @location(8) a_model0 : vec4f,\n"
" @location(9) a_model1 : vec4f,\n"
" @location(10) a_model2 : vec4f,\n"
+ "#ifdef MESH_LIGHTMAP\n"
+ " @location(11) a_lightmapRect : vec4f,\n"
+ "#endif\n"
" @location(12) a_instTint : vec4f,\n"
"#endif\n"
"#ifdef MESH_NORMALS\n"
@@ -254,6 +266,10 @@ std::string canonicalVertexStageWGSL(bool lit) {
" out.v_worldNormal = mat3x3f(v.a_nrm0, v.a_nrm1, v.a_nrm2) * localNormal;\n"
"#endif\n"
" out.v_worldXYZ = world.xyz;\n"
+ "#endif\n"
+ "#ifdef MESH_LIGHTMAP\n"
+ " out.v_lightmap = vec3f(v.a_texCoord1 * v.a_lightmapRect.xy + v.a_lightmapRect.zw,\n"
+ " select(0.0, 1.0, v.a_lightmapRect.x > 0.0));\n"
"#endif\n";
if (lit) {
src += " out.v_worldPos = world.xy;\n";
@@ -333,6 +349,9 @@ std::string canonicalVertexStage(bool lit) {
"#ifdef MESH_NORMALS\n"
"layout(location = 3) in vec3 a_normal;\n"
"#endif\n"
+ "#ifdef MESH_LIGHTMAP\n"
+ "layout(location = 7) in vec2 a_texCoord1;\n"
+ "#endif\n"
"#ifdef SKINNED\n"
"layout(location = 5) in uvec4 a_joints;\n"
"layout(location = 6) in vec4 a_weights;\n"
@@ -346,6 +365,9 @@ std::string canonicalVertexStage(bool lit) {
"layout(location = 8) in vec4 a_model0;\n"
"layout(location = 9) in vec4 a_model1;\n"
"layout(location = 10) in vec4 a_model2;\n"
+ "#ifdef MESH_LIGHTMAP\n"
+ "layout(location = 11) in vec4 a_lightmapRect;\n"
+ "#endif\n"
"layout(location = 12) in vec4 a_instTint;\n"
"#endif\n"
"#ifdef MESH_NORMALS\n"
@@ -385,6 +407,9 @@ std::string canonicalVertexStage(bool lit) {
"#ifdef MESH_NORMALS\n"
"out highp vec3 v_worldNormal;\n"
"out highp vec3 v_worldXYZ;\n"
+ "#endif\n"
+ "#ifdef MESH_LIGHTMAP\n"
+ "out highp vec3 v_lightmap;\n"
"#endif\n";
if (lit) {
src += "out highp vec2 v_worldPos;\n";
@@ -450,6 +475,10 @@ std::string canonicalVertexStage(bool lit) {
" v_worldNormal = mat3(a_nrm0, a_nrm1, a_nrm2) * localNormal;\n"
"#endif\n"
" v_worldXYZ = world.xyz;\n"
+ "#endif\n"
+ "#ifdef MESH_LIGHTMAP\n"
+ " v_lightmap = vec3(a_texCoord1 * a_lightmapRect.xy + a_lightmapRect.zw,\n"
+ " a_lightmapRect.x > 0.0 ? 1.0 : 0.0);\n"
"#endif\n";
if (lit) {
src += " v_worldPos = world.xy;\n";
diff --git a/tests/aot/generated/conformance/handshake.h b/tests/aot/generated/conformance/handshake.h
index 637c125eb..67307cd6a 100644
--- a/tests/aot/generated/conformance/handshake.h
+++ b/tests/aot/generated/conformance/handshake.h
@@ -1,5 +1,5 @@
/* GENERATED by sdk/tests/aot-conformance.test.ts — do not edit. */
/* The contract half of the handshake. The width half is the harness. */
-#define ES_CONF_EXPECTED_CONTRACT_HASH 0xcfe06bb8128f6f6bULL
+#define ES_CONF_EXPECTED_CONTRACT_HASH 0xb6ad0af24d9719e3ULL
/* And which BUILD the artifact beside this one is. */
#define ES_CONF_EXPECTED_MODULE_CONTRACT 0xc3d0e057d5701a2eULL
diff --git a/tests/aot/generated/conformance/systems_decl.c b/tests/aot/generated/conformance/systems_decl.c
index e4ae544d2..0330e98d1 100644
--- a/tests/aot/generated/conformance/systems_decl.c
+++ b/tests/aot/generated/conformance/systems_decl.c
@@ -10,7 +10,7 @@
answer, it is a read of a different field. The address width belongs
to the MACHINE, so it mixes in here rather than in the compiler and a
32-bit artifact cannot load into a 64-bit host. */
-#define ES_ABI_ENGINE_DIGEST 0xcfe06bb8128f6f6bULL
+#define ES_ABI_ENGINE_DIGEST 0xb6ad0af24d9719e3ULL
ES_EXPORT const uint64_t es_abi_hash =
ES_ABI_ENGINE_DIGEST ^ (0x9e3779b97f4a7c15ULL * (uint64_t)sizeof(es_addr_t));
diff --git a/tests/aot/generated/move_system_decl.c b/tests/aot/generated/move_system_decl.c
index 04a97338b..57ae0ebb4 100644
--- a/tests/aot/generated/move_system_decl.c
+++ b/tests/aot/generated/move_system_decl.c
@@ -10,7 +10,7 @@
answer, it is a read of a different field. The address width belongs
to the MACHINE, so it mixes in here rather than in the compiler and a
32-bit artifact cannot load into a 64-bit host. */
-#define ES_ABI_ENGINE_DIGEST 0xcfe06bb8128f6f6bULL
+#define ES_ABI_ENGINE_DIGEST 0xb6ad0af24d9719e3ULL
ES_EXPORT const uint64_t es_abi_hash =
ES_ABI_ENGINE_DIGEST ^ (0x9e3779b97f4a7c15ULL * (uint64_t)sizeof(es_addr_t));
diff --git a/tests/aot/generated/move_system_hash.h b/tests/aot/generated/move_system_hash.h
index f1be0a0e7..f4ab3e09e 100644
--- a/tests/aot/generated/move_system_hash.h
+++ b/tests/aot/generated/move_system_hash.h
@@ -1,6 +1,6 @@
/* GENERATED by @estella/compiler — do not edit. */
/* The contract half of the handshake. The width half is the harness. */
-#define ES_EXPECTED_CONTRACT_HASH 0xcfe06bb8128f6f6bULL
+#define ES_EXPECTED_CONTRACT_HASH 0xb6ad0af24d9719e3ULL
/* And which BUILD the artifact beside this one is, which the sidecar
written with it has to carry too. */
#define ES_EXPECTED_MODULE_CONTRACT 0x10bf77bb714ea1e3ULL
diff --git a/tests/renderer/test_shader_device.cpp b/tests/renderer/test_shader_device.cpp
index fa7529c32..5d89d44c8 100644
--- a/tests/renderer/test_shader_device.cpp
+++ b/tests/renderer/test_shader_device.cpp
@@ -32,15 +32,15 @@ int main() {
CHECK(d.getActiveUniformsCalls == 1, "reflection routes through device.getActiveUniforms");
// compile() pins the engine-injected samplers to their units, so the counts
- // below start from what that seeding left behind. Five: the shadow map,
- // the reflection, the two 2D masks, and the morph deltas.
- CHECK(d.setUniform1iCalls == 5
- && d.lastUniform1iVal == static_cast<i32>(MORPH_DELTA_TEXTURE_UNIT),
+ // below start from what that seeding left behind. Six: the shadow map, the
+ // reflection, the two 2D masks, the morph deltas and the baked atlas.
+ CHECK(d.setUniform1iCalls == 6
+ && d.lastUniform1iVal == static_cast<i32>(LIGHTMAP_TEXTURE_UNIT),
"compile pins the injected samplers to their texture units");
CHECK(d.useProgramCalls == 2, "seeding them binds and unbinds the program once");
shader->setUniform("u_tex", 3);
- CHECK(d.setUniform1iCalls == 6, "setUniform(name,int) routes through device.setUniform1i");
+ CHECK(d.setUniform1iCalls == 7, "setUniform(name,int) routes through device.setUniform1i");
CHECK(d.lastUniform1iVal == 3, "uniform value forwarded");
shader->setUniform("u_color", glm::vec4(1, 0, 0, 1));
diff --git a/tools/check-corpus-authoring.mjs b/tools/check-corpus-authoring.mjs
index da32e5b88..368f3e110 100644
--- a/tools/check-corpus-authoring.mjs
+++ b/tools/check-corpus-authoring.mjs
@@ -120,6 +120,7 @@ const DISPOSITION = {
// — owed: a creator-facing component nothing in the shipped corpus authors.
// Each reason names where the coverage belongs. —
+ MeshLightmap: ['owed', 'the reading side shipped before the baking side, deliberately: nothing in the editor produces an atlas yet, so a corpus scene would have to carry one baked in another tool. The coverage belongs with the lightmapper, in the example whose room it lights'],
};
diff --git a/tools/check-mesh-instance-record.mjs b/tools/check-mesh-instance-record.mjs
index a68455cac..2eef97eae 100644
--- a/tools/check-mesh-instance-record.mjs
+++ b/tools/check-mesh-instance-record.mjs
@@ -40,6 +40,7 @@ const constant = (name) => {
const FIRST = constant('MESH_INSTANCE_FIRST_LOCATION');
const STRIDE = constant('MESH_INSTANCE_STRIDE');
const STRIDE_LIT = constant('MESH_INSTANCE_STRIDE_LIT');
+const LIGHTMAP_BYTES = constant('MESH_INSTANCE_LIGHTMAP_BYTES');
/** Every instance-range attribute a source declares: location → name, per language. */
function declarations(text) {
@@ -87,21 +88,22 @@ for (const [file, langs] of Object.entries(sources)) {
}
/**
- * What the declarations add up to, against what the packer sends. The model rows
- * and the lightmap rectangle are vec4s, the tint is four bytes it packs itself,
- * and the normal rows are the vec3s only lit geometry carries.
+ * What the declarations add up to, against what the packer sends. Measured by
+ * WHERE each part is rather than by how many there are: normals and a bake are
+ * each optional, so a count alone cannot say which record a total is of.
*/
+const LIGHTMAP = FIRST + 3;
const TINT = FIRST + 4;
const NORMAL_FIRST = FIRST + 5;
-const wide = every.filter((loc) => loc < TINT).length;
+const modelRows = every.filter((loc) => loc < LIGHTMAP).length;
const normalRows = every.filter((loc) => loc >= NORMAL_FIRST).length;
-const base = wide * 16 + 4;
+const base = modelRows * 16 + 4;
const lit = base + normalRows * 12;
if (!spellings.has(TINT)) {
problems.push(`no attribute at location ${TINT}, where the record's tint is`);
}
if (base !== STRIDE) {
- problems.push(`${wide} vec4 part(s) plus the tint is ${base} bytes, but`
+ problems.push(`${modelRows} model row(s) plus the tint is ${base} bytes, but`
+ ` MESH_INSTANCE_STRIDE is ${STRIDE} — the record is packed to a different shape`
+ ' than it is declared');
}
@@ -109,6 +111,17 @@ if (lit !== STRIDE_LIT) {
problems.push(`with ${normalRows} normal row(s) that is ${lit} bytes, but`
+ ` MESH_INSTANCE_STRIDE_LIT is ${STRIDE_LIT}`);
}
+// The bake's rectangle is APPENDED, so its size is all the packer needs to agree
+// on: everything before it keeps the offset it had, which is what lets one
+// record serve an object with a bake and one without.
+if (spellings.has(LIGHTMAP) && LIGHTMAP_BYTES !== 16) {
+ problems.push(`location ${LIGHTMAP} declares a vec4 atlas rectangle, which is 16 bytes,`
+ + ` but MESH_INSTANCE_LIGHTMAP_BYTES is ${LIGHTMAP_BYTES}`);
+}
+if (!spellings.has(LIGHTMAP) && LIGHTMAP_BYTES !== 0) {
+ problems.push(`MESH_INSTANCE_LIGHTMAP_BYTES is ${LIGHTMAP_BYTES}, but no attribute at`
+ + ` location ${LIGHTMAP} carries an atlas rectangle — the bytes are sent and never read`);
+}
if (problems.length) {
console.error('check-mesh-instance-record: the per-object record is described'
@@ -119,5 +132,7 @@ if (problems.length) {
process.exit(1);
}
+const bake = spellings.has(LIGHTMAP) ? ` (+${LIGHTMAP_BYTES} where a bake is read)` : '';
console.log(`check-mesh-instance-record: ${every.length} part(s) of the per-object record,`
- + ` spelled the same in all four declarations and adding to ${STRIDE}/${STRIDE_LIT} bytes.`);
+ + ` spelled the same in all four declarations and adding to ${STRIDE}/${STRIDE_LIT}`
+ + ` bytes${bake}.`);
diff --git a/tools/make-lightmap-fixture.mjs b/tools/make-lightmap-fixture.mjs
new file mode 100644
index 000000000..af010bc77
--- /dev/null
+++ b/tools/make-lightmap-fixture.mjs
@@ -0,0 +1,94 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * Regenerate the baked-light fixture: one quad with TWO UV sets, and a four-texel
+ * atlas, red half then blue half. The second UV set is the TRANSPOSE of the first,
+ * so a bake read through the wrong channel comes out turned ninety degrees.
+ *
+ * node tools/make-lightmap-fixture.mjs
+ */
+import { writeFileSync } from 'node:fs';
+import { deflateSync } from 'node:zlib';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { encodeMesh, packChannels, MeshChannel, MeshChannelType } from '../sdk/dist/index.node.js';
+
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const MESH = path.join(ROOT, 'fixtures', 'scenes', 'lightmap-quad.esmesh');
+const ATLAS = path.join(ROOT, 'fixtures', 'scenes', 'lightmap-atlas.png');
+
+/** Wide enough that every gate point lands well inside the quad. */
+const HALF = 80;
+const POSITIONS = [
+ [-HALF, -HALF, 0], [HALF, -HALF, 0], [HALF, HALF, 0], [-HALF, HALF, 0],
+];
+const UV0 = [[0, 0], [1, 0], [1, 1], [0, 1]];
+/** (u, v) -> (v, u): the atlas's left-to-right becomes the quad's bottom-to-top. */
+const UV1 = UV0.map(([u, v]) => [v, u]);
+
+const { channels, vertexStride } = packChannels([
+ { semantic: MeshChannel.Position, components: 3, type: MeshChannelType.Float32 },
+ { semantic: MeshChannel.TexCoord0, components: 2, type: MeshChannelType.Float32 },
+ { semantic: MeshChannel.TexCoord1, components: 2, type: MeshChannelType.Float32 },
+ { semantic: MeshChannel.Color, components: 4, type: MeshChannelType.UNorm8 },
+]);
+const at = (semantic) => channels.find((c) => c.semantic === semantic).offset;
+
+const vertices = new Uint8Array(POSITIONS.length * vertexStride);
+const view = new DataView(vertices.buffer);
+POSITIONS.forEach((p, i) => {
+ const base = i * vertexStride;
+ for (let c = 0; c < 3; c++) view.setFloat32(base + at(MeshChannel.Position) + c * 4, p[c], true);
+ view.setFloat32(base + at(MeshChannel.TexCoord0), UV0[i][0], true);
+ view.setFloat32(base + at(MeshChannel.TexCoord0) + 4, UV0[i][1], true);
+ view.setFloat32(base + at(MeshChannel.TexCoord1), UV1[i][0], true);
+ view.setFloat32(base + at(MeshChannel.TexCoord1) + 4, UV1[i][1], true);
+ for (let c = 0; c < 4; c++) view.setUint8(base + at(MeshChannel.Color) + c, 255);
+});
+
+writeFileSync(MESH, encodeMesh({
+ channels, vertexStride, vertexCount: POSITIONS.length, vertices,
+ indices: Uint32Array.from([0, 1, 2, 0, 2, 3]),
+ aabbMin: [-HALF, -HALF, 0], aabbMax: [HALF, HALF, 0],
+}));
+
+/** Four texels, not two: every gate point then sits between two texels of ONE
+ * colour, so linear filtering cannot put the answer on a boundary. */
+const TEXELS = [[255, 0, 0], [255, 0, 0], [0, 0, 255], [0, 0, 255]];
+
+const crcTable = Array.from({ length: 256 }, (_, n) => {
+ let c = n;
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
+ return c >>> 0;
+});
+const crc32 = (buf) => {
+ let c = 0xffffffff;
+ for (const b of buf) c = crcTable[(c ^ b) & 0xff] ^ (c >>> 8);
+ return (c ^ 0xffffffff) >>> 0;
+};
+const chunk = (type, body) => {
+ const head = Buffer.alloc(4);
+ head.writeUInt32BE(body.length);
+ const typed = Buffer.concat([Buffer.from(type, 'latin1'), body]);
+ const tail = Buffer.alloc(4);
+ tail.writeUInt32BE(crc32(typed));
+ return Buffer.concat([head, typed, tail]);
+};
+
+const ihdr = Buffer.alloc(13);
+ihdr.writeUInt32BE(TEXELS.length, 0);
+ihdr.writeUInt32BE(1, 4);
+ihdr[8] = 8; // bit depth
+ihdr[9] = 6; // RGBA
+const raw = Buffer.concat([
+ Buffer.from([0]), // filter: none
+ ...TEXELS.map(([r, g, b]) => Buffer.from([r, g, b, 255])),
+]);
+writeFileSync(ATLAS, Buffer.concat([
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
+ chunk('IHDR', ihdr),
+ chunk('IDAT', deflateSync(raw)),
+ chunk('IEND', Buffer.alloc(0)),
+]));
+
+console.log(`wrote ${path.relative(ROOT, MESH)} and ${path.relative(ROOT, ATLAS)}`);
diff --git a/tools/renderScenes.mjs b/tools/renderScenes.mjs
index f36b1927f..967ff2e92 100644
--- a/tools/renderScenes.mjs
+++ b/tools/renderScenes.mjs
@@ -115,6 +115,18 @@ export const SCENES = [
// DIFFERENT copy of the deform. Through the other source, the same shape: the
// two must move the quad alike or one of them is not deforming at all.
{ id: "mesh-morph-material", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mesh-morph-mat.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.75,\"y\":0.5,\"rgb\":[0,0,255],\"tol\":30},{\"x\":0.25,\"y\":0.5,\"rgb\":[0,0,0],\"tol\":20}]" } },
+ // A BAKE, read through the second UV set. The atlas runs red-to-blue left to
+ // right and the quad's second UV set is the transpose of its first, so reading
+ // the wrong channel turns the halves and swaps two of these four points.
+ { id: "lightmap-unlit", tier: "pr", webgpu: true, env: { "ESTELLA_VERIFY_SCENE": "/scenes/lightmap-unlit.esscene", "ESTELLA_VERIFY_MANIFEST": "/scenes/lightmap-unlit.textures.json", "ESTELLA_VERIFY_W": "256", "ESTELLA_VERIFY_H": "256", "ESTELLA_VERIFY_STEPS": "2", "ESTELLA_VERIFY_EXPECT": "[{\"x\":0.3,\"y\":0.25,\"rgb\":[0,0,255],\"tol\":30},{\"x\":0.7,\"y\":0.25,\"rgb\":[0,0,255],\"tol\":30},{\"x\":0.3,\"y\":0.75,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.7,\"y\":0.75,\"rgb\":[255,0,0],\"tol\":30}]" } },
+ // A baked object and an unbaked one in ONE lit frame. Cyan and yellow halves
+ // say the green sun SURVIVED, so the bake adds rather than replaces; the plain
+ // green quad says an unbaked one is not brightened by an unbound unit's white.
+ { id: "lightmap-mixed", tier: "pr", webgpu: true, env: { "ESTELLA_VERIFY_SCENE": "/scenes/lightmap-mixed.esscene", "ESTELLA_VERIFY_MANIFEST": "/scenes/lightmap-mixed.textures.json", "ESTELLA_VERIFY_W": "256", "ESTELLA_VERIFY_H": "256", "ESTELLA_VERIFY_STEPS": "2", "ESTELLA_VERIFY_EXPECT": "[{\"x\":0.25,\"y\":0.4,\"rgb\":[0,255,255],\"tol\":40},{\"x\":0.25,\"y\":0.6,\"rgb\":[255,255,0],\"tol\":40},{\"x\":0.75,\"y\":0.4,\"rgb\":[0,255,0],\"tol\":40},{\"x\":0.75,\"y\":0.6,\"rgb\":[0,255,0],\"tol\":40}]" } },
+ // Why the rectangle rides the per-object record: ONE mesh and ONE atlas, and
+ // the two objects drawn from them read different halves of it. A rectangle
+ // that belonged to the mesh would paint these two the same colour.
+ { id: "lightmap-atlas", tier: "pr", webgpu: true, env: { "ESTELLA_VERIFY_SCENE": "/scenes/lightmap-atlas-share.esscene", "ESTELLA_VERIFY_MANIFEST": "/scenes/lightmap-atlas-share.textures.json", "ESTELLA_VERIFY_W": "256", "ESTELLA_VERIFY_H": "256", "ESTELLA_VERIFY_STEPS": "2", "ESTELLA_VERIFY_EXPECT": "[{\"x\":0.25,\"y\":0.4,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.25,\"y\":0.6,\"rgb\":[255,0,0],\"tol\":30},{\"x\":0.75,\"y\":0.4,\"rgb\":[0,0,255],\"tol\":30},{\"x\":0.75,\"y\":0.6,\"rgb\":[0,0,255],\"tol\":30}]" } },
// A clip driving the weight, which is what an imported `weights` channel
// becomes. The shape has to cross the boundary as a LIST — a weight written
// into a component the runtime hands back as an embind vector goes nowhere.