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): shader effect shelf — engine time, effect templates, graph nodes, shader manual

yhh2308bbea1c39
diff --git a/desktop/package.json b/desktop/package.json
index e1d0ff656..c99f10006 100644
--- a/desktop/package.json
+++ b/desktop/package.json
@@ -46,6 +46,7 @@
"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:dissolve": "vite build && ESTELLA_VERIFY_SCENE=/scenes/mat-dissolve.esscene ESTELLA_VERIFY_MANIFEST=/scenes/mat-dissolve.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\\\":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-dissolve.esscene b/desktop/public/scenes/mat-dissolve.esscene
new file mode 100644
index 000000000..1a5564b75
--- /dev/null
+++ b/desktop/public/scenes/mat-dissolve.esscene
@@ -0,0 +1,35 @@
+{
+ "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": "Dissolve",
+ "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": 0, "b": 0, "a": 1 },
+ "material": "/scenes/mat-dissolve/dissolve.esmaterial"
+ }
+ }
+ ],
+ "visible": true
+ }
+ ]
+}
diff --git a/desktop/public/scenes/mat-dissolve.textures.json b/desktop/public/scenes/mat-dissolve.textures.json
new file mode 100644
index 000000000..0967ef424
--- /dev/null
+++ b/desktop/public/scenes/mat-dissolve.textures.json
@@ -0,0 +1 @@
+{}
diff --git a/desktop/public/scenes/mat-dissolve/dissolve.esmaterial b/desktop/public/scenes/mat-dissolve/dissolve.esmaterial
new file mode 100644
index 000000000..ca90043f9
--- /dev/null
+++ b/desktop/public/scenes/mat-dissolve/dissolve.esmaterial
@@ -0,0 +1,8 @@
+{
+ "version": "1.0",
+ "type": "material",
+ "shader": "dissolve.esshader",
+ "blendMode": 0,
+ "depthTest": false,
+ "properties": {}
+}
diff --git a/desktop/public/scenes/mat-dissolve/dissolve.esshader b/desktop/public/scenes/mat-dissolve/dissolve.esshader
new file mode 100644
index 000000000..6a71111bc
--- /dev/null
+++ b/desktop/public/scenes/mat-dissolve/dissolve.esshader
@@ -0,0 +1,37 @@
+#pragma shader "Dissolve"
+#pragma version 300 es
+#pragma domain Unlit2D
+#pragma param u_progress float default(0) range(0,1) ui(slider)
+#pragma param u_edgeColor color default(1,0.5,0,1)
+#pragma param u_edgeWidth float default(0.08) range(0,0.5)
+#pragma param u_noiseScale float default(12) range(1,64)
+
+#pragma fragment
+precision mediump float;
+
+in vec4 v_color;
+in vec2 v_texCoord;
+
+uniform sampler2D u_textures[8];
+
+out vec4 fragColor;
+
+float es_hash(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453123); }
+float es_noise(vec2 p) {
+ vec2 i = floor(p);
+ vec2 f = fract(p);
+ f = f * f * (3.0 - 2.0 * f);
+ return mix(mix(es_hash(i), es_hash(i + vec2(1.0, 0.0)), f.x),
+ mix(es_hash(i + vec2(0.0, 1.0)), es_hash(i + vec2(1.0, 1.0)), f.x), f.y);
+}
+
+// u_progress 0 = intact, 1 = fully dissolved; a glowing edge leads the cut.
+void main() {
+ vec4 base = texture(u_textures[0], v_texCoord) * v_color;
+ float n = es_noise(v_texCoord * u_noiseScale);
+ float cut = u_progress * (1.0 + u_edgeWidth);
+ if (n < cut - u_edgeWidth) discard;
+ vec3 rgb = (n < cut) ? u_edgeColor.rgb : base.rgb;
+ fragColor = vec4(rgb, base.a);
+}
+#pragma end
diff --git a/desktop/src/components/Menu.tsx b/desktop/src/components/Menu.tsx
index f223d6f84..235962f80 100644
--- a/desktop/src/components/Menu.tsx
+++ b/desktop/src/components/Menu.tsx
@@ -9,14 +9,16 @@
*/
import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from 'react';
import { createPortal } from 'react-dom';
-import { Check } from 'lucide-react';
+import { Check, ChevronRight } from 'lucide-react';
export type MenuItem =
| { sep: true }
| {
label: string;
shortcut?: string;
- onClick: () => void;
+ onClick?: () => void;
+ /** Submenu — the item opens a flyout on hover (ContextMenu only); onClick is ignored. */
+ children?: MenuItem[];
disabled?: boolean;
checked?: boolean;
icon?: ReactNode;
@@ -43,7 +45,7 @@ export function MenuItems({ items, onSelect }: { items: MenuItem[]; onSelect: ()
disabled={it.disabled}
onClick={() => {
onSelect();
- it.onClick();
+ it.onClick?.();
}}
>
<span className="menu-dropdown__check">
@@ -114,9 +116,42 @@ export function ContextMenu({
style={{ left: pos.left, top: pos.top }}
onMouseDown={(e) => e.stopPropagation()}
>
+ <CtxItems items={items} onClose={onClose} />
+ </div>,
+ document.body,
+ );
+}
+
+// Context-menu item list; an item with `children` opens a hover flyout, flipped
+// to the left edge when there's no room on the right.
+function CtxItems({ items, onClose }: { items: MenuItem[]; onClose: () => void }) {
+ const [open, setOpen] = useState<{ i: number; flip: boolean } | null>(null);
+ return (
+ <>
{items.map((it, i) =>
'sep' in it ? (
<div key={i} className="ctx-sep" />
+ ) : it.children ? (
+ <div
+ key={i}
+ className="ctx-sub"
+ onMouseEnter={(e) => {
+ const r = e.currentTarget.getBoundingClientRect();
+ setOpen({ i, flip: r.right + 200 > window.innerWidth });
+ }}
+ onMouseLeave={() => setOpen((o) => (o?.i === i ? null : o))}
+ >
+ <button type="button" role="menuitem" className="ctx-item" aria-haspopup="menu" disabled={it.disabled}>
+ <span className="ci">{it.icon}</span>
+ <span className="cl">{it.label}</span>
+ <span className="ck"><ChevronRight size={12} /></span>
+ </button>
+ {open?.i === i ? (
+ <div className={`ctx ctx-flyout${open.flip ? ' flip' : ''}`} role="menu">
+ <CtxItems items={it.children} onClose={onClose} />
+ </div>
+ ) : null}
+ </div>
) : (
<button
key={i}
@@ -126,7 +161,7 @@ export function ContextMenu({
disabled={it.disabled}
onClick={() => {
onClose();
- it.onClick();
+ it.onClick?.();
}}
>
<span className="ci">{it.checked ? <Check size={13} strokeWidth={2.4} /> : it.icon}</span>
@@ -135,7 +170,6 @@ export function ContextMenu({
</button>
),
)}
- </div>,
- document.body,
+ </>
);
}
diff --git a/desktop/src/panels/ContentBrowser.tsx b/desktop/src/panels/ContentBrowser.tsx
index b07524440..f911d8e39 100644
--- a/desktop/src/panels/ContentBrowser.tsx
+++ b/desktop/src/panels/ContentBrowser.tsx
@@ -14,6 +14,7 @@ import { referencingPaths } from '@/project/assetRefs';
import { parseAssetQuery, filterAndSortAssets, type AssetSort } from '@/project/assetFilter';
import { createTilesetFromTexture } from '@/tileset/openTileset';
import { createTilemapFromTileset } from '@/tilemap/createTilemap';
+import { BUILTIN_SHADER_TEMPLATES } from 'esengine';
import { createMaterial, createMaterialInstance } from '@/material/openMaterial';
import { createMaterialGraph } from '@/material/openMaterialGraph';
import { createStateMachine } from '@/fsm/openStateMachine';
@@ -558,8 +559,13 @@ 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 (Unlit)', onClick: () => void createMaterial(cwd, 'sprite-unlit') },
- { label: 'New Material (Lit)', onClick: () => void createMaterial(cwd, 'sprite-lit') },
+ {
+ label: 'New Material',
+ children: BUILTIN_SHADER_TEMPLATES.map((t) => ({
+ label: t.label,
+ onClick: () => void createMaterial(cwd, t.id),
+ })),
+ },
{ 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/desktop/src/theme/menus.css b/desktop/src/theme/menus.css
index 526a27042..e063d1dfe 100644
--- a/desktop/src/theme/menus.css
+++ b/desktop/src/theme/menus.css
@@ -40,6 +40,9 @@
.ctx-item.danger:hover { background: rgba(214, 90, 90, 0.14); color: var(--error); }
.ctx-item.danger:hover .ci { color: var(--error); }
.ctx-sep { height: 1px; background: var(--border-line); margin: 4px 6px; }
+.ctx-sub { position: relative; }
+.ctx-flyout { position: absolute; left: calc(100% - 4px); top: -5px; }
+.ctx-flyout.flip { left: auto; right: calc(100% - 4px); }
/* ════════════════════════ Hover tooltip ════════════════════════ */
/* The floating container for the shared <Tooltip> primitive (asset hover card,
diff --git a/docs/astro/src/content/docs/guides/material.mdx b/docs/astro/src/content/docs/guides/material.mdx
index b1c250747..de89dffa7 100644
--- a/docs/astro/src/content/docs/guides/material.mdx
+++ b/docs/astro/src/content/docs/guides/material.mdx
@@ -17,11 +17,60 @@ name and they reach the GPU safely. A `Material` binds a compiled shader to a se
parameter values; assigning its handle to a renderer's `material` field draws that
renderer with it.
-## Declaring parameters with `#pragma param`
+## Built-in shader templates
+
+You rarely start from a blank file. The Content Browser's **New Material** submenu
+creates a material from a built-in template — the same list ships in code as
+`BUILTIN_SHADER_TEMPLATES`:
+
+| Template | What it does |
+|---|---|
+| **Unlit** | Texture × vertex color × `u_tint`. The plain default. |
+| **Lit** | Lit by the scene's 2D lights; `u_tint` + optional `u_normalMap`. |
+| **Hit Flash** | Blends toward `u_flashColor` by `u_flash` — drive it from code for damage blinks. |
+| **Outline** | Colored silhouette outline (`u_outlineColor`, `u_outlineWidth` in texels). |
+| **Dissolve** | Noise burn-away with a glowing edge (`u_progress` 0→1). |
+| **Pixelate** | Quantizes UVs to a `u_pixels` grid. |
+| **UV Scroll** | Scrolls the texture by `u_scrollSpeed` × time. |
+
+Each template is an ordinary `.esshader` created next to the material — open it and
+edit; nothing about it is special.
+
+## The `.esshader` format
+
+One file holds every stage plus its metadata, separated by pragmas:
+
+| Pragma | Meaning |
+|---|---|
+| `#pragma shader "Name"` | Display name. |
+| `#pragma version 300 es` | GLSL version line for every stage. |
+| `#pragma domain <D>` | `Unlit2D` (default), `Lit2D`, `PostProcess`, `UI`. `Lit2D` injects the lighting uniforms + helpers. |
+| `#pragma param …` | A reflected material parameter (table below). |
+| `#pragma switch NAME [default(on)]` | Material-facing static permutation toggle (a `#define`). |
+| `#pragma feature NAME` | Engine-chosen compile-time variant keyword. |
+| `#pragma vertex` / `#pragma fragment` … `#pragma end` | Stage bodies. **The vertex block is optional for 2D domains** — the engine injects the canonical stage. |
+| `#include "path"` | Textual include (resolved by the host). |
+
+### Fragment-only authoring
+
+2D sprites bake their world transform into the batch vertices, so every 2D shader
+shares one vertex stage. Omit `#pragma vertex` and write only the fragment; these
+varyings arrive ready to use:
+
+| Varying | Type | Value |
+|---|---|---|
+| `v_color` | `vec4` | Per-instance tint (the sprite's `color`). |
+| `v_texCoord` | `vec2` | Texture UV. |
+| `v_worldPos` | `highp vec2` | World-space position (**Lit2D domain only**). |
+
+The sprite's texture is `u_textures[0]` (declare `uniform sampler2D u_textures[8];`
+— units 0–7 belong to the batch; texture *params* bind above them automatically).
+
+### Declaring parameters with `#pragma param`
```glsl
#pragma param u_tint color default(1, 1, 1, 1)
-#pragma param u_intensity float default(1.0)
+#pragma param u_intensity float default(1.0) range(0, 4) ui(slider)
#pragma param u_mask texture default(white)
// … your GLSL fragment code, reading u_tint / u_intensity / u_mask …
@@ -29,9 +78,25 @@ renderer with it.
| Param type | GLSL | Value shape | Notes |
|---|---|---|---|
-| `float` | `float` | `number` | Scalar knob. |
-| `color` | `vec4` | `[r, g, b, a]` | RGBA, 0..1. |
-| `texture` | `sampler2D` | texture handle | `default(white)` etc. for a fallback. |
+| `float` / `int` | `float` / `int` | `number` | Scalar knob; `range(min,max)` + `ui(slider)` for the inspector. |
+| `vec2` / `vec3` / `vec4` | same | `[x, y, …]` | Vector knob. |
+| `color` | `vec4` | `[r, g, b, a]` | RGBA, 0..1; color picker in the inspector. |
+| `texture` | `sampler2D` | texture handle | `default(white \| black \| flatnormal)` fallback when unset. |
+
+Params live in an engine-generated std140 block, initialized from their `default(…)`
+values — a material that never sets a param still draws correctly.
+
+### Injected uniforms & helpers
+
+The engine injects these into every compiled `.esshader` — never declare them yourself:
+
+| Injected | Available | What |
+|---|---|---|
+| `u_esTime` | always | `vec4` frame clock: `.x` elapsed seconds, `.y` delta seconds. |
+| MaterialConstants block | when the shader has params | Your `#pragma param` values. |
+| `es_applyLighting2D(albedo, N, worldPos)` | Lit2D | Applies every scene light (+shadows); returns the lit color. |
+| `es_sampleNormal(map, uv)` | Lit2D | Unpacks a tangent-space normal map (RGB → [-1,1], normalized). |
+| `es_shadowFactor2D(worldPos, target, softness)` | Lit2D | Occlusion factor toward a point (used by `es_applyLighting2D`). |
A `#pragma switch` selects a static shader permutation baked into the material at
compile time (via the `features` argument to `compileShader`).
diff --git a/docs/astro/src/content/docs/zh-cn/guides/material.mdx b/docs/astro/src/content/docs/zh-cn/guides/material.mdx
index 7a749d5e1..cbbffd2f2 100644
--- a/docs/astro/src/content/docs/zh-cn/guides/material.mdx
+++ b/docs/astro/src/content/docs/zh-cn/guides/material.mdx
@@ -14,11 +14,57 @@ import { Aside } from '@astrojs/starlight/components';
std140 uniform 块,于是 CPU 能按名字设置、并安全地送到 GPU。一个 `Material` 把编译好的
着色器绑定到一组参数值;把它的句柄赋给渲染器的 `material` 字段,就用它来绘制该渲染器。
-## 用 `#pragma param` 声明参数
+## 内置着色器模板
+
+你很少需要从空白文件开始。内容浏览器的 **New Material** 子菜单从内置模板创建材质——
+同一份清单在代码里是 `BUILTIN_SHADER_TEMPLATES`:
+
+| 模板 | 作用 |
+|---|---|
+| **Unlit** | 纹理 × 顶点色 × `u_tint`,普通默认。 |
+| **Lit** | 被场景 2D 灯光照亮;`u_tint` + 可选 `u_normalMap`。 |
+| **Hit Flash** | 按 `u_flash` 混向 `u_flashColor`——代码里驱动它做受击闪白。 |
+| **Outline** | 彩色剪影描边(`u_outlineColor`、`u_outlineWidth`,单位纹素)。 |
+| **Dissolve** | 噪声烧蚀 + 发光边缘(`u_progress` 0→1)。 |
+| **Pixelate** | UV 量化到 `u_pixels` 网格。 |
+| **UV Scroll** | 按 `u_scrollSpeed` × 时间滚动纹理。 |
+
+每个模板就是生成在材质旁边的普通 `.esshader`——直接打开改,没有任何特殊之处。
+
+## `.esshader` 格式
+
+一个文件容纳所有 stage 与元数据,用 pragma 分段:
+
+| Pragma | 含义 |
+|---|---|
+| `#pragma shader "Name"` | 显示名。 |
+| `#pragma version 300 es` | 每个 stage 的 GLSL 版本行。 |
+| `#pragma domain <D>` | `Unlit2D`(默认)、`Lit2D`、`PostProcess`、`UI`。`Lit2D` 注入光照 uniform + helper。 |
+| `#pragma param …` | 反射的材质参数(见下表)。 |
+| `#pragma switch NAME [default(on)]` | 材质可控的静态排列开关(一个 `#define`)。 |
+| `#pragma feature NAME` | 引擎选择的编译期变体关键字。 |
+| `#pragma vertex` / `#pragma fragment` … `#pragma end` | Stage 代码体。**2D 域的顶点段可省略**——引擎注入规范顶点段。 |
+| `#include "path"` | 文本 include(由宿主解析)。 |
+
+### 只写片元
+
+2D 精灵的世界变换烘焙进批处理顶点,所以所有 2D 着色器共享同一个顶点段。省略
+`#pragma vertex`,只写片元;以下 varying 开箱即用:
+
+| Varying | 类型 | 值 |
+|---|---|---|
+| `v_color` | `vec4` | 每实例色调(精灵的 `color`)。 |
+| `v_texCoord` | `vec2` | 纹理 UV。 |
+| `v_worldPos` | `highp vec2` | 世界坐标(**仅 Lit2D 域**)。 |
+
+精灵纹理是 `u_textures[0]`(声明 `uniform sampler2D u_textures[8];`——单元 0–7 归批处理;
+纹理*参数*自动绑定在其上方)。
+
+### 用 `#pragma param` 声明参数
```glsl
#pragma param u_tint color default(1, 1, 1, 1)
-#pragma param u_intensity float default(1.0)
+#pragma param u_intensity float default(1.0) range(0, 4) ui(slider)
#pragma param u_mask texture default(white)
// … your GLSL fragment code, reading u_tint / u_intensity / u_mask …
@@ -26,9 +72,24 @@ std140 uniform 块,于是 CPU 能按名字设置、并安全地送到 GPU。一
| 参数类型 | GLSL | 值的形状 | 备注 |
|---|---|---|---|
-| `float` | `float` | `number` | 标量旋钮。 |
-| `color` | `vec4` | `[r, g, b, a]` | RGBA,0..1。 |
-| `texture` | `sampler2D` | 纹理句柄 | `default(white)` 等作为回退。 |
+| `float` / `int` | `float` / `int` | `number` | 标量旋钮;`range(min,max)` + `ui(slider)` 控制检视器。 |
+| `vec2` / `vec3` / `vec4` | 同名 | `[x, y, …]` | 向量旋钮。 |
+| `color` | `vec4` | `[r, g, b, a]` | RGBA,0..1;检视器里是取色器。 |
+| `texture` | `sampler2D` | 纹理句柄 | `default(white \| black \| flatnormal)` 未设置时的回退。 |
+
+参数存在引擎生成的 std140 块里,并从 `default(…)` 初始化——材质从未设置某参数也能正确绘制。
+
+### 注入的 uniform 与 helper
+
+引擎向每个编译的 `.esshader` 注入以下内容——永远不要自己声明它们:
+
+| 注入项 | 可用范围 | 说明 |
+|---|---|---|
+| `u_esTime` | 总是 | `vec4` 帧时钟:`.x` 累计秒,`.y` 帧间隔秒。 |
+| MaterialConstants 块 | 着色器有参数时 | 你的 `#pragma param` 值。 |
+| `es_applyLighting2D(albedo, N, worldPos)` | Lit2D | 应用场景所有灯光(含阴影),返回受光颜色。 |
+| `es_sampleNormal(map, uv)` | Lit2D | 解包切线空间法线贴图(RGB → [-1,1],归一化)。 |
+| `es_shadowFactor2D(worldPos, target, softness)` | Lit2D | 朝向目标点的遮挡系数(`es_applyLighting2D` 内部使用)。 |
`#pragma switch` 选择编译期烘焙进材质的静态着色器排列(通过 `compileShader` 的 `features` 参数)。
diff --git a/sdk/src/builtinShaders.ts b/sdk/src/builtinShaders.ts
index 217758156..ff4cc7414 100644
--- a/sdk/src/builtinShaders.ts
+++ b/sdk/src/builtinShaders.ts
@@ -62,6 +62,147 @@ void main() {
#pragma end
`;
+const SPRITE_HIT_FLASH = `#pragma shader "Hit Flash"
+#pragma version 300 es
+#pragma domain Unlit2D
+#pragma param u_flash float default(0) range(0,1) ui(slider)
+#pragma param u_flashColor 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;
+
+// Drive u_flash 1 → 0 from code (tween) for the classic damage blink.
+void main() {
+ vec4 base = texture(u_textures[0], v_texCoord) * v_color;
+ fragColor = vec4(mix(base.rgb, u_flashColor.rgb, u_flash), base.a);
+}
+#pragma end
+`;
+
+const SPRITE_OUTLINE = `#pragma shader "Outline"
+#pragma version 300 es
+#pragma domain Unlit2D
+#pragma param u_outlineColor color default(1,1,1,1)
+#pragma param u_outlineWidth float default(1) range(0,8)
+
+#pragma fragment
+precision mediump float;
+
+in vec4 v_color;
+in vec2 v_texCoord;
+
+uniform sampler2D u_textures[8];
+
+out vec4 fragColor;
+
+void main() {
+ vec4 base = texture(u_textures[0], v_texCoord) * v_color;
+ highp vec2 texel = u_outlineWidth / vec2(textureSize(u_textures[0], 0));
+ float edge = 0.0;
+ edge = max(edge, texture(u_textures[0], v_texCoord + vec2( texel.x, 0.0)).a);
+ edge = max(edge, texture(u_textures[0], v_texCoord + vec2(-texel.x, 0.0)).a);
+ edge = max(edge, texture(u_textures[0], v_texCoord + vec2(0.0, texel.y)).a);
+ edge = max(edge, texture(u_textures[0], v_texCoord + vec2(0.0, -texel.y)).a);
+ edge = max(edge, texture(u_textures[0], v_texCoord + vec2( texel.x, texel.y)).a);
+ edge = max(edge, texture(u_textures[0], v_texCoord + vec2( texel.x, -texel.y)).a);
+ edge = max(edge, texture(u_textures[0], v_texCoord + vec2(-texel.x, texel.y)).a);
+ edge = max(edge, texture(u_textures[0], v_texCoord + vec2(-texel.x, -texel.y)).a);
+ fragColor = mix(vec4(u_outlineColor.rgb, edge * u_outlineColor.a), base, base.a);
+}
+#pragma end
+`;
+
+const SPRITE_DISSOLVE = `#pragma shader "Dissolve"
+#pragma version 300 es
+#pragma domain Unlit2D
+#pragma param u_progress float default(0) range(0,1) ui(slider)
+#pragma param u_edgeColor color default(1,0.5,0,1)
+#pragma param u_edgeWidth float default(0.08) range(0,0.5)
+#pragma param u_noiseScale float default(12) range(1,64)
+
+#pragma fragment
+precision mediump float;
+
+in vec4 v_color;
+in vec2 v_texCoord;
+
+uniform sampler2D u_textures[8];
+
+out vec4 fragColor;
+
+float es_hash(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453123); }
+float es_noise(vec2 p) {
+ vec2 i = floor(p);
+ vec2 f = fract(p);
+ f = f * f * (3.0 - 2.0 * f);
+ return mix(mix(es_hash(i), es_hash(i + vec2(1.0, 0.0)), f.x),
+ mix(es_hash(i + vec2(0.0, 1.0)), es_hash(i + vec2(1.0, 1.0)), f.x), f.y);
+}
+
+// u_progress 0 = intact, 1 = fully dissolved; a glowing edge leads the cut.
+void main() {
+ vec4 base = texture(u_textures[0], v_texCoord) * v_color;
+ float n = es_noise(v_texCoord * u_noiseScale);
+ float cut = u_progress * (1.0 + u_edgeWidth);
+ if (n < cut - u_edgeWidth) discard;
+ vec3 rgb = (n < cut) ? u_edgeColor.rgb : base.rgb;
+ fragColor = vec4(rgb, base.a);
+}
+#pragma end
+`;
+
+const SPRITE_PIXELATE = `#pragma shader "Pixelate"
+#pragma version 300 es
+#pragma domain Unlit2D
+#pragma param u_pixels float default(32) range(2,256)
+
+#pragma fragment
+precision mediump float;
+
+in vec4 v_color;
+in vec2 v_texCoord;
+
+uniform sampler2D u_textures[8];
+
+out vec4 fragColor;
+
+void main() {
+ vec2 uv = (floor(v_texCoord * u_pixels) + 0.5) / u_pixels;
+ fragColor = texture(u_textures[0], uv) * v_color;
+}
+#pragma end
+`;
+
+const SPRITE_UV_SCROLL = `#pragma shader "UV Scroll"
+#pragma version 300 es
+#pragma domain Unlit2D
+#pragma param u_scrollSpeed vec2 default(0.1,0)
+
+#pragma fragment
+precision mediump float;
+
+in vec4 v_color;
+in vec2 v_texCoord;
+
+uniform sampler2D u_textures[8];
+
+out vec4 fragColor;
+
+// u_esTime.x is the engine frame clock (seconds), injected into every shader.
+void main() {
+ vec2 uv = fract(v_texCoord + u_esTime.x * u_scrollSpeed);
+ fragColor = texture(u_textures[0], uv) * v_color;
+}
+#pragma end
+`;
+
export const BUILTIN_SHADER_TEMPLATES: readonly BuiltinShaderTemplate[] = [
{
id: 'sprite-unlit',
@@ -77,6 +218,41 @@ export const BUILTIN_SHADER_TEMPLATES: readonly BuiltinShaderTemplate[] = [
source: SPRITE_LIT,
defaults: { u_tint: { r: 1, g: 1, b: 1, a: 1 } },
},
+ {
+ id: 'sprite-hit-flash',
+ label: 'Hit Flash',
+ description: 'Blend toward a flash color; drive u_flash from code for damage blinks.',
+ source: SPRITE_HIT_FLASH,
+ defaults: {},
+ },
+ {
+ id: 'sprite-outline',
+ label: 'Outline',
+ description: 'Colored silhouette outline around the sprite\'s opaque pixels.',
+ source: SPRITE_OUTLINE,
+ defaults: {},
+ },
+ {
+ id: 'sprite-dissolve',
+ label: 'Dissolve',
+ description: 'Noise-driven burn-away with a glowing edge (u_progress 0→1).',
+ source: SPRITE_DISSOLVE,
+ defaults: {},
+ },
+ {
+ id: 'sprite-pixelate',
+ label: 'Pixelate',
+ description: 'Quantizes UVs to a coarse pixel grid.',
+ source: SPRITE_PIXELATE,
+ defaults: {},
+ },
+ {
+ id: 'sprite-uv-scroll',
+ label: 'UV Scroll',
+ description: 'Scrolls the texture over time (conveyors, water, clouds).',
+ source: SPRITE_UV_SCROLL,
+ defaults: {},
+ },
];
export function builtinShaderTemplate(id: string): BuiltinShaderTemplate | undefined {
diff --git a/sdk/src/camera/CameraPlugin.ts b/sdk/src/camera/CameraPlugin.ts
index 3f9aac2e8..1e0169154 100644
--- a/sdk/src/camera/CameraPlugin.ts
+++ b/sdk/src/camera/CameraPlugin.ts
@@ -476,7 +476,7 @@ export function cameraPlugin(
width, height, elapsed,
});
} else {
- pipeline.beginFrame();
+ pipeline.beginFrame(elapsed);
pipeline.beginScreenCapture();
for (const cam of cameras) {
const vp = cam.viewportRect;
diff --git a/sdk/src/materialGraph.ts b/sdk/src/materialGraph.ts
index ca42cb7ce..2f4ff768c 100644
--- a/sdk/src/materialGraph.ts
+++ b/sdk/src/materialGraph.ts
@@ -20,6 +20,7 @@ export type GraphNodeType =
| 'output' // the root: its `color` input becomes fragColor
| 'uv' // v_texCoord
| 'vertexColor' // v_color (the sprite's per-instance tint)
+ | 'time' // u_esTime.x — the injected engine frame clock (seconds)
| 'constFloat' // a scalar material param (#pragma param ... float)
| 'constColor' // an RGBA material param (#pragma param ... color)
| 'textureSample' // sample a texture material param at a UV (#pragma param ... texture)
@@ -27,7 +28,11 @@ export type GraphNodeType =
| 'add'
| 'lerp'
| 'oneMinus' // 1 - x (invert a mask)
- | 'saturate'; // clamp(x, 0, 1)
+ | 'saturate' // clamp(x, 0, 1)
+ | 'sin'
+ | 'smoothstep' // smoothstep(edge0, edge1, x) — edges are node literals
+ | 'noise' // procedural value noise over a UV (scale is a node literal)
+ | 'panner'; // uv + time × speed (speed is a node literal pair)
export interface MaterialGraphNode {
id: string;
@@ -77,9 +82,16 @@ export function compileMaterialGraph(graph: MaterialGraph): string {
const memo = new Map<string, { expr: string; type: GraphType }>();
const visiting = new Set<string>();
const params: string[] = [];
+ const helpers = new Set<string>();
const body: string[] = [];
let tmp = 0;
+ const numParam = (n: MaterialGraphNode, key: string, fallback: number): string => {
+ const v = n.params?.[key];
+ const f = typeof v === 'number' && Number.isFinite(v) ? v : fallback;
+ return f.toFixed(4);
+ };
+
const paramName = (n: MaterialGraphNode) =>
typeof n.params?.name === 'string' ? (n.params.name as string) : `u_${n.id}`;
@@ -105,6 +117,9 @@ export function compileMaterialGraph(graph: MaterialGraph): string {
case 'vertexColor':
out = { expr: 'v_color', type: 'vec4' };
break;
+ case 'time':
+ out = { expr: 'u_esTime.x', type: 'float' };
+ break;
case 'constFloat': {
const name = paramName(n);
const v = typeof n.params?.value === 'number' ? n.params.value : 0;
@@ -150,15 +165,40 @@ export function compileMaterialGraph(graph: MaterialGraph): string {
break;
}
case 'oneMinus':
- case 'saturate': {
- // Both are single-input and preserve type — GLSL broadcasts the scalar over any genType.
+ case 'saturate':
+ case 'sin': {
+ // Single-input, type-preserving — GLSL broadcasts over any genType.
const a = input('x');
const t = `n${tmp++}`;
- const expr = n.type === 'oneMinus' ? `1.0 - ${a.expr}` : `clamp(${a.expr}, 0.0, 1.0)`;
+ const expr = n.type === 'oneMinus' ? `1.0 - ${a.expr}`
+ : n.type === 'saturate' ? `clamp(${a.expr}, 0.0, 1.0)`
+ : `sin(${a.expr})`;
body.push(`${a.type} ${t} = ${expr};`);
out = { expr: t, type: a.type };
break;
}
+ case 'smoothstep': {
+ const a = input('x');
+ const t = `n${tmp++}`;
+ body.push(`${a.type} ${t} = smoothstep(${numParam(n, 'edge0', 0)}, ${numParam(n, 'edge1', 1)}, ${a.expr});`);
+ out = { expr: t, type: a.type };
+ break;
+ }
+ case 'noise': {
+ helpers.add(NOISE_HELPER);
+ const uv = n.inputs?.uv ? input('uv').expr : 'v_texCoord';
+ const t = `n${tmp++}`;
+ body.push(`float ${t} = es_noise(${uv} * ${numParam(n, 'scale', 12)});`);
+ out = { expr: t, type: 'float' };
+ break;
+ }
+ case 'panner': {
+ const uv = n.inputs?.uv ? input('uv').expr : 'v_texCoord';
+ const t = `n${tmp++}`;
+ body.push(`vec2 ${t} = fract(${uv} + u_esTime.x * vec2(${numParam(n, 'speedX', 0.1)}, ${numParam(n, 'speedY', 0)}));`);
+ out = { expr: t, type: 'vec2' };
+ break;
+ }
case 'output': {
const c = input('color');
out = { expr: toVec4(c.expr, c.type), type: 'vec4' };
@@ -182,39 +222,21 @@ export function compileMaterialGraph(graph: MaterialGraph): string {
const name = graph.name ?? 'Graph';
const domain = graph.domain ?? 'Unlit2D';
const paramBlock = params.length ? params.join('\n') + '\n' : '';
+ const helperBlock = helpers.size ? [...helpers].join('\n') + '\n\n' : '';
const bodyBlock = body.map((l) => ' ' + l).join('\n');
+ // Fragment-only: the canonical 2D vertex stage is injected by the engine's ShaderParser.
return `#pragma shader "${name}"
#pragma version 300 es
#pragma domain ${domain}
${paramBlock}
-#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;
-out vec4 fragColor;
+${helperBlock}out vec4 fragColor;
void main() {
${bodyBlock}
@@ -224,6 +246,15 @@ ${bodyBlock}
`;
}
+const NOISE_HELPER = `float es_hash(vec2 p) { return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453123); }
+float es_noise(vec2 p) {
+ vec2 i = floor(p);
+ vec2 f = fract(p);
+ f = f * f * (3.0 - 2.0 * f);
+ return mix(mix(es_hash(i), es_hash(i + vec2(1.0, 0.0)), f.x),
+ mix(es_hash(i + vec2(0.0, 1.0)), es_hash(i + vec2(1.0, 1.0)), f.x), f.y);
+}`;
+
// =============================================================================
// Editor schema + graph operations (the visual node editor, P5b)
// =============================================================================
@@ -257,6 +288,7 @@ export const NODE_SPECS: Record<GraphNodeType, NodeSpec> = {
output: { label: 'Output', inputs: [{ name: 'color', type: 'vec4' }], output: null, params: [], addable: false },
uv: { label: 'UV', inputs: [], output: 'vec2', params: [], addable: true },
vertexColor: { label: 'Vertex Color', inputs: [], output: 'vec4', params: [], addable: true },
+ time: { label: 'Time', inputs: [], output: 'float', params: [], addable: true },
constFloat: { label: 'Float', inputs: [], output: 'float', params: [{ key: 'value', label: 'Value', kind: 'float' }], addable: true },
constColor: { label: 'Color', inputs: [], output: 'vec4', params: [{ key: 'value', label: 'Color', kind: 'color' }], addable: true },
textureSample: { label: 'Texture', inputs: [{ name: 'uv', type: 'vec2' }], output: 'vec4', params: [{ key: 'name', label: 'Param', kind: 'texture' }], addable: true },
@@ -265,6 +297,10 @@ export const NODE_SPECS: Record<GraphNodeType, NodeSpec> = {
lerp: { label: 'Lerp', inputs: [{ name: 'a', type: 'vec4' }, { name: 'b', type: 'vec4' }, { name: 't', type: 'float' }], output: 'vec4', params: [], addable: true },
oneMinus: { label: 'One Minus', inputs: [{ name: 'x', type: 'vec4' }], output: 'vec4', params: [], addable: true },
saturate: { label: 'Saturate', inputs: [{ name: 'x', type: 'vec4' }], output: 'vec4', params: [], addable: true },
+ sin: { label: 'Sin', inputs: [{ name: 'x', type: 'float' }], output: 'float', params: [], addable: true },
+ smoothstep: { label: 'Smoothstep', inputs: [{ name: 'x', type: 'float' }], output: 'float', params: [{ key: 'edge0', label: 'Edge 0', kind: 'float' }, { key: 'edge1', label: 'Edge 1', kind: 'float' }], addable: true },
+ noise: { label: 'Noise', inputs: [{ name: 'uv', type: 'vec2' }], output: 'float', params: [{ key: 'scale', label: 'Scale', kind: 'float' }], addable: true },
+ panner: { label: 'Panner', inputs: [{ name: 'uv', type: 'vec2' }], output: 'vec2', params: [{ key: 'speedX', label: 'Speed X', kind: 'float' }, { key: 'speedY', label: 'Speed Y', kind: 'float' }], addable: true },
};
/** A default starter graph: a white texture sample straight into the output. */
@@ -296,6 +332,9 @@ function defaultParams(type: GraphNodeType, id: string): Record<string, unknown>
case 'constFloat': return { name: `u_${id}`, value: 1 };
case 'constColor': return { name: `u_${id}`, value: [1, 1, 1, 1] };
case 'textureSample': return { name: `u_${id}`, default: 'white' };
+ case 'smoothstep': return { edge0: 0, edge1: 1 };
+ case 'noise': return { scale: 12 };
+ case 'panner': return { speedX: 0.1, speedY: 0 };
default: return undefined;
}
}
diff --git a/sdk/src/renderPipeline.ts b/sdk/src/renderPipeline.ts
index fcb5a5eaf..fc4089e05 100644
--- a/sdk/src/renderPipeline.ts
+++ b/sdk/src/renderPipeline.ts
@@ -66,8 +66,8 @@ export class RenderPipeline {
this.preFlushCallbacks_.push(cb);
}
- beginFrame(): void {
- Renderer.beginFrame();
+ beginFrame(elapsedSec = 0): void {
+ Renderer.beginFrame(elapsedSec);
}
beginScreenCapture(): void {
@@ -116,7 +116,7 @@ export class RenderPipeline {
this.lastHeight_ = height;
}
- Renderer.beginFrame();
+ Renderer.beginFrame(elapsed);
Renderer.setViewport(0, 0, width, height);
Renderer.clearBuffers(3);
Renderer.begin(viewProjection);
diff --git a/sdk/src/renderer.ts b/sdk/src/renderer.ts
index 854f95838..9c7a1bc69 100644
--- a/sdk/src/renderer.ts
+++ b/sdk/src/renderer.ts
@@ -59,8 +59,8 @@ export const Renderer = {
module?.renderer_resize(width, height);
},
- beginFrame(): void {
- module?.renderer_beginFrame();
+ beginFrame(elapsedSec = 0): void {
+ module?.renderer_beginFrame(elapsedSec);
},
updateTransforms(registry: { _cpp: CppRegistry }): void {
diff --git a/sdk/src/wasm.ts b/sdk/src/wasm.ts
index 36f7c3158..d703ebb71 100644
--- a/sdk/src/wasm.ts
+++ b/sdk/src/wasm.ts
@@ -241,7 +241,7 @@ export interface ESEngineModule {
// Renderer API (RenderFrame)
renderer_init(width: number, height: number): void;
renderer_resize(width: number, height: number): void;
- renderer_beginFrame(): void;
+ renderer_beginFrame(elapsedSec: number): void;
renderer_updateTransforms(registry: CppRegistry): void;
renderer_begin(matrixPtr: number, targetHandle: number): void;
renderer_flush(): void;
diff --git a/sdk/tests/materialGraph.test.ts b/sdk/tests/materialGraph.test.ts
index 8a4e0826e..7ffa10eb8 100644
--- a/sdk/tests/materialGraph.test.ts
+++ b/sdk/tests/materialGraph.test.ts
@@ -43,6 +43,34 @@ describe('compileMaterialGraph', () => {
expect(src.indexOf('texture(u_albedo')).toBeLessThan(src.indexOf('n0 * u_tint'));
});
+ it('emits fragment-only shaders (the canonical vertex stage is engine-injected)', () => {
+ expect(compileMaterialGraph(tintGraph)).not.toContain('#pragma vertex');
+ });
+
+ it('compiles time/sin/panner/noise/smoothstep nodes', () => {
+ const g: MaterialGraph = {
+ output: 'out',
+ nodes: [
+ { id: 'uv', type: 'uv' },
+ { id: 'pan', type: 'panner', inputs: { uv: 'uv' }, params: { speedX: 0.25, speedY: 0 } },
+ { id: 'tex', type: 'textureSample', inputs: { uv: 'pan' }, params: { name: 'u_albedo', default: 'white' } },
+ { id: 't', type: 'time' },
+ { id: 's', type: 'sin', inputs: { x: 't' } },
+ { id: 'n', type: 'noise', inputs: { uv: 'uv' }, params: { scale: 8 } },
+ { id: 'ss', type: 'smoothstep', inputs: { x: 'n' }, params: { edge0: 0.2, edge1: 0.8 } },
+ { id: 'mask', type: 'multiply', inputs: { a: 'ss', b: 's' } },
+ { id: 'mul', type: 'multiply', inputs: { a: 'tex', b: 'mask' } },
+ { id: 'out', type: 'output', inputs: { color: 'mul' } },
+ ],
+ };
+ const src = compileMaterialGraph(g);
+ expect(src).toContain('fract(v_texCoord + u_esTime.x * vec2(0.2500, 0.0000))');
+ expect(src).toContain('sin(u_esTime.x)');
+ expect(src).toContain('es_noise(v_texCoord * 8.0000)');
+ expect(src).toContain('smoothstep(0.2000, 0.8000,');
+ expect(src.match(/float es_noise/g)?.length).toBe(1); // helper emitted once
+ });
+
it('reuses a shared node once (DAG, not a tree)', () => {
const g: MaterialGraph = {
output: 'out',
diff --git a/src/esengine/bindings/RendererBindings.cpp b/src/esengine/bindings/RendererBindings.cpp
index 81764697d..aaf67f048 100644
--- a/src/esengine/bindings/RendererBindings.cpp
+++ b/src/esengine/bindings/RendererBindings.cpp
@@ -238,8 +238,9 @@ void renderer_resize(u32 width, u32 height) {
g_renderFrame->resize(width, height);
}
-void renderer_beginFrame() {
+void renderer_beginFrame(f32 elapsedSec) {
ctx().state().transforms_updated = false;
+ if (auto* rc = ctx().tryGet<RenderContext>()) rc->setFrameTime(elapsedSec);
}
void renderer_begin(uintptr_t matrixPtr, u32 targetHandle) {
diff --git a/src/esengine/bindings/RendererBindings.hpp b/src/esengine/bindings/RendererBindings.hpp
index 0bc0caa9e..b6eb6a513 100644
--- a/src/esengine/bindings/RendererBindings.hpp
+++ b/src/esengine/bindings/RendererBindings.hpp
@@ -44,7 +44,7 @@ void renderFrameWithMatrix(ecs::Registry& registry, i32 viewportWidth, i32 viewp
void renderer_init(u32 width, u32 height);
void renderer_resize(u32 width, u32 height);
-void renderer_beginFrame();
+void renderer_beginFrame(f32 elapsedSec);
void renderer_begin(uintptr_t matrixPtr, u32 targetHandle);
void renderer_flush();
void renderer_end();
diff --git a/src/esengine/renderer/FrameConstants.hpp b/src/esengine/renderer/FrameConstants.hpp
index a8ea850cb..13494aa65 100644
--- a/src/esengine/renderer/FrameConstants.hpp
+++ b/src/esengine/renderer/FrameConstants.hpp
@@ -40,4 +40,16 @@ inline constexpr u32 FRAME_CONSTANTS_BINDING = 0;
/** @brief GLSL block name; must match the shader declarations and Shader::compile lookup. */
inline constexpr const char* FRAME_CONSTANTS_BLOCK = "FrameConstants";
+/**
+ * @brief CPU mirror of the injected TimeConstants block (std140).
+ * @details u_esTime = (elapsed seconds, delta seconds, 0, 0). Engine-owned: ShaderParser
+ * injects the block into every assembled stage — shaders never declare it.
+ */
+struct TimeConstants {
+ glm::vec4 time{0.0f};
+};
+
+inline constexpr u32 TIME_CONSTANTS_BINDING = 3;
+inline constexpr const char* TIME_CONSTANTS_BLOCK = "TimeConstants";
+
} // namespace esengine
diff --git a/src/esengine/renderer/RenderContext.cpp b/src/esengine/renderer/RenderContext.cpp
index d8bac652f..3f7d96b4a 100644
--- a/src/esengine/renderer/RenderContext.cpp
+++ b/src/esengine/renderer/RenderContext.cpp
@@ -61,6 +61,10 @@ void RenderContext::shutdown() {
device_.deleteBuffer(frameUbo_);
frameUbo_ = 0;
}
+ if (timeUbo_ != 0) {
+ device_.deleteBuffer(timeUbo_);
+ timeUbo_ = 0;
+ }
materials_.clear(); // free per-material UBOs while the device is still valid
lights_.free(); // free the lighting UBO while the device is still valid
@@ -105,6 +109,12 @@ void RenderContext::initFrameUbo() {
// at compile time (Shader::compile).
device_.bindBufferBase(FRAME_CONSTANTS_BINDING, frameUbo_);
+ timeUbo_ = device_.createBuffer();
+ TimeConstants time{};
+ device_.bindUniformBuffer(timeUbo_);
+ device_.bufferData(GfxBufferTarget::Uniform, &time, sizeof(TimeConstants), /*dynamic=*/true);
+ device_.bindBufferBase(TIME_CONSTANTS_BINDING, timeUbo_);
+
ES_LOG_DEBUG("FrameConstants UBO created (ID: {})", frameUbo_);
}
@@ -115,4 +125,12 @@ void RenderContext::updateFrameConstants(const glm::mat4& viewProjection) {
sizeof(glm::mat4));
}
+void RenderContext::setFrameTime(f32 elapsedSec) {
+ const f32 dt = (lastElapsed_ > 0.0f && elapsedSec > lastElapsed_) ? elapsedSec - lastElapsed_ : 0.0f;
+ lastElapsed_ = elapsedSec;
+ TimeConstants time{ glm::vec4(elapsedSec, dt, 0.0f, 0.0f) };
+ device_.bindUniformBuffer(timeUbo_);
+ device_.bufferSubData(GfxBufferTarget::Uniform, 0, &time, sizeof(TimeConstants));
+}
+
} // namespace esengine
diff --git a/src/esengine/renderer/RenderContext.hpp b/src/esengine/renderer/RenderContext.hpp
index ec001f355..37f0d4655 100644
--- a/src/esengine/renderer/RenderContext.hpp
+++ b/src/esengine/renderer/RenderContext.hpp
@@ -157,6 +157,9 @@ public:
*/
void updateFrameConstants(const glm::mat4& viewProjection);
+ /** @brief Uploads the frame clock into the injected TimeConstants UBO (u_esTime = elapsed, dt). */
+ void setFrameTime(f32 elapsedSec);
+
/**
* @brief The engine-side material registry (handle -> resolved render state).
* @details Written by the SDK material binding (defineMaterial) and read by the render
@@ -187,6 +190,8 @@ private:
u32 blackTextureId_ = 0;
u32 flatNormalTextureId_ = 0;
u32 frameUbo_ = 0;
+ u32 timeUbo_ = 0;
+ f32 lastElapsed_ = 0.0f;
MaterialStore materials_;
LightStore lights_;
diff --git a/src/esengine/renderer/Shader.cpp b/src/esengine/renderer/Shader.cpp
index b27e09968..ba13dfbf8 100644
--- a/src/esengine/renderer/Shader.cpp
+++ b/src/esengine/renderer/Shader.cpp
@@ -179,6 +179,12 @@ bool Shader::compile(const std::string& vertexSrc, const std::string& fragmentSr
device_->uniformBlockBinding(programId_, lightBlock, LIGHT_CONSTANTS_BINDING);
}
+ // Same for the injected frame clock (u_esTime).
+ u32 timeBlock = device_->getUniformBlockIndex(programId_, TIME_CONSTANTS_BLOCK);
+ if (timeBlock != GFX_INVALID_UNIFORM_BLOCK) {
+ device_->uniformBlockBinding(programId_, timeBlock, TIME_CONSTANTS_BINDING);
+ }
+
ES_LOG_DEBUG("Shader compiled successfully (program ID: {}, active uniforms: {})",
programId_, activeUniforms_.size());
return true;
diff --git a/src/esengine/resource/ShaderParser.cpp b/src/esengine/resource/ShaderParser.cpp
index 0bbc68019..0dcc9fa2f 100644
--- a/src/esengine/resource/ShaderParser.cpp
+++ b/src/esengine/resource/ShaderParser.cpp
@@ -429,6 +429,13 @@ ShaderParser::AssembledStage ShaderParser::assembleStageEx(const ParsedShader& p
++headerLines;
}
+ // Engine-owned frame clock, injected into every stage (identical in both, so the
+ // program links). u_esTime = (elapsed s, delta s, 0, 0); binding 3 (Shader::compile).
+ static const char* kTimeHeader =
+ "layout(std140) uniform TimeConstants { highp vec4 u_esTime; };\n";
+ assembled << kTimeHeader;
+ headerLines += countNewlines(kTimeHeader);
+
// Auto-generated material params (#pragma param): the std140 MaterialConstants block
// (non-texture params in declared order == std140 offset order) plus sampler uniforms.
// Injected after the #defines so both stages share one block and the body can use the
diff --git a/tests/renderer/test_shader_variant.cpp b/tests/renderer/test_shader_variant.cpp
index 0cdb00a5f..9c95c1f0a 100644
--- a/tests/renderer/test_shader_variant.cpp
+++ b/tests/renderer/test_shader_variant.cpp
@@ -100,6 +100,11 @@ static void testFragmentOnly() {
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");
+
+ const std::string af = ShaderParser::assembleStage(authored, ShaderStage::Fragment);
+ CHECK(av.find("uniform TimeConstants") != std::string::npos &&
+ af.find("uniform TimeConstants") != std::string::npos,
+ "u_esTime clock block injected into both stages");
}
int main() {