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 mesh shader that declares MESH_LOCAL_POSITION is handed the mesh's own position by the canonical vertex stage, and a converted effect that reads its vertex position in model space asks for it

yhheb9938b2fac7
diff --git a/pipeline/src/import/cocos/effectConvert.ts b/pipeline/src/import/cocos/effectConvert.ts
index 352e59957..3275dd800 100644
--- a/pipeline/src/import/cocos/effectConvert.ts
+++ b/pipeline/src/import/cocos/effectConvert.ts
@@ -257,7 +257,7 @@ const ATTRIBUTE_SOURCES: Record<string, string> = {
const STANDARD_ATTRIBUTES: Record<string, string> = { a_position: 'vec3', a_normal: 'vec3', a_texCoord: 'vec2', a_tangent: 'vec4' };
/** The varyings the engine's vertex stage owns. */
-const ENGINE_VARYING_NAMES = new Set(['v_color', 'v_texCoord', 'v_worldPos', 'v_worldXYZ', 'v_worldNormal', 'v_worldTangent']);
+const ENGINE_VARYING_NAMES = new Set(['v_color', 'v_texCoord', 'v_worldPos', 'v_worldXYZ', 'v_worldNormal', 'v_worldTangent', 'v_localPos']);
/** The second uv set: the engine hands it down wherever the vertices carry one (MESH_LIGHTMAP), and a draw with none reads the first. */
const UV1_VARYING = `#ifdef MESH_LIGHTMAP
@@ -268,13 +268,25 @@ in highp vec2 v_texCoord1;
#endif`;
const TANGENT_VARYING = `#ifdef MESH_TANGENTS
-in highp vec4 v_worldTangent;
#define cocos_tangent v_worldTangent
#else
#define cocos_tangent vec4(1.0, 0.0, 0.0, 1.0)
#endif`;
+/**
+ * The mesh's position before it is placed, which the engine's vertex stage hands down to a shader that declares MESH_LOCAL_POSITION. Where a draw has none
+ * (a sprite, whose vertices are already in the world) it is the world position, which is what it would be.
+ */
+const LOCAL_POSITION_VARYING = `#ifdef MESH_LOCAL_POSITION
+in highp vec3 v_localPos;
+#define cocos_localPosition v_localPos
+#else
+#define cocos_localPosition cocos_position
+#endif`;
+
interface Emulated {
+ /** The program reads the position as the mesh has it, in its own space (a swizzle of it, not a point it puts through the world matrix). */
+ readsModelPosition: boolean;
/** The program, as GLSL that declares what it wrote as globals and has the entry `cocos_vert`. */
source: string;
/** The attributes it reads, as globals. */
@@ -350,15 +362,19 @@ function emulateVertex(program: string, entry: string): Emulated | { error: stri
text = text.replace(entryRe, 'vec4 cocos_vert()');
// 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);
+ // A statement that takes components of the position and does not put it through the world matrix reads it in the mesh's own space (a terrain tiles its
+ // detail by `position.xz`); the engine's value for it, the world position, is the same only for a mesh that stands at the origin, unscaled and unturned.
+ const readsModelPosition = text.split(';').some((statement) => /(?:\bIn\.position|\bposition|\ba_position)\.[xyzw]{1,4}\b/.test(statement) && !/matWorld|cc_matWorld|matWorldIT/.test(statement));
const setup: string[] = [];
const declared: string[] = [];
for (const [name, type] of attributes) {
declared.push(`${type} ${name};`);
- const source = ATTRIBUTE_SOURCES[name];
+ const source = name === 'a_position' && readsModelPosition ? 'cocos_localPosition' : ATTRIBUTE_SOURCES[name];
if (source) setup.push(` ${name} = ${source}${coerce(type, name)};`);
if (name === 'a_texCoord1') approximations.push('the second uv is the mesh\'s own where it has one and the first uv where it has none');
}
- return { source: text, attributes: declared.join('\n'), outputs, attributeSetup: setup, approximations, displaces };
+ if (readsModelPosition) approximations.push('the vertex position is the mesh\'s own where the draw is a mesh, and the world position where it is a sprite');
+ return { source: text, attributes: declared.join('\n'), outputs, attributeSetup: setup, approximations, displaces, readsModelPosition };
}
/** The conversion that makes an engine value of one width fit the type an attribute is declared with. */
@@ -515,6 +531,7 @@ export function convertPass(
needed.add(NORMAL_VARYING);
needed.add(TANGENT_VARYING);
if (/\ba_texCoord1\b/.test(vertex.attributes)) needed.add(UV1_VARYING);
+ if (vertex.readsModelPosition) needed.add(LOCAL_POSITION_VARYING);
}
const usesPosition = needed.has(POSITION_VARYING);
if (usesPosition) approximations.push('v_position is the world position of the draw: the engine gives the full position to meshes with normals, and the plane position to sprites');
@@ -580,7 +597,7 @@ export function convertPass(
// has no switches: one shader per combination a project uses, which is the same set of programs and a shader that can be given a WGSL twin
// (a twin carries a body for every combination of what is left to toggle). Without them they are switches a material turns on.
const found = macrosIn(`${vertexText}\n${body}`);
- const ENGINE_FEATURE = /^(?:MESH_NORMALS|MESH_TANGENTS|MESH_LIGHTMAP|GL_ES|CC_[A-Z_]+_ENABLED)$/;
+ const ENGINE_FEATURE = /^(?:MESH_NORMALS|MESH_TANGENTS|MESH_LIGHTMAP|MESH_LOCAL_POSITION|GL_ES|CC_[A-Z_]+_ENABLED)$/;
const named = found.switches.filter((m) => !ENGINE_FEATURE.test(m) && !found.compared.includes(m));
const compared = found.compared.filter((m) => !ENGINE_FEATURE.test(m));
let switches: string[] = [];
@@ -604,7 +621,7 @@ ${body}`;
if (compared.length > 0) approximations.push(`${compared.join(', ')} is compared to a number; the engine's switches are on or off`);
}
// What the engine's vertex stage offers a fragment, which the shader asks for by name so that a twin carries a body for each.
- const offered = ['MESH_NORMALS', 'MESH_TANGENTS', 'MESH_LIGHTMAP']
+ const offered = ['MESH_NORMALS', 'MESH_TANGENTS', 'MESH_LIGHTMAP', 'MESH_LOCAL_POSITION']
.filter((f) => new RegExp(`\\b${f}\\b`).test(`${[...needed].join('\n')}\n${vertexText}\n${body}`));
const lines: string[] = [
diff --git a/pipeline/tests/cocos-effect-local-position.test.ts b/pipeline/tests/cocos-effect-local-position.test.ts
new file mode 100644
index 000000000..0d3f86785
--- /dev/null
+++ b/pipeline/tests/cocos-effect-local-position.test.ts
@@ -0,0 +1,72 @@
+// SPDX-License-Identifier: Apache-2.0
+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
+/**
+ * @file A vertex program that reads the position in the mesh's own space (a terrain tiles its detail by `position.xz`) is given the engine's local position,
+ * and one that puts it through the world matrix keeps the world position it was given.
+ */
+import { describe, expect, it } from 'vitest';
+import { convertPass } from '../src/import/cocos/effectConvert';
+import { parseEffect } from '../src/import/cocos/effects';
+
+const effectWith = (vertexBody: string): string => `
+CCEffect %{
+ techniques:
+ - name: opaque
+ passes:
+ - vert: pos-vs:vert
+ frag: pos-fs:frag
+ properties:
+ mainColor: { value: [1, 1, 1, 1], editor: { type: color } }
+}%
+
+CCProgram pos-vs %{
+ precision highp float;
+ in vec3 a_position;
+ out vec2 v_uv;
+${vertexBody}
+}%
+
+CCProgram pos-fs %{
+ precision highp float;
+ in vec2 v_uv;
+ uniform Constant {
+ vec4 mainColor;
+ };
+ vec4 frag () { return mainColor * vec4(v_uv, 0.0, 1.0); }
+}%
+`;
+
+const convert = (vertexBody: string) => {
+ const effect = parseEffect(effectWith(vertexBody));
+ return convertPass(effect, effect.techniques[0]!.passes[0]!, 'pos.opaque.0');
+};
+
+describe('the position a vertex program reads', () => {
+ it('is the mesh\'s own when the program takes components of it', () => {
+ const converted = convert(`
+ vec4 vert () {
+ vec4 position = vec4(a_position, 1.0);
+ v_uv = position.xz * 0.5;
+ return position;
+ }`);
+ expect(converted.unsupported).toBeNull();
+ const source = converted.shader!.source;
+ expect(source).toContain('#pragma feature MESH_LOCAL_POSITION');
+ expect(source).toContain('a_position = cocos_localPosition');
+ expect(source).toContain('in highp vec3 v_localPos;');
+ });
+
+ it('stays the world position when the program puts it through the world matrix', () => {
+ const converted = convert(`
+ uniform Local { mat4 cc_matWorld; };
+ vec4 vert () {
+ vec4 world = cc_matWorld * vec4(a_position, 1.0);
+ v_uv = world.xz * 0.5;
+ return world;
+ }`);
+ expect(converted.unsupported).toBeNull();
+ const source = converted.shader!.source;
+ expect(source).not.toContain('MESH_LOCAL_POSITION');
+ expect(source).toContain('a_position = cocos_position');
+ });
+});
diff --git a/src/esengine/resource/ShaderParser.cpp b/src/esengine/resource/ShaderParser.cpp
index b2364283a..58712aed5 100644
--- a/src/esengine/resource/ShaderParser.cpp
+++ b/src/esengine/resource/ShaderParser.cpp
@@ -277,6 +277,11 @@ std::string wgslCanonicalVSOut(bool lit) {
// The mesh's own second uv set, as authored: what a material that is not a bake reads it for (a mask, a dissolve map). The vertices carry it
// whenever MESH_LIGHTMAP is on, which is what that feature says.
" @location(9) v_texCoord1 : vec2f,\n"
+ "#endif\n"
+ // The mesh's own position, before it is placed: what an effect authored against model space reads (a terrain tiles its detail by it).
+ // Only a shader that declares the feature gets it.
+ "#ifdef MESH_LOCAL_POSITION\n"
+ " @location(10) v_localPos : vec3f,\n"
"#endif\n";
if (lit) {
// Which run of coefficients this instance reads. Flat: an index, not a
@@ -435,6 +440,9 @@ std::string canonicalVertexStageWGSL(bool lit, const std::string& hook = {}) {
" out.v_lightmap = vec3f(v.a_texCoord1 * lmRect.xy + lmRect.zw,\n"
" select(0.0, 1.0, lmRect.x > 0.0));\n"
" out.v_texCoord1 = v.a_texCoord1;\n"
+ "#endif\n"
+ "#if defined(MESH_LOCAL_POSITION) && defined(MESH)\n"
+ " out.v_localPos = v.a_position;\n"
"#endif\n";
if (lit) {
src += " out.v_worldPos = world.xy;\n";
@@ -587,6 +595,10 @@ std::string canonicalVertexStage(bool lit, const std::string& hook = {}) {
"#ifdef MESH_LIGHTMAP\n"
"out highp vec3 v_lightmap;\n"
"out highp vec2 v_texCoord1;\n"
+ "#endif\n"
+ // The mesh's own position, before it is placed, for a shader that declares MESH_LOCAL_POSITION (see the WGSL twin's v_localPos).
+ "#ifdef MESH_LOCAL_POSITION\n"
+ "out highp vec3 v_localPos;\n"
"#endif\n";
if (lit) {
src += "out highp vec2 v_worldPos;\n";
@@ -673,6 +685,9 @@ std::string canonicalVertexStage(bool lit, const std::string& hook = {}) {
" v_lightmap = vec3(a_texCoord1 * lmRect.xy + lmRect.zw,\n"
" lmRect.x > 0.0 ? 1.0 : 0.0);\n"
" v_texCoord1 = a_texCoord1;\n"
+ "#endif\n"
+ "#if defined(MESH_LOCAL_POSITION) && defined(MESH)\n"
+ " v_localPos = a_position;\n"
"#endif\n";
if (lit) {
src += " v_worldPos = world.xy;\n";
@@ -2491,6 +2506,13 @@ ShaderParser::AssembledStage ShaderParser::assembleStageEx(const ParsedShader& p
&& std::find(parsed.features.begin(), parsed.features.end(), "MESH_TANGENTS") == parsed.features.end()) {
features.erase(std::remove(features.begin(), features.end(), std::string("MESH_TANGENTS")), features.end());
}
+ // The mesh's own position is handed down only on the engine's canonical vertex stage, for a mesh draw of a shader that asks for it: it costs a
+ // varying, which no other shader should pay.
+ const auto has = [](const std::vector<std::string>& list, const char* name) { return std::find(list.begin(), list.end(), name) != list.end(); };
+ features.erase(std::remove(features.begin(), features.end(), std::string("MESH_LOCAL_POSITION")), features.end());
+ if (parsed.vertexIsCanonical && has(parsed.features, "MESH_LOCAL_POSITION") && has(features, "MESH")) {
+ features.push_back("MESH_LOCAL_POSITION");
+ }
if (target == ShaderTargetLanguage::WGSL) {
return assembleWGSLStage(parsed, stage, features);
}