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(shaders): a material vertex hook gets a derived WGSL twin, and an effect that displaces its vertices is converted with the displacement as that hook

yhhde28ed8825b8
diff --git a/pipeline/src/import/cocos/effectConvert.ts b/pipeline/src/import/cocos/effectConvert.ts
index 87e656811..0c8ff1e19 100644
--- a/pipeline/src/import/cocos/effectConvert.ts
+++ b/pipeline/src/import/cocos/effectConvert.ts
@@ -187,7 +187,8 @@ function expandIncludes(
* and the rest are arithmetic on them. So the vertex program is not given a stage of its own: it is run in the fragment, ahead of the fragment's own
* function, with the attributes it reads standing for what the engine's stage passes down. The result is the same for everything that is a function
* of the vertex's own values and the material's (a tiling, a world position, a tangent frame), and costs a little more per pixel than per vertex.
- * What it cannot reproduce is where the vertex is drawn: a displacement of the position is not applied, which the pass says.
+ * Where the vertex is drawn is the engine's, so a program that displaces the position (a sway, a wave) is also given to the engine as the material's
+ * vertex hook, run with the same attributes, which moves the vertex where the effect moved it. The hook reads no texture: one that does is not given.
*/
const VERTEX_PRELUDE = `// The vertex stage of the effect, run per fragment on what the engine's vertex stage hands down.
struct StandardVertInput { highp vec4 position; vec3 normal; vec4 tangent; };
@@ -227,6 +228,8 @@ interface Emulated {
/** The assignments that give the attributes it declares their values. */
attributeSetup: string[];
approximations: string[];
+ /** The program moves the vertex before it is placed (a displacement by time or by a function of the position). */
+ displaces: boolean;
}
function emulateVertex(program: string, entry: string): Emulated | { error: string } {
@@ -251,9 +254,8 @@ function emulateVertex(program: string, entry: string): Emulated | { error: stri
const entryRe = new RegExp(`\\bvec4\\s+${entry}\\s*\\(\\s*\\)`);
if (!entryRe.test(text)) return { error: `the vertex entry ${entry}() is not there` };
text = text.replace(entryRe, 'vec4 cocos_vert()');
- if (/\bcc_(?:time)\b[^;]*\b(?:position|pos)\b|\b(?:position|pos)\b[^;]*\bcc_time\b/.test(text) || /\bsin\s*\([^;]*\b(?:position|pos)\b/.test(text)) {
- approximations.push('a displacement of the vertex position is not applied');
- }
+ // A statement that assigns the position before the matrices are applied, from time or a periodic function: a displacement.
+ const displaces = /(?:\bIn\.position|\bposition|\ba_position)\b[^;]*\b(?:cc_time|sin|cos)\b|\b(?:cc_time|sin|cos)\b[^;]*(?:\bIn\.position|\bposition|\ba_position)\b/.test(text);
const setup: string[] = [];
const declared: string[] = [];
for (const [name, type] of attributes) {
@@ -262,7 +264,7 @@ function emulateVertex(program: string, entry: string): Emulated | { error: stri
if (source) setup.push(` ${name} = ${source}${coerce(type, name)};`);
if (name === 'a_texCoord1') approximations.push('the second uv is the first until the engine carries one');
}
- return { source: text, attributes: declared.join('\n'), outputs, attributeSetup: setup, approximations };
+ return { source: text, attributes: declared.join('\n'), outputs, attributeSetup: setup, approximations, displaces };
}
/** The conversion that makes an engine value of one width fit the type an attribute is declared with. */
@@ -477,6 +479,31 @@ export function convertPass(effect: CocosEffect, pass: EffectPass, shaderName: s
...(usesSpriteTexture ? ['uniform sampler2D u_textures[8];'] : []), 'out vec4 fragColor;', '', PRELUDE,
...(matrixDefs ? [matrixDefs, ''] : []), ...(alphaTest ? [alphaTest, ''] : []),
...(vertex ? [vertex.attributes, VERTEX_PRELUDE, vertexText.trim(), ''] : []), body.trim(), '', ...main, '#pragma end', '');
+ // The displacement, given to the engine as the material's vertex hook: the same program, run on the vertex's own position and normal. The engine's
+ // vertex stage owns the attribute names, so the program's are its own here.
+ if (vertex?.displaces) {
+ const vertexReadsTexture = params.some((p) => p.type === 'texture' && new RegExp(`\b${p.name}\b`).test(vertexText));
+ if (vertexReadsTexture) {
+ approximations.push('a displacement of the vertex position that reads a texture is not applied');
+ } else {
+ const own = (text: string): string => text.replace(/\ba_(\w+)\b/g, 'hook_a_$1');
+ const extra = [...vertex.attributes.matchAll(/\ba_(texCoord1|uv0)\b/g)].map((m) => ` hook_a_${m[1]} = uv;`);
+ const hook = [
+ '#pragma vertexoffset',
+ '#define cc_time u_time',
+ ...(matrixDefs ? [matrixDefs] : []),
+ own(vertex.attributes), own(VERTEX_PRELUDE), own(vertexText.trim()), '',
+ 'void esMaterialVertex(inout vec3 local, inout vec3 localNormal, in vec2 uv) {',
+ ' hook_a_position = local; hook_a_normal = localNormal; hook_a_tangent = vec4(1.0, 0.0, 0.0, 1.0); hook_a_texCoord = uv; hook_a_color = es_vertexColor;',
+ ...extra,
+ ' local = cocos_vert().xyz;',
+ '}', '#pragma end', '',
+ ];
+ lines.splice(lines.indexOf('#pragma fragment'), 0, ...hook);
+ }
+ } else if (vertex && /\bcc_time\b/.test(vertexText) && /\bsin\b|\bcos\b/.test(vertexText)) {
+ approximations.push('the vertex program computes something of time that the fragment does not reproduce');
+ }
return { shader: { source: lines.join('\n'), switches, params, approximations }, unsupported: null, state };
}
diff --git a/pipeline/tests/cocos-effect-convert.test.ts b/pipeline/tests/cocos-effect-convert.test.ts
index 8189750bb..9a054215f 100644
--- a/pipeline/tests/cocos-effect-convert.test.ts
+++ b/pipeline/tests/cocos-effect-convert.test.ts
@@ -127,11 +127,29 @@ describe('converting a pass', () => {
describe('a pass whose vertex program does more than place the vertex', () => {
const SWAY = SPRITE_ADD.replace('vec4 pos = cc_matViewProj * vec4(a_position, 1);', 'vec4 pos = cc_matViewProj * vec4(a_position + vec3(sin(cc_time.x), 0, 0), 1);');
- it('is converted without the displacement, and says so', () => {
+ it('is converted with its displacement as the material vertex hook, and that hook translates for WebGPU as well', async () => {
const swayed = convertEffect(parseEffect(SWAY), 'sway').techniques[0]!.passes[0]!;
expect(swayed.unsupported).toBeNull();
- expect(swayed.shader!.approximations).toContain('a displacement of the vertex position is not applied');
- });
+ const source = swayed.shader!.source;
+ expect(source).toContain('#pragma vertexoffset');
+ expect(source).toContain('void esMaterialVertex(inout vec3 local, inout vec3 localNormal, in vec2 uv)');
+ expect(source).toContain('local = cocos_vert().xyz;');
+ // the hook has attribute names of its own: the engine vertex stage declares a_position and the others
+ const hook = /#pragma vertexoffset\n([\s\S]*?)#pragma end/.exec(source)![1]!;
+ expect(hook).not.toMatch(/(?<!hook_)\ba_position\b/);
+ expect(swayed.shader!.approximations.join('\n')).not.toContain('displacement');
+ // and the twin tool derives its WGSL, which is what a GLSL error in it would show as
+ // @ts-expect-error a repo tool, shipped as .mjs with no declarations
+ const tool = await import('../../tools/gen-shader-twins.mjs');
+ let module: unknown = null;
+ try { module = await tool.loadTwinModule(); } catch { /* no built engine here */ }
+ if (module) {
+ const derived = await tool.deriveTwin(module, source, {});
+ expect(derived.status).toBe('generated');
+ expect(derived.text).toContain('#pragma vertexoffset wgsl');
+ expect(derived.text).toContain('tc.u_time');
+ }
+ }, 120000);
it('is not converted when its vertex program skins the mesh', () => {
const skinned = SPRITE_ADD.replace('in vec4 a_color;', 'in vec4 a_color;\n in vec4 a_joints;');
diff --git a/tools/gen-shader-twins.mjs b/tools/gen-shader-twins.mjs
index d49dee0b0..e79fbb006 100644
--- a/tools/gen-shader-twins.mjs
+++ b/tools/gen-shader-twins.mjs
@@ -19,6 +19,10 @@
* naga (vendored WASI wasm) — SPIR-V → WGSL, in-process
* post (this file) — entry rename to vs_main/fs_main
*
+ * A material's vertex hook (`#pragma vertexoffset`) is translated the same way, as a small program of its own: the hook, the material's block and
+ * a `main` that calls it. What comes out is the hook's function and the helpers it calls, under the names the engine's WGSL vertex stage injects them
+ * with (`esMaterialVertex(local, localNormal, uv)`, the material block as `mc`). A hook that reads a texture is not translated.
+ *
* Both converters live in build-tools/shader-twins/ as committed wasm — the
* pipeline needs no Vulkan SDK, no Rust toolchain, no PATH binaries.
*
@@ -354,9 +358,81 @@ async function glslToWgsl(glsl, stage, entryName, workDir) {
return text.replace(/\bfn main\(/, `fn ${entryName}(`);
}
+/** The authored GLSL vertex hook of a shader (its `#pragma vertexoffset` section), or null. */
+function glslHookOf(source) {
+ const m = /#pragma vertexoffset[ \t]*\r?\n([\s\S]*?)#pragma end/.exec(source);
+ return m ? m[1] : null;
+}
+
+/** Whether the shader carries a hook twin written by hand: such a twin is authored, and is not replaced. */
+function hasAuthoredHookTwin(source) {
+ return /#pragma vertexoffset wgsl\r?\n(?!\/\/ GENERATED)/.test(source);
+}
+
+/**
+ * One permutation of a shader's vertex hook as WGSL: the hook is compiled as a vertex program of its own (the material's block, the vertex inputs, a
+ * `main` that calls it), and what the engine's vertex stage needs of the result is taken out of it. Null when the hook reads a texture, which
+ * the engine's stage binds on units a program of this size does not know.
+ */
+async function translateHook(hookGlsl, materialBlock, on, textures, workDir) {
+ if (textures.some((t) => new RegExp(`\\b${t.name ?? t}\\b`).test(hookGlsl))) return null;
+ const defines = on.map((n) => `#define ${n}`).join('\n');
+ const glsl = adaptGlsl([
+ '#version 300 es',
+ defines,
+ 'layout(std140) uniform TimeConstants { highp vec4 u_time; highp vec4 u_viewport; };',
+ materialBlock,
+ 'layout(location = 0) in vec3 a_position;',
+ 'layout(location = 1) in vec3 a_normal;',
+ 'layout(location = 2) in vec2 a_texCoord;',
+ 'highp vec4 es_vertexColor;',
+ hookGlsl,
+ 'void main() {',
+ ' vec3 l = a_position; vec3 n = a_normal;',
+ ' es_vertexColor = vec4(1.0);',
+ ' esMaterialVertex(l, n, a_texCoord);',
+ ' gl_Position = vec4(l + n * 0.0, 1.0);',
+ '}',
+ ].join('\n'), []);
+ const spv = path.join(workDir, 'hook.spv');
+ const wgslFile = path.join(workDir, 'hook.wgsl');
+ await writeFile(spv, await glslToSpv(glsl, 'vert'));
+ await spvFileToWgsl(spv, wgslFile);
+ const text = await readFile(wgslFile, 'utf8');
+ // Everything but what the engine's stage declares itself: the material block (it is `mc`), the stage's inputs and outputs, and `main`.
+ const uniformNames = new Map([...text.matchAll(/var<uniform> (\w+): (\w+);/g)].map((m) => [m[1], { MaterialConstants: 'mc', TimeConstants: 'tc' }[m[2]] ?? m[1]]));
+ const keep = [];
+ const blocks = text.split(/\n(?=fn |struct |var<|const |@group)/);
+ let entryName = null;
+ for (const block of blocks) {
+ const fn = /^fn (\w+)\(/.exec(block);
+ if (fn) {
+ if (fn[1] === 'main_1' || fn[1] === 'main') continue;
+ if (fn[1].startsWith('esMaterialVertex_u0028_')) { entryName = fn[1]; }
+ keep.push(block);
+ continue;
+ }
+ if (/^struct (MaterialConstants|TimeConstants|gl_PerVertex)\b/.test(block)) continue;
+ if (/^@group\(\d+\)/.test(block)) continue;
+ if (/^var<uniform>/.test(block)) continue;
+ if (/^var<private> (a_position_1|a_normal_1|a_texCoord_1|es_vertexColor\w*)\b/.test(block) || /^var<private> unnamed_\d+: gl_PerVertex/.test(block)) continue;
+ keep.push(block);
+ }
+ if (!entryName) throw new Error('the translated hook has no esMaterialVertex');
+ let body = keep.join('\n');
+ for (const [from, to] of uniformNames) body = body.replace(new RegExp(`\\b${from}\\b`, 'g'), to);
+ body = body
+ // naga hands every function parameter over as a pointer, and the engine's stage hands the hook its uv by value.
+ .replace(new RegExp(`\\b${entryName}\\b`, 'g'), 'esMaterialVertexBody')
+ .replace(/\bes_vertexColor_1\b/g, 'es_vertexColor');
+ return `${body.trimEnd()}\n\nfn esMaterialVertex(local : ptr<function, vec3f>, localNormal : ptr<function, vec3f>, uv : vec2f) {\n var uvArg = uv;\n esMaterialVertexBody(local, localNormal, &uvArg);\n}`;
+}
+
/** Strip previously generated `wgsl full` sections (for --force / stale regen). */
function stripGeneratedTwins(source) {
- return source.replace(/\n?#pragma (?:vertex|fragment) wgsl full\n[\s\S]*?#pragma end\n?/g, '\n');
+ return source
+ .replace(/\n?#pragma (?:vertex|fragment) wgsl full\n[\s\S]*?#pragma end\n?/g, '\n')
+ .replace(/\n?#pragma vertexoffset wgsl\n\/\/ GENERATED[\s\S]*?#pragma end\n?/g, '\n');
}
/** Hash of a shader's AUTHORED content — everything but the generated twins, i.e.
@@ -501,10 +577,27 @@ export async function deriveTwin(module, original, opts = {}) {
}
const banner = bannerFor(sourceHash(source), assembled);
+ // A vertex hook is translated beside the stages, unless one was written by hand or it reads a texture.
+ let hookTwin = '';
+ const hookGlsl = glslHookOf(source);
+ if (hookGlsl !== null && !hasAuthoredHookTwin(source)) {
+ const block = (/layout\s*\(\s*std140\s*\)\s*uniform\s+MaterialConstants\s*\{[\s\S]*?\}\s*;/.exec(info.vertGlsl) ?? [''])[0];
+ const hooks = new Map();
+ let translatable = true;
+ for (const on of permutationsOf(toggles)) {
+ const cooked = toggles.length === 0 ? info : module.esshader_cookInfo(source, permutationKey(on));
+ const textures = [];
+ for (let i = 0; i < cooked.textures.length; i++) textures.push(cooked.textures[i]);
+ const text = await translateHook(hookGlsl, block, on, textures, workDir);
+ if (text === null) { translatable = false; break; }
+ hooks.set(permutationKey(on), text);
+ }
+ if (translatable) hookTwin = `\n#pragma vertexoffset wgsl\n${banner}\n${composePermutations(toggles, hooks)}\n#pragma end\n`;
+ }
const fragBody = composePermutations(toggles, frag);
const twin =
(engineVertex ? '' : `\n#pragma vertex wgsl full\n${banner}\n${composePermutations(toggles, vert)}\n#pragma end\n`) +
- `\n#pragma fragment wgsl full\n${banner}\n${fragBody}\n#pragma end\n`;
+ `\n#pragma fragment wgsl full\n${banner}\n${fragBody}\n#pragma end\n` + hookTwin;
return { status: 'generated', text: source.trimEnd() + '\n' + twin };
} finally {
diff --git a/tools/tests/shader-twin-hook.test.ts b/tools/tests/shader-twin-hook.test.ts
new file mode 100644
index 000000000..a57ae1b45
--- /dev/null
+++ b/tools/tests/shader-twin-hook.test.ts
@@ -0,0 +1,75 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file A material's vertex hook (`#pragma vertexoffset`) gets a derived WGSL twin, so the shader runs on the WebGPU backend as it does on WebGL.
+ * The hook is translated as a program of its own; what the engine's WGSL vertex stage injects is the function under the name it calls
+ * (`esMaterialVertex`), the material block as `mc`, and the helpers the hook uses.
+ */
+import { describe, it, expect, beforeAll } from 'vitest';
+// @ts-expect-error — a repo tool, shipped as .mjs with no declarations
+import { deriveTwin, loadTwinModule, needsTwin } from '../gen-shader-twins.mjs';
+
+const SWAY = `#pragma shader "SwayTest"
+#pragma version 300 es
+#pragma domain Lit
+#pragma param u_amp float default(2)
+#pragma switch WILD default(off)
+
+#pragma vertexoffset
+float wobble(float x) { return sin(x * 3.0); }
+void esMaterialVertex(inout vec3 local, inout vec3 localNormal, in vec2 uv) {
+#ifdef WILD
+ local.x += wobble(uv.y) * u_amp * 3.0;
+#else
+ local.x += wobble(uv.y) * u_amp;
+#endif
+}
+#pragma end
+
+#pragma fragment
+precision mediump float;
+in vec4 v_color;
+in vec2 v_texCoord;
+out vec4 fragColor;
+void main() { fragColor = v_color; }
+#pragma end
+`;
+
+let module: unknown = null;
+beforeAll(async () => {
+ try { module = await loadTwinModule(); } catch { module = null; }
+});
+
+describe('the twin of a vertex hook', () => {
+ it('is derived with the fragment, behind the same switches, in the names the engine\'s stage injects', async (ctx) => {
+ if (!module) return ctx.skip();
+ const r = await deriveTwin(module, SWAY, {});
+ expect(r.status).toBe('generated');
+ const hook = /#pragma vertexoffset wgsl\n([\s\S]*?)#pragma end/.exec(r.text)![1]!;
+ expect(hook).toContain('// GENERATED by tools/gen-shader-twins.mjs');
+ expect(hook).toContain('#ifdef WILD');
+ expect(hook).toContain('fn esMaterialVertex(local : ptr<function, vec3f>, localNormal : ptr<function, vec3f>, uv : vec2f)');
+ expect(hook).toContain('mc.u_amp');
+ expect(hook).not.toContain('var<uniform>');
+ expect(hook).not.toContain('gl_PerVertex');
+ // a program of the engine's own parser accepts what was written
+ expect((module as { esshader_cookInfo(s: string, f: string): { valid: boolean } }).esshader_cookInfo(r.text, 'WILD').valid).toBe(true);
+ });
+
+ it('leaves a hook written by hand alone', async (ctx) => {
+ if (!module) return ctx.skip();
+ const authored = SWAY.replace('#pragma fragment\n', '#pragma vertexoffset wgsl\nfn esMaterialVertex(local : ptr<function, vec3f>, localNormal : ptr<function, vec3f>, uv : vec2f) {}\n#pragma end\n\n#pragma fragment\n');
+ const r = await deriveTwin(module, authored, {});
+ expect(r.status).toBe('generated');
+ expect(r.text.match(/#pragma vertexoffset wgsl/g)).toHaveLength(1);
+ expect(r.text).not.toContain('esMaterialVertexBody');
+ });
+
+ it('is replaced with the rest when the shader is derived again', async (ctx) => {
+ if (!module) return ctx.skip();
+ const first = (await deriveTwin(module, SWAY, {})).text as string;
+ expect(needsTwin(first)).toBe(false);
+ const again = await deriveTwin(module, first, { force: true });
+ expect(again.text.match(/#pragma vertexoffset wgsl/g)).toHaveLength(1);
+ });
+});