A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(render): a particle is drawn with the material its emitter names
esenginee8b71537c78e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 950482c5d..b58eb8653 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,18 @@ published separately; it ships inside the editor.### Changed+- **A particle can be drawn with a material, and the billboard it is drawn on is+ one piece of arithmetic.** `ParticleEmitter.material` was the last authorable+ material field with nothing reading it. A material is compiled per vertex+ source — the engine's canonical vertex stage under a feature, with the author's+ fragment untouched — and that stage now has a `PARTICLE` shape beside `MESH`+ and `SKINNED`, reading the instance's position, size, rotation, colour and+ sheet frame. The built-in particle shader became fragment-only and goes through+ the very same stage, so the billboard maths that faces a quad at the viewer+ exists once rather than in the built-in shader and again in every material.+ `MaterialStore` compiles both variants through one path now (`meshProgram` and+ `particleProgram` differ only in which features they ask for).+- **A skeleton can be drawn with a material.** `SpineAnimation.material` and`DragonBonesAnimation.material` were authorable and unread: a skeleton alwaysdrew with the built-in batch shader. Both now resolve the same way a `Sprite`'sdiff --git a/examples/effects-gallery/assets/materials/dissolve.esshader b/examples/effects-gallery/assets/materials/dissolve.esshaderindex 64fe7ab90..5105acd9c 100644--- a/examples/effects-gallery/assets/materials/dissolve.esshader+++ b/examples/effects-gallery/assets/materials/dissolve.esshader@@ -40,7 +40,7 @@ void main() {// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.// Regenerate after changing the GLSL stages above.// source-hash: 0a687499da49fe50-// assembled-hash: b25f4206f2477249+// assembled-hash: ebcc8cde720cdc42struct gl_PerVertex {@builtin(position) gl_Position: vec4<f32>,gl_PointSize: f32,@@ -114,7 +114,7 @@ fn vs_main(@location(0) a_position: vec3<f32>, @location(1) a_color: vec4<f32>,// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.// Regenerate after changing the GLSL stages above.// source-hash: 0a687499da49fe50-// assembled-hash: b25f4206f2477249+// assembled-hash: ebcc8cde720cdc42struct MaterialConstants {u_progress: f32,u_edgeColor: vec4<f32>,diff --git a/examples/effects-gallery/assets/materials/hit-flash.esshader b/examples/effects-gallery/assets/materials/hit-flash.esshaderindex 34f762fed..af5649017 100644--- a/examples/effects-gallery/assets/materials/hit-flash.esshader+++ b/examples/effects-gallery/assets/materials/hit-flash.esshader@@ -25,7 +25,7 @@ void main() {// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.// Regenerate after changing the GLSL stages above.// source-hash: 674537b45fb865fb-// assembled-hash: 0a587e1ebadddcdf+// assembled-hash: bb0a3ae7a9b98b6cstruct gl_PerVertex {@builtin(position) gl_Position: vec4<f32>,gl_PointSize: f32,@@ -97,7 +97,7 @@ fn vs_main(@location(0) a_position: vec3<f32>, @location(1) a_color: vec4<f32>,// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.// Regenerate after changing the GLSL stages above.// source-hash: 674537b45fb865fb-// assembled-hash: 0a587e1ebadddcdf+// assembled-hash: bb0a3ae7a9b98b6cstruct MaterialConstants {u_flash: f32,u_flashColor: vec4<f32>,diff --git a/examples/effects-gallery/assets/materials/outline.esshader b/examples/effects-gallery/assets/materials/outline.esshaderindex 2989df9ed..c7795e88c 100644--- a/examples/effects-gallery/assets/materials/outline.esshader+++ b/examples/effects-gallery/assets/materials/outline.esshader@@ -34,7 +34,7 @@ void main() {// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.// Regenerate after changing the GLSL stages above.// source-hash: 7ed4f4686c6bfd8d-// assembled-hash: 3790668aef426091+// assembled-hash: 501b40fd7be94f90struct gl_PerVertex {@builtin(position) gl_Position: vec4<f32>,gl_PointSize: f32,@@ -106,7 +106,7 @@ fn vs_main(@location(0) a_position: vec3<f32>, @location(1) a_color: vec4<f32>,// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.// Regenerate after changing the GLSL stages above.// source-hash: 7ed4f4686c6bfd8d-// assembled-hash: 3790668aef426091+// assembled-hash: 501b40fd7be94f90struct MaterialConstants {u_outlineColor: vec4<f32>,u_outlineWidth: f32,diff --git a/examples/effects-gallery/assets/materials/pixelate.esshader b/examples/effects-gallery/assets/materials/pixelate.esshaderindex 672480f90..768cfe835 100644--- a/examples/effects-gallery/assets/materials/pixelate.esshader+++ b/examples/effects-gallery/assets/materials/pixelate.esshader@@ -23,7 +23,7 @@ void main() {// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.// Regenerate after changing the GLSL stages above.// source-hash: 0c2fb4b31599ec7a-// assembled-hash: fe3f56d6195fed46+// assembled-hash: 9916e03640c99510struct gl_PerVertex {@builtin(position) gl_Position: vec4<f32>,gl_PointSize: f32,@@ -94,7 +94,7 @@ fn vs_main(@location(0) a_position: vec3<f32>, @location(1) a_color: vec4<f32>,// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.// Regenerate after changing the GLSL stages above.// source-hash: 0c2fb4b31599ec7a-// assembled-hash: fe3f56d6195fed46+// assembled-hash: 9916e03640c99510struct MaterialConstants {u_pixels: f32,}diff --git a/examples/effects-gallery/assets/materials/uv-scroll.esshader b/examples/effects-gallery/assets/materials/uv-scroll.esshaderindex 0402dee2d..ca4a2dde0 100644--- a/examples/effects-gallery/assets/materials/uv-scroll.esshader+++ b/examples/effects-gallery/assets/materials/uv-scroll.esshader@@ -24,7 +24,7 @@ void main() {// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.// Regenerate after changing the GLSL stages above.// source-hash: 301c5b2b73d966f3-// assembled-hash: c8cc6f14bb51a809+// assembled-hash: dbcce3ef59e9ddf8struct gl_PerVertex {@builtin(position) gl_Position: vec4<f32>,gl_PointSize: f32,@@ -95,7 +95,7 @@ fn vs_main(@location(0) a_position: vec3<f32>, @location(1) a_color: vec4<f32>,// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.// Regenerate after changing the GLSL stages above.// source-hash: 301c5b2b73d966f3-// assembled-hash: c8cc6f14bb51a809+// assembled-hash: dbcce3ef59e9ddf8struct TimeConstants {u_time: vec4<f32>,u_viewport: vec4<f32>,diff --git a/fixtures/scenes/depth-layers/opaque.esshader b/fixtures/scenes/depth-layers/opaque.esshaderindex 3bbe2f0fe..c094a2abb 100644--- a/fixtures/scenes/depth-layers/opaque.esshader+++ b/fixtures/scenes/depth-layers/opaque.esshader@@ -24,7 +24,7 @@ void main() {// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.// Regenerate after changing the GLSL stages above.// source-hash: 930787555114ce9c-// assembled-hash: 608493cc809284d8+// assembled-hash: 1464abff8ecb4bd2struct gl_PerVertex {@builtin(position) gl_Position: vec4<f32>,gl_PointSize: f32,@@ -89,7 +89,7 @@ fn vs_main(@location(0) a_position: vec3<f32>, @location(1) a_color: vec4<f32>,// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.// Regenerate after changing the GLSL stages above.// source-hash: 930787555114ce9c-// assembled-hash: 608493cc809284d8+// assembled-hash: 1464abff8ecb4bd2struct FrameConstants {u_projection: mat4x4<f32>,u_camera: vec4<f32>,diff --git a/fixtures/scenes/mat-builtin-lit/lit.esshader b/fixtures/scenes/mat-builtin-lit/lit.esshaderindex 9716e9d79..bf8a7345c 100644--- a/fixtures/scenes/mat-builtin-lit/lit.esshader+++ b/fixtures/scenes/mat-builtin-lit/lit.esshader@@ -27,7 +27,7 @@ void main() {// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.// Regenerate after changing the GLSL stages above.// source-hash: 5330079245724fa2-// assembled-hash: 4c0c9d4c327408ac+// assembled-hash: 6826d891cde0e6eestruct gl_PerVertex {@builtin(position) gl_Position: vec4<f32>,gl_PointSize: f32,@@ -107,7 +107,7 @@ fn vs_main(@location(0) a_position: vec3<f32>, @location(1) a_color: vec4<f32>,// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.// Regenerate after changing the GLSL stages above.// source-hash: 5330079245724fa2-// assembled-hash: 4c0c9d4c327408ac+// assembled-hash: 6826d891cde0e6eestruct FrameConstants {u_projection: mat4x4<f32>,u_camera: vec4<f32>,diff --git a/fixtures/scenes/mat-dissolve/dissolve.esshader b/fixtures/scenes/mat-dissolve/dissolve.esshaderindex 64fe7ab90..5105acd9c 100644--- a/fixtures/scenes/mat-dissolve/dissolve.esshader+++ b/fixtures/scenes/mat-dissolve/dissolve.esshader@@ -40,7 +40,7 @@ void main() {// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.// Regenerate after changing the GLSL stages above.// source-hash: 0a687499da49fe50-// assembled-hash: b25f4206f2477249+// assembled-hash: ebcc8cde720cdc42struct gl_PerVertex {@builtin(position) gl_Position: vec4<f32>,gl_PointSize: f32,@@ -114,7 +114,7 @@ fn vs_main(@location(0) a_position: vec3<f32>, @location(1) a_color: vec4<f32>,// GENERATED by tools/gen-shader-twins.mjs (glslang + naga) - do not edit.// Regenerate after changing the GLSL stages above.// source-hash: 0a687499da49fe50-// assembled-hash: b25f4206f2477249+// assembled-hash: ebcc8cde720cdc42struct MaterialConstants {u_progress: f32,u_edgeColor: vec4<f32>,diff --git a/fixtures/scenes/particle-material.esscene b/fixtures/scenes/particle-material.esscenenew file mode 100644index 000000000..f103d9fda--- /dev/null+++ b/fixtures/scenes/particle-material.esscene@@ -0,0 +1,94 @@+{+ "version": 2,+ "name": "ParticleMaterial",+ "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": "Tinted",+ "parent": null,+ "children": [],+ "components": [+ {+ "type": "Transform",+ "data": {+ "position": {+ "x": 0,+ "y": 0,+ "z": 0+ }+ }+ },+ {+ "type": "ParticleEmitter",+ "data": {+ "rate": 0,+ "burstCount": 1,+ "burstInterval": 1000,+ "maxParticles": 1,+ "lifetimeMin": 10,+ "lifetimeMax": 10,+ "shape": 0,+ "speedMin": 0,+ "speedMax": 0,+ "startSizeMin": 120,+ "startSizeMax": 120,+ "endSizeMin": 120,+ "endSizeMax": 120,+ "gravity": {+ "x": 0,+ "y": 0,+ "z": 0+ },+ "damping": 0,+ "simulationSpace": 0,+ "looping": false,+ "playOnStart": true,+ "startColor": {+ "r": 0,+ "g": 1,+ "b": 0,+ "a": 1+ },+ "endColor": {+ "r": 0,+ "g": 1,+ "b": 0,+ "a": 1+ },+ "texture": "@uuid:24cb4e0f-7c75-4df4-9a4d-58480ee405c0",+ "material": "/scenes/particle-material/tint.esmaterial"+ }+ }+ ],+ "visible": true+ }+ ]+}diff --git a/fixtures/scenes/particle-material.textures.json b/fixtures/scenes/particle-material.textures.jsonnew file mode 100644index 000000000..0acb647eb--- /dev/null+++ b/fixtures/scenes/particle-material.textures.json@@ -0,0 +1,3 @@+{+ "24cb4e0f-7c75-4df4-9a4d-58480ee405c0": "/scenes/particle-demo/textures/particle.png"+}diff --git a/fixtures/scenes/particle-material/tint.esmaterial b/fixtures/scenes/particle-material/tint.esmaterialnew file mode 100644index 000000000..bd01059ad--- /dev/null+++ b/fixtures/scenes/particle-material/tint.esmaterial@@ -0,0 +1,10 @@+{+ "version": "1.0",+ "type": "material",+ "shader": "tint.esshader",+ "blendMode": 0,+ "depthTest": false,+ "properties": {+ "u_tint": { "r": 1, "g": 0, "b": 0, "a": 1 }+ }+}diff --git a/fixtures/scenes/particle-material/tint.esshader b/fixtures/scenes/particle-material/tint.esshadernew file mode 100644index 000000000..278965d70--- /dev/null+++ b/fixtures/scenes/particle-material/tint.esshader@@ -0,0 +1,30 @@+#pragma shader "ParticleMaterialTest"+#pragma version 300 es+#pragma domain Unlit+#pragma param u_tint color default(1,1,1,1)++// Colour entirely from the material, shape still from the texture: a particle+// drawn WITHOUT this material keeps its own green, so the two are told apart by+// the pixel rather than by both being plausible.+#pragma fragment+precision mediump float;++in vec4 v_color;+in vec2 v_texCoord;++uniform sampler2D u_textures[8];++out vec4 fragColor;++void main() {+ float a = texture(u_textures[0], v_texCoord).a * v_color.a;+ fragColor = vec4(u_tint.rgb, a);+}+#pragma end++#pragma fragment wgsl+@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {+ let a = textureSampleLevel(t0, s0, v.v_texCoord, 0.0).a * v.v_color.a;+ return vec4f(mc.u_tint.rgb, a);+}+#pragma enddiff --git a/src/esengine/data/shaders/particle.esshader b/src/esengine/data/shaders/particle.esshaderindex ee3fbb1f9..a2b90e662 100644--- a/src/esengine/data/shaders/particle.esshader+++ b/src/esengine/data/shaders/particle.esshader@@ -1,123 +1,29 @@#pragma shader "ParticleInstance"#pragma version 300 es-#pragma vertex-layout(location = 0) in vec2 a_position;-layout(location = 1) in vec2 a_texCoord;--layout(location = 2) in vec3 a_inst_position;-layout(location = 3) in vec2 a_inst_size;-layout(location = 4) in float a_inst_rotation;-layout(location = 5) in vec4 a_inst_color;-layout(location = 6) in vec2 a_inst_uv_offset;-layout(location = 7) in vec2 a_inst_uv_scale;--out vec2 v_texCoord;-out vec4 v_color;--// The quad's own axes in world space: a particle faces the viewer wherever it is-// seen from. Head-on and orthographic these come out (1,0,0) and (0,1,0), which-// is the flat quad every 2D scene has always drawn — a billboard is not a second-// path, it is the general case the flat one is a corner of.-void billboardAxes(in highp vec3 worldCenter, out highp vec3 right, out highp vec3 up) {- highp vec3 fwd = viewDirection(worldCenter);- // Looking straight down the world up, that axis cannot orient the quad.- highp vec3 refUp = abs(fwd.y) > 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(0.0, 1.0, 0.0);- right = normalize(cross(refUp, fwd));- up = cross(fwd, right);-}--void main() {- vec2 scaled = a_position * a_inst_size;-- float cosR = cos(a_inst_rotation);- float sinR = sin(a_inst_rotation);- vec2 rotated = vec2(- scaled.x * cosR - scaled.y * sinR,- scaled.x * sinR + scaled.y * cosR- );-- highp vec3 right;- highp vec3 up;- billboardAxes(a_inst_position, right, up);- vec3 worldPos = a_inst_position + right * rotated.x + up * rotated.y;- gl_Position = u_projection * vec4(worldPos, 1.0);-- v_texCoord = a_texCoord * a_inst_uv_scale + a_inst_uv_offset;- v_color = a_inst_color;-}-#pragma end-+// Fragment-only, on the engine's canonical vertex stage under the PARTICLE+// feature: what turns instance data into a billboarded quad is the same stage a+// material is compiled against, so a custom particle material and this one are+// posed by one piece of arithmetic rather than two kept in step.#pragma fragmentprecision mediump float;-in vec2 v_texCoord;in vec4 v_color;+in vec2 v_texCoord;-uniform sampler2D u_texture;+uniform sampler2D u_textures[8];out vec4 fragColor;void main() {- vec4 texColor = texture(u_texture, v_texCoord);+ vec4 texColor = texture(u_textures[0], v_texCoord);fragColor = texColor * v_color;}#pragma end-#pragma vertex wgsl-struct VSIn {- @location(0) a_position : vec2f,- @location(1) a_texCoord : vec2f,- @location(2) a_inst_position : vec3f,- @location(3) a_inst_size : vec2f,- @location(4) a_inst_rotation : f32,- @location(5) a_inst_color : vec4f,- @location(6) a_inst_uv_offset : vec2f,- @location(7) a_inst_uv_scale : vec2f,-};-struct VSOut {- @builtin(position) pos : vec4f,- @location(0) v_texCoord : vec2f,- @location(1) v_color : vec4f,-};--@vertex fn vs_main(v : VSIn) -> VSOut {- let scaled = v.a_position * v.a_inst_size;-- let cosR = cos(v.a_inst_rotation);- let sinR = sin(v.a_inst_rotation);- let rotated = vec2f(- scaled.x * cosR - scaled.y * sinR,- scaled.x * sinR + scaled.y * cosR- );-- // The GLSL stage's billboardAxes, in the dialect: face the viewer, and fall- // back to world +Z as the reference when looking straight down world up.- let fwd = viewDirection(v.a_inst_position);- var refUp = vec3f(0.0, 1.0, 0.0);- if (abs(fwd.y) > 0.999) { refUp = vec3f(0.0, 0.0, 1.0); }- let right = normalize(cross(refUp, fwd));- let up = cross(fwd, right);- let worldPos = v.a_inst_position + right * rotated.x + up * rotated.y;-- var out : VSOut;- out.pos = frame.projection * vec4f(worldPos, 1.0);- out.v_texCoord = v.a_texCoord * v.a_inst_uv_scale + v.a_inst_uv_offset;- out.v_color = v.a_inst_color;- return out;-}-#pragma end-+// VSOut and the t0/s0 texture contract are injected for a twin on the engine's+// vertex stage — declaring them here would declare them twice.#pragma fragment wgsl-@group(1) @binding(0) var t0 : texture_2d<f32>;-@group(1) @binding(8) var s0 : sampler;--struct VSOut {- @builtin(position) pos : vec4f,- @location(0) v_texCoord : vec2f,- @location(1) v_color : vec4f,-};-@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {let texColor = textureSampleLevel(t0, s0, v.v_texCoord, 0.0);return texColor * v.v_color;diff --git a/src/esengine/renderer/plugins/ParticlePlugin.cpp b/src/esengine/renderer/plugins/ParticlePlugin.cppindex bca370a7a..4f480b26b 100644--- a/src/esengine/renderer/plugins/ParticlePlugin.cpp+++ b/src/esengine/renderer/plugins/ParticlePlugin.cpp@@ -15,6 +15,7 @@#include "../../particle/Particle.hpp"#include <algorithm>+#include <string>#include <cmath>namespace esengine {@@ -41,10 +42,13 @@ void ParticlePlugin::init(RenderFrameContext& ctx) {if (particle_shader_handle_.isValid()) ctx.resources.releaseShader(particle_shader_handle_);const auto target = ctx.resources.preferredShaderTarget();auto parsed = resource::ShaderParser::parse(ShaderEmbeds::PARTICLE);+ // The same feature a material's particle variant is compiled with, so the+ // built-in fragment and an authored one sit on one vertex stage.+ const std::vector<std::string> features{ "PARTICLE" };resource::ShaderHandle& handle = particle_shader_handle_;handle = ctx.resources.createShaderWithBindings(- resource::ShaderParser::assembleStage(parsed, resource::ShaderStage::Vertex, "", {}, target),- resource::ShaderParser::assembleStage(parsed, resource::ShaderStage::Fragment, "", {}, target),+ resource::ShaderParser::assembleStage(parsed, resource::ShaderStage::Vertex, "", features, target),+ resource::ShaderParser::assembleStage(parsed, resource::ShaderStage::Fragment, "", features, target),{}, ctx.resources.preferredShaderLanguage());Shader* shader = ctx.resources.getShader(handle);if (shader && shader->isValid()) {@@ -53,7 +57,9 @@ void ParticlePlugin::init(RenderFrameContext& ctx) {// Sampler seeding is a GLSL concept; on WGSL the texture rides the// bind group.shader->bind();- shader->setUniform("u_texture", 0); // sampler unit 0+ for (i32 unit = 0; unit < 8; ++unit) {+ shader->setUniform("u_textures[" + std::to_string(unit) + "]", unit);+ }shader->unbind();}}@@ -152,11 +158,28 @@ void ParticlePlugin::collect(RenderCollectContext& collect_ctx) {d.uvScaleY = sheet ? uvScaleY : 1.0f;});+ // A material owns shading fully: its program is this one compiled for the+ // particle vertex source, so the author's fragment sees the same quad the+ // built-in one does. A handle nothing registered draws plainly.+ u32 shaderId = particle_shader_id_;+ u32 materialId = 0;+ BlendMode blend = blendMode;+ if (emitter.material != 0 && ctx.materials) {+ if (const MaterialRecord* m = ctx.materials->find(emitter.material)) {+ const u32 program = ctx.materials->particleProgram(emitter.material, ctx.resources);+ if (program != 0) {+ shaderId = program;+ materialId = emitter.material;+ blend = m->blend;+ }+ }+ }+BatchDrawKey key{.stage = ctx.current_stage,.layer = emitter.layer,- .shaderId = particle_shader_id_,- .blend = blendMode,+ .shaderId = shaderId,+ .blend = blend,.textureId = textureId,.depth = collect_ctx.camera.viewDepth(emitterWorldPos),// Sorted by world Y like every other draw — a burst left at y = 0@@ -165,6 +188,7 @@ void ParticlePlugin::collect(RenderCollectContext& collect_ctx) {.y = emitterWorldPos.y,.entity = entity,.type = RenderType::Particle,+ .materialId = materialId,.layoutId = LayoutId::ParticleInstance,.instanceCount = particleCount,};diff --git a/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp b/src/esengine/renderer/rhi/ShaderEmbeds.generated.hppindex fac70db9f..70af399a1 100644--- a/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp+++ b/src/esengine/renderer/rhi/ShaderEmbeds.generated.hpp@@ -583,123 +583,29 @@ struct VSOut {inline constexpr const char* PARTICLE = R"esshader(#pragma shader "ParticleInstance"#pragma version 300 es-#pragma vertex-layout(location = 0) in vec2 a_position;-layout(location = 1) in vec2 a_texCoord;--layout(location = 2) in vec3 a_inst_position;-layout(location = 3) in vec2 a_inst_size;-layout(location = 4) in float a_inst_rotation;-layout(location = 5) in vec4 a_inst_color;-layout(location = 6) in vec2 a_inst_uv_offset;-layout(location = 7) in vec2 a_inst_uv_scale;--out vec2 v_texCoord;-out vec4 v_color;--// The quad's own axes in world space: a particle faces the viewer wherever it is-// seen from. Head-on and orthographic these come out (1,0,0) and (0,1,0), which-// is the flat quad every 2D scene has always drawn — a billboard is not a second-// path, it is the general case the flat one is a corner of.-void billboardAxes(in highp vec3 worldCenter, out highp vec3 right, out highp vec3 up) {- highp vec3 fwd = viewDirection(worldCenter);- // Looking straight down the world up, that axis cannot orient the quad.- highp vec3 refUp = abs(fwd.y) > 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(0.0, 1.0, 0.0);- right = normalize(cross(refUp, fwd));- up = cross(fwd, right);-}--void main() {- vec2 scaled = a_position * a_inst_size;-- float cosR = cos(a_inst_rotation);- float sinR = sin(a_inst_rotation);- vec2 rotated = vec2(- scaled.x * cosR - scaled.y * sinR,- scaled.x * sinR + scaled.y * cosR- );-- highp vec3 right;- highp vec3 up;- billboardAxes(a_inst_position, right, up);- vec3 worldPos = a_inst_position + right * rotated.x + up * rotated.y;- gl_Position = u_projection * vec4(worldPos, 1.0);-- v_texCoord = a_texCoord * a_inst_uv_scale + a_inst_uv_offset;- v_color = a_inst_color;-}-#pragma end-+// Fragment-only, on the engine's canonical vertex stage under the PARTICLE+// feature: what turns instance data into a billboarded quad is the same stage a+// material is compiled against, so a custom particle material and this one are+// posed by one piece of arithmetic rather than two kept in step.#pragma fragmentprecision mediump float;-in vec2 v_texCoord;in vec4 v_color;+in vec2 v_texCoord;-uniform sampler2D u_texture;+uniform sampler2D u_textures[8];out vec4 fragColor;void main() {- vec4 texColor = texture(u_texture, v_texCoord);+ vec4 texColor = texture(u_textures[0], v_texCoord);fragColor = texColor * v_color;}#pragma end-#pragma vertex wgsl-struct VSIn {- @location(0) a_position : vec2f,- @location(1) a_texCoord : vec2f,- @location(2) a_inst_position : vec3f,- @location(3) a_inst_size : vec2f,- @location(4) a_inst_rotation : f32,- @location(5) a_inst_color : vec4f,- @location(6) a_inst_uv_offset : vec2f,- @location(7) a_inst_uv_scale : vec2f,-};-struct VSOut {- @builtin(position) pos : vec4f,- @location(0) v_texCoord : vec2f,- @location(1) v_color : vec4f,-};--@vertex fn vs_main(v : VSIn) -> VSOut {- let scaled = v.a_position * v.a_inst_size;-- let cosR = cos(v.a_inst_rotation);- let sinR = sin(v.a_inst_rotation);- let rotated = vec2f(- scaled.x * cosR - scaled.y * sinR,- scaled.x * sinR + scaled.y * cosR- );-- // The GLSL stage's billboardAxes, in the dialect: face the viewer, and fall- // back to world +Z as the reference when looking straight down world up.- let fwd = viewDirection(v.a_inst_position);- var refUp = vec3f(0.0, 1.0, 0.0);- if (abs(fwd.y) > 0.999) { refUp = vec3f(0.0, 0.0, 1.0); }- let right = normalize(cross(refUp, fwd));- let up = cross(fwd, right);- let worldPos = v.a_inst_position + right * rotated.x + up * rotated.y;-- var out : VSOut;- out.pos = frame.projection * vec4f(worldPos, 1.0);- out.v_texCoord = v.a_texCoord * v.a_inst_uv_scale + v.a_inst_uv_offset;- out.v_color = v.a_inst_color;- return out;-}-#pragma end-+// VSOut and the t0/s0 texture contract are injected for a twin on the engine's+// vertex stage — declaring them here would declare them twice.#pragma fragment wgsl-@group(1) @binding(0) var t0 : texture_2d<f32>;-@group(1) @binding(8) var s0 : sampler;--struct VSOut {- @builtin(position) pos : vec4f,- @location(0) v_texCoord : vec2f,- @location(1) v_color : vec4f,-};-@fragment fn fs_main(v : VSOut) -> @location(0) vec4f {let texColor = textureSampleLevel(t0, s0, v.v_texCoord, 0.0);return texColor * v.v_color;diff --git a/src/esengine/renderer/store/MaterialStore.cpp b/src/esengine/renderer/store/MaterialStore.cppindex 711ec7c30..43e321fc8 100644--- a/src/esengine/renderer/store/MaterialStore.cpp+++ b/src/esengine/renderer/store/MaterialStore.cpp@@ -46,14 +46,35 @@ void MaterialStore::recreateGpuResources() {u32 MaterialStore::meshProgram(u32 materialId, resource::ResourceManager& resources,bool withNormals, bool skinned, bool envMapped) const {- const MaterialRecord* rec = find(materialId);- if (!rec || !rec->shaderRef.isValid()) return 0;// Keyed by shader AND vertex shape: a layout may not declare an attribute its// shader ignores, so geometry with normals — or posed by bones — needs its own.- const u64 key = static_cast<u64>(rec->shaderRef.id())- | (withNormals ? (1ull << 32) : 0ull)- | (skinned ? (1ull << 33) : 0ull)- | (envMapped ? (1ull << 34) : 0ull);+ const u64 shape = (withNormals ? (1ull << 32) : 0ull)+ | (skinned ? (1ull << 33) : 0ull)+ | (envMapped ? (1ull << 34) : 0ull);+ std::vector<std::string> features{ "MESH" };+ if (withNormals) features.push_back("MESH_NORMALS");+ if (skinned) features.push_back("SKINNED");+ // Resident geometry carries the frame's shadow map on its own slot 2 and the+ // reflection on slot 3; the batch variant of the same material must not, which+ // is why these ride the mesh path.+ features.push_back("ES_RECEIVE_SHADOW");+ if (envMapped) features.push_back("ES_ENV_MAP");+ // As above: this vertex source gives the fragment a real world position, so a+ // positional light is read from where it is rather than from the plane.+ features.push_back("ES_SURFACE_3D");+ return variantProgram(materialId, resources, shape, features, "resident geometry");+}++u32 MaterialStore::particleProgram(u32 materialId, resource::ResourceManager& resources) const {+ return variantProgram(materialId, resources, 1ull << 35, { "PARTICLE" }, "particles");+}++u32 MaterialStore::variantProgram(u32 materialId, resource::ResourceManager& resources,+ u64 shape, std::vector<std::string> extraFeatures,+ const char* what) const {+ const MaterialRecord* rec = find(materialId);+ if (!rec || !rec->shaderRef.isValid()) return 0;+ const u64 key = static_cast<u64>(rec->shaderRef.id()) | shape;auto cached = mesh_programs_.find(key);if (cached != mesh_programs_.end()) return cached->second;@@ -64,22 +85,12 @@ u32 MaterialStore::meshProgram(u32 materialId, resource::ResourceManager& resourreturn 0;}- // The SAME source and features plus MESH: the author's fragment is untouched- // and only the engine's vertex stage changes, which is what makes this one- // material rather than two that must be kept in step.+ // The SAME source and features plus this vertex source's: the author's+ // fragment is untouched and only the engine's vertex stage changes, which is+ // what makes this one material rather than two that must be kept in step.resource::ParsedShader parsed = resource::ShaderParser::parse(src->second.source);std::vector<std::string> features = resource::ShaderParser::splitFeatures(src->second.features);- features.push_back("MESH");- if (withNormals) features.push_back("MESH_NORMALS");- if (skinned) features.push_back("SKINNED");- // Resident geometry carries the frame's shadow map on its own slot 2 and the- // reflection on slot 3; the batch variant of the same material must not, which- // is why these ride the mesh path.- features.push_back("ES_RECEIVE_SHADOW");- if (envMapped) features.push_back("ES_ENV_MAP");- // As above: this vertex source gives the fragment a real world position, so a- // positional light is read from where it is rather than from the plane.- features.push_back("ES_SURFACE_3D");+ for (auto& f : extraFeatures) features.push_back(std::move(f));const auto target = resources.preferredShaderTarget();const std::string vert = resource::ShaderParser::assembleStage(parsed, resource::ShaderStage::Vertex, "", features, target);@@ -90,13 +101,13 @@ u32 MaterialStore::meshProgram(u32 materialId, resource::ResourceManager& resour// would compile a program that still ignores the per-object transform.if (!parsed.vertexIsCanonical) {ES_LOG_WARN("MaterialStore: material {} writes its own vertex stage, so it cannot draw "- "resident geometry (only a shader on the engine's vertex stage can)", materialId);+ "{} (only a shader on the engine's vertex stage can)", materialId, what);mesh_programs_[key] = 0;return 0;}if (!parsed.valid || vert.empty() || frag.empty()) {- ES_LOG_WARN("MaterialStore: no mesh variant for material {} ({})",- materialId, parsed.valid ? "stage assembly failed" : parsed.errorMessage);+ ES_LOG_WARN("MaterialStore: no {} variant for material {} ({})",+ what, materialId, parsed.valid ? "stage assembly failed" : parsed.errorMessage);mesh_programs_[key] = 0;return 0;}diff --git a/src/esengine/renderer/store/MaterialStore.hpp b/src/esengine/renderer/store/MaterialStore.hppindex 2d3d25523..79b7708d8 100644--- a/src/esengine/renderer/store/MaterialStore.hpp+++ b/src/esengine/renderer/store/MaterialStore.hpp@@ -176,6 +176,11 @@ public:bool withNormals = false, bool skinned = false,bool envMapped = false) const;+ /// The program that draws @p materialId on PARTICLE geometry — the instanced+ /// quad an emitter streams. Same source, same author's fragment, a different+ /// engine vertex stage; 0 on the same terms as {@link meshProgram}.+ u32 particleProgram(u32 materialId, resource::ResourceManager& resources) const;+/// Registers (or replaces) a shader's MaterialConstants layout — called when a shader/// authored with #pragma param is compiled, so materials on it can pack their uniforms./// Filed under the HANDLE, not the program id: rebuilding the program (a@@ -290,10 +295,16 @@ private:std::string features;};std::unordered_map<u32, ShaderSource> sources_;- /// Handle → the program compiled for the mesh vertex source (0 = tried and+ /// (Handle, vertex source) → the program compiled for it (0 = tried and/// failed). Mutable because compiling it is memoization: the collect path/// asks a read-only store, and the answer is the same every time.mutable std::unordered_map<u64, u32> mesh_programs_;++ /// One material compiled for one vertex source: @p shape distinguishes the+ /// cache entries, @p extraFeatures the engine vertex stage, @p what the log.+ u32 variantProgram(u32 materialId, resource::ResourceManager& resources,+ u64 shape, std::vector<std::string> extraFeatures,+ const char* what) const;GfxDevice* device_ = nullptr;resource::ResourceManager* resources_ = nullptr;TextureHandle defaultWhite_ = TextureHandle::Invalid;diff --git a/src/esengine/resource/ShaderParser.cpp b/src/esengine/resource/ShaderParser.cppindex 6de8605e3..aa4b5886d 100644--- a/src/esengine/resource/ShaderParser.cpp+++ b/src/esengine/resource/ShaderParser.cpp@@ -130,6 +130,18 @@ std::string canonicalVertexStageWGSL(bool lit) {"#endif\n""\n""struct VSIn {\n"+ // A particle's quad corner is the vertex; where that corner lands is on the+ // instance, so this layout replaces the block rather than adding to it.+ "#ifdef PARTICLE\n"+ " @location(0) a_position : vec2f,\n"+ " @location(1) a_texCoord : vec2f,\n"+ " @location(2) a_inst_position : vec3f,\n"+ " @location(3) a_inst_size : vec2f,\n"+ " @location(4) a_inst_rotation : f32,\n"+ " @location(5) a_inst_color : vec4f,\n"+ " @location(6) a_inst_uv_offset : vec2f,\n"+ " @location(7) a_inst_uv_scale : vec2f,\n"+ "#else\n"" @location(0) a_position : vec3f,\n"" @location(1) a_color : vec4f,\n"" @location(2) a_texCoord : vec2f,\n"@@ -154,13 +166,31 @@ std::string canonicalVertexStageWGSL(bool lit) {" @location(15) a_nrm2 : vec3f,\n""#endif\n""#endif\n"+ "#endif\n""};\n""\n""@vertex fn vs_main(v : VSIn) -> VSOut {\n"" var out : VSOut;\n"+ // A particle faces the viewer wherever it is seen from; head-on and+ // orthographic the axes come out (1,0,0) and (0,1,0), the flat quad a 2D+ // scene has always drawn.+ "#ifdef PARTICLE\n"+ " let scaled = v.a_position * v.a_inst_size;\n"+ " let cosR = cos(v.a_inst_rotation);\n"+ " let sinR = sin(v.a_inst_rotation);\n"+ " let rotated = vec2f(scaled.x * cosR - scaled.y * sinR,\n"+ " scaled.x * sinR + scaled.y * cosR);\n"+ " let fwd = viewDirection(v.a_inst_position);\n"+ // Looking straight down the world up, that axis cannot orient the quad.+ " var refUp = vec3f(0.0, 1.0, 0.0);\n"+ " if (abs(fwd.y) > 0.999) { refUp = vec3f(0.0, 0.0, 1.0); }\n"+ " let right = normalize(cross(refUp, fwd));\n"+ " let up = cross(fwd, right);\n"+ " let world = vec4f(v.a_inst_position + right * rotated.x + up * rotated.y, 1.0);\n"+ " out.v_color = v.a_inst_color;\n"// Bones are already world-space, so a skinned mesh's own transform is not// read — which is what glTF requires of one.- "#ifdef SKINNED\n"+ "#elif defined(SKINNED)\n"" let pose = v.a_weights.x * skin.bones[v.a_joints.x]\n"" + v.a_weights.y * skin.bones[v.a_joints.y]\n"" + v.a_weights.z * skin.bones[v.a_joints.z]\n"@@ -175,7 +205,12 @@ std::string canonicalVertexStageWGSL(bool lit) {" out.v_color = v.a_color;\n""#endif\n"" out.pos = frame.projection * world;\n"+ "#ifdef PARTICLE\n"+ // A sheet animation moves the frame under the same quad.+ " out.v_texCoord = v.a_texCoord * v.a_inst_uv_scale + v.a_inst_uv_offset;\n"+ "#else\n"" out.v_texCoord = v.a_texCoord;\n"+ "#endif\n""#ifdef MESH_NORMALS\n""#ifdef SKINNED\n"" out.v_worldNormal = mat3x3f(pose[0].xyz, pose[1].xyz, pose[2].xyz) * v.a_normal;\n"@@ -243,6 +278,19 @@ std::string canonicalPPVertexStage() {// transform), skinned (posed by bones). One material serves all three.std::string canonicalVertexStage(bool lit) {std::string src =+ // A particle's quad corner is the vertex; where that corner lands is on the+ // instance. The layout differs from every other source, so it replaces the+ // block rather than adding to it.+ "#ifdef PARTICLE\n"+ "layout(location = 0) in vec2 a_position;\n"+ "layout(location = 1) in vec2 a_texCoord;\n"+ "layout(location = 2) in vec3 a_inst_position;\n"+ "layout(location = 3) in vec2 a_inst_size;\n"+ "layout(location = 4) in float a_inst_rotation;\n"+ "layout(location = 5) in vec4 a_inst_color;\n"+ "layout(location = 6) in vec2 a_inst_uv_offset;\n"+ "layout(location = 7) in vec2 a_inst_uv_scale;\n"+ "#else\n""layout(location = 0) in vec3 a_position;\n""layout(location = 1) in vec4 a_color;\n""layout(location = 2) in vec2 a_texCoord;\n"@@ -271,6 +319,7 @@ std::string canonicalVertexStage(bool lit) {"layout(location = 15) in vec3 a_nrm2;\n""#endif\n""#endif\n"+ "#endif\n""\n""out vec4 v_color;\n""out vec2 v_texCoord;\n"@@ -284,9 +333,25 @@ std::string canonicalVertexStage(bool lit) {src +="\n""void main() {\n"+ // A particle faces the viewer wherever it is seen from; head-on and+ // orthographic the axes come out (1,0,0) and (0,1,0), the flat quad a 2D+ // scene has always drawn.+ "#ifdef PARTICLE\n"+ " vec2 scaled = a_position * a_inst_size;\n"+ " float cosR = cos(a_inst_rotation);\n"+ " float sinR = sin(a_inst_rotation);\n"+ " vec2 rotated = vec2(scaled.x * cosR - scaled.y * sinR,\n"+ " scaled.x * sinR + scaled.y * cosR);\n"+ " highp vec3 fwd = viewDirection(a_inst_position);\n"+ // Looking straight down the world up, that axis cannot orient the quad.+ " highp vec3 refUp = abs(fwd.y) > 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(0.0, 1.0, 0.0);\n"+ " highp vec3 right = normalize(cross(refUp, fwd));\n"+ " highp vec3 up = cross(fwd, right);\n"+ " vec4 world = vec4(a_inst_position + right * rotated.x + up * rotated.y, 1.0);\n"+ " v_color = a_inst_color;\n"// Bones are already world-space, so a skinned mesh's own transform is not// read — which is what glTF requires of one.- "#ifdef SKINNED\n"+ "#elif defined(SKINNED)\n"" mat4 skin = a_weights.x * u_bones[a_joints.x]\n"" + a_weights.y * u_bones[a_joints.y]\n"" + a_weights.z * u_bones[a_joints.z]\n"@@ -301,7 +366,12 @@ std::string canonicalVertexStage(bool lit) {" v_color = a_color;\n""#endif\n"" gl_Position = u_projection * world;\n"+ "#ifdef PARTICLE\n"+ // A sheet animation moves the frame under the same quad.+ " v_texCoord = a_texCoord * a_inst_uv_scale + a_inst_uv_offset;\n"+ "#else\n"" v_texCoord = a_texCoord;\n"+ "#endif\n""#ifdef MESH_NORMALS\n""#ifdef SKINNED\n"" v_worldNormal = mat3(skin) * a_normal;\n"diff --git a/tests/renderer/test_shader_variant.cpp b/tests/renderer/test_shader_variant.cppindex 97a7c935c..eeb769e38 100644--- a/tests/renderer/test_shader_variant.cpp+++ b/tests/renderer/test_shader_variant.cpp@@ -372,6 +372,29 @@ static void testFragmentOnly() {ppv.find("u_projection *") == std::string::npos,"PostProcess canonical vertex is the clip-space pass-through (no projection)");+ // A particle is drawn from an instanced vertex source, so the canonical stage+ // has a third shape. Both dialects: a twin that will not build is a pipeline+ // the device refuses with no mention of a shader.+ ParsedShader particle = ShaderParser::parse(+ "#pragma shader \"P\"\n#pragma version 300 es\n#pragma domain Unlit\n"+ "#pragma fragment\nvoid main() { fragColor = vec4(1.0); }\n#pragma end\n"+ "#pragma fragment wgsl\n@fragment fn fs_main(v : VSOut) -> @location(0) vec4f "+ "{ return vec4f(1.0); }\n#pragma end\n");+ const std::string pVs = ShaderParser::assembleStage(particle, ShaderStage::Vertex, "", {"PARTICLE"});+ CHECK(pVs.find("#define PARTICLE") != std::string::npos &&+ pVs.find("in vec3 a_inst_position;") != std::string::npos,+ "PARTICLE reaches the GLSL driver as a define, with the instance attributes");+ CHECK(pVs.find("viewDirection(a_inst_position)") != std::string::npos,+ "and billboards the quad from the instance's world position");+ const std::string pVsW = ShaderParser::assembleStage(+ particle, ShaderStage::Vertex, "", {"PARTICLE"}, ShaderTargetLanguage::WGSL);+ CHECK(pVsW.find("a_inst_position : vec3f") != std::string::npos &&+ pVsW.find("a_color : vec4f") == std::string::npos,+ "the WGSL twin takes the same attributes");+ CHECK(pVsW.find("fn viewDirection") != std::string::npos &&+ pVsW.find("fn viewDirection") < pVsW.find("viewDirection(v.a_inst_position)"),+ "and the helper it billboards with is declared before it is called");+ParsedShader unknownDomain = ShaderParser::parse(FRAG_ONLY_UNKNOWN_DOMAIN);CHECK(!unknownDomain.valid, "a domain with no canonical vertex still errors");diff --git a/tools/check-component-fields.mjs b/tools/check-component-fields.mjsindex 997672407..385adac97 100644--- a/tools/check-component-fields.mjs+++ b/tools/check-component-fields.mjs@@ -35,10 +35,6 @@ const DECLARED_GAPS = {'CacheAsBitmap.dirty': 'see CacheAsBitmap.enabled','CacheAsBitmap.width': 'see CacheAsBitmap.enabled','CacheAsBitmap.height': 'see CacheAsBitmap.enabled',- 'ParticleEmitter.material': 'a particle is drawn from an instanced vertex source,'- + ' and a material is compiled per vertex source (MaterialStore::meshProgram takes'- + ' the mesh ones) — nothing compiles the instanced variant, so the table has no'- + ' program to hand back',};const components = JSON.parse(diff --git a/tools/renderScenes.mjs b/tools/renderScenes.mjsindex 9bc28a283..7d16d4e6d 100644--- a/tools/renderScenes.mjs+++ b/tools/renderScenes.mjs@@ -186,6 +186,10 @@ export const SCENES = [// A quad fixed in the x/y plane is edge-on from there and covers nothing; a// billboard faces the viewer wherever it stands, which is the whole claim.{ id: "particles-billboard", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_PLAY: "1", ESTELLA_VERIFY_SCENE: "/scenes/particle-billboard.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/particle-billboard.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "20", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.5,\"y\":0.5,\"rgb\":[0,255,0],\"tol\":90}]" } },+ // A particle drawn by an AUTHORED material: the fixture's shader ignores the+ // particle's own green and paints the material's red, so the two are told+ // apart by the pixel rather than by both being plausible.+ { id: "particles-material", tier: "pr", webgpu: true, env: { ESTELLA_VERIFY_PLAY: "1", ESTELLA_VERIFY_SCENE: "/scenes/particle-material.esscene", ESTELLA_VERIFY_MANIFEST: "/scenes/particle-material.textures.json", ESTELLA_VERIFY_W: "256", ESTELLA_VERIFY_H: "256", ESTELLA_VERIFY_STEPS: "20", ESTELLA_VERIFY_EXPECT: "[{\"x\":0.5,\"y\":0.5,\"rgb\":[255,0,0],\"tol\":90}]" } },// Trail, floor collision and force fields — fixtures that existed with nothing// running them. Probe-less for the reason `particles` is; each claims its path// still produces a frame. PR tier: half a second each, otherwise unwatched.