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(renderer): built-in lit rendering — Sprite.lit toggle, fragment-only shaders, material templates

yhhf16e9df8ff90
diff --git a/desktop/package.json b/desktop/package.json
index a9157a9c5..e1d0ff656 100644
--- a/desktop/package.json
+++ b/desktop/package.json
@@ -44,6 +44,8 @@
"verify:render:material:lit:normal": "vite build && ESTELLA_VERIFY_SCENE=/scenes/mat-lit-normal.esscene ESTELLA_VERIFY_MANIFEST=/scenes/mat-lit-normal.textures.json ESTELLA_VERIFY_W=256 ESTELLA_VERIFY_H=256 ESTELLA_VERIFY_STEPS=2 ESTELLA_VERIFY_EXPECT=\"[{\\\"x\\\":0.333,\\\"y\\\":0.5,\\\"rgb\\\":[0,252,0],\\\"tol\\\":45},{\\\"x\\\":0.667,\\\"y\\\":0.5,\\\"rgb\\\":[0,36,0],\\\"tol\\\":50}]\" electron scripts/headless-verify.mjs",
"verify:render:material:lit:spot": "vite build && ESTELLA_VERIFY_SCENE=/scenes/mat-lit-spot.esscene ESTELLA_VERIFY_MANIFEST=/scenes/mat-lit-spot.textures.json ESTELLA_VERIFY_W=256 ESTELLA_VERIFY_H=256 ESTELLA_VERIFY_STEPS=2 ESTELLA_VERIFY_EXPECT=\"[{\\\"x\\\":0.5,\\\"y\\\":0.5,\\\"rgb\\\":[0,228,0],\\\"tol\\\":55},{\\\"x\\\":0.75,\\\"y\\\":0.5,\\\"rgb\\\":[0,0,0],\\\"tol\\\":35}]\" electron scripts/headless-verify.mjs",
"verify:render:material:lit:flatnormal": "vite build && ESTELLA_VERIFY_SCENE=/scenes/mat-lit-flatnormal.esscene ESTELLA_VERIFY_MANIFEST=/scenes/mat-lit-flatnormal.textures.json ESTELLA_VERIFY_W=256 ESTELLA_VERIFY_H=256 ESTELLA_VERIFY_STEPS=2 ESTELLA_VERIFY_EXPECT=\"[{\\\"x\\\":0.5,\\\"y\\\":0.5,\\\"rgb\\\":[0,255,0],\\\"tol\\\":30}]\" electron scripts/headless-verify.mjs",
+ "verify:render:sprite:lit": "vite build && ESTELLA_VERIFY_SCENE=/scenes/sprite-lit.esscene ESTELLA_VERIFY_MANIFEST=/scenes/sprite-lit.textures.json ESTELLA_VERIFY_W=256 ESTELLA_VERIFY_H=256 ESTELLA_VERIFY_STEPS=2 ESTELLA_VERIFY_EXPECT=\"[{\\\"x\\\":0.5,\\\"y\\\":0.5,\\\"rgb\\\":[0,255,0],\\\"tol\\\":30}]\" electron scripts/headless-verify.mjs",
+ "verify:render:material:builtin:lit": "vite build && ESTELLA_VERIFY_SCENE=/scenes/mat-builtin-lit.esscene ESTELLA_VERIFY_MANIFEST=/scenes/mat-builtin-lit.textures.json ESTELLA_VERIFY_W=256 ESTELLA_VERIFY_H=256 ESTELLA_VERIFY_STEPS=2 ESTELLA_VERIFY_EXPECT=\"[{\\\"x\\\":0.5,\\\"y\\\":0.5,\\\"rgb\\\":[0,255,0],\\\"tol\\\":30}]\" electron scripts/headless-verify.mjs",
"verify:render:material:graph": "vite build && ESTELLA_VERIFY_SCENE=/scenes/mat-graph.esscene ESTELLA_VERIFY_MANIFEST=/scenes/mat-graph.textures.json ESTELLA_VERIFY_W=256 ESTELLA_VERIFY_H=256 ESTELLA_VERIFY_STEPS=2 ESTELLA_VERIFY_EXPECT=\"[{\\\"x\\\":0.5,\\\"y\\\":0.5,\\\"rgb\\\":[255,0,0],\\\"tol\\\":40}]\" electron scripts/headless-verify.mjs",
"verify:render:material:preview": "vite build && ESTELLA_VERIFY_SCENE=/scenes/mat-tint.esscene ESTELLA_VERIFY_MANIFEST=/scenes/mat-tint.textures.json ESTELLA_VERIFY_W=256 ESTELLA_VERIFY_H=256 ESTELLA_VERIFY_STEPS=2 ESTELLA_VERIFY_PREVIEW=\"{\\\"w\\\":64,\\\"h\\\":64,\\\"rgb\\\":[255,0,0],\\\"tol\\\":45}\" electron scripts/headless-verify.mjs",
"verify:smoke": "vite build && electron scripts/headless-smoke.mjs",
diff --git a/desktop/public/scenes/mat-builtin-lit.esscene b/desktop/public/scenes/mat-builtin-lit.esscene
new file mode 100644
index 000000000..e7dc9bad2
--- /dev/null
+++ b/desktop/public/scenes/mat-builtin-lit.esscene
@@ -0,0 +1,53 @@
+{
+ "version": "1.0",
+ "name": "Main",
+ "entities": [
+ {
+ "id": 0,
+ "name": "Camera",
+ "parent": null,
+ "children": [],
+ "components": [
+ { "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": 10 } } },
+ { "type": "Camera", "data": { "projectionType": 1, "orthoSize": 300, "isActive": true, "priority": 0 } }
+ ],
+ "visible": true
+ },
+ {
+ "id": 1,
+ "name": "Lit",
+ "parent": null,
+ "children": [],
+ "components": [
+ { "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": 0 } } },
+ {
+ "type": "Sprite",
+ "data": {
+ "size": { "x": 400, "y": 400 },
+ "color": { "r": 1, "g": 1, "b": 1, "a": 1 },
+ "material": "/scenes/mat-builtin-lit/lit.esmaterial"
+ }
+ }
+ ],
+ "visible": true
+ },
+ {
+ "id": 2,
+ "name": "GreenLight",
+ "parent": null,
+ "children": [],
+ "components": [
+ { "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": 0 } } },
+ {
+ "type": "Light2D",
+ "data": {
+ "type": 1,
+ "color": { "r": 0, "g": 1, "b": 0, "a": 1 },
+ "intensity": 1
+ }
+ }
+ ],
+ "visible": true
+ }
+ ]
+}
diff --git a/desktop/public/scenes/mat-builtin-lit.textures.json b/desktop/public/scenes/mat-builtin-lit.textures.json
new file mode 100644
index 000000000..0967ef424
--- /dev/null
+++ b/desktop/public/scenes/mat-builtin-lit.textures.json
@@ -0,0 +1 @@
+{}
diff --git a/desktop/public/scenes/mat-builtin-lit/lit.esmaterial b/desktop/public/scenes/mat-builtin-lit/lit.esmaterial
new file mode 100644
index 000000000..ac92f1385
--- /dev/null
+++ b/desktop/public/scenes/mat-builtin-lit/lit.esmaterial
@@ -0,0 +1,8 @@
+{
+ "version": "1.0",
+ "type": "material",
+ "shader": "lit.esshader",
+ "blendMode": 0,
+ "depthTest": false,
+ "properties": {}
+}
diff --git a/desktop/public/scenes/mat-builtin-lit/lit.esshader b/desktop/public/scenes/mat-builtin-lit/lit.esshader
new file mode 100644
index 000000000..49d65cc67
--- /dev/null
+++ b/desktop/public/scenes/mat-builtin-lit/lit.esshader
@@ -0,0 +1,24 @@
+#pragma shader "Sprite Lit"
+#pragma version 300 es
+#pragma domain Lit2D
+#pragma param u_tint color default(1,1,1,1)
+#pragma param u_normalMap texture default(flatnormal)
+
+#pragma fragment
+precision mediump float;
+
+in vec4 v_color;
+in vec2 v_texCoord;
+in highp vec2 v_worldPos;
+
+uniform sampler2D u_textures[8];
+
+out vec4 fragColor;
+
+// Unset u_normalMap = flat normal, so lighting works with no normal map assigned.
+void main() {
+ vec4 base = texture(u_textures[0], v_texCoord) * v_color * u_tint;
+ vec3 N = es_sampleNormal(u_normalMap, v_texCoord);
+ fragColor = vec4(es_applyLighting2D(base.rgb, N, v_worldPos), base.a);
+}
+#pragma end
diff --git a/desktop/public/scenes/sprite-lit.esscene b/desktop/public/scenes/sprite-lit.esscene
new file mode 100644
index 000000000..6eba99e5f
--- /dev/null
+++ b/desktop/public/scenes/sprite-lit.esscene
@@ -0,0 +1,53 @@
+{
+ "version": "1.0",
+ "name": "Main",
+ "entities": [
+ {
+ "id": 0,
+ "name": "Camera",
+ "parent": null,
+ "children": [],
+ "components": [
+ { "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": 10 } } },
+ { "type": "Camera", "data": { "projectionType": 1, "orthoSize": 300, "isActive": true, "priority": 0 } }
+ ],
+ "visible": true
+ },
+ {
+ "id": 1,
+ "name": "LitSprite",
+ "parent": null,
+ "children": [],
+ "components": [
+ { "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": 0 } } },
+ {
+ "type": "Sprite",
+ "data": {
+ "size": { "x": 400, "y": 400 },
+ "color": { "r": 1, "g": 1, "b": 1, "a": 1 },
+ "lit": true
+ }
+ }
+ ],
+ "visible": true
+ },
+ {
+ "id": 2,
+ "name": "GreenLight",
+ "parent": null,
+ "children": [],
+ "components": [
+ { "type": "Transform", "data": { "position": { "x": 0, "y": 0, "z": 0 } } },
+ {
+ "type": "Light2D",
+ "data": {
+ "type": 1,
+ "color": { "r": 0, "g": 1, "b": 0, "a": 1 },
+ "intensity": 1
+ }
+ }
+ ],
+ "visible": true
+ }
+ ]
+}
diff --git a/desktop/public/scenes/sprite-lit.textures.json b/desktop/public/scenes/sprite-lit.textures.json
new file mode 100644
index 000000000..0967ef424
--- /dev/null
+++ b/desktop/public/scenes/sprite-lit.textures.json
@@ -0,0 +1 @@
+{}
diff --git a/desktop/src/material/openMaterial.ts b/desktop/src/material/openMaterial.ts
index ae9000029..e6445d5a3 100644
--- a/desktop/src/material/openMaterial.ts
+++ b/desktop/src/material/openMaterial.ts
@@ -3,61 +3,17 @@
/**
* @file openMaterial.ts
* @brief Open / create a `.esmaterial` from the Content Browser. Mirrors openTileset.ts
- * (open + create + .meta + registry re-scan). A new material is born with its own
- * default unlit `.esshader` (a `u_tint` color param) so it renders and is editable
- * immediately; a material instance writes only its parent ref (UE MIC).
+ * (open + create + .meta + registry re-scan). A new material is born from a
+ * built-in shader template (Unlit / Lit); a material instance writes only its
+ * parent ref (UE MIC).
*/
-import type { MaterialAssetData } from 'esengine';
+import { builtinShaderTemplate, type MaterialAssetData } from 'esengine';
import { ProjectStore } from '@/project/ProjectStore';
import { dockApi } from '@/layout/dockApi';
import { useSelection } from '@/store/selectionStore';
import { baseName } from '@/project/assetMeta';
import { Toasts } from '@/store/Toasts';
-// Default material shader: the batch vertex layout + an unlit fragment that tints the sampled
-// texture by the per-instance color and a `u_tint` material param (the auto-generated
-// MaterialConstants block supplies u_tint). Gives a new material a visible, editable param.
-const DEFAULT_MATERIAL_SHADER = `#pragma shader "Material"
-#pragma version 300 es
-#pragma domain Unlit2D
-#pragma param u_tint color default(1,1,1,1)
-
-#pragma vertex
-layout(location = 0) in vec2 a_position;
-layout(location = 1) in vec4 a_color;
-layout(location = 2) in vec2 a_texCoord;
-layout(location = 3) in float a_texIndex;
-
-layout(std140) uniform FrameConstants {
- mat4 u_projection;
-};
-
-out vec4 v_color;
-out vec2 v_texCoord;
-
-void main() {
- gl_Position = u_projection * vec4(a_position, 0.0, 1.0);
- v_color = a_color;
- v_texCoord = a_texCoord;
-}
-#pragma end
-
-#pragma fragment
-precision mediump float;
-
-in vec4 v_color;
-in vec2 v_texCoord;
-
-uniform sampler2D u_textures[8];
-
-out vec4 fragColor;
-
-void main() {
- fragColor = texture(u_textures[0], v_texCoord) * v_color * u_tint;
-}
-#pragma end
-`;
-
/**
* Open a `.esmaterial` for editing: select it so the unified Details inspector edits it inline
* (reflection-driven Parameters + Render State), and reveal the Details panel. There is no
@@ -82,10 +38,15 @@ async function writeMeta(rel: string): Promise<void> {
);
}
-/** Create a new base material (+ its own default shader) in @p dir, then open it. */
-export async function createMaterial(dir: string): Promise<void> {
+/** Create a new base material (+ its own shader from a builtin template) in @p dir, then open it. */
+export async function createMaterial(dir: string, templateId = 'sprite-unlit'): Promise<void> {
+ const template = builtinShaderTemplate(templateId);
+ if (!template) {
+ Toasts.push(`未知材质模板:${templateId}`, 'error');
+ return;
+ }
const folder = dir ? (dir.endsWith('/') ? dir : `${dir}/`) : '';
- const matRel = uniqueMaterialPath(folder, 'NewMaterial');
+ const matRel = uniqueMaterialPath(folder, `New${template.label}Material`);
const base = baseName(matRel).replace(/\.esmaterial$/, '');
const shaderRel = `${folder}${base}.esshader`;
@@ -97,11 +58,11 @@ export async function createMaterial(dir: string): Promise<void> {
depthTest: false,
depthWrite: true,
cull: 0,
- properties: { u_tint: { r: 1, g: 1, b: 1, a: 1 } },
+ properties: structuredClone(template.defaults) as MaterialAssetData['properties'],
};
try {
- await window.estella.fs.write(shaderRel, DEFAULT_MATERIAL_SHADER);
+ await window.estella.fs.write(shaderRel, template.source);
await window.estella.fs.write(matRel, JSON.stringify(asset, null, 2) + '\n');
await writeMeta(matRel);
} catch (e) {
diff --git a/desktop/src/panels/ContentBrowser.tsx b/desktop/src/panels/ContentBrowser.tsx
index 84b57b621..b07524440 100644
--- a/desktop/src/panels/ContentBrowser.tsx
+++ b/desktop/src/panels/ContentBrowser.tsx
@@ -558,7 +558,8 @@ export function ContentBrowser() {
{ label: 'New Scene', onClick: () => void newScene() },
{ label: 'New Animation', onClick: () => void createAnimationClip(cwd) },
{ label: 'New Input Map', onClick: () => void newInputMap() },
- { label: 'New Material', onClick: () => void createMaterial(cwd) },
+ { label: 'New Material (Unlit)', onClick: () => void createMaterial(cwd, 'sprite-unlit') },
+ { label: 'New Material (Lit)', onClick: () => void createMaterial(cwd, 'sprite-lit') },
{ label: 'New Material Graph', onClick: () => void createMaterialGraph(cwd) },
{ label: 'New State Machine', onClick: () => void createStateMachine(cwd) },
{ label: 'New Behavior Tree', onClick: () => void createBehaviorTree(cwd) },
diff --git a/docs/astro/src/content/docs/guides/lighting.mdx b/docs/astro/src/content/docs/guides/lighting.mdx
index c1a3ec560..979c1bd43 100644
--- a/docs/astro/src/content/docs/guides/lighting.mdx
+++ b/docs/astro/src/content/docs/guides/lighting.mdx
@@ -74,19 +74,28 @@ const addSun = defineSystem([Commands()], (cmds) => {
## Making a renderer receive light
-By default a `Sprite` draws with an **unlit** material and ignores every light. To make
-it respond, give it a material whose shader declares the **Lit-2D domain**. In an
-`.esshader`, that's one pragma plus a call to the injected lighting helper:
+By default a `Sprite` draws with an **unlit** material and ignores every light. The
+simplest way to light one is the `lit` flag — no material, no shader:
+
+```typescript
+app.world.spawn()
+ .insert(Transform, { position: { x: 0, y: 0, z: 0 } })
+ .insert(Sprite, { texture: hero, lit: true });
+```
+
+In the editor this is the **Lit** checkbox on the Sprite component. The sprite is lit
+with a flat normal — every 2D light type, falloff, and shadow works out of the box.
+
+When you need more than the flag (a tint parameter, a normal map, custom surface
+logic), use a material whose shader declares the **Lit-2D domain**. The engine injects
+the lighting uniforms and helpers, and the vertex stage is optional for 2D shaders —
+you write only the fragment:
```glsl
#pragma shader "MyLit"
#pragma version 300 es
#pragma domain Lit2D
-#pragma vertex
-// … pass the world-space position out as v_worldPos …
-#pragma end
-
#pragma fragment
precision mediump float;
in vec4 v_color;
@@ -106,8 +115,9 @@ void main() {
#pragma end
```
-Compile it and assign the material to the renderer exactly as in
-[Materials & Shaders](/docs/guides/material/):
+In the editor, **New Material (Lit)** in the Content Browser creates exactly this —
+a ready lit material with a tint and an optional normal map. From code, compile and
+assign it as in [Materials & Shaders](/docs/guides/material/):
```typescript
import { Material, defineSystem, Query, Mut, Sprite } from 'esengine';
diff --git a/docs/astro/src/content/docs/zh-cn/guides/lighting.mdx b/docs/astro/src/content/docs/zh-cn/guides/lighting.mdx
index 8d1706444..bc288beeb 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/lighting.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/lighting.mdx
@@ -72,18 +72,27 @@ const addSun = defineSystem([Commands()], (cmds) => {
## 让渲染器接受光照
-默认情况下,一个 `Sprite` 用**不受光**材质绘制,会忽略每一盏灯。要让它响应光照,给它一个着色器
-声明了 **Lit-2D 域**的材质。在 `.esshader` 里,就是一个 pragma 加一次对注入的光照 helper 的调用:
+默认情况下,一个 `Sprite` 用**不受光**材质绘制,会忽略每一盏灯。让它受光最简单的方式是
+`lit` 开关——不需要材质、不需要着色器:
+
+```typescript
+app.world.spawn()
+ .insert(Transform, { position: { x: 0, y: 0, z: 0 } })
+ .insert(Sprite, { texture: hero, lit: true });
+```
+
+在编辑器里就是 Sprite 组件上的 **Lit** 勾选框。精灵以平法线受光——每种 2D 光源、
+衰减和阴影都开箱即用。
+
+当你需要的不止这个开关(色调参数、法线贴图、自定义表面逻辑)时,给它一个着色器声明了
+**Lit-2D 域**的材质。引擎会注入光照 uniform 和 helper,而且 2D 着色器的顶点段是可选的——
+你只写片元:
```glsl
#pragma shader "MyLit"
#pragma version 300 es
#pragma domain Lit2D
-#pragma vertex
-// …把世界空间位置作为 v_worldPos 输出…
-#pragma end
-
#pragma fragment
precision mediump float;
in vec4 v_color;
@@ -103,7 +112,9 @@ void main() {
#pragma end
```
-编译它并把材质赋给渲染器,方式与[材质与着色器](/docs/zh-cn/guides/material/)里完全一致:
+在编辑器里,内容浏览器的 **New Material (Lit)** 创建的正是这样一个现成的受光材质,
+自带色调参数和可选法线贴图。代码侧的编译与赋材质方式与
+[材质与着色器](/docs/zh-cn/guides/material/)里完全一致:
```typescript
import { Material, defineSystem, Query, Mut, Sprite } from 'esengine';
diff --git a/sdk/src/builtinShaders.ts b/sdk/src/builtinShaders.ts
new file mode 100644
index 000000000..217758156
--- /dev/null
+++ b/sdk/src/builtinShaders.ts
@@ -0,0 +1,84 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file builtinShaders.ts
+ * @brief Built-in .esshader templates — the engine's stock material starting points.
+ */
+
+export interface BuiltinShaderTemplate {
+ id: string;
+ /** Menu / picker label, e.g. "Lit". */
+ label: string;
+ description: string;
+ source: string;
+ /** Initial .esmaterial `properties` for a material born from this template. */
+ defaults: Record<string, unknown>;
+}
+
+const SPRITE_UNLIT = `#pragma shader "Sprite Unlit"
+#pragma version 300 es
+#pragma domain Unlit2D
+#pragma param u_tint color default(1,1,1,1)
+
+#pragma fragment
+precision mediump float;
+
+in vec4 v_color;
+in vec2 v_texCoord;
+
+uniform sampler2D u_textures[8];
+
+out vec4 fragColor;
+
+void main() {
+ fragColor = texture(u_textures[0], v_texCoord) * v_color * u_tint;
+}
+#pragma end
+`;
+
+const SPRITE_LIT = `#pragma shader "Sprite Lit"
+#pragma version 300 es
+#pragma domain Lit2D
+#pragma param u_tint color default(1,1,1,1)
+#pragma param u_normalMap texture default(flatnormal)
+
+#pragma fragment
+precision mediump float;
+
+in vec4 v_color;
+in vec2 v_texCoord;
+in highp vec2 v_worldPos;
+
+uniform sampler2D u_textures[8];
+
+out vec4 fragColor;
+
+// Unset u_normalMap = flat normal, so lighting works with no normal map assigned.
+void main() {
+ vec4 base = texture(u_textures[0], v_texCoord) * v_color * u_tint;
+ vec3 N = es_sampleNormal(u_normalMap, v_texCoord);
+ fragColor = vec4(es_applyLighting2D(base.rgb, N, v_worldPos), base.a);
+}
+#pragma end
+`;
+
+export const BUILTIN_SHADER_TEMPLATES: readonly BuiltinShaderTemplate[] = [
+ {
+ id: 'sprite-unlit',
+ label: 'Unlit',
+ description: 'Texture × vertex color × tint, no lighting.',
+ source: SPRITE_UNLIT,
+ defaults: { u_tint: { r: 1, g: 1, b: 1, a: 1 } },
+ },
+ {
+ id: 'sprite-lit',
+ label: 'Lit',
+ description: 'Lit by the scene\'s 2D lights; optional normal map.',
+ source: SPRITE_LIT,
+ defaults: { u_tint: { r: 1, g: 1, b: 1, a: 1 } },
+ },
+];
+
+export function builtinShaderTemplate(id: string): BuiltinShaderTemplate | undefined {
+ return BUILTIN_SHADER_TEMPLATES.find((t) => t.id === id);
+}
diff --git a/sdk/src/component.generated.ts b/sdk/src/component.generated.ts
index 002d86813..2ffa3e1f8 100644
--- a/sdk/src/component.generated.ts
+++ b/sdk/src/component.generated.ts
@@ -15,7 +15,7 @@ import type { Dimension, Padding, VisualState } from './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 = '9f76797e876d6436';
+export const ABI_LAYOUT_HASH = '1bd58a735ff10d7f';
export interface AssetFieldMeta {
field: string;
@@ -433,6 +433,7 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
uvOffset: { x: 0, y: 0 },
uvScale: { x: 1, y: 1 },
layer: 0,
+ lit: false,
flipX: false,
flipY: false,
tileSize: { x: 0, y: 0 },
@@ -451,6 +452,7 @@ export const COMPONENT_META: Record<string, ComponentMetaEntry> = {
uvOffset: { advanced: true },
uvScale: { advanced: true },
layer: { step: 1, tooltip: "Sorting layer — controls draw order across sprites.", enumSource: "sortingLayers" },
+ lit: { tooltip: "Receive 2D lights: Light2D entities light this sprite (flat normal). A custom material overrides this." },
tileSize: { advanced: true },
tileSpacing: { advanced: true },
parallax: { tooltip: "Parallax scroll factor (1 = with world, <1 = slower, 0 = locked to camera).", advanced: true },
@@ -831,6 +833,7 @@ export interface SpriteData {
uvOffset: Vec2;
uvScale: Vec2;
layer: number;
+ lit: boolean;
flipX: boolean;
flipY: boolean;
tileSize: Vec2;
diff --git a/sdk/src/core-render.ts b/sdk/src/core-render.ts
index 2c78ebf94..ad99278cb 100644
--- a/sdk/src/core-render.ts
+++ b/sdk/src/core-render.ts
@@ -82,6 +82,12 @@ export {
type TextureRef,
} from './material';
+export {
+ BUILTIN_SHADER_TEMPLATES,
+ builtinShaderTemplate,
+ type BuiltinShaderTemplate,
+} from './builtinShaders';
+
export {
compileMaterialGraph,
newMaterialGraph,
diff --git a/sdk/src/ecs/ptrAccessors.generated.ts b/sdk/src/ecs/ptrAccessors.generated.ts
index a48b4199b..344683b7c 100644
--- a/sdk/src/ecs/ptrAccessors.generated.ts
+++ b/sdk/src/ecs/ptrAccessors.generated.ts
@@ -897,6 +897,7 @@ export interface SpritePtrData {
uvOffset: Vec2;
uvScale: Vec2;
layer: number;
+ lit: boolean;
flipX: boolean;
flipY: boolean;
tileSize: Vec2;
@@ -917,8 +918,9 @@ export function fillSprite(
const uvOffset_ = out.uvOffset; uvOffset_.x = f32[(ptr + 36) >> 2]; uvOffset_.y = f32[((ptr + 36) >> 2) + 1];
const uvScale_ = out.uvScale; uvScale_.x = f32[(ptr + 44) >> 2]; uvScale_.y = f32[((ptr + 44) >> 2) + 1];
out.layer = u32[(ptr + 52) >> 2] | 0;
- out.flipX = u8[ptr + 56] !== 0;
- out.flipY = u8[ptr + 57] !== 0;
+ out.lit = u8[ptr + 56] !== 0;
+ out.flipX = u8[ptr + 57] !== 0;
+ out.flipY = u8[ptr + 58] !== 0;
const tileSize_ = out.tileSize; tileSize_.x = f32[(ptr + 60) >> 2]; tileSize_.y = f32[((ptr + 60) >> 2) + 1];
const tileSpacing_ = out.tileSpacing; tileSpacing_.x = f32[(ptr + 68) >> 2]; tileSpacing_.y = f32[((ptr + 68) >> 2) + 1];
const parallax_ = out.parallax; parallax_.x = f32[(ptr + 76) >> 2]; parallax_.y = f32[((ptr + 76) >> 2) + 1];
@@ -937,8 +939,9 @@ export function writeSprite(
f32[(ptr + 36) >> 2] = data.uvOffset.x; f32[((ptr + 36) >> 2) + 1] = data.uvOffset.y;
f32[(ptr + 44) >> 2] = data.uvScale.x; f32[((ptr + 44) >> 2) + 1] = data.uvScale.y;
u32[(ptr + 52) >> 2] = data.layer | 0;
- u8[ptr + 56] = data.flipX ? 1 : 0;
- u8[ptr + 57] = data.flipY ? 1 : 0;
+ u8[ptr + 56] = data.lit ? 1 : 0;
+ u8[ptr + 57] = data.flipX ? 1 : 0;
+ u8[ptr + 58] = data.flipY ? 1 : 0;
f32[(ptr + 60) >> 2] = data.tileSize.x; f32[((ptr + 60) >> 2) + 1] = data.tileSize.y;
f32[(ptr + 68) >> 2] = data.tileSpacing.x; f32[((ptr + 68) >> 2) + 1] = data.tileSpacing.y;
f32[(ptr + 76) >> 2] = data.parallax.x; f32[((ptr + 76) >> 2) + 1] = data.parallax.y;
@@ -955,6 +958,7 @@ export function createSpriteData(): SpritePtrData {
uvOffset: { x: 0, y: 0 },
uvScale: { x: 0, y: 0 },
layer: 0,
+ lit: false,
flipX: false,
flipY: false,
tileSize: { x: 0, y: 0 },
diff --git a/sdk/src/ptrLayouts.generated.ts b/sdk/src/ptrLayouts.generated.ts
index e2a0a28fe..4d21523a3 100644
--- a/sdk/src/ptrLayouts.generated.ts
+++ b/sdk/src/ptrLayouts.generated.ts
@@ -248,8 +248,9 @@ export const PTR_LAYOUTS: Record<string, PtrLayout> = {
{ name: 'uvOffset', type: 'vec2', offset: 36 },
{ name: 'uvScale', type: 'vec2', offset: 44 },
{ name: 'layer', type: 'i32', offset: 52 },
- { name: 'flipX', type: 'bool', offset: 56 },
- { name: 'flipY', type: 'bool', offset: 57 },
+ { name: 'lit', type: 'bool', offset: 56 },
+ { name: 'flipX', type: 'bool', offset: 57 },
+ { name: 'flipY', type: 'bool', offset: 58 },
{ name: 'tileSize', type: 'vec2', offset: 60 },
{ name: 'tileSpacing', type: 'vec2', offset: 68 },
{ name: 'parallax', type: 'vec2', offset: 76 },
diff --git a/sdk/src/wasm.generated.ts b/sdk/src/wasm.generated.ts
index 5a84343b3..a8029e32c 100644
--- a/sdk/src/wasm.generated.ts
+++ b/sdk/src/wasm.generated.ts
@@ -374,6 +374,7 @@ export interface Sprite {
uvOffset: Vec2;
uvScale: Vec2;
layer: number;
+ lit: boolean;
flipX: boolean;
flipY: boolean;
tileSize: Vec2;
diff --git a/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap b/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap
index ca4696b03..d4a22283f 100644
--- a/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap
+++ b/sdk/tests/__snapshots__/component-fieldmeta-golden.test.ts.snap
@@ -473,6 +473,9 @@ exports[`builtin FieldMeta (RC9-1 equivalence gate) > matches the golden snapsho
"step": 1,
"tooltip": "Sorting layer — controls draw order across sprites.",
},
+ "lit": {
+ "tooltip": "Receive 2D lights: Light2D entities light this sprite (flat normal). A custom material overrides this.",
+ },
"material": {
"advanced": true,
},
diff --git a/src/esengine/bindings/EditorAPI.generated.cpp b/src/esengine/bindings/EditorAPI.generated.cpp
index 1ab97add3..6c9990061 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 1adb3706c1ad59cb
+ * @schema_hash 3e406753fbcb117c
*/
-#define ES_EDITOR_API_SCHEMA_HASH "1adb3706c1ad59cb"
+#define ES_EDITOR_API_SCHEMA_HASH "3e406753fbcb117c"
#include <emscripten/bind.h>
#include <string>
@@ -346,6 +346,7 @@ std::string editor_getComponentSchema(const std::string& name) {
{"key":"uvScale.x","type":"float","group":"Sprite"},
{"key":"uvScale.y","type":"float","group":"Sprite"},
{"key":"layer","type":"int","group":"Sprite"},
+ {"key":"lit","type":"bool","group":"Sprite"},
{"key":"flipX","type":"bool","group":"Sprite"},
{"key":"flipY","type":"bool","group":"Sprite"},
{"key":"tileSize.x","type":"float","group":"Sprite"},
@@ -1713,7 +1714,8 @@ bool editor_setBool(Registry& reg, u32 e, const std::string& comp, const std::st
} else if (comp == "Sprite") {
if (!reg.has<esengine::ecs::Sprite>(entity)) return false;
auto& c = reg.get<esengine::ecs::Sprite>(entity);
- if (field == "flipX") { c.flipX = value; }
+ if (field == "lit") { c.lit = value; }
+ else if (field == "flipX") { c.flipX = value; }
else if (field == "flipY") { c.flipY = value; }
else if (field == "enabled") { c.enabled = value; }
else { return false; }
@@ -1825,7 +1827,8 @@ bool editor_getBool(Registry& reg, u32 e, const std::string& comp, const std::st
} else if (comp == "Sprite") {
if (!reg.has<esengine::ecs::Sprite>(entity)) return false;
const auto& c = reg.get<esengine::ecs::Sprite>(entity);
- if (field == "flipX") { return c.flipX; }
+ if (field == "lit") { return c.lit; }
+ else if (field == "flipX") { return c.flipX; }
else if (field == "flipY") { return c.flipY; }
else if (field == "enabled") { return c.enabled; }
} else if (comp == "TilemapLayer") {
diff --git a/src/esengine/bindings/WebBindings.generated.cpp b/src/esengine/bindings/WebBindings.generated.cpp
index 41f17d9ac..3fc9e4541 100644
--- a/src/esengine/bindings/WebBindings.generated.cpp
+++ b/src/esengine/bindings/WebBindings.generated.cpp
@@ -573,6 +573,7 @@ struct SpriteJS {
glm::vec2 uvOffset;
glm::vec2 uvScale;
i32 layer;
+ bool lit;
bool flipX;
bool flipY;
glm::vec2 tileSize;
@@ -591,6 +592,7 @@ esengine::ecs::Sprite spriteFromJS(const SpriteJS& js) {
c.uvOffset = js.uvOffset;
c.uvScale = js.uvScale;
c.layer = js.layer;
+ c.lit = js.lit;
c.flipX = js.flipX;
c.flipY = js.flipY;
c.tileSize = js.tileSize;
@@ -610,6 +612,7 @@ SpriteJS spriteToJS(const esengine::ecs::Sprite& c) {
js.uvOffset = c.uvOffset;
js.uvScale = c.uvScale;
js.layer = c.layer;
+ js.lit = c.lit;
js.flipX = c.flipX;
js.flipY = c.flipY;
js.tileSize = c.tileSize;
@@ -1027,6 +1030,7 @@ EMSCRIPTEN_BINDINGS(esengine_components) {
.field("uvOffset", &SpriteJS::uvOffset)
.field("uvScale", &SpriteJS::uvScale)
.field("layer", &SpriteJS::layer)
+ .field("lit", &SpriteJS::lit)
.field("flipX", &SpriteJS::flipX)
.field("flipY", &SpriteJS::flipY)
.field("tileSize", &SpriteJS::tileSize)
@@ -1898,8 +1902,9 @@ static_assert(offsetof(esengine::ecs::Sprite, pivot) == 28, "ABI offset drift: e
static_assert(offsetof(esengine::ecs::Sprite, uvOffset) == 36, "ABI offset drift: esengine::ecs::Sprite.uvOffset (EHT expected 36)");
static_assert(offsetof(esengine::ecs::Sprite, uvScale) == 44, "ABI offset drift: esengine::ecs::Sprite.uvScale (EHT expected 44)");
static_assert(offsetof(esengine::ecs::Sprite, layer) == 52, "ABI offset drift: esengine::ecs::Sprite.layer (EHT expected 52)");
-static_assert(offsetof(esengine::ecs::Sprite, flipX) == 56, "ABI offset drift: esengine::ecs::Sprite.flipX (EHT expected 56)");
-static_assert(offsetof(esengine::ecs::Sprite, flipY) == 57, "ABI offset drift: esengine::ecs::Sprite.flipY (EHT expected 57)");
+static_assert(offsetof(esengine::ecs::Sprite, lit) == 56, "ABI offset drift: esengine::ecs::Sprite.lit (EHT expected 56)");
+static_assert(offsetof(esengine::ecs::Sprite, flipX) == 57, "ABI offset drift: esengine::ecs::Sprite.flipX (EHT expected 57)");
+static_assert(offsetof(esengine::ecs::Sprite, flipY) == 58, "ABI offset drift: esengine::ecs::Sprite.flipY (EHT expected 58)");
static_assert(offsetof(esengine::ecs::Sprite, tileSize) == 60, "ABI offset drift: esengine::ecs::Sprite.tileSize (EHT expected 60)");
static_assert(offsetof(esengine::ecs::Sprite, tileSpacing) == 68, "ABI offset drift: esengine::ecs::Sprite.tileSpacing (EHT expected 68)");
static_assert(offsetof(esengine::ecs::Sprite, parallax) == 76, "ABI offset drift: esengine::ecs::Sprite.parallax (EHT expected 76)");
@@ -1951,7 +1956,7 @@ static_assert(offsetof(esengine::ecs::Velocity, angular) == 12, "ABI offset drif
// ABI Hash -- runtime handshake against the SDK bundle
// =============================================================================
-static const char* kEsAbiLayoutHash = "9f76797e876d6436";
+static const char* kEsAbiLayoutHash = "1bd58a735ff10d7f";
std::string esengineGetAbiLayoutHash() {
return std::string(kEsAbiLayoutHash);
diff --git a/src/esengine/bindings/WebSDKEntry.cpp b/src/esengine/bindings/WebSDKEntry.cpp
index ef5b3ccbf..c476c4f65 100644
--- a/src/esengine/bindings/WebSDKEntry.cpp
+++ b/src/esengine/bindings/WebSDKEntry.cpp
@@ -56,8 +56,10 @@
#include "../core/Log.hpp"
#include <glm/glm.hpp>
+#include <cstdlib>
#include <cstring>
#include <cstddef>
+#include <sstream>
static_assert(sizeof(void*) == 4, "EM_JS pointer passing assumes wasm32 (4-byte pointers)");
@@ -105,7 +107,14 @@ static MaterialUniformLayout buildMaterialLayout(const resource::ParsedShader& p
rc.defaultTextureByName(p.defaultValue) });
}
} else if (p.std140Offset >= 0) {
- layout.params.push_back({ p.name, static_cast<u32>(p.std140Offset), materialParamArity(p.type) });
+ MaterialParamSlot slot{ p.name, static_cast<u32>(p.std140Offset), materialParamArity(p.type) };
+ // default(a,b,c,d) csv → the slot's initial block value.
+ std::istringstream csv(p.defaultValue);
+ std::string tok;
+ for (u32 i = 0; i < slot.arity && std::getline(csv, tok, ','); ++i) {
+ slot.defaults[i] = std::strtof(tok.c_str(), nullptr);
+ }
+ layout.params.push_back(slot);
}
}
return layout;
diff --git a/src/esengine/data/shaders/batch.esshader b/src/esengine/data/shaders/batch.esshader
index c5e661a6b..7f2d4242e 100644
--- a/src/esengine/data/shaders/batch.esshader
+++ b/src/esengine/data/shaders/batch.esshader
@@ -6,6 +6,10 @@
// derives crisp, resolution-independent coverage instead of sampling RGBA.
#pragma feature SDF
+// Compile-time variant: lit by the scene's 2D lights (Sprite.lit). Compiled as a
+// Lit2D-domain shader, so es_applyLighting2D + LightConstants are injected.
+#pragma feature LIT
+
#pragma vertex
layout(location = 0) in vec2 a_position;
layout(location = 1) in vec4 a_color;
@@ -19,12 +23,18 @@ layout(std140) uniform FrameConstants {
out vec4 v_color;
out vec2 v_texCoord;
flat out int v_texIndex;
+#ifdef LIT
+out highp vec2 v_worldPos;
+#endif
void main() {
gl_Position = u_projection * vec4(a_position, 0.0, 1.0);
v_color = a_color;
v_texCoord = a_texCoord;
v_texIndex = int(a_texIndex);
+#ifdef LIT
+ v_worldPos = a_position;
+#endif
}
#pragma end
@@ -36,6 +46,9 @@ precision highp float;
in vec4 v_color;
in vec2 v_texCoord;
flat in int v_texIndex;
+#ifdef LIT
+in highp vec2 v_worldPos;
+#endif
// Up to 8 textures bound per multi-texture batch. GLSL ES 3.00 forbids indexing a
// sampler array with a non-uniform expression, so the slot is selected by a constant
@@ -62,6 +75,10 @@ void main() {
float screenPxDist = (dist - 0.5) / max(fwidth(dist), 1e-6);
float coverage = clamp(screenPxDist + 0.5, 0.0, 1.0);
fragColor = vec4(v_color.rgb, v_color.a * coverage);
+#elif defined(LIT)
+ // Flat normal; the tinted color is the albedo. Normal maps need a material.
+ vec4 base = texColor * v_color;
+ fragColor = vec4(es_applyLighting2D(base.rgb, vec3(0.0, 0.0, 1.0), v_worldPos), base.a);
#else
fragColor = texColor * v_color;
#endif
diff --git a/src/esengine/ecs/components/Sprite.hpp b/src/esengine/ecs/components/Sprite.hpp
index 0cd0c4935..7b144e051 100644
--- a/src/esengine/ecs/components/Sprite.hpp
+++ b/src/esengine/ecs/components/Sprite.hpp
@@ -73,6 +73,10 @@ struct Sprite {
ES_PROPERTY(step=1, enum_source=sortingLayers, tooltip="Sorting layer — controls draw order across sprites.")
i32 layer{0};
+ /** @brief Lit by the scene's 2D lights (Light2D), no material needed. Off = unlit. */
+ ES_PROPERTY(tooltip="Receive 2D lights: Light2D entities light this sprite (flat normal). A custom material overrides this.")
+ bool lit{false};
+
/** @brief Flip sprite horizontally */
ES_PROPERTY()
bool flipX{false};
diff --git a/src/esengine/renderer/MaterialStore.cpp b/src/esengine/renderer/MaterialStore.cpp
index 69afb2f69..7fc298026 100644
--- a/src/esengine/renderer/MaterialStore.cpp
+++ b/src/esengine/renderer/MaterialStore.cpp
@@ -35,6 +35,9 @@ void MaterialStore::bindForDraw(u32 materialId) {
if (it == materials_.end()) return;
MaterialRecord& rec = it->second;
+ auto lit = layouts_.find(rec.shader);
+ if (lit != layouts_.end()) ensureDefaults(rec, lit->second);
+
// Per-material constants UBO (binding 1) — present only when the shader declares params.
if (!rec.uboBytes.empty()) {
if (rec.ubo == 0) {
@@ -54,7 +57,6 @@ void MaterialStore::bindForDraw(u32 materialId) {
// batch path's 0..7. Iterate the shader's layout (not just the material's explicit bindings)
// so an unset param binds its declared default (white/black/flatnormal) instead of sampling
// whatever stale texture is at the unit.
- auto lit = layouts_.find(rec.shader);
if (lit != layouts_.end()) {
for (const auto& slot : lit->second.textures) {
u32 glTexture = slot.defaultGlTexture;
diff --git a/src/esengine/renderer/MaterialStore.hpp b/src/esengine/renderer/MaterialStore.hpp
index b71494020..ae05c41d8 100644
--- a/src/esengine/renderer/MaterialStore.hpp
+++ b/src/esengine/renderer/MaterialStore.hpp
@@ -47,6 +47,7 @@ struct MaterialParamSlot {
std::string name;
u32 offset = 0; ///< std140 byte offset within the block.
u32 arity = 1; ///< Float component count (1..4); textures are not slots.
+ f32 defaults[4] = {0, 0, 0, 0}; ///< Shader-declared default(...); the block's initial value.
};
/** @brief A texture param's sampler unit (>= MATERIAL_TEXTURE_UNIT_BASE, above the batch's 0..7). */
@@ -156,9 +157,7 @@ public:
if (lit == layouts_.end()) return;
const MaterialParamSlot* slot = lit->second.find(name);
if (!slot) return;
- if (rec.uboBytes.size() < lit->second.blockSize) {
- rec.uboBytes.resize(lit->second.blockSize, 0);
- }
+ ensureDefaults(rec, lit->second);
const u32 n = std::min(arity, slot->arity);
std::memcpy(rec.uboBytes.data() + slot->offset, values, n * sizeof(f32));
rec.uboDirty = true;
@@ -197,6 +196,17 @@ public:
void clear();
private:
+ /// Fills an unpacked block with the shader's param defaults, so a material that never
+ /// sets a param still draws with the declared default(...) values (not zeros).
+ static void ensureDefaults(MaterialRecord& rec, const MaterialUniformLayout& layout) {
+ if (layout.blockSize == 0 || rec.uboBytes.size() >= layout.blockSize) return;
+ rec.uboBytes.resize(layout.blockSize, 0);
+ for (const auto& p : layout.params) {
+ std::memcpy(rec.uboBytes.data() + p.offset, p.defaults, p.arity * sizeof(f32));
+ }
+ rec.uboDirty = true;
+ }
+
std::unordered_map<u32, MaterialRecord> materials_;
std::unordered_map<u32, MaterialUniformLayout> layouts_;
GfxDevice* device_ = nullptr;
diff --git a/src/esengine/renderer/RenderFrame.cpp b/src/esengine/renderer/RenderFrame.cpp
index 937c71a17..70ea06a73 100644
--- a/src/esengine/renderer/RenderFrame.cpp
+++ b/src/esengine/renderer/RenderFrame.cpp
@@ -165,7 +165,9 @@ void RenderFrame::init(u32 width, u32 height) {
context_.getWhiteTextureId(),
batch_shader_id_,
RenderStage::Transparent,
- glm::mat4(1.0f)
+ glm::mat4(1.0f),
+ nullptr,
+ this
};
for (auto& plugin : plugins_) {
plugin->init(initCtx);
@@ -496,7 +498,8 @@ RenderFrameContext RenderFrame::makeContext() {
batch_shader_id_,
current_stage_,
view_projection_,
- &context_.materials()
+ &context_.materials(),
+ this
};
}
@@ -605,6 +608,11 @@ u32 RenderFrame::compileBatchVariant(const std::vector<std::string>& features) {
// Parse it and assemble the two GLSL ES 3.00 stages (single source of truth),
// injecting the requested feature #defines (e.g. SDF).
auto parsed = resource::ShaderParser::parse(ShaderEmbeds::BATCH);
+ // LIT is a Lit2D-domain variant: the domain drives the lighting injection,
+ // same path as Lit2D material shaders.
+ if (std::find(features.begin(), features.end(), "LIT") != features.end()) {
+ parsed.domain = "Lit2D";
+ }
resource::ShaderHandle handle = resource_manager_.createShaderWithBindings(
resource::ShaderParser::assembleStage(parsed, resource::ShaderStage::Vertex, "", features),
resource::ShaderParser::assembleStage(parsed, resource::ShaderStage::Fragment, "", features),
diff --git a/src/esengine/renderer/RenderTypePlugin.hpp b/src/esengine/renderer/RenderTypePlugin.hpp
index 6dd516513..bfc1ff879 100644
--- a/src/esengine/renderer/RenderTypePlugin.hpp
+++ b/src/esengine/renderer/RenderTypePlugin.hpp
@@ -19,6 +19,7 @@ namespace esengine {
struct Frustum;
class RenderContext;
class MaterialStore;
+class RenderFrame;
struct RenderFrameContext {
RenderContext& render_context;
@@ -28,6 +29,8 @@ struct RenderFrameContext {
RenderStage current_stage = RenderStage::Transparent;
glm::mat4 view_projection{1.0f};
const MaterialStore* materials = nullptr;
+ /// The owning frame, for lazily-compiled batch variants (RenderFrame::batchProgram).
+ RenderFrame* frame = nullptr;
};
struct RenderCollectContext {
diff --git a/src/esengine/renderer/ShaderEmbeds.generated.hpp b/src/esengine/renderer/ShaderEmbeds.generated.hpp
index c87a6624c..521923f2c 100644
--- a/src/esengine/renderer/ShaderEmbeds.generated.hpp
+++ b/src/esengine/renderer/ShaderEmbeds.generated.hpp
@@ -10,6 +10,10 @@ inline constexpr const char* BATCH = R"esshader(#pragma shader "Batch"
// derives crisp, resolution-independent coverage instead of sampling RGBA.
#pragma feature SDF
+// Compile-time variant: lit by the scene's 2D lights (Sprite.lit). Compiled as a
+// Lit2D-domain shader, so es_applyLighting2D + LightConstants are injected.
+#pragma feature LIT
+
#pragma vertex
layout(location = 0) in vec2 a_position;
layout(location = 1) in vec4 a_color;
@@ -23,12 +27,18 @@ layout(std140) uniform FrameConstants {
out vec4 v_color;
out vec2 v_texCoord;
flat out int v_texIndex;
+#ifdef LIT
+out highp vec2 v_worldPos;
+#endif
void main() {
gl_Position = u_projection * vec4(a_position, 0.0, 1.0);
v_color = a_color;
v_texCoord = a_texCoord;
v_texIndex = int(a_texIndex);
+#ifdef LIT
+ v_worldPos = a_position;
+#endif
}
#pragma end
@@ -40,6 +50,9 @@ precision highp float;
in vec4 v_color;
in vec2 v_texCoord;
flat in int v_texIndex;
+#ifdef LIT
+in highp vec2 v_worldPos;
+#endif
// Up to 8 textures bound per multi-texture batch. GLSL ES 3.00 forbids indexing a
// sampler array with a non-uniform expression, so the slot is selected by a constant
@@ -66,6 +79,10 @@ void main() {
float screenPxDist = (dist - 0.5) / max(fwidth(dist), 1e-6);
float coverage = clamp(screenPxDist + 0.5, 0.0, 1.0);
fragColor = vec4(v_color.rgb, v_color.a * coverage);
+#elif defined(LIT)
+ // Flat normal; the tinted color is the albedo. Normal maps need a material.
+ vec4 base = texColor * v_color;
+ fragColor = vec4(es_applyLighting2D(base.rgb, vec3(0.0, 0.0, 1.0), v_worldPos), base.a);
#else
fragColor = texColor * v_color;
#endif
diff --git a/src/esengine/renderer/plugins/SpritePlugin.cpp b/src/esengine/renderer/plugins/SpritePlugin.cpp
index aeea05fe7..5fc7622f6 100644
--- a/src/esengine/renderer/plugins/SpritePlugin.cpp
+++ b/src/esengine/renderer/plugins/SpritePlugin.cpp
@@ -31,6 +31,8 @@ void SpritePlugin::collect(RenderCollectContext& collect_ctx) {
const f32 camCenterX = (camBL.x / camBL.w + camTR.x / camTR.w) * 0.5f;
const f32 camCenterY = (camBL.y / camBL.w + camTR.y / camTR.w) * 0.5f;
+ u32 litProgram = 0;
+
for (auto entity : spriteView) {
const auto& sprite = spriteView.get<ecs::Sprite>(entity);
if (!sprite.enabled) continue;
@@ -114,6 +116,10 @@ void SpritePlugin::collect(RenderCollectContext& collect_ctx) {
key.depthWrite = m->depthWrite;
key.cull = static_cast<u8>(m->cull);
}
+ } else if (sprite.lit && ctx.frame) {
+ // A material owns shading fully, so it takes precedence over the toggle.
+ if (litProgram == 0) litProgram = ctx.frame->batchProgram({"LIT"});
+ if (litProgram != 0) key.shaderId = litProgram;
}
if (hasTiling) {
diff --git a/src/esengine/resource/ShaderParser.cpp b/src/esengine/resource/ShaderParser.cpp
index 5cd846d6b..0bbc68019 100644
--- a/src/esengine/resource/ShaderParser.cpp
+++ b/src/esengine/resource/ShaderParser.cpp
@@ -92,6 +92,36 @@ bool expandIncludes(const std::string& source,
return true;
}
+// Canonical 2D vertex stage for fragment-only .esshaders: the batch path bakes the
+// world transform into the vertices, so all 2D shaders share this pass-through.
+std::string canonical2DVertexStage(bool lit) {
+ std::string src =
+ "layout(location = 0) in vec2 a_position;\n"
+ "layout(location = 1) in vec4 a_color;\n"
+ "layout(location = 2) in vec2 a_texCoord;\n"
+ "\n"
+ "layout(std140) uniform FrameConstants {\n"
+ " mat4 u_projection;\n"
+ "};\n"
+ "\n"
+ "out vec4 v_color;\n"
+ "out vec2 v_texCoord;\n";
+ if (lit) {
+ src += "out highp vec2 v_worldPos;\n";
+ }
+ src +=
+ "\n"
+ "void main() {\n"
+ " gl_Position = u_projection * vec4(a_position, 0.0, 1.0);\n"
+ " v_color = a_color;\n"
+ " v_texCoord = a_texCoord;\n";
+ if (lit) {
+ src += " v_worldPos = a_position;\n";
+ }
+ src += "}\n";
+ return src;
+}
+
} // namespace
// =============================================================================
@@ -310,8 +340,13 @@ ParsedShader ShaderParser::parse(const std::string& source, const ShaderIncludeR
}
if (result.stages.find(ShaderStage::Vertex) == result.stages.end()) {
- result.errorMessage = "Missing vertex shader stage";
- return result;
+ // 2D domains: `#pragma vertex` is optional — the canonical stage is injected.
+ if (result.domain == "Unlit2D" || result.domain == "Lit2D") {
+ result.stages[ShaderStage::Vertex] = canonical2DVertexStage(result.domain == "Lit2D");
+ } else {
+ result.errorMessage = "Missing vertex shader stage";
+ return result;
+ }
}
if (result.stages.find(ShaderStage::Fragment) == result.stages.end()) {
diff --git a/tests/renderer/test_shader_variant.cpp b/tests/renderer/test_shader_variant.cpp
index 8260051a0..0cdb00a5f 100644
--- a/tests/renderer/test_shader_variant.cpp
+++ b/tests/renderer/test_shader_variant.cpp
@@ -41,6 +41,67 @@ void main() {
#pragma end
)";
+// Fragment-only authoring: `#pragma vertex` is optional for 2D domains.
+static const char* FRAG_ONLY_UNLIT = R"(#pragma shader "FragOnly"
+#pragma version 300 es
+#pragma domain Unlit2D
+
+#pragma fragment
+precision mediump float;
+in vec4 v_color;
+in vec2 v_texCoord;
+out vec4 fragColor;
+void main() { fragColor = v_color; }
+#pragma end
+)";
+
+static const char* FRAG_ONLY_LIT = R"(#pragma shader "FragOnlyLit"
+#pragma version 300 es
+#pragma domain Lit2D
+
+#pragma fragment
+precision mediump float;
+in vec4 v_color;
+in highp vec2 v_worldPos;
+out vec4 fragColor;
+void main() { fragColor = vec4(es_applyLighting2D(v_color.rgb, vec3(0.0, 0.0, 1.0), v_worldPos), v_color.a); }
+#pragma end
+)";
+
+static const char* FRAG_ONLY_POSTPROCESS = R"(#pragma shader "NoCanonical"
+#pragma version 300 es
+#pragma domain PostProcess
+
+#pragma fragment
+precision mediump float;
+out vec4 fragColor;
+void main() { fragColor = vec4(1.0); }
+#pragma end
+)";
+
+static void testFragmentOnly() {
+ ParsedShader unlit = ShaderParser::parse(FRAG_ONLY_UNLIT);
+ CHECK(unlit.valid, "fragment-only Unlit2D shader parses");
+ const std::string uv = ShaderParser::assembleStage(unlit, ShaderStage::Vertex);
+ CHECK(uv.find("a_position") != std::string::npos, "canonical vertex stage injected");
+ CHECK(uv.find("FrameConstants") != std::string::npos, "canonical vertex reads the FrameConstants UBO");
+ CHECK(uv.find("v_worldPos") == std::string::npos, "Unlit2D canonical vertex has no world-pos varying");
+
+ ParsedShader lit = ShaderParser::parse(FRAG_ONLY_LIT);
+ CHECK(lit.valid, "fragment-only Lit2D shader parses");
+ const std::string lv = ShaderParser::assembleStage(lit, ShaderStage::Vertex);
+ CHECK(lv.find("v_worldPos = a_position") != std::string::npos, "Lit2D canonical vertex forwards world position");
+ const std::string lf = ShaderParser::assembleStage(lit, ShaderStage::Fragment);
+ CHECK(lf.find("es_applyLighting2D") != std::string::npos, "Lit2D fragment gets the lighting helper injected");
+
+ ParsedShader pp = ShaderParser::parse(FRAG_ONLY_POSTPROCESS);
+ CHECK(!pp.valid, "non-2D domain without a vertex stage still errors");
+
+ ParsedShader authored = ShaderParser::parse(SRC);
+ const std::string av = ShaderParser::assembleStage(authored, ShaderStage::Vertex);
+ CHECK(av.find("a_pos") != std::string::npos, "an authored vertex stage is untouched");
+}
+
int main() {
ParsedShader p = ShaderParser::parse(SRC);
CHECK(p.valid, "shader parses");
@@ -59,6 +120,8 @@ int main() {
"variantKey is order-independent");
CHECK(ShaderParser::variantKey({}).empty(), "variantKey of no features is empty");
+ testFragmentOnly();
+
if (g_failures == 0) {
std::printf("\nALL SHADER-VARIANT TESTS PASSED\n");
return 0;