A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(render): a mesh casts a shadow on a mesh
esengineed3c0a5882fe
diff --git a/desktop/public/scenes/lit-triangles.esmesh b/desktop/public/scenes/lit-triangles.esmeshindex 759af2f6f..7cda97b1a 100644Binary files a/desktop/public/scenes/lit-triangles.esmesh and b/desktop/public/scenes/lit-triangles.esmesh differdiff --git a/desktop/public/scenes/mesh-shadow.esscene b/desktop/public/scenes/mesh-shadow.esscenenew file mode 100644index 000000000..68dfb8f05--- /dev/null+++ b/desktop/public/scenes/mesh-shadow.esscene@@ -0,0 +1,149 @@+{+ "version": 1,+ "name": "MeshShadow",+ "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": 300,+ "isActive": true,+ "priority": 0+ }+ }+ ]+ },+ {+ "id": 1,+ "name": "Ground",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 0,+ "z": -200+ },+ "scale": {+ "x": 600,+ "y": 600,+ "z": 1+ }+ }+ },+ {+ "type": "Mesh2D",+ "data": {+ "mesh": "/scenes/shadow-quad.esmesh",+ "color": {+ "r": 1,+ "g": 1,+ "b": 1,+ "a": 1+ },+ "lit": true,+ "opaque": true,+ "enabled": true+ }+ }+ ]+ },+ {+ "id": 2,+ "name": "Blocker",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 0,+ "z": 0+ },+ "scale": {+ "x": 150,+ "y": 150,+ "z": 1+ }+ }+ },+ {+ "type": "Mesh2D",+ "data": {+ "mesh": "/scenes/shadow-quad.esmesh",+ "color": {+ "r": 1,+ "g": 1,+ "b": 1,+ "a": 1+ },+ "lit": true,+ "opaque": true,+ "enabled": true+ }+ }+ ]+ },+ {+ "id": 3,+ "name": "Sun",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 0,+ "z": 0+ }+ }+ },+ {+ "type": "Light2D",+ "data": {+ "type": 1,+ "color": {+ "r": 1,+ "g": 1,+ "b": 1,+ "a": 1+ },+ "intensity": 1,+ "direction": {+ "x": 0.5,+ "y": 0+ },+ "meshShadows": true+ }+ }+ ]+ }+ ]+}diff --git a/desktop/public/scenes/model-material_0_0.esmesh b/desktop/public/scenes/model-material_0_0.esmeshindex f1248f700..6c9511371 100644Binary files a/desktop/public/scenes/model-material_0_0.esmesh and b/desktop/public/scenes/model-material_0_0.esmesh differdiff --git a/desktop/public/scenes/model-material_1_0.esmesh b/desktop/public/scenes/model-material_1_0.esmeshindex f1248f700..6c9511371 100644Binary files a/desktop/public/scenes/model-material_1_0.esmesh and b/desktop/public/scenes/model-material_1_0.esmesh differdiff --git a/desktop/public/scenes/model-material_2_0.esmesh b/desktop/public/scenes/model-material_2_0.esmeshindex f1248f700..6c9511371 100644Binary files a/desktop/public/scenes/model-material_2_0.esmesh and b/desktop/public/scenes/model-material_2_0.esmesh differdiff --git a/desktop/public/scenes/model-material_m0.esmaterial b/desktop/public/scenes/model-material_m0.esmaterialindex a8e7257ab..8cd4099b0 100644--- a/desktop/public/scenes/model-material_m0.esmaterial+++ b/desktop/public/scenes/model-material_m0.esmaterial@@ -8,13 +8,13 @@"cull": 1,"properties": {"u_emissiveMap": "model-material_0.png",+ "u_metallic": 0,+ "u_roughness": 1,"u_emissive": {"r": 0,"g": 1,"b": 0,"a": 1- },- "u_metallic": 0,- "u_roughness": 1+ }}}diff --git a/desktop/public/scenes/model-material_m1.esmaterial b/desktop/public/scenes/model-material_m1.esmaterialindex c32586716..66acfce35 100644--- a/desktop/public/scenes/model-material_m1.esmaterial+++ b/desktop/public/scenes/model-material_m1.esmaterial@@ -8,8 +8,8 @@"cull": 1,"properties": {"u_occlusionMap": "model-material_0.png",- "u_occlusionStrength": 1,"u_metallic": 0,- "u_roughness": 1+ "u_roughness": 1,+ "u_occlusionStrength": 1}}diff --git a/desktop/public/scenes/model-material_m2.esmaterial b/desktop/public/scenes/model-material_m2.esmaterialindex 8612b1430..1ad96c2a2 100644--- a/desktop/public/scenes/model-material_m2.esmaterial+++ b/desktop/public/scenes/model-material_m2.esmaterial@@ -7,8 +7,8 @@"depthWrite": true,"cull": 1,"properties": {- "u_alphaCutoff": 0.5,"u_metallic": 0,- "u_roughness": 1+ "u_roughness": 1,+ "u_alphaCutoff": 0.5}}diff --git a/desktop/public/scenes/moving-quad.esmesh b/desktop/public/scenes/moving-quad.esmeshindex 76d12f34b..9d094f811 100644Binary files a/desktop/public/scenes/moving-quad.esmesh and b/desktop/public/scenes/moving-quad.esmesh differdiff --git a/desktop/public/scenes/node-tree_0_0.esmesh b/desktop/public/scenes/node-tree_0_0.esmeshindex c90a0f0e0..6b6f3337e 100644Binary files a/desktop/public/scenes/node-tree_0_0.esmesh and b/desktop/public/scenes/node-tree_0_0.esmesh differdiff --git a/desktop/public/scenes/node-tree_1_0.esmesh b/desktop/public/scenes/node-tree_1_0.esmeshindex c90a0f0e0..6b6f3337e 100644Binary files a/desktop/public/scenes/node-tree_1_0.esmesh and b/desktop/public/scenes/node-tree_1_0.esmesh differdiff --git a/desktop/public/scenes/normalmap-quad.esmesh b/desktop/public/scenes/normalmap-quad.esmeshindex 722d7dd13..48a589bf5 100644Binary files a/desktop/public/scenes/normalmap-quad.esmesh and b/desktop/public/scenes/normalmap-quad.esmesh differdiff --git a/desktop/public/scenes/normalmap-quad_m0.esmaterial b/desktop/public/scenes/normalmap-quad_m0.esmaterialindex e1640478a..5f327cb22 100644--- a/desktop/public/scenes/normalmap-quad_m0.esmaterial+++ b/desktop/public/scenes/normalmap-quad_m0.esmaterial@@ -7,6 +7,8 @@"depthWrite": true,"cull": 1,"properties": {- "u_normalMap": "normalmap-quad_0.png"+ "u_normalMap": "normalmap-quad_0.png",+ "u_metallic": 0,+ "u_roughness": 1}}diff --git a/desktop/public/scenes/shadow-quad.esmesh b/desktop/public/scenes/shadow-quad.esmeshnew file mode 100644index 000000000..50c383e43Binary files /dev/null and b/desktop/public/scenes/shadow-quad.esmesh differdiff --git a/desktop/public/scenes/shadow-quad.esmesh.meta b/desktop/public/scenes/shadow-quad.esmesh.metanew file mode 100644index 000000000..b448e1628--- /dev/null+++ b/desktop/public/scenes/shadow-quad.esmesh.meta@@ -0,0 +1,6 @@+{+ "uuid": "9c23b250-067f-4227-b95d-08da6cc0f07d",+ "version": "2.0",+ "type": "mesh",+ "importer": {}+}diff --git a/desktop/public/scenes/shadow-quad.esprefab b/desktop/public/scenes/shadow-quad.esprefabnew file mode 100644index 000000000..6cee602a7--- /dev/null+++ b/desktop/public/scenes/shadow-quad.esprefab@@ -0,0 +1,36 @@+{+ "version": "2",+ "name": "shadow-quad",+ "rootEntityId": "n0",+ "entities": [+ {+ "prefabEntityId": "n0",+ "name": "Quad",+ "parent": null,+ "children": [],+ "visible": true,+ "components": [+ {+ "type": "Transform",+ "data": {}+ },+ {+ "type": "Mesh2D",+ "data": {+ "mesh": "scenes/shadow-quad.esmesh",+ "lit": true,+ "color": {+ "r": 1,+ "g": 1,+ "b": 1,+ "a": 1+ },+ "opaque": true,+ "cullBackfaces": true,+ "enabled": true+ }+ }+ ]+ }+ ]+}diff --git a/desktop/public/scenes/shadow-quad.esprefab.meta b/desktop/public/scenes/shadow-quad.esprefab.metanew file mode 100644index 000000000..c3bec342e--- /dev/null+++ b/desktop/public/scenes/shadow-quad.esprefab.meta@@ -0,0 +1,6 @@+{+ "uuid": "a0ac9edc-792b-4db1-816c-dc8e2729c341",+ "version": "2.0",+ "type": "prefab",+ "importer": {}+}diff --git a/desktop/public/scenes/shadow-quad.gltf b/desktop/public/scenes/shadow-quad.gltfnew file mode 100644index 000000000..2b376b657--- /dev/null+++ b/desktop/public/scenes/shadow-quad.gltf@@ -0,0 +1,115 @@+{+ "asset": {+ "version": "2.0",+ "generator": "estella shadow fixture"+ },+ "scene": 0,+ "scenes": [+ {+ "nodes": [+ 0+ ]+ }+ ],+ "nodes": [+ {+ "name": "Quad",+ "mesh": 0+ }+ ],+ "meshes": [+ {+ "name": "Quad",+ "primitives": [+ {+ "attributes": {+ "POSITION": 0,+ "NORMAL": 1,+ "TEXCOORD_0": 2+ },+ "indices": 3,+ "material": 0+ }+ ]+ }+ ],+ "materials": [+ {+ "name": "Plain",+ "pbrMetallicRoughness": {+ "baseColorFactor": [+ 1,+ 1,+ 1,+ 1+ ],+ "metallicFactor": 0,+ "roughnessFactor": 1+ }+ }+ ],+ "accessors": [+ {+ "bufferView": 0,+ "componentType": 5126,+ "count": 4,+ "type": "VEC3",+ "min": [+ -0.5,+ -0.5,+ 0+ ],+ "max": [+ 0.5,+ 0.5,+ 0+ ]+ },+ {+ "bufferView": 1,+ "componentType": 5126,+ "count": 4,+ "type": "VEC3"+ },+ {+ "bufferView": 2,+ "componentType": 5126,+ "count": 4,+ "type": "VEC2"+ },+ {+ "bufferView": 3,+ "componentType": 5123,+ "count": 6,+ "type": "SCALAR"+ }+ ],+ "bufferViews": [+ {+ "buffer": 0,+ "byteOffset": 0,+ "byteLength": 48+ },+ {+ "buffer": 0,+ "byteOffset": 48,+ "byteLength": 48+ },+ {+ "buffer": 0,+ "byteOffset": 96,+ "byteLength": 32+ },+ {+ "buffer": 0,+ "byteOffset": 128,+ "byteLength": 12+ }+ ],+ "buffers": [+ {+ "byteLength": 140,+ "uri": "data:application/octet-stream;base64,AAAAvwAAAL8AAAAAAAAAPwAAAL8AAAAAAAAAPwAAAD8AAAAAAAAAvwAAAD8AAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAgD8AAIA/AACAPwAAgD8AAAAAAAAAAAAAAAAAAAEAAgAAAAIAAwA="+ }+ ]+}diff --git a/desktop/public/scenes/textured-quad.esmesh b/desktop/public/scenes/textured-quad.esmeshindex fe70e22dd..d9eba7553 100644Binary files a/desktop/public/scenes/textured-quad.esmesh and b/desktop/public/scenes/textured-quad.esmesh differdiff --git a/desktop/public/scenes/two-triangles.esmesh b/desktop/public/scenes/two-triangles.esmeshindex fe219d59b..d9321789f 100644Binary files a/desktop/public/scenes/two-triangles.esmesh and b/desktop/public/scenes/two-triangles.esmesh differdiff --git a/desktop/public/scenes/white-triangles.esmesh b/desktop/public/scenes/white-triangles.esmeshindex 699743bee..93bc580e2 100644Binary files a/desktop/public/scenes/white-triangles.esmesh and b/desktop/public/scenes/white-triangles.esmesh differdiff --git a/desktop/scripts/make-mesh-fixture.mjs b/desktop/scripts/make-mesh-fixture.mjsindex 3e518d7a4..ff89f57cd 100644--- a/desktop/scripts/make-mesh-fixture.mjs+++ b/desktop/scripts/make-mesh-fixture.mjs@@ -31,9 +31,12 @@ const cli = path.join(HERE, '..', '..', 'pipeline', 'bin', 'estella.mjs');// occlusion, an alpha cutoff — one quad each.// moving-quad: one node with a translation clip, which is what a node animation// is once nothing is skinned — the products include its `.estimeline`.+// shadow-quad: a unit quad with normals, placed twice by the shadow scene — one+// scaled into a floor, one held above it. A caster and a receiver need nothing+// else, and one mesh for both is one mesh that cannot disagree with itself.for (const name of ['two-triangles.gltf', 'lit-triangles.gltf', 'white-triangles.gltf','textured-quad.gltf', 'node-tree.gltf', 'normalmap-quad.gltf',- 'model-material.gltf', 'moving-quad.gltf']) {+ 'model-material.gltf', 'moving-quad.gltf', 'shadow-quad.gltf']) {const run = spawnSync(process.execPath,[cli, 'import-gltf', path.join(scenes, name), '--project', path.join(HERE, '..', 'public')], {stdio: 'inherit',diff --git a/docs/astro/src/content/docs/graphics/lighting.mdx b/docs/astro/src/content/docs/graphics/lighting.mdxindex ba39f0704..1d26a83a3 100644--- a/docs/astro/src/content/docs/graphics/lighting.mdx+++ b/docs/astro/src/content/docs/graphics/lighting.mdx@@ -186,6 +186,33 @@ show.normal and the view vector are the three-dimensional part of the model.</Aside>+## Shadows between meshes++A `ShadowCaster2D` box (below) shadows in the XY plane, which is what a 2D scene means+by a shadow. Geometry with height needs the other kind: turn on **`meshShadows`** on a+`Directional` light and the frame renders the scene's meshes once from that light, so a+mesh standing above another darkens it.++```typescript+cmds.spawn()+ .insert(Light2D, {+ type: Light2DType.Directional,+ direction: { x: 0.5, y: 0 }, // where the rays lean+ meshShadows: true,+ });+```++- One light per frame casts a map — the first that asks for one.+- Only `Mesh2D` geometry the GPU holds casts and receives. Sprites are lit by the same+ light but shadow through `ShadowCaster2D`, which is the 2D answer.+- Coverage follows the camera. `shadowExtent` fixes it to a radius instead, trading+ sharpness for reach.++<Aside type="caution">+ A shadow map is a second pass over the scene's meshes. It costs a draw call per+ caster and is off until a light asks, so a scene that wants none pays nothing.+</Aside>+## Casting shadowsAdd a **`ShadowCaster2D`** to an entity to make it block light and cast a shadow:diff --git a/docs/astro/src/content/docs/zh-cn/graphics/lighting.mdx b/docs/astro/src/content/docs/zh-cn/graphics/lighting.mdxindex ef80a916c..5b1466a0a 100644--- a/docs/astro/src/content/docs/zh-cn/graphics/lighting.mdx+++ b/docs/astro/src/content/docs/zh-cn/graphics/lighting.mdx@@ -176,6 +176,31 @@ highp vec3 lit = applyLightingPBR(半径。法线与视线才是这个模型里三维的部分。</Aside>+## mesh 之间的阴影++`ShadowCaster2D` 的方块(见下)在 XY 平面上投影,那是 2D 场景所说的阴影。有高度的几何+需要另一种:给一盏 `Directional` 灯打开 **`meshShadows`**,引擎每帧会从那盏灯的方向把场景的+mesh 再画一遍,于是站得高的 mesh 会让下面的暗下来。++```typescript+cmds.spawn()+ .insert(Light2D, {+ type: Light2DType.Directional,+ direction: { x: 0.5, y: 0 }, // 光线偏向哪边+ meshShadows: true,+ });+```++- 每帧只有一盏灯投出这张图 —— 第一盏要求它的。+- 只有 GPU 持有的 `Mesh2D` 几何参与投射与接收。精灵被同一盏灯照亮,但它们的阴影走+ `ShadowCaster2D`,那才是 2D 的答案。+- 覆盖范围跟着相机走。`shadowExtent` 把它固定成一个半径,用锐度换范围。++<Aside type="caution">+ 阴影贴图是对场景 mesh 的第二遍绘制,每个投射者一次 draw call。没有灯要求它时它根本不跑,+ 所以不需要阴影的场景一分钱不付。+</Aside>+## 投射阴影给一个实体加 **`ShadowCaster2D`**,让它遮挡光并投出阴影:diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.jsonindex 034b2cbd6..498218170 100644--- a/docs/astro/src/data/components.generated.json+++ b/docs/astro/src/data/components.generated.json@@ -1243,6 +1243,20 @@"range": "≥ 0","advanced": true},+ {+ "key": "meshShadows",+ "type": "boolean",+ "default": "false",+ "doc": "Cast a shadow map over 3D meshes (Directional)."+ },+ {+ "key": "shadowExtent",+ "type": "number",+ "default": "0",+ "doc": "Shadow map coverage radius; 0 = fit the view.",+ "range": "≥ 0",+ "advanced": true+ },{"key": "enabled","type": "boolean",diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 984d5fef9..93854b323 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -5,7 +5,7 @@ Symbols: 113 public · 58 beta · 1418 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```-"9b942024c64872cd"+"9e0ab90e452805c7"```## ANCHOR_AXES — const @experimental@@ -3815,9 +3815,11 @@ direction: Vec2enabled: booleaninnerAngle: numberintensity: number+meshShadows: booleanouterAngle: numberradius: numbershadowDistance: number+shadowExtent: numbershadowSoftness: numbertype: number```diff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 7e87b7296..7b242fa5a 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -5,7 +5,7 @@ Symbols: 113 public · 63 beta · 1437 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```-"9b942024c64872cd"+"9e0ab90e452805c7"```## ANCHOR_AXES — const @experimental@@ -3823,9 +3823,11 @@ direction: Vec2enabled: booleaninnerAngle: numberintensity: number+meshShadows: booleanouterAngle: numberradius: numbershadowDistance: number+shadowExtent: numbershadowSoftness: numbertype: number```diff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex d1adef3da..18f623fb8 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -3810,9 +3810,11 @@ direction: Vec2enabled: booleaninnerAngle: numberintensity: number+meshShadows: booleanouterAngle: numberradius: numbershadowDistance: number+shadowExtent: numbershadowSoftness: numbertype: number```diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 1b5969dde..f8cadd874 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -3810,9 +3810,11 @@ direction: Vec2enabled: booleaninnerAngle: numberintensity: number+meshShadows: booleanouterAngle: numberradius: numbershadowDistance: number+shadowExtent: numbershadowSoftness: numbertype: number```diff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 4d93c0613..9974755c2 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -3817,9 +3817,11 @@ direction: Vec2enabled: booleaninnerAngle: numberintensity: number+meshShadows: booleanouterAngle: numberradius: numbershadowDistance: number+shadowExtent: numbershadowSoftness: numbertype: number```diff --git a/sdk/src/ecs/bridge/ptrAccessors.generated.ts b/sdk/src/ecs/bridge/ptrAccessors.generated.tsindex 6fb74ee49..95f5f4e97 100644--- a/sdk/src/ecs/bridge/ptrAccessors.generated.ts+++ b/sdk/src/ecs/bridge/ptrAccessors.generated.ts@@ -499,6 +499,8 @@ export interface Light2DPtrData {outerAngle: number;shadowSoftness: number;shadowDistance: number;+ meshShadows: boolean;+ shadowExtent: number;enabled: boolean;}@@ -515,7 +517,9 @@ export function fillLight2D(out.outerAngle = f32[(ptr + 40) >> 2];out.shadowSoftness = f32[(ptr + 44) >> 2];out.shadowDistance = f32[(ptr + 48) >> 2];- out.enabled = u8[ptr + 52] !== 0;+ out.meshShadows = u8[ptr + 52] !== 0;+ out.shadowExtent = f32[(ptr + 56) >> 2];+ out.enabled = u8[ptr + 60] !== 0;}export function writeLight2D(@@ -531,7 +535,9 @@ export function writeLight2D(f32[(ptr + 40) >> 2] = data.outerAngle;f32[(ptr + 44) >> 2] = data.shadowSoftness;f32[(ptr + 48) >> 2] = data.shadowDistance;- u8[ptr + 52] = data.enabled ? 1 : 0;+ u8[ptr + 52] = data.meshShadows ? 1 : 0;+ f32[(ptr + 56) >> 2] = data.shadowExtent;+ u8[ptr + 60] = data.enabled ? 1 : 0;}export function createLight2DData(): Light2DPtrData {@@ -545,6 +551,8 @@ export function createLight2DData(): Light2DPtrData {outerAngle: 0,shadowSoftness: 0,shadowDistance: 0,+ meshShadows: false,+ shadowExtent: 0,enabled: false,};}diff --git a/sdk/src/ecs/component.generated.ts b/sdk/src/ecs/component.generated.tsindex 039324db7..873a3b2a2 100644--- a/sdk/src/ecs/component.generated.ts+++ b/sdk/src/ecs/component.generated.ts@@ -15,7 +15,7 @@ import type { Dimension, Padding } from '../wasm/wasm.generated';* getAbiLayoutHash(); BuiltinBridge.connect() compares them and refuses to* run on mismatch, because mismatched offsets read the wrong heap bytes.*/-export const ABI_LAYOUT_HASH = '9b942024c64872cd';+export const ABI_LAYOUT_HASH = '9e0ab90e452805c7';/*** One asset-valued field of a component: which field, and what kind of@@ -308,6 +308,8 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {outerAngle: 45,shadowSoftness: 0,shadowDistance: 0,+ meshShadows: false,+ shadowExtent: 0,enabled: true,},renderableField: 'enabled',@@ -324,6 +326,8 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {outerAngle: { min: 0, max: 180, unit: "°", advanced: true },shadowSoftness: { min: 0, tooltip: "Shadow softness (light-source size); 0 = hard edge." },shadowDistance: { min: 0, tooltip: "Directional shadow distance; 0 = no directional shadow.", advanced: true },+ meshShadows: { tooltip: "Cast a shadow map over 3D meshes (Directional)." },+ shadowExtent: { min: 0, tooltip: "Shadow map coverage radius; 0 = fit the view.", advanced: true },},},Mesh2D: {@@ -1010,6 +1014,8 @@ export interface Light2DData {outerAngle: number;shadowSoftness: number;shadowDistance: number;+ meshShadows: boolean;+ shadowExtent: number;enabled: boolean;}diff --git a/sdk/src/wasm/ptrLayouts.generated.ts b/sdk/src/wasm/ptrLayouts.generated.tsindex dcb46fa6b..7b9be5a24 100644--- a/sdk/src/wasm/ptrLayouts.generated.ts+++ b/sdk/src/wasm/ptrLayouts.generated.ts@@ -159,7 +159,9 @@ export const PTR_LAYOUTS: Record<string, PtrLayout> = {{ name: 'outerAngle', type: 'f32', offset: 40 },{ name: 'shadowSoftness', type: 'f32', offset: 44 },{ name: 'shadowDistance', type: 'f32', offset: 48 },- { name: 'enabled', type: 'bool', offset: 52 },+ { name: 'meshShadows', type: 'bool', offset: 52 },+ { name: 'shadowExtent', type: 'f32', offset: 56 },+ { name: 'enabled', type: 'bool', offset: 60 },],},Mesh2D: {diff --git a/sdk/src/wasm/wasm.generated.ts b/sdk/src/wasm/wasm.generated.tsindex e63a8ba9f..4c4bb5951 100644--- a/sdk/src/wasm/wasm.generated.ts+++ b/sdk/src/wasm/wasm.generated.ts@@ -339,6 +339,8 @@ export interface Light2D {outerAngle: number;shadowSoftness: number;shadowDistance: number;+ meshShadows: boolean;+ shadowExtent: number;enabled: boolean;}diff --git a/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap b/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snapindex bdfe34a35..d129936b0 100644--- a/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap+++ b/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap@@ -175,6 +175,9 @@ exports[`builtin FieldMeta (RC9-1 equivalence gate) > matches the golden snapsho"min": 0,"tooltip": "Brightness multiplier of the light.",},+ "meshShadows": {+ "tooltip": "Cast a shadow map over 3D meshes (Directional).",+ },"outerAngle": {"advanced": true,"max": 180,@@ -190,6 +193,11 @@ exports[`builtin FieldMeta (RC9-1 equivalence gate) > matches the golden snapsho"min": 0,"tooltip": "Directional shadow distance; 0 = no directional shadow.",},+ "shadowExtent": {+ "advanced": true,+ "min": 0,+ "tooltip": "Shadow map coverage radius; 0 = fit the view.",+ },"shadowSoftness": {"min": 0,"tooltip": "Shadow softness (light-source size); 0 = hard edge.",diff --git a/src/esengine/bindings/EditorAPI.generated.cpp b/src/esengine/bindings/EditorAPI.generated.cppindex b3d275893..ed11c99f7 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 b194d72fddb41534+ * @schema_hash ae111705aaf429d7*/-#define ES_EDITOR_API_SCHEMA_HASH "b194d72fddb41534"+#define ES_EDITOR_API_SCHEMA_HASH "ae111705aaf429d7"#include <emscripten/bind.h>#include <string>@@ -242,6 +242,8 @@ std::string editor_getComponentSchema(const std::string& name) {{"key":"outerAngle","type":"float","group":"Light2D"},{"key":"shadowSoftness","type":"float","group":"Light2D"},{"key":"shadowDistance","type":"float","group":"Light2D"},+ {"key":"meshShadows","type":"bool","group":"Light2D"},+ {"key":"shadowExtent","type":"float","group":"Light2D"},{"key":"enabled","type":"bool","group":"Light2D"}])JSON";} else if (name == "Mesh2D") {@@ -965,6 +967,7 @@ bool editor_setFloat(Registry& reg, u32 e, const std::string& comp, const std::selse if (field == "outerAngle") { c.outerAngle = value; }else if (field == "shadowSoftness") { c.shadowSoftness = value; }else if (field == "shadowDistance") { c.shadowDistance = value; }+ else if (field == "shadowExtent") { c.shadowExtent = value; }else { return false; }return true;} else if (comp == "Mesh2D") {@@ -1357,6 +1360,7 @@ f32 editor_getFloat(Registry& reg, u32 e, const std::string& comp, const std::stelse if (field == "outerAngle") { return c.outerAngle; }else if (field == "shadowSoftness") { return c.shadowSoftness; }else if (field == "shadowDistance") { return c.shadowDistance; }+ else if (field == "shadowExtent") { return c.shadowExtent; }} else if (comp == "Mesh2D") {if (!reg.has<esengine::ecs::Mesh2D>(entity)) return 0.0f;const auto& c = reg.get<esengine::ecs::Mesh2D>(entity);@@ -2027,7 +2031,8 @@ bool editor_setBool(Registry& reg, u32 e, const std::string& comp, const std::st} else if (comp == "Light2D") {if (!reg.has<esengine::ecs::Light2D>(entity)) return false;auto& c = reg.get<esengine::ecs::Light2D>(entity);- if (field == "enabled") { c.enabled = value; }+ if (field == "meshShadows") { c.meshShadows = value; }+ else if (field == "enabled") { c.enabled = value; }else { return false; }return true;} else if (comp == "Mesh2D") {@@ -2196,7 +2201,8 @@ bool editor_getBool(Registry& reg, u32 e, const std::string& comp, const std::st} else if (comp == "Light2D") {if (!reg.has<esengine::ecs::Light2D>(entity)) return false;const auto& c = reg.get<esengine::ecs::Light2D>(entity);- if (field == "enabled") { return c.enabled; }+ if (field == "meshShadows") { return c.meshShadows; }+ else if (field == "enabled") { return c.enabled; }} else if (comp == "Mesh2D") {if (!reg.has<esengine::ecs::Mesh2D>(entity)) return false;const auto& c = reg.get<esengine::ecs::Mesh2D>(entity);diff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cppindex 54ef656ae..6e9fbdf1c 100644--- a/src/esengine/bindings/WebBindings.generated.cpp+++ b/src/esengine/bindings/WebBindings.generated.cpp@@ -1240,6 +1240,8 @@ EMSCRIPTEN_BINDINGS(esengine_components) {.field("outerAngle", &esengine::ecs::Light2D::outerAngle).field("shadowSoftness", &esengine::ecs::Light2D::shadowSoftness).field("shadowDistance", &esengine::ecs::Light2D::shadowDistance)+ .field("meshShadows", &esengine::ecs::Light2D::meshShadows)+ .field("shadowExtent", &esengine::ecs::Light2D::shadowExtent).field("enabled", &esengine::ecs::Light2D::enabled);value_object<Mesh2DJS>("Mesh2D")@@ -2362,7 +2364,9 @@ static_assert(offsetof(esengine::ecs::Light2D, innerAngle) == 36, "ABI offset drstatic_assert(offsetof(esengine::ecs::Light2D, outerAngle) == 40, "ABI offset drift: esengine::ecs::Light2D.outerAngle (EHT expected 40)");static_assert(offsetof(esengine::ecs::Light2D, shadowSoftness) == 44, "ABI offset drift: esengine::ecs::Light2D.shadowSoftness (EHT expected 44)");static_assert(offsetof(esengine::ecs::Light2D, shadowDistance) == 48, "ABI offset drift: esengine::ecs::Light2D.shadowDistance (EHT expected 48)");-static_assert(offsetof(esengine::ecs::Light2D, enabled) == 52, "ABI offset drift: esengine::ecs::Light2D.enabled (EHT expected 52)");+static_assert(offsetof(esengine::ecs::Light2D, meshShadows) == 52, "ABI offset drift: esengine::ecs::Light2D.meshShadows (EHT expected 52)");+static_assert(offsetof(esengine::ecs::Light2D, shadowExtent) == 56, "ABI offset drift: esengine::ecs::Light2D.shadowExtent (EHT expected 56)");+static_assert(offsetof(esengine::ecs::Light2D, enabled) == 60, "ABI offset drift: esengine::ecs::Light2D.enabled (EHT expected 60)");static_assert(offsetof(esengine::ecs::Mesh2D, texture) == 0, "ABI offset drift: esengine::ecs::Mesh2D.texture (EHT expected 0)");static_assert(offsetof(esengine::ecs::Mesh2D, normalMap) == 4, "ABI offset drift: esengine::ecs::Mesh2D.normalMap (EHT expected 4)");static_assert(offsetof(esengine::ecs::Mesh2D, color) == 8, "ABI offset drift: esengine::ecs::Mesh2D.color (EHT expected 8)");@@ -2577,7 +2581,7 @@ static_assert(offsetof(esengine::ecs::Velocity, angular) == 12, "ABI offset drif// ABI Hash -- runtime handshake against the SDK bundle// =============================================================================-static const char* kEsAbiLayoutHash = "9b942024c64872cd";+static const char* kEsAbiLayoutHash = "9e0ab90e452805c7";std::string esengineGetAbiLayoutHash() {return std::string(kEsAbiLayoutHash);diff --git a/src/esengine/data/shaders/mesh.esshader b/src/esengine/data/shaders/mesh.esshaderindex 8d356b0dc..341c2f627 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+// 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+// land where its skinned self lands, and one copy of that is one that cannot drift.+#pragma feature SHADOW_DEPTH+// GPU-resident geometry. Slot 0 is the mesh's own vertices, which are LOCAL// space and are never rewritten; slot 1 is the per-object record the frame// streams, so the same mesh drawn twice costs one more transform rather than@@ -77,6 +83,9 @@ out highp vec3 v_worldNormal;// it changes across a fragment, which xy alone cannot say for a tilted surface.out highp vec3 v_worldPos;#endif+#ifdef SHADOW_DEPTH+out highp float v_shadowDepth;+#endifvoid main() {#ifdef SKINNED@@ -94,6 +103,11 @@ void main() {gl_Position = u_projection * world;v_texCoord = a_texCoord;v_color = a_color * a_instTint;+#ifdef SHADOW_DEPTH+ // The expression the receiver evaluates on u_shadowMatrix, evaluated here on the+ // same matrix: whatever each backend's clip z means, both sides mean it alike.+ v_shadowDepth = clamp(gl_Position.z / gl_Position.w * 0.5 + 0.5, 0.0, 1.0);+#endif#ifdef LIT#if defined(MESH_NORMALS) && defined(SKINNED)v_worldNormal = mat3(skin) * a_normal;@@ -117,6 +131,9 @@ in vec4 v_color;in highp vec3 v_worldNormal;in highp vec3 v_worldPos;#endif+#ifdef SHADOW_DEPTH+in highp float v_shadowDepth;+#endifuniform sampler2D u_texture;#ifdef NORMAL_MAP@@ -126,16 +143,23 @@ uniform sampler2D u_normalMap;out vec4 fragColor;void main() {+#ifdef SHADOW_DEPTH+ fragColor = vec4(packDepth(v_shadowDepth), 1.0);+#elsevec4 base = texture(u_texture, v_texCoord) * v_color;#ifdef LIThighp vec3 N = normalize(v_worldNormal);#ifdef NORMAL_MAPN = perturbNormal(N, v_worldPos, v_texCoord, sampleNormal(u_normalMap, v_texCoord));#endif- fragColor = vec4(applyLighting2D(base.rgb, N, v_worldPos.xy), base.a);+ // The general form at a 2D surface's own parameters, but with the position it+ // really has: a shadow is cast on a point in space, and xy is not one.+ fragColor = vec4(applyLightingPBR(base.rgb, N, v_worldPos, viewDirection(v_worldPos),+ 0.0, 1.0, 0.0, 1.0), base.a);#elsefragColor = base;#endif+#endif}#pragma end@@ -178,6 +202,9 @@ struct VSOut {@location(2) v_worldNormal : vec3f,@location(3) v_worldPos : vec3f,#endif+#ifdef SHADOW_DEPTH+ @location(4) v_shadowDepth : f32,+#endif};@vertex fn vs_main(v : VSIn) -> VSOut {@@ -198,6 +225,11 @@ struct VSOut {out.pos = frame.projection * world;out.v_texCoord = v.a_texCoord;out.v_color = v.a_color * v.a_instTint;+#ifdef SHADOW_DEPTH+ // The expression the receiver evaluates on u_shadowMatrix, evaluated here on the+ // same matrix: whatever each backend's clip z means, both sides mean it alike.+ out.v_shadowDepth = clamp(out.pos.z / out.pos.w * 0.5 + 0.5, 0.0, 1.0);+#endif#ifdef LIT#ifdef MESH_NORMALS#ifdef SKINNED@@ -222,6 +254,12 @@ struct VSOut {@group(1) @binding(1) var t1 : texture_2d<f32>;@group(1) @binding(9) var s1 : sampler;#endif+#ifdef ES_RECEIVE_SHADOW+// The shadow map, on the slot the injected header samples. A fragment-only twin+// gets these from the batch texture contract; one that writes its own says so.+@group(1) @binding(2) var t2 : texture_2d<f32>;+@group(1) @binding(10) var s2 : sampler;+#endifstruct VSOut {@builtin(position) pos : vec4f,@@ -231,18 +269,28 @@ struct VSOut {@location(2) v_worldNormal : vec3f,@location(3) v_worldPos : vec3f,#endif+#ifdef SHADOW_DEPTH+ @location(4) v_shadowDepth : f32,+#endif};@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {+#ifdef SHADOW_DEPTH+ return vec4f(packDepth(v.v_shadowDepth), 1.0);+#elselet base = textureSampleLevel(t0, s0, v.v_texCoord, 0.0) * v.v_color;#ifdef LITvar N = normalize(v.v_worldNormal);#ifdef NORMAL_MAPN = perturbNormal(N, v.v_worldPos, v.v_texCoord, sampleNormal(t1, s1, v.v_texCoord));#endif- return vec4f(applyLighting2D(base.rgb, N, v.v_worldPos.xy), base.a);+ // The general form at a 2D surface's own parameters, but with the position it+ // really has: a shadow is cast on a point in space, and xy is not one.+ return vec4f(applyLightingPBR(base.rgb, N, v.v_worldPos, viewDirection(v.v_worldPos),+ 0.0, 1.0, 0.0, 1.0), base.a);#elsereturn base;#endif+#endif}#pragma enddiff --git a/src/esengine/ecs/components/Light2D.hpp b/src/esengine/ecs/components/Light2D.hppindex 57b731ef7..4eb20c7f6 100644--- a/src/esengine/ecs/components/Light2D.hpp+++ b/src/esengine/ecs/components/Light2D.hpp@@ -92,6 +92,18 @@ struct Light2D {ES_PROPERTY(animatable, min=0, advanced, tooltip="Directional shadow distance; 0 = no directional shadow.")f32 shadowDistance{0.0f};+ /** @brief Casts a shadow map over 3D meshes (Directional only). Separate from+ * @ref shadowDistance, which shadows 2D ShadowCaster2D boxes in the XY plane:+ * one light can do both, and a 2.5D scene often wants exactly that. One light+ * per frame casts a map — the first that asks. */+ ES_PROPERTY(tooltip="Cast a shadow map over 3D meshes (Directional).")+ bool meshShadows{false};++ /** @brief Half-extent of the shadow map's world coverage, centred on the camera.+ * 0 = fit what the camera can see. Larger trades sharpness for reach. */+ ES_PROPERTY(min=0, advanced, tooltip="Shadow map coverage radius; 0 = fit the view.")+ f32 shadowExtent{0.0f};+/** @brief Disabled lights are skipped during collection. */ES_PROPERTY()bool enabled{true};diff --git a/src/esengine/renderer/RenderTypePlugin.hpp b/src/esengine/renderer/RenderTypePlugin.hppindex 74b868085..5d2c10974 100644--- a/src/esengine/renderer/RenderTypePlugin.hpp+++ b/src/esengine/renderer/RenderTypePlugin.hpp@@ -32,6 +32,11 @@ struct RenderFrameContext {const MaterialStore* materials = nullptr;/// The owning frame, for lazily-compiled batch variants (RenderFrame::batchProgram).RenderFrame* frame = nullptr;+ /// This collect is the shadow pass: geometry draws depth-only, from the light.+ /// Set by the frame, which also skips every plugin that casts nothing.+ bool shadow_pass = false;+ /// The map that pass produced, handed to the meshes that receive it (0 = none).+ u32 shadow_texture_id = 0;};/** @brief The camera's view bounds in world space, derived once per collect from thediff --git a/src/esengine/renderer/draw/BatchBuilder.cpp b/src/esengine/renderer/draw/BatchBuilder.cppindex f51aa88bf..59d3f8c00 100644--- a/src/esengine/renderer/draw/BatchBuilder.cpp+++ b/src/esengine/renderer/draw/BatchBuilder.cpp@@ -109,6 +109,13 @@ void pushBatchDraw(DrawList& drawList, const ClipState& clips,cmd.texture_ids[1] = key.normalTextureId;cmd.texture_count = 2;}+ // The shadow map's unit is pinned in the shader, so the gap below it is filled+ // rather than the slot moved: a draw with no normal map still samples slot 2.+ if (key.shadowTextureId != 0 && cmd.texture_count >= 1 && key.layoutId != LayoutId::Batch) {+ if (cmd.texture_count == 1) cmd.texture_ids[1] = key.textureId;+ cmd.texture_ids[2] = key.shadowTextureId;+ cmd.texture_count = 3;+ }cmd.entity = key.entity;cmd.type = key.type;cmd.layer = key.layer;diff --git a/src/esengine/renderer/draw/BatchBuilder.hpp b/src/esengine/renderer/draw/BatchBuilder.hppindex 525a3ddf5..bd7eaf6aa 100644--- a/src/esengine/renderer/draw/BatchBuilder.hpp+++ b/src/esengine/renderer/draw/BatchBuilder.hpp@@ -87,6 +87,10 @@ struct BatchDrawKey {// slot 1. Not the same thing as the Batch stream's extra slots, which are a// MERGE product chosen per vertex.u32 normalTextureId = 0;+ // The frame's shadow map, on the slot the injected Lit2D header samples. Per-draw+ // like the two above rather than a global unit: which draws receive a shadow is a+ // question the collect answers, and the device has no "bind for everyone" seam.+ u32 shadowTextureId = 0;f32 depth = 0.0f;// World-space Y of the draw's anchor. Consumed only when the layer is y-sorted// (DrawList::ySortMask); layers outside 0..31 cannot y-sort.diff --git a/src/esengine/renderer/frame/RenderFrame.cpp b/src/esengine/renderer/frame/RenderFrame.cppindex 555af1a2d..a085c2755 100644--- a/src/esengine/renderer/frame/RenderFrame.cpp+++ b/src/esengine/renderer/frame/RenderFrame.cpp@@ -11,6 +11,7 @@#include "../../core/Log.hpp"#include "../../core/FrameProfiler.hpp"+#include <glm/gtc/matrix_transform.hpp>#include <glm/gtc/type_ptr.hpp>#include <algorithm>@@ -243,6 +244,13 @@ void RenderFrame::begin(const glm::mat4& view_projection, RenderTargetManager::Hdraw_list_.clear();clip_state_.clear();+ openPass(clear, target);+}++// Opening the frame's target: the load-op clear, the post-process capture when one is+// engaged, the default surface otherwise. Its own method because the shadow pass draws+// through a target of its own and has to hand this one back when it is done.+void RenderFrame::openPass(const PassClear& clear, RenderTargetManager::Handle target) {#ifdef ES_ENABLE_POSTPROCESS// Linear mode keeps the capture+blit engaged even with zero passes: the// final blit is where the mandatory linear->sRGB encode lives (the WebGL2@@ -621,13 +629,16 @@ RenderFrameContext RenderFrame::makeContext() {current_stage_,view_projection_,&context_.materials(),- this+ this,+ false,+ shadow_texture_id_};}void RenderFrame::collectLights(ecs::Registry& registry) {LightStore& lights = context_.lights();lights.clear();+ shadow_light_slot_ = -1;// Gather non-ambient lights, then (if over the UBO's cap) keep the most intense — the// brightest contribute most, and an explicit importance cull beats silently dropping@@ -662,6 +673,13 @@ void RenderFrame::collectLights(ecs::Registry& registry) {if (type == ecs::Light2DType::Directional) {// Direction in the 2D plane; z=1 flags directional (no attenuation) in the shader.gpu.posDir = glm::vec4(light.direction.x, light.direction.y, 1.0f, 0.0f);+ // Marked here and read back after the cap sort, so the slot recorded is the+ // slot the shader will index. shadow.z is cleared before it reaches the GPU.+ if (light.meshShadows && shadow_light_slot_ < 0) {+ gpu.shadow.z = 1.0f;+ shadow_light_dir_ = light.direction;+ shadow_light_extent_ = std::max(light.shadowExtent, 0.0f);+ }} else { // Point / Spot — world position from the Transform, w=falloff radius.auto* transform = registry.tryGet<ecs::Transform>(entity);if (!transform) continue; // a positional light with no position casts nothing@@ -687,7 +705,14 @@ void RenderFrame::collectLights(ecs::Registry& registry) {collected.size(), MAX_LIGHTS_2D);collected.resize(MAX_LIGHTS_2D);}- for (const auto& gpu : collected) lights.addLight(gpu);+ for (u32 slot = 0; slot < collected.size(); ++slot) {+ GpuLight2D& gpu = collected[slot];+ if (gpu.shadow.z > 0.5f) {+ shadow_light_slot_ = static_cast<i32>(slot);+ gpu.shadow.z = 0.0f; // a mark for this loop, not a field the shader reads+ }+ lights.addLight(gpu);+ }// Shadow occluders: each enabled ShadowCaster2D becomes a world-space AABB (centered on its// Transform, `size` wide/tall). The injected shadowFactor2D blocks point/spot light at any@@ -705,10 +730,119 @@ void RenderFrame::collectLights(ecs::Registry& registry) {}}+/// Side length of a shadow map. One size for every scene: the coverage adapts to the+/// camera instead, so the texel density a scene gets is a property of how far it asked+/// the light to reach rather than of a knob nobody can calibrate.+static constexpr u32 kShadowMapSize = 1024;++/// Depth bias in the map's own [0,1] units. Large enough for a 1024 map over a+/// camera-sized area to stop shadowing itself, small enough not to detach contact.+static constexpr f32 kShadowBias = 0.0015f;++void RenderFrame::renderShadowMap(ecs::Registry& registry) {+ shadow_texture_id_ = 0;+ // Zeroed params first: a matrix that outlived its map would shadow the scene+ // against geometry from a frame that no longer exists.+ context_.lights().setShadow(glm::mat4(1.0f), glm::vec4(0.0f));+ if (!in_frame_ || shadow_light_slot_ < 0 || !device_.isDeviceUsable()) return;++ if (shadow_rt_ == 0) {+ shadow_rt_ = target_manager_.create(kShadowMapSize, kShadowMapSize,+ /*depth=*/true, /*linearFilter=*/false);+ }+ auto* rt = target_manager_.get(shadow_rt_);+ if (!rt) return;++ // What the map has to cover: the camera's own view, unless the light asked for a+ // fixed reach. A radius rather than the rect, so the coverage does not change as+ // the light turns — a shadow that resized when the sun moved would crawl.+ const CameraWorldRect view = computeCameraWorldRect(view_projection_);+ const f32 fitted = 0.5f * glm::length(glm::vec2(view.right - view.left,+ view.top - view.bottom));+ const f32 radius = shadow_light_extent_ > 0.0f ? shadow_light_extent_+ : std::max(fitted, 1.0f);+ const glm::vec3 centre(view.center.x, view.center.y, 0.0f);++ // The light's own direction, in the three dimensions the 2D field implies: the+ // shader lights a surface from normalize(-dir.xy, 1), so rays travel the other way.+ glm::vec3 toLight = glm::normalize(glm::vec3(-shadow_light_dir_.x, -shadow_light_dir_.y, 1.0f));+ // An up that cannot be parallel to it, whichever way the light points.+ const glm::vec3 up = std::abs(toLight.z) > 0.99f ? glm::vec3(0.0f, 1.0f, 0.0f)+ : glm::vec3(0.0f, 0.0f, 1.0f);+ const glm::mat4 lightView = glm::lookAt(centre + toLight * (radius * 2.0f), centre, up);++ // Zero-to-one depth on purpose: the engine's shared ortho() is the GL convention+ // (z in [-1,1]) and WebGPU clips everything below 0 of it. Written out here rather+ // than reused, because this matrix is the one place the choice is free.+ glm::mat4 lightProj(1.0f);+ const f32 range = radius * 4.0f;+ lightProj[0][0] = 1.0f / radius;+ lightProj[1][1] = 1.0f / radius;+ lightProj[2][2] = -1.0f / range;+ lightProj[3][2] = 0.0f;+ const glm::mat4 lightVP = lightProj * lightView;++ // A self-contained pass, in the shape renderToTarget uses: swap what the frame is+ // looking through, collect only what casts, draw, and hand the target back.+ const glm::mat4 sceneVP = view_projection_;+ RenderPassDesc pass{rt->getFramebuffer(), /*clearColor=*/true};+ // Depth too: the map keeps the NEAREST occluder, which is the depth buffer's job,+ // and last frame's contents would reject this frame's geometry outright.+ pass.clearDepth = true;+ // White is depth 1 unpacked — "nothing here", so an untouched texel never shadows.+ pass.clearColorValue[0] = pass.clearColorValue[1] = pass.clearColorValue[2] = 1.0f;+ pass.clearColorValue[3] = 1.0f;+ // The frame's own viewport, taken back at the end: a split-screen camera owns+ // part of the target, so it cannot be recomputed from the frame's size — and a+ // pass that left 1024x1024 behind magnified the whole scene four times.+ const GfxDevice::Viewport sceneViewport = device_.viewport();+ device_.beginRenderPass(pass);+ device_.setViewport(0, 0, kShadowMapSize, kShadowMapSize);++ view_projection_ = lightVP;+ frustum_.extractFromMatrix(lightVP);+ pool_.beginFrame();+ draw_list_.clear();++ auto ctx = makeContext();+ ctx.shadow_pass = true;+ RenderCollectContext collectCtx{registry, frustum_, clip_state_, pool_, draw_list_, ctx,+ computeCameraWorldRect(lightVP)};+ for (auto& plugin : plugins_) plugin->collect(collectCtx);++ draw_list_.finalize(pool_);+ pool_.upload();+ context_.updateFrameConstants(lightVP);+ // The depth variant is still a Lit2D shader and still declares the light block,+ // and a draw whose declared UBO is unbound is undefined behaviour that draws+ // nothing — the whole pass came back empty for exactly this.+ context_.lights().uploadAndBind();+ draw_list_.execute(device_, pool_, context_.materials(), context_.getWhiteTextureId(),+ nullptr, context_.skinUbo());++ rt->unbind();+ device_.invalidatePipelineCache();++ shadow_texture_id_ = static_cast<u32>(rt->getColorTexture());+ context_.lights().setShadow(+ lightVP, glm::vec4(1.0f, kShadowBias, 1.0f / static_cast<f32>(kShadowMapSize),+ static_cast<f32>(shadow_light_slot_)));++ // Back to the frame's own target and camera. The scene has drawn nothing yet, so+ // re-opening the pass costs a load rather than the frame's contents.+ view_projection_ = sceneVP;+ frustum_.extractFromMatrix(sceneVP);+ pool_.beginFrame();+ draw_list_.clear();+ openPass(PassClear{}, current_target_);+ device_.setViewport(sceneViewport.x, sceneViewport.y, sceneViewport.w, sceneViewport.h);+}+void RenderFrame::collectAll(ecs::Registry& registry, u32 skipFlags) {ES_PROFILE_SCOPE("render.collect");buildClipState();collectLights(registry);+ renderShadowMap(registry);auto ctx = makeContext();diff --git a/src/esengine/renderer/frame/RenderFrame.hpp b/src/esengine/renderer/frame/RenderFrame.hppindex 1f1a49429..87956420e 100644--- a/src/esengine/renderer/frame/RenderFrame.hpp+++ b/src/esengine/renderer/frame/RenderFrame.hpp@@ -292,10 +292,29 @@ private:/// (point/directional into the light array, ambient summed). Run each frame in collectAll;/// flush() uploads + binds the result so Lit2D material shaders read it.void collectLights(ecs::Registry& registry);+ /**+ * @brief Draws the scene's mesh occluders from the shadow-casting light, into a map+ * the main pass samples.+ * @details Runs at the top of collectAll and re-opens the frame's own target behind+ * itself. A no-op unless collectLights found a Directional light asking for+ * one: the map is one per frame, the receiving shader having one of each.+ */+ void renderShadowMap(ecs::Registry& registry);+ /// Opens the frame's own target with @p clear's load-op. Shared by begin() and the+ /// shadow pass, which re-opens it after drawing through a target of its own.+ void openPass(const PassClear& clear, RenderTargetManager::Handle target);u32 initBatchShader();resource::ShaderHandle compileBatchVariant(const std::vector<std::string>& features);std::vector<GpuLight2D> light_scratch_; // reused across frames; collectLights only+ /// Which light slot casts the map, and the direction + coverage it asked for.+ /// Written by collectLights, read by renderShadowMap; -1 = nobody asked.+ i32 shadow_light_slot_ = -1;+ glm::vec2 shadow_light_dir_{0.0f};+ f32 shadow_light_extent_ = 0.0f;+ RenderTargetManager::Handle shadow_rt_ = 0;+ /// The map's colour texture, handed to every mesh that receives it. 0 = none this frame.+ u32 shadow_texture_id_ = 0;// processMasks scratch, reused across cameras/frames.std::vector<Entity> mask_scissor_scratch_;diff --git a/src/esengine/renderer/plugins/MeshPlugin.cpp b/src/esengine/renderer/plugins/MeshPlugin.cppindex 948cbcb0f..43d7b23b9 100644--- a/src/esengine/renderer/plugins/MeshPlugin.cpp+++ b/src/esengine/renderer/plugins/MeshPlugin.cpp@@ -66,9 +66,9 @@ u32 skinPose(ecs::Registry& registry, Entity entity, const Mesh& mesh,return count;}-u32 meshVariant(bool normals, bool lit, bool normalMapped, bool skinned) {+u32 meshVariant(bool normals, bool lit, bool normalMapped, bool skinned, bool depthOnly) {return (normals ? 1u : 0u) | (lit ? 2u : 0u) | (normalMapped ? 4u : 0u)- | (skinned ? 8u : 0u);+ | (skinned ? 8u : 0u) | (depthOnly ? 16u : 0u);}} // namespace@@ -97,8 +97,8 @@ void MeshPlugin::init(RenderFrameContext& ctx) {* and unlit geometry carrying normals still has to declare them.*/u32 MeshPlugin::meshProgram(RenderFrameContext& ctx, bool normals, bool lit, bool normalMapped,- bool skinned) {- const u32 variant = meshVariant(normals, lit, normalMapped, skinned);+ bool skinned, bool depthOnly) {+ const u32 variant = meshVariant(normals, lit, normalMapped, skinned, depthOnly);if (mesh_compiled_[variant]) return mesh_programs_[variant];mesh_compiled_[variant] = true;@@ -107,6 +107,10 @@ u32 MeshPlugin::meshProgram(RenderFrameContext& ctx, bool normals, bool lit, booif (lit) features.emplace_back("LIT");if (normalMapped) features.emplace_back("NORMAL_MAP");if (skinned) features.emplace_back("SKINNED");+ 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 — the batch stream's are a per-vertex merge product.+ else if (lit) features.emplace_back("ES_RECEIVE_SHADOW");// Authored as mesh.esshader, WGSL twin included. Its vertex stage is the one// that reads a model matrix, which is what lets the vertices stay local.@@ -161,6 +165,10 @@ void MeshPlugin::collect(RenderCollectContext& collect_ctx) {// own, and the inline payload's are recomputed on upload. Reading the// component's for a resident mesh would cull it against an empty box.const Mesh* resident = mesh.mesh.isValid() ? ctx.resources.getMesh(mesh.mesh) : nullptr;+ // Only GPU-resident geometry casts: the inline payload takes the CPU path+ // below, which bakes world space into vertices for the BATCH shader — a+ // shader that writes colour, not the depth this pass is here to collect.+ if (ctx.shadow_pass && !resident) continue;const glm::vec3 localMin = resident ? resident->localMin : glm::vec3(mesh.localMin, 0.0f);const glm::vec3 localMax = resident ? resident->localMax : glm::vec3(mesh.localMax, 0.0f);@@ -193,6 +201,7 @@ void MeshPlugin::collect(RenderCollectContext& collect_ctx) {.blend = BlendMode::Normal,.textureId = textureId,.normalTextureId = normalTextureId,+ .shadowTextureId = ctx.shadow_texture_id,.depth = position.z,.y = position.y,.entity = entity,@@ -210,6 +219,18 @@ void MeshPlugin::collect(RenderCollectContext& collect_ctx) {}if (mesh.cullBackfaces) key.cull = static_cast<u8>(CullMode::Back);+ // Casting into a shadow map: every occluder is opaque and depth-tested for+ // this pass whatever it is in the camera's, because the map holds the+ // NEAREST occluder and a blended one would let a later draw overwrite it.+ if (ctx.shadow_pass) {+ key.stage = RenderStage::Opaque;+ key.blend = BlendMode::None;+ key.depthTest = true;+ key.depthWrite = true;+ key.materialId = 0;+ key.shadowTextureId = 0;+ }+// Material resolve mirrors SpritePlugin: an unregistered handle falls back to// the default batch shader; a material owns shading fully, so it takes// precedence over the lit toggle.@@ -241,7 +262,8 @@ void MeshPlugin::collect(RenderCollectContext& collect_ctx) {// with normals can be drawn unlit, and geometry without them takes// light off the constant normal a 2D surface has.const u32 residentShader =- meshProgram(ctx, resident->hasNormals, mesh.lit, normalTextureId != 0, skinned);+ meshProgram(ctx, resident->hasNormals, mesh.lit && !ctx.shadow_pass,+ normalTextureId != 0 && !ctx.shadow_pass, skinned, ctx.shadow_pass);if (resident->isDrawable() && residentShader != 0) {const u32 stride = skinned ? MESH_INSTANCE_STRIDE_SKINNED: resident->hasNormals ? MESH_INSTANCE_STRIDE_LITdiff --git a/src/esengine/renderer/plugins/MeshPlugin.hpp b/src/esengine/renderer/plugins/MeshPlugin.hppindex d1dd514d3..989867020 100644--- a/src/esengine/renderer/plugins/MeshPlugin.hpp+++ b/src/esengine/renderer/plugins/MeshPlugin.hpp@@ -25,19 +25,19 @@ public:private:std::vector<BatchVertex> scratch_; ///< Reused per mesh; amortizes the transform buffer.- /// Resident-geometry programs, indexed by {has normals, lit, normal-mapped}:- /// what the geometry carries and what the draw asked for are separate- /// questions. Compiled on first use — a scene draws one or two of the five.- std::array<u32, 16> mesh_programs_{};- std::array<bool, 16> mesh_compiled_{};+ /// Resident-geometry programs, indexed by {has normals, lit, normal-mapped,+ /// skinned, depth-only}: what the geometry carries and what the draw asked for+ /// are separate questions. Compiled on first use — a scene draws a few.+ std::array<u32, 32> mesh_programs_{};+ std::array<bool, 32> 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, 16> mesh_shaders_{};+ std::array<resource::ShaderHandle, 32> 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, bool normals, bool lit, bool normalMapped,- bool skinned);+ bool skinned, bool depthOnly = false);bool warned_material_ = false; ///< A material on resident geometry is said once.};diff --git a/src/esengine/renderer/rhi/GLDevice.cpp b/src/esengine/renderer/rhi/GLDevice.cppindex 9350eb54e..eb80b9a09 100644--- a/src/esengine/renderer/rhi/GLDevice.cpp+++ b/src/esengine/renderer/rhi/GLDevice.cpp@@ -404,6 +404,7 @@ bool GLDevice::pollDeviceLost() {// =============================================================================void GLDevice::setViewport(i32 x, i32 y, u32 w, u32 h) {+ viewport_ = {x, y, w, h};glViewport(x, y, static_cast<GLsizei>(w), static_cast<GLsizei>(h));}diff --git a/src/esengine/renderer/rhi/GfxDevice.hpp b/src/esengine/renderer/rhi/GfxDevice.hppindex adaffd1c4..98f35e683 100644--- a/src/esengine/renderer/rhi/GfxDevice.hpp+++ b/src/esengine/renderer/rhi/GfxDevice.hpp@@ -227,6 +227,15 @@ public:/** @brief Sets the rendering viewport */virtual void setViewport(i32 x, i32 y, u32 w, u32 h) = 0;+ /**+ * @brief The viewport last set, so a pass that borrows the device can give it back.+ * @details Mirrored here because neither API this wraps reads it back cheaply, and+ * a pass rendering elsewhere cannot recompute what to restore: a+ * split-screen camera owns only part of the target. Set in setViewport.+ */+ struct Viewport { i32 x = 0, y = 0; u32 w = 0, h = 0; };+ const Viewport& viewport() const { return viewport_; }+// Clears are pass-scoped: RenderPassDesc carries the load-ops AND their values// (color / stencil / optional region). There is no public clear entry point and// no sticky clear state a pass could inherit by accident.@@ -611,6 +620,9 @@ public:virtual GfxLiveObjects liveObjects() const { return {}; }protected:+ /// Backends record what they were last handed; see @ref viewport.+ Viewport viewport_;+/*** @brief Records who this backend is, so a later loss report can name it.* @details Called from init() while the backend still answers, and againdiff --git a/src/esengine/renderer/rhi/Shader.cpp b/src/esengine/renderer/rhi/Shader.cppindex b893390f4..38e97597b 100644--- a/src/esengine/renderer/rhi/Shader.cpp+++ b/src/esengine/renderer/rhi/Shader.cpp@@ -259,6 +259,15 @@ bool Shader::compile(const std::string& vertexSrc, const std::string& fragmentSrdevice_->uniformBlockBinding(program_, drawParamsBlock, DRAW_PARAMS_BINDING);}+ // Engine-injected samplers sit on fixed units, pinned here for the same reason the+ // blocks above are: the header reaches every Lit2D shader, so a compile site that+ // forgot the unit would sample slot 0 silently. GLSL ES 300 has no layout(binding).+ if (hasUniform(SHADOW_MAP_SAMPLER)) {+ bind();+ setUniform(SHADOW_MAP_SAMPLER, static_cast<i32>(SHADOW_MAP_TEXTURE_UNIT));+ unbind();+ }+ES_LOG_DEBUG("Shader compiled successfully (program handle: {}, active uniforms: {})",static_cast<u32>(program_), activeUniforms_.size());return true;diff --git a/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp b/src/esengine/renderer/rhi/ShaderEmbeds.generated.hppindex fefb4a094..baa6b9cb6 100644--- a/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp+++ b/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp@@ -293,6 +293,12 @@ inline constexpr const char* MESH = R"esshader(#pragma shader "Mesh"// channel — which is why this rides LIT rather than a vertex attribute.#pragma feature NORMAL_MAP+// 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+// land where its skinned self lands, and one copy of that is one that cannot drift.+#pragma feature SHADOW_DEPTH+// GPU-resident geometry. Slot 0 is the mesh's own vertices, which are LOCAL// space and are never rewritten; slot 1 is the per-object record the frame// streams, so the same mesh drawn twice costs one more transform rather than@@ -343,6 +349,9 @@ out highp vec3 v_worldNormal;// it changes across a fragment, which xy alone cannot say for a tilted surface.out highp vec3 v_worldPos;#endif+#ifdef SHADOW_DEPTH+out highp float v_shadowDepth;+#endifvoid main() {#ifdef SKINNED@@ -360,6 +369,11 @@ void main() {gl_Position = u_projection * world;v_texCoord = a_texCoord;v_color = a_color * a_instTint;+#ifdef SHADOW_DEPTH+ // The expression the receiver evaluates on u_shadowMatrix, evaluated here on the+ // same matrix: whatever each backend's clip z means, both sides mean it alike.+ v_shadowDepth = clamp(gl_Position.z / gl_Position.w * 0.5 + 0.5, 0.0, 1.0);+#endif#ifdef LIT#if defined(MESH_NORMALS) && defined(SKINNED)v_worldNormal = mat3(skin) * a_normal;@@ -383,6 +397,9 @@ in vec4 v_color;in highp vec3 v_worldNormal;in highp vec3 v_worldPos;#endif+#ifdef SHADOW_DEPTH+in highp float v_shadowDepth;+#endifuniform sampler2D u_texture;#ifdef NORMAL_MAP@@ -392,16 +409,23 @@ uniform sampler2D u_normalMap;out vec4 fragColor;void main() {+#ifdef SHADOW_DEPTH+ fragColor = vec4(packDepth(v_shadowDepth), 1.0);+#elsevec4 base = texture(u_texture, v_texCoord) * v_color;#ifdef LIThighp vec3 N = normalize(v_worldNormal);#ifdef NORMAL_MAPN = perturbNormal(N, v_worldPos, v_texCoord, sampleNormal(u_normalMap, v_texCoord));#endif- fragColor = vec4(applyLighting2D(base.rgb, N, v_worldPos.xy), base.a);+ // The general form at a 2D surface's own parameters, but with the position it+ // really has: a shadow is cast on a point in space, and xy is not one.+ fragColor = vec4(applyLightingPBR(base.rgb, N, v_worldPos, viewDirection(v_worldPos),+ 0.0, 1.0, 0.0, 1.0), base.a);#elsefragColor = base;#endif+#endif}#pragma end@@ -444,6 +468,9 @@ struct VSOut {@location(2) v_worldNormal : vec3f,@location(3) v_worldPos : vec3f,#endif+#ifdef SHADOW_DEPTH+ @location(4) v_shadowDepth : f32,+#endif};@vertex fn vs_main(v : VSIn) -> VSOut {@@ -464,6 +491,11 @@ struct VSOut {out.pos = frame.projection * world;out.v_texCoord = v.a_texCoord;out.v_color = v.a_color * v.a_instTint;+#ifdef SHADOW_DEPTH+ // The expression the receiver evaluates on u_shadowMatrix, evaluated here on the+ // same matrix: whatever each backend's clip z means, both sides mean it alike.+ out.v_shadowDepth = clamp(out.pos.z / out.pos.w * 0.5 + 0.5, 0.0, 1.0);+#endif#ifdef LIT#ifdef MESH_NORMALS#ifdef SKINNED@@ -488,6 +520,12 @@ struct VSOut {@group(1) @binding(1) var t1 : texture_2d<f32>;@group(1) @binding(9) var s1 : sampler;#endif+#ifdef ES_RECEIVE_SHADOW+// The shadow map, on the slot the injected header samples. A fragment-only twin+// gets these from the batch texture contract; one that writes its own says so.+@group(1) @binding(2) var t2 : texture_2d<f32>;+@group(1) @binding(10) var s2 : sampler;+#endifstruct VSOut {@builtin(position) pos : vec4f,@@ -497,19 +535,29 @@ struct VSOut {@location(2) v_worldNormal : vec3f,@location(3) v_worldPos : vec3f,#endif+#ifdef SHADOW_DEPTH+ @location(4) v_shadowDepth : f32,+#endif};@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {+#ifdef SHADOW_DEPTH+ return vec4f(packDepth(v.v_shadowDepth), 1.0);+#elselet base = textureSampleLevel(t0, s0, v.v_texCoord, 0.0) * v.v_color;#ifdef LITvar N = normalize(v.v_worldNormal);#ifdef NORMAL_MAPN = perturbNormal(N, v.v_worldPos, v.v_texCoord, sampleNormal(t1, s1, v.v_texCoord));#endif- return vec4f(applyLighting2D(base.rgb, N, v.v_worldPos.xy), base.a);+ // The general form at a 2D surface's own parameters, but with the position it+ // really has: a shadow is cast on a point in space, and xy is not one.+ return vec4f(applyLightingPBR(base.rgb, N, v.v_worldPos, viewDirection(v.v_worldPos),+ 0.0, 1.0, 0.0, 1.0), base.a);#elsereturn base;#endif+#endif}#pragma end)esshader";diff --git a/src/esengine/renderer/store/LightConstants.hpp b/src/esengine/renderer/store/LightConstants.hppindex 8eb804ece..635a597d4 100644--- a/src/esengine/renderer/store/LightConstants.hpp+++ b/src/esengine/renderer/store/LightConstants.hpp@@ -24,6 +24,15 @@ inline constexpr u32 LIGHT_CONSTANTS_BINDING = 2;/** @brief GLSL block name; must match ShaderParser's injected block + Shader::compile lookup. */inline constexpr const char* LIGHT_CONSTANTS_BLOCK = "LightConstants";+/**+ * @brief The injected shadow-map sampler, and the texture unit Shader::compile pins it to.+ * @details Every Lit2D shader gets the sampler from the injected header, so the unit is a+ * contract rather than something each compile site repeats. Slot 2 sits after the+ * draw's own two (base colour, normal map) — see BatchBuilder's slot assembly.+ */+inline constexpr const char* SHADOW_MAP_SAMPLER = "u_shadowMap";+inline constexpr u32 SHADOW_MAP_TEXTURE_UNIT = 2;+/*** @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@@ -74,10 +83,18 @@ struct LightConstants {/// fragment→light segment (or, for directional, the fragment→far-along-light-dir segment)/// crosses any box.glm::vec4 occluders[MAX_OCCLUDERS_2D];+ /// World -> the shadow map's clip space, for the one directional light casting one.+ /// Identity when none does; `shadowParams.x` is what says whether to read it.+ glm::mat4 shadowMatrix{1.0f};+ /// x = 1 when a shadow map was rendered this frame — the master switch, so w's+ /// zeroed default cannot darken slot 0 before one exists; y = depth bias in the+ /// map's own [0,1] units; z = one texel of it; w = the light slot that cast it.+ glm::vec4 shadowParams{0.0f};};static_assert(sizeof(GpuLight2D) == 64, "GpuLight2D must be std140-tight (four vec4s)");-static_assert(sizeof(LightConstants) == 16 + 64 * MAX_LIGHTS_2D + 16 + 16 * MAX_OCCLUDERS_2D,+static_assert(sizeof(LightConstants) == 16 + 64 * MAX_LIGHTS_2D + 16 + 16 * MAX_OCCLUDERS_2D+ + 64 + 16,"LightConstants must match the std140 GLSL block layout");} // namespace esenginediff --git a/src/esengine/renderer/store/LightStore.hpp b/src/esengine/renderer/store/LightStore.hppindex 87317cac8..027d39895 100644--- a/src/esengine/renderer/store/LightStore.hpp+++ b/src/esengine/renderer/store/LightStore.hpp@@ -68,6 +68,15 @@ public:dirty_ = true;}+ /// Hands over the shadow map a frame rendered: the world -> map matrix, and the+ /// params whose x is the master switch. Called with a zeroed `params` when no+ /// light cast one, so a stale matrix cannot outlive the map it belonged to.+ void setShadow(const glm::mat4& matrix, const glm::vec4& params) {+ data_.shadowMatrix = matrix;+ data_.shadowParams = params;+ dirty_ = true;+ }+/// Appends a world-space AABB occluder (minX, minY, maxX, maxY). Silently drops past/// MAX_OCCLUDERS_2D. With no occluders added, the injected shader shadow test is a no-op.void addOccluder(const glm::vec4& box) {diff --git a/src/esengine/renderer/store/MaterialStore.cpp b/src/esengine/renderer/store/MaterialStore.cppindex 9b27e371c..dabf78caf 100644--- a/src/esengine/renderer/store/MaterialStore.cpp+++ b/src/esengine/renderer/store/MaterialStore.cpp@@ -71,6 +71,9 @@ u32 MaterialStore::meshProgram(u32 materialId, resource::ResourceManager& resourfeatures.push_back("MESH");if (withNormals) features.push_back("MESH_NORMALS");if (skinned) features.push_back("SKINNED");+ // Resident geometry carries the frame's shadow map on its own slot 2; the batch+ // variant of the same material must not, which is why this rides the mesh path.+ features.push_back("ES_RECEIVE_SHADOW");const auto target = resources.preferredShaderTarget();const std::string vert = resource::ShaderParser::assembleStage(parsed, resource::ShaderStage::Vertex, "", features, target);diff --git a/src/esengine/renderer/webgpu/WebGPUDevice.cpp b/src/esengine/renderer/webgpu/WebGPUDevice.cppindex dd78bcd3c..282f6065c 100644--- a/src/esengine/renderer/webgpu/WebGPUDevice.cpp+++ b/src/esengine/renderer/webgpu/WebGPUDevice.cpp@@ -507,6 +507,7 @@ i32 WebGPUDevice::flipRectY(i32 y, i32 height) const {}void WebGPUDevice::setViewport(i32 x, i32 y, u32 w, u32 h) {+ viewport_ = {x, y, w, h};if (pass_) {wgpuRenderPassEncoderSetViewport(pass_, static_cast<f32>(x),static_cast<f32>(flipRectY(y, static_cast<i32>(h))),diff --git a/src/esengine/resource/ShaderParser.cpp b/src/esengine/resource/ShaderParser.cppindex 9ff06a065..af0618e19 100644--- a/src/esengine/resource/ShaderParser.cpp+++ b/src/esengine/resource/ShaderParser.cpp@@ -731,8 +731,38 @@ struct LightConstants {u_lights : array<Light2D, 16>,u_occluderCount : vec4f,u_occluders : array<vec4f, 8>,+ u_shadowMatrix : mat4x4f,+ u_shadowParams : vec4f,};@group(0) @binding(2) var<uniform> lc : LightConstants;+fn packDepth(d : f32) -> vec3f {+ let enc = fract(d * vec3f(1.0, 255.0, 65025.0));+ return enc - enc.yzz * vec3f(1.0 / 255.0, 1.0 / 255.0, 0.0);+}+fn unpackDepth(c : vec3f) -> f32 {+ return dot(c, vec3f(1.0, 1.0 / 255.0, 1.0 / 65025.0));+}+fn shadowFactor3D(worldPos : vec3f) -> f32 {+#ifndef ES_RECEIVE_SHADOW+ return 1.0;+#else+ if (lc.u_shadowParams.x < 0.5) { return 1.0; }+ let lcp = lc.u_shadowMatrix * vec4f(worldPos, 1.0);+ let proj = lcp.xyz / lcp.w;+ let uv = proj.xy * 0.5 + 0.5;+ let here = clamp(proj.z * 0.5 + 0.5, 0.0, 1.0) - lc.u_shadowParams.y;+ if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) { return 1.0; }+ var lit = 0.0;+ for (var y = 0; y < 2; y++) {+ for (var x = 0; x < 2; x++) {+ let o = (vec2f(f32(x), f32(y)) - 0.5) * lc.u_shadowParams.z;+ let d = unpackDepth(textureSampleLevel(t2, s2, uv + o, 0.0).rgb);+ if (d >= here) { lit += 1.0; }+ }+ }+ return lit * 0.25;+#endif+}fn sampleNormal(map : texture_2d<f32>, samp : sampler, uv : vec2f) -> vec3f {return normalize(textureSampleLevel(map, samp, uv, 0.0).xyz * 2.0 - 1.0);}@@ -858,6 +888,9 @@ fn applyLightingPBR(albedo : vec3f, N : vec3f, worldPos : vec3f, V : vec3f, metaif (castShadow && col.a > 0.0 && atten > 0.0) {atten *= shadowFactor2D(worldPos.xy, aim, sh.x);}+ if (f32(i) == lc.u_shadowParams.w && atten > 0.0) {+ atten *= shadowFactor3D(worldPos);+ }let ndotl = max(dot(N, L), 0.0);let radiance = col.rgb * (col.a * ndotl * atten);lit += radiance;@@ -1174,7 +1207,50 @@ ShaderParser::AssembledStage ShaderParser::assembleStageEx(const ParsedShader& p" Light2D u_lights[16];\n"" highp vec4 u_occluderCount;\n" // x = active occluder count" highp vec4 u_occluders[8];\n" // world AABBs (minX,minY,maxX,maxY)+ " highp mat4 u_shadowMatrix;\n" // world -> shadow map clip+ " highp vec4 u_shadowParams;\n" // x = has map, y = bias, z = texel"};\n"+ // The shadow map rides the draw's third texture slot, behind the feature the+ // MESH vertex sources set: the batch stream owns 0..7 as a per-vertex merge+ // product, so a sampler pinned to slot 2 there would read someone's sprite.+ "#ifdef ES_RECEIVE_SHADOW\n"+ "uniform highp sampler2D u_shadowMap;\n"+ "#endif\n"+ // 24 bits of depth across RGB — an 8-bit target is what both backends have+ // in common, and a metre of world depth does not survive 8 of them. The+ // pair lives together: two files would be two chances to disagree.+ "highp vec3 packDepth(in highp float d) {\n"+ " highp vec3 enc = fract(d * vec3(1.0, 255.0, 65025.0));\n"+ " return enc - enc.yzz * vec3(1.0 / 255.0, 1.0 / 255.0, 0.0);\n"+ "}\n"+ "highp float unpackDepth(in highp vec3 c) {\n"+ " return dot(c, vec3(1.0, 1.0 / 255.0, 1.0 / 65025.0));\n"+ "}\n"+ // Visibility of a world point from the light that rendered the map. Depth is+ // written and compared through the SAME matrix and expression, so the two+ // backends' clip-z conventions cancel. 2x2 taps: one is a staircase.+ "highp float shadowFactor3D(in highp vec3 worldPos) {\n"+ "#ifndef ES_RECEIVE_SHADOW\n"+ " return 1.0;\n"+ "#else\n"+ " if (u_shadowParams.x < 0.5) return 1.0;\n"+ " highp vec4 lc = u_shadowMatrix * vec4(worldPos, 1.0);\n"+ " highp vec3 proj = lc.xyz / lc.w;\n"+ " highp vec2 uv = proj.xy * 0.5 + 0.5;\n"+ " highp float here = clamp(proj.z * 0.5 + 0.5, 0.0, 1.0) - u_shadowParams.y;\n"+ // Outside the map is lit: a shadow map covers what the camera can see, and+ // darkening everything beyond it would be a visible square of night.+ " if (uv.x < 0.0 || uv.x > 1.0 || uv.y < 0.0 || uv.y > 1.0) return 1.0;\n"+ " highp float lit = 0.0;\n"+ " for (int y = 0; y < 2; ++y) {\n"+ " for (int x = 0; x < 2; ++x) {\n"+ " highp vec2 o = (vec2(float(x), float(y)) - 0.5) * u_shadowParams.z;\n"+ " lit += unpackDepth(texture(u_shadowMap, uv + o).rgb) < here ? 0.0 : 1.0;\n"+ " }\n"+ " }\n"+ " return lit * 0.25;\n"+ "#endif\n"+ "}\n"// Engine-owned normal-map convention (RGB[0,1] -> normal[-1,1], normalized), so every// Lit2D shader unpacks tangent-space normals the same way. 2D applies it screen-space// (no per-sprite tangent frame); a flat surface uses vec3(0,0,1).@@ -1337,6 +1413,11 @@ ShaderParser::AssembledStage ShaderParser::assembleStageEx(const ParsedShader& p" if (castShadow && col.a > 0.0 && atten > 0.0) {\n"" atten *= shadowFactor2D(worldPos.xy, target, sh.x);\n"" }\n"+ // One map, one light: params.w names the slot that rendered it, so the+ // other fifteen are not darkened by someone else's occluders.+ " if (float(i) == u_shadowParams.w && atten > 0.0) {\n"+ " atten *= shadowFactor3D(worldPos);\n"+ " }\n"" highp float ndotl = max(dot(N, L), 0.0);\n"" highp vec3 radiance = col.rgb * (col.a * ndotl * atten);\n"" lit += radiance;\n"diff --git a/tests/renderer/test_draw_params.cpp b/tests/renderer/test_draw_params.cppindex e6b4defcd..61baa1897 100644--- a/tests/renderer/test_draw_params.cpp+++ b/tests/renderer/test_draw_params.cpp@@ -148,8 +148,11 @@ int main() {shader->setUniform("u_intensity", 0.5f);CHECK(d.setUniform1fCalls == 0, "lifted float write issues no loose upload");+ // compile() already seeded the engine-injected shadow sampler, so this is the+ // second loose int write rather than the first.+ const int seeded = d.setUniform1iCalls;shader->setUniform("u_texture", 3);- CHECK(d.setUniform1iCalls == 1, "sampler still goes through the loose path");+ CHECK(d.setUniform1iCalls == seeded + 1, "sampler still goes through the loose path");// First commit creates the UBO from the shadow and binds slot 4.shader->commitParams();diff --git a/tests/renderer/test_shader_device.cpp b/tests/renderer/test_shader_device.cppindex 926ef7d78..46e746c38 100644--- a/tests/renderer/test_shader_device.cpp+++ b/tests/renderer/test_shader_device.cpp@@ -6,6 +6,7 @@#include "MockGfxDevice.hpp"#include "esengine/renderer/rhi/Shader.hpp"+#include "esengine/renderer/store/LightConstants.hpp"#include <cstdio>@@ -29,17 +30,24 @@ int main() {CHECK(shader->getProgramId() == 1, "programId is the device-returned id");CHECK(d.getActiveUniformsCalls == 1, "reflection routes through device.getActiveUniforms");+ // compile() pins the engine-injected samplers to their units, so the counts+ // the rest of this block asserts start from what that seeding left behind.+ CHECK(d.setUniform1iCalls == 1+ && d.lastUniform1iVal == static_cast<i32>(SHADOW_MAP_TEXTURE_UNIT),+ "compile pins the injected shadow sampler to its texture unit");+ CHECK(d.useProgramCalls == 2, "seeding it binds and unbinds the program");+shader->setUniform("u_tex", 3);- CHECK(d.setUniform1iCalls == 1, "setUniform(name,int) routes through device.setUniform1i");+ CHECK(d.setUniform1iCalls == 2, "setUniform(name,int) routes through device.setUniform1i");CHECK(d.lastUniform1iVal == 3, "uniform value forwarded");shader->setUniform("u_color", glm::vec4(1, 0, 0, 1));CHECK(d.setUniform4fCalls == 1, "setUniform(name,vec4) routes through device.setUniform4f");shader->bind();- CHECK(d.useProgramCalls == 1 && d.lastProgram == ShaderHandle{1}, "bind routes through device.useProgram");+ CHECK(d.useProgramCalls == 3 && d.lastProgram == ShaderHandle{1}, "bind routes through device.useProgram");shader->unbind();- CHECK(d.useProgramCalls == 2 && d.lastProgram == ShaderHandle::Invalid,+ CHECK(d.useProgramCalls == 4 && d.lastProgram == ShaderHandle::Invalid,"unbind routes through device.useProgram(Invalid)");// shader destructed at scope end -> device.deleteProgramdiff --git a/tools/renderScenes.mjs b/tools/renderScenes.mjsindex 095d6724e..0abad2827 100644--- a/tools/renderScenes.mjs+++ b/tools/renderScenes.mjs@@ -52,6 +52,10 @@ export const SCENES = [// and there was no skinned one, so a skinned mesh fell back to the engine's// shader and ignored what it was made of (sabotage: the probes come back white).{ id: "mesh-skin-material", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mesh-skin-mat.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.35,\"y\":0.6,\"rgb\":[0,0,255],\"tol\":30},{\"x\":0.75,\"y\":0.35,\"rgb\":[0,0,255],\"tol\":30},{\"x\":0.75,\"y\":0.60,\"rgb\":[0,0,0],\"tol\":20}]" } },+ // A mesh casting on a mesh: a floor 200 units below a blocker, sun leaning 0.5 in+ // x, so the shadow lands 100 along +x and x 75..175 is floor the light cannot see.+ // The blocker itself stays lit — shadowing one's own caster is the classic bug.+ { id: "mesh-shadow", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_SCENE: "/scenes/mesh-shadow.esscene", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "2", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.708,\"y\":0.5,\"rgb\":[0,0,0],\"tol\":20},{\"x\":0.167,\"y\":0.5,\"rgb\":[228,228,228],\"tol\":20},{\"x\":0.5,\"y\":0.5,\"rgb\":[228,228,228],\"tol\":20}]" } },// A glTF animation, through the shipped importer. The scene puts the quad at// x=150 and the clip runs -120 to 120 over a second, so 30 fixed steps is its// midpoint: the model is at the origin and where the SCENE put it is empty.