reze-engine 0.69.8 → 0.69.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,682 +1,706 @@
1
- import { sceneFsOutWgsl } from "../passes/scene-contract"
2
- import { lightsApi } from "../lights"
3
- import { SHADOW_CASCADES } from "../../shadow-cascades"
4
- import { sunShadowWgsl } from "../scene-light-api"
5
- import { WORLD_AMBIENT_WGSL } from "../lights"
6
-
7
- // Shared WGSL blocks concatenated by every material shader.
8
- // Splits the boilerplate (uniform structs, bind group layout, skinning VS, PCF shadow)
9
- // away from the per-material fragment code so each material file only contains what
10
- // makes it visually distinct.
11
- //
12
- // Concat order in every material:
13
- // NODES_WGSL (nodes.ts — math/noise/BSDF helpers)
14
- // COMMON_BINDINGS_WGSL (uniform structs + @group/@binding declarations)
15
- // SAMPLE_SHADOW_WGSL (3×3 PCF shadow sampler; reads bindings above)
16
- // COMMON_VS_WGSL (skinning vertex shader; reads bindings above)
17
- // <material's own constants + @fragment fn fs>
18
- //
19
- // WGSL is a whole-module compile — declaration order at module scope doesn't matter,
20
- // but the readable order is: types → bindings → helpers → entry points.
21
-
22
- // ─── Uniform structs + bind group layout ────────────────────────────
23
- // Every material pipeline uses the same bind group layout, so the same bindings are
24
- // declared here once. Groups:
25
- // group(0): per-frame scene (camera, lights, shadow map, BRDF LUT via nodes.ts)
26
- // group(1): per-model skinning
27
- // group(2): per-material (diffuse texture + material uniforms)
28
-
29
- /** The jelly eyes' vertex move (jelly-eyes.ts). Every pass that places model
30
- * vertices takes it, or a pass that skips it draws the iris where it was —
31
- * the shadow map then shades half the moved iris with its own unmoved copy.
32
- * Reads `objectLight.jelly` and `material.materialId`, which the including
33
- * module declares. */
34
- export const JELLY_VERTEX_WGSL = /* wgsl */ `
35
- fn _rzJellyTurn(q: vec2f, a: f32) -> vec2f {
36
- let c = cos(a);
37
- let s = sin(a);
38
- return vec2f(c * q.x - s * q.y, s * q.x + c * q.y);
39
- }
40
-
41
- /**
42
- * Where the jelly puts an iris vertex. The iris is the part of the eye the eye
43
- * bones carry, so it is moved as a whole, in bind space before skinning:
44
- * scaled about its centre (the CPU composes the blink's spring, the lid's
45
- * press and her motion's knock into one scale), turned and drifted a hair on
46
- * the spring, brought forward a hair, and rolled about the eye bone with a
47
- * closing expression — inside the white, which stays where it is. A highlight
48
- * layer (this draw's material is one of jelly[1].w's) takes the iris's move,
49
- * then its own scale, turn and tremble, before the roll. Vertices take it by their weight on the eye bones
50
- * (jelly[2].w, jelly[3].w), so nothing else on the face moves.
51
- */
52
- fn rzJellyVertex(p: vec3f, joints: vec4<u32>, nw: vec4f) -> vec3f {
53
- let j = objectLight.jelly;
54
- let ids = u32(j[1].w);
55
- let mid = u32(material.materialId);
56
- let hl = mid > 0u && (mid == (ids & 4095u) || mid == (ids >> 12u));
57
- var out = p;
58
- for (var e = 0u; e < 2u; e++) {
59
- let bone = j[2u + e].w;
60
- if (bone < 0.0) { continue; }
61
- let b = u32(bone);
62
- let w = dot(nw, select(vec4f(0.0), vec4f(1.0), joints == vec4<u32>(b)));
63
- if (w <= 0.0) { continue; }
64
- let c = j[e].xyz;
65
- // A rig that carries both eyes on one bone: each vertex follows its own side.
66
- if (j[2].w == j[3].w && e == 0u && distance(p.xy, j[1].xy) < distance(p.xy, j[0].xy)) { continue; }
67
- if (j[2].w == j[3].w && e == 1u && distance(p.xy, j[0].xy) <= distance(p.xy, j[1].xy)) { continue; }
68
- let t = j[4u + e];
69
- let m = j[6u + e];
70
- let h = j[10u + e];
71
- var q = _rzJellyTurn((p.xy - c.xy) * t.xy, t.z) + m.xy;
72
- // Forward is −Z (MMD faces −Z).
73
- var push = h.z;
74
- if (hl) {
75
- // Sliding over the iris's dome on its own, a highlight sheet a hair in
76
- // front of it would sink into it where the dome bulges more and the two
77
- // fight for depth; so it comes forward by as far as it slid — a slope of
78
- // one, steeper than the dome anywhere it draws.
79
- let before = q;
80
- q = _rzJellyTurn(q * h.xy, t.w) + m.zw;
81
- push += length(q - before);
82
- }
83
- var moved = vec3f(c.xy + q, p.z - push);
84
- let roll = j[8u + e];
85
- if (roll.w != 0.0) {
86
- let d = moved - roll.xyz;
87
- let rd = _rzJellyTurn(d.yz, roll.w);
88
- moved = roll.xyz + vec3f(d.x, rd.x, rd.y);
89
- }
90
- out = mix(p, moved, w);
91
- }
92
- return out;
93
- }
94
- `
95
-
96
- /** A model's ObjectLight as WGSL declares it (see the layout below). One copy
97
- * for every pass that binds it, so their layouts cannot drift. */
98
- export const OBJECT_LIGHT_STRUCT_WGSL =
99
- "struct ObjectLight { layers: vec4u, ambient: vec4f, sh: array<vec4f, 9>, fill: vec4f, jelly: array<vec4f, 12>, bloom: vec4f, xray: array<vec4f, 4>, xrayMask: array<vec4u, 16> }"
100
-
101
- /**
102
- * The see-through window (#xray): a rectangle on the frame, in pixels —
103
- * xray[0] is (left, top, right, bottom), xray[3].x is 1 while a window is open
104
- * on this model — and which of the model's materials it cuts: a bit a
105
- * material, by its 1-based draw index (materialId), up to 512. Tested against
106
- * the fragment's own position, so it sits where the lens is, whatever moves
107
- * behind it. Declared after the pass's own `objectLight` binding.
108
- */
109
- export const XRAY_WGSL = /* wgsl */ `
110
- fn rz_xray_inside(fp: vec4f) -> bool {
111
- if (objectLight.xray[3].x < 0.5) { return false; }
112
- let r = objectLight.xray[0];
113
- return fp.x >= r.x && fp.y >= r.y && fp.x <= r.z && fp.y <= r.w;
114
- }
115
- fn rz_xray_cut(fp: vec4f, materialId: f32) -> bool {
116
- let i = u32(materialId);
117
- if (i >= 512u) { return false; }
118
- let word = objectLight.xrayMask[i / 128u][(i / 32u) % 4u];
119
- if (((word >> (i % 32u)) & 1u) == 0u) { return false; }
120
- return rz_xray_inside(fp);
121
- }
122
- `
123
-
124
- export const COMMON_BINDINGS_WGSL = /* wgsl */ `
125
-
126
- struct CameraUniforms {
127
- view: mat4x4f,
128
- projection: mat4x4f,
129
- viewPos: vec3f,
130
- /** Render-target height in device pixels. */
131
- viewportHeight: f32,
132
- /** The scene clock in seconds — what the time node reads. Paused with the
133
- * transport and stepped exactly by an export, so an animated material lands
134
- * in the file where it stood on screen. (No backticks in here: this WGSL
135
- * lives in a template literal and one would end it.) */
136
- time: f32,
137
- // NOTHING AFTER THIS. A trailing vec3f aligns to 16 and pushes the struct to
138
- // 176 bytes against a 160-byte buffer, which fails validation on every
139
- // pipeline at once; ending on the f32 rounds the struct to exactly 160.
140
- };
141
-
142
- struct Light {
143
- direction: vec4f,
144
- color: vec4f,
145
- };
146
-
147
- struct LightUniforms {
148
- ambientColor: vec4f,
149
- lights: array<Light, 4>,
150
- /** Irradiance SH of the HDRI world; [0].w is the on-flag. */
151
- sh: array<vec4f, 9>,
152
- /** The scene fog (Engine.setSceneFog): haze (colour, amount), (distance,
153
- * height), then the second layer the same. Amount 0 is none. */
154
- fog: array<vec4f, 4>,
155
- /** The cast's shadow on a stage (Engine.setStageCastShadow): colour, amount;
156
- * amount 0 is off. Then the view-projection its map was drawn with. */
157
- castShadow: vec4f,
158
- castVP: mat4x4f,
159
- /** The rendering layers each directional light reaches, slot by slot — a
160
- * draw is lit by the first whose bits it shares (rzMainLight). */
161
- dirLayers: vec4u,
162
- };
163
-
164
- // Per-material uniforms. Every material binds this layout even if it ignores fields;
165
- // the engine keeps one bind group layout across all material pipelines. The PMX
166
- // classic-material fields (ambient/specular/shininess) are carried for graph nodes that
167
- // want them; most graphs read only diffuseColor + alpha.
168
- struct MaterialUniforms {
169
- diffuseColor: vec3f, // PMX diffuse rgb — the material_diffuse node reads this
170
- alpha: f32, // 0 → discard; <1 → transparent draw call
171
- ambient: vec3f, // PMX ambient rgb
172
- shininess: f32, // PMX specular power
173
- specular: vec3f, // PMX specular rgb
174
- sphereMode: f32, // 0 none · 1 multiply (sph) · 2 add (spa)
175
- // Skeleton index of the 頭 (head) bone, or -1. Lets the eye shader gate
176
- // the post-alpha-eye stencil by camera-vs-face hemisphere.
177
- headBoneIndex: f32,
178
- // The draw's identity, for the id attachment: which material, which object.
179
- // They ride HERE, in padding this struct already carried, so the buffer's
180
- // size and layout are untouched and the indirect-draw path keeps working —
181
- // the ids arrive with the same per-draw uniform the material already binds,
182
- // rather than needing a channel of their own. Zero while ids are off, and
183
- // zero is the reserved "nothing" value, so reading them then is not wrong,
184
- // just empty. f32 because the buffer is written as floats; the shader casts.
185
- materialId: f32,
186
- objectId: f32,
187
- // How much of this material is still THERE: 1 whole, 0 gone. Rides the last
188
- // of the padding this struct already carried, for the same reason the ids do
189
- // — the buffer's size and layout are untouched, so the indirect-draw path and
190
- // every existing pipeline keep working, and a material that never dissolves
191
- // pays one float it was already paying.
192
- //
193
- // A material morph rebuilds this block from its base copy, which is why the
194
- // engine writes the value into that copy as well as into the live buffer: a
195
- // face morphing while she dissolves must not come back solid for those frames.
196
- dissolve: f32,
197
- };
198
-
199
- struct VertexOutput {
200
- // @invariant: the opaque depth prepass rasterises this same skinned position
201
- // through a DIFFERENT shader module, and the colour pass then depth-tests
202
- // less-equal against what it wrote. Without invariance a backend is free to
203
- // optimise the two position computations differently, and a one-ulp
204
- // disagreement is a pixel of missing character. Invariance pins both to the
205
- // same result; it costs only that freedom.
206
- @builtin(position) @invariant position: vec4f,
207
- @location(0) normal: vec3f,
208
- @location(1) uv: vec2f,
209
- @location(2) worldPos: vec3f,
210
- // Bind-pose object-space position (the raw pre-skin vertex attribute). Procedural
211
- // textures (noise bump, sparkle, Generated-coord gradients) key off this instead of
212
- // worldPos so the pattern rides with the surface — otherwise the mesh swims through a
213
- // world-static noise field under any skinning deformation or root (センター) motion.
214
- // At rest skinMats are identity so restPos == worldPos, which is why existing noise-
215
- // scale constants stay valid without retuning.
216
- @location(3) restPos: vec3f,
217
- /** The scene fog's two amounts, computed PER VERTEX as the game does — see
218
- * Engine.setSceneFog — and interpolated across the face. */
219
- @location(5) fog: vec2f,
220
- /** The vertex colour, RGBA — white on a mesh that carries none. A PMX keeps
221
- * it in its first additional UV (what a converted game stage writes there:
222
- * a plant's occlusion rides in its alpha). The attribute node reads it. */
223
- @location(6) vcolor: vec4f,
224
- /** The second UV set — a PMX's second additional UV (xy), else the first
225
- * UV again. The uv_map node's uv2. */
226
- @location(7) uv2: vec2f,
227
- };
228
-
229
- /** One fog layer's amount at a vertex of view depth d and world height y. */
230
- fn _rzFogAmount(d: f32, y: f32, col: vec4f, p: vec4f) -> f32 {
231
- if (col.w <= 0.0) { return 0.0; }
232
- let f = clamp(d * p.x + p.y, 0.0, 1.0);
233
- let h = clamp((p.z - y) / p.w, -1.0, 1.0);
234
- return (1.0 - clamp(f - (1.0 - f) * h, 0.0, 1.0)) * col.w;
235
- }
236
-
237
- // One view-projection per shadow cascade, inner to outer — the volumes built
238
- // by shadow-cascades.ts, in the same order.
239
- struct LightVP { viewProj: array<mat4x4f, ${SHADOW_CASCADES.length}>, };
240
-
241
- @group(0) @binding(0) var<uniform> camera: CameraUniforms;
242
- @group(0) @binding(1) var<uniform> light: LightUniforms;
243
- @group(0) @binding(2) var diffuseSampler: sampler;
244
- // The sun's shadow atlas: every cascade in its own tile — see shadow-cascades.ts.
245
- @group(0) @binding(3) var shadowAtlas: texture_depth_2d;
246
- @group(0) @binding(4) var shadowSampler: sampler_comparison;
247
- @group(0) @binding(5) var<uniform> lightVP: LightVP;
248
- // The world's own sky, for a surface that REFLECTS it rather than merely being
249
- // lit by it. Equirect, in the same layout and the same linear radiance the
250
- // composite draws the dome from, and mipped — a rough surface reads a coarser
251
- // level, which is what a prefiltered environment is for. A scene with no HDRI
252
- // has the 1x1 fallback bound here; rzWorldSpecular checks the SH flag and
253
- // answers with the flat ambient instead, so nothing samples the placeholder.
254
- @group(0) @binding(8) var worldEnvTexture: texture_2d<f32>;
255
- // The cast's own shadow map for a stage's floor — see _rzCastShadow.
256
- @group(0) @binding(10) var castShadowMap: texture_depth_2d;
257
-
258
- /** The stage's reflection probe (Engine.captureReflectionProbe): where it was
259
- * captured (xyz) and its strength (w); the box it projects onto, min with the
260
- * on-flag in w, then max with the local flag in w (1: outside the box the
261
- * sky stands in). Off (boxMin.w 0) the sky stands in everywhere. */
262
- struct ProbeUniforms {
263
- center: vec4f,
264
- boxMin: vec4f,
265
- boxMax: vec4f,
266
- };
267
- // A cube, GGX-prefiltered down its mips — see rzProbeSpecular in nodes.ts.
268
- @group(0) @binding(11) var probeCube: texture_cube<f32>;
269
- @group(0) @binding(12) var<uniform> probe: ProbeUniforms;
270
-
271
- /**
272
- * How much of the cast stands between this point and the stage's shadow
273
- * direction, 0–1 — setStageCastShadow. A 5×5 comparison filter at 1.5 texels:
274
- * the game blurs its character shadow before laying it, and a single tap reads
275
- * as a stencil.
276
- */
277
- fn _rzCastShadow(wp: vec3f) -> f32 {
278
- if (light.castShadow.w <= 0.0) { return 0.0; }
279
- let c = light.castVP * vec4f(wp, 1.0);
280
- let ndc = c.xyz / c.w;
281
- if (abs(ndc.x) >= 1.0 || abs(ndc.y) >= 1.0 || ndc.z <= 0.0 || ndc.z >= 1.0) { return 0.0; }
282
- let uv = vec2f(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5);
283
- let ts = 1.5 / f32(textureDimensions(castShadowMap).x);
284
- var lit = 0.0;
285
- for (var y = -2; y <= 2; y++) {
286
- for (var x = -2; x <= 2; x++) {
287
- lit += textureSampleCompareLevel(castShadowMap, shadowSampler, uv + vec2f(f32(x), f32(y)) * ts, ndc.z - 0.001);
288
- }
289
- }
290
- return 1.0 - lit / 25.0;
291
- }
292
- @group(1) @binding(0) var<storage, read> skinMats: array<mat4x4f>;
293
- // What this object's lighting is, apart from the scene's, as the game's
294
- // pipeline gives each renderer its own:
295
- // layers.x its rendering-layer bits, which decide the lights that reach it —
296
- // a stage's daylight and the cast's key are two lights on two
297
- // layers, as the game lights them;
298
- // ambient.x 1 while it has an ambient of its own (Engine.setModelAmbient),
299
- // 0 for the world's;
300
- // sh that ambient's irradiance, folded as the world's (ibl.ts);
301
- // fill.rgb its fill (Engine.setModelFill), added after its graph times its
302
- // surface colour — zero for a model that has none.
303
- // jelly its jelly eyes (Engine.setModelJellyEyes, jelly-eyes.ts), not
304
- // lighting but per-model all the same, so it rides here:
305
- // [0] left iris centre (bind space), strength — 0 is off
306
- // [1] right iris centre, the highlight layers' materialIds
307
- // (a + b·4096, 0 none)
308
- // [2] left iris half extents, closure, eye bone (−1 none)
309
- // [3] the right's
310
- // [4] left scale x, y, twist, highlight turn (radians)
311
- // [5] the right's
312
- // [6] left drift x, y, highlight's own offset x, y (bind units)
313
- // [7] the right's
314
- // [8] left eye bone's head (the roll's pivot), roll (radians)
315
- // [9] the right's
316
- // [10] left highlight scale x, y, forward push (bind units), 0
317
- // [11] the right's
318
- // bloom.x 1 while it feeds the bloom, 0 when it is left out
319
- // (Engine.setModelBloom): the bloom mask its surfaces and
320
- // outlines write.
321
- ${OBJECT_LIGHT_STRUCT_WGSL}
322
- @group(1) @binding(1) var<uniform> objectLight: ObjectLight;
323
- ${XRAY_WGSL}
324
-
325
- ${JELLY_VERTEX_WGSL}
326
- /** The light arriving at a surface of this object facing n: its own ambient
327
- * where loaded data gave it one (a stage's probes, a character's), else the
328
- * world's. The same polynomial rzWorldAmbient evaluates. */
329
- fn rzObjectAmbient(n: vec3f) -> vec3f {
330
- if (objectLight.ambient.x < 0.5) { return rzWorldAmbient(n); }
331
- let s = objectLight.sh;
332
- let c = s[0].xyz + s[1].xyz * n.y + s[2].xyz * n.z + s[3].xyz * n.x
333
- + s[4].xyz * (n.x * n.y) + s[5].xyz * (n.y * n.z) + s[6].xyz * (3.0 * n.z * n.z - 1.0)
334
- + s[7].xyz * (n.x * n.z) + s[8].xyz * (n.x * n.x - n.y * n.y);
335
- return max(c, vec3f(0.0));
336
- }
337
-
338
- /** The directional light slot that lights this draw: the first whose layers
339
- * it shares, else the sun's. */
340
- fn rzMainLight() -> u32 {
341
- for (var k = 0u; k < 4u; k++) {
342
- if ((light.dirLayers[k] & objectLight.layers.x) != 0u) { return k; }
343
- }
344
- return 0u;
345
- }
346
- @group(2) @binding(0) var diffuseTexture: texture_2d<f32>;
347
- @group(2) @binding(1) var<uniform> material: MaterialUniforms;
348
- // Reserved for future sphere/toon graph nodes; graphs that don't read them get the
349
- // 1×1 white fallback bound here.
350
- @group(2) @binding(2) var toonTexture: texture_2d<f32>;
351
- @group(2) @binding(3) var sphereTexture: texture_2d<f32>;
352
- // Extra maps supplied by the STYLE GROUP rather than by the PMX — the lightmap /
353
- // ILM / ramp textures a Blender-authored look is built on. A PMX material carries
354
- // exactly one image, and this whole family of shading encodes shadow thresholds,
355
- // specular masks and material IDs in the channels of a second and third. Unset
356
- // slots get the 1×1 white fallback, so a graph reading one that was never
357
- // supplied sees white rather than garbage.
358
- @group(2) @binding(5) var groupTexture0: texture_2d<f32>;
359
- @group(2) @binding(6) var groupTexture1: texture_2d<f32>;
360
- @group(2) @binding(7) var groupTexture2: texture_2d<f32>;
361
- @group(2) @binding(8) var groupTexture3: texture_2d<f32>;
362
-
363
- // Four-bone blended normals can cancel to ~zero on physics-driven parts
364
- // (opposing bone rotations at 50/50 weights) — normalize(0) is 0/0 = NaN,
365
- // which poisons the whole shading stack and flashes through bloom. Fall
366
- // back to up for degenerate normals instead.
367
- // A fragment's colour as it may leave the material: every channel finite. A NaN
368
- // or Inf from any graph on any GPU is one pixel here, written as nothing; let
369
- // through, it blooms into a block and the skin blur smears it into bars. Read
370
- // off the exponent bits, which fast math cannot fold away.
371
- fn rz_finite(c: vec4f) -> vec4f {
372
- let e = bitcast<vec4u>(c) & vec4u(0x7f800000u);
373
- return select(vec4f(0.0), c, e != vec4u(0x7f800000u));
374
- }
375
-
376
- fn safe_normal(nIn: vec3f) -> vec3f {
377
- let l2 = dot(nIn, nIn);
378
- if (l2 < 1e-12) { return vec3f(0.0, 1.0, 0.0); }
379
- return nIn * inverseSqrt(l2);
380
- }
381
-
382
- `;
383
-
384
- // ─── Shadow sampler (3×3 PCF, cascade-selected) ─────────────────────
385
- // Normal-bias 0.08, depth-bias 0.001 NDC; the lookup is sunShadowWgsl in
386
- // scene-light-api.ts, shared with the ground and effects.
387
- //
388
- // Selection: the first cascade whose box covers the point — with a margin that
389
- // keeps the whole PCF kernel inside its tile — else LIT. Lit is a fix, not
390
- // merely a default: past every cascade there is no occlusion information, and
391
- // comparing against unrelated depths would silently shadow any stage deeper
392
- // than the boxes.
393
-
394
- const SAMPLE_SHADOW_WGSL = /* wgsl */ `
395
- ${sunShadowWgsl("_rzSun", "shadowAtlas", "shadowSampler", "lightVP.viewProj")}
396
-
397
- /** The sun's cast shadow alone, without sampleShadow's facing test: what a
398
- * character's ramp is min'd with (its own N·L carries the terminator). */
399
- fn rzSunOcclusion(worldPos: vec3f, n: vec3f) -> f32 {
400
- let castAmt = light.lights[0].direction.w;
401
- if (castAmt <= 0.0) { return 1.0; }
402
- let a = _rzSunLocate(worldPos + n * 0.08);
403
- if (a.w < 0.0) { return 1.0; }
404
- return mix(1.0, _rzSunTaps(a), castAmt);
405
- }
406
-
407
- fn sampleShadow(worldPos: vec3f, n: vec3f) -> f32 {
408
- // THE SCENE'S ONE SHADOW SWITCH, and it lives on the sun because the sun is
409
- // the only thing that casts. Lit is the answer when it is off: returning 0
410
- // would be "fully shadowed", the opposite of what a disabled shadow means.
411
- let castAmt = light.lights[0].direction.w;
412
- if (castAmt <= 0.0) { return 1.0; }
413
- // A surface turned from the sun is in its own shade — when the sun is what
414
- // keys it. Under a key of its own layer the atlas is only the occluders'
415
- // shadow, and the key's N·L decides its terminator.
416
- if (rzMainLight() == 0u && dot(n, -light.lights[0].direction.xyz) <= 0.0) { return 0.0; }
417
- let a = _rzSunLocate(worldPos + n * 0.08);
418
- if (a.w < 0.0) { return 1.0; }
419
- return mix(1.0, _rzSunTaps(a), castAmt);
420
- }
421
-
422
- /**
423
- * The cast's shadow on a stage surface where the stage ROOFS the cast from the
424
- * sun, 0–1 — setStageCastShadow on a graph-drawn stage (a GLB's). Under open
425
- * sky the sun's own map already lays the cast's shadow, and laying this one too
426
- * doubled it; under a ceiling the sun reaches neither the floor nor her, the
427
- * lamps cast nothing, and she stood on the floor with no shadow at all. So
428
- * per pixel: find the point of the cast that throws this shadow (the cast
429
- * map's nearest depth, walked back toward the light along the map's z row),
430
- * step off her toward the light, and ask the sun's map whether it reaches
431
- * there. Lit: the sun shadow has it, answer 0. Shadowed: this is the only
432
- * shadow she gets. Zero on everything that is not a stage (objectLight
433
- * layers.y).
434
- */
435
- fn rzRoofedCastShadow(wp: vec3f) -> f32 {
436
- if (light.castShadow.w <= 0.0 || objectLight.layers.y == 0u) { return 0.0; }
437
- let cover = _rzCastShadow(wp);
438
- if (cover <= 0.0) { return 0.0; }
439
- let ndc = (light.castVP * vec4f(wp, 1.0)).xyz;
440
- let size = vec2i(textureDimensions(castShadowMap));
441
- let px = vec2i(vec2f(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5) * vec2f(size));
442
- // The nearest of her over the filter's footprint: a penumbra texel's own
443
- // depth may be the cleared 1.
444
- var occ = 1.0;
445
- for (var y = -2; y <= 2; y += 2) {
446
- for (var x = -2; x <= 2; x += 2) {
447
- occ = min(occ, textureLoad(castShadowMap, clamp(px + vec2i(x, y), vec2i(0), size - 1), 0));
448
- }
449
- }
450
- if (occ >= ndc.z) { return 0.0; }
451
- // Orthographic: depth grows away from the light at |g| per unit.
452
- let g = vec3f(light.castVP[0].z, light.castVP[1].z, light.castVP[2].z);
453
- let k = length(g);
454
- let q = wp - (g / k) * ((ndc.z - occ) / k + 0.5);
455
- return cover * (1.0 - rzSunOcclusion(q, vec3f(0.0)));
456
- }
457
-
458
- `;
459
-
460
- // ─── Skinning vertex shader ─────────────────────────────────────────
461
- // Four-bone linear blend skinning. Renormalizes weights when they don't sum to 1
462
- // (PMX models occasionally ship with unnormalized weights on extras like hair tips).
463
- // VS normalize on the outgoing normal is skipped — interpolation denormalizes it
464
- // anyway and every fragment shader does `normalize(input.normal)` as its first line.
465
-
466
- const COMMON_VS_WGSL = /* wgsl */ `
467
-
468
- @vertex fn vs(
469
- @location(0) position: vec3f,
470
- @location(1) normal: vec3f,
471
- @location(2) uv: vec2f,
472
- @location(3) joints0: vec4<u32>,
473
- @location(4) weights0: vec4<f32>,
474
- // The extra stream (Engine: the model's attribute buffer, slot 4).
475
- @location(5) vcolor: vec4<f32>,
476
- @location(6) uv2: vec2<f32>
477
- ) -> VertexOutput {
478
- var output: VertexOutput;
479
- output.vcolor = vcolor;
480
- output.uv2 = uv2;
481
- let weightSum = weights0.x + weights0.y + weights0.z + weights0.w;
482
- let invWeightSum = select(1.0, 1.0 / weightSum, weightSum > 0.0001);
483
- let nw = select(vec4f(1.0, 0.0, 0.0, 0.0), weights0 * invWeightSum, weightSum > 0.0001);
484
- var pos4 = vec4f(position, 1.0);
485
- if (objectLight.jelly[0].w > 0.0) { pos4 = vec4f(rzJellyVertex(position, joints0, nw), 1.0); }
486
- var skinnedPos = vec4f(0.0);
487
- var skinnedNrm = vec3f(0.0);
488
- for (var i = 0u; i < 4u; i++) {
489
- let m = skinMats[joints0[i]];
490
- let w = nw[i];
491
- skinnedPos += (m * pos4) * w;
492
- skinnedNrm += (mat3x3f(m[0].xyz, m[1].xyz, m[2].xyz) * normal) * w;
493
- }
494
- output.position = camera.projection * camera.view * vec4f(skinnedPos.xyz, 1.0);
495
- output.normal = skinnedNrm;
496
- output.uv = uv;
497
- output.worldPos = skinnedPos.xyz;
498
- output.restPos = position;
499
- let viewZ = (camera.view * vec4f(skinnedPos.xyz, 1.0)).z;
500
- output.fog = vec2f(
501
- _rzFogAmount(viewZ, skinnedPos.y, light.fog[0], light.fog[1]),
502
- _rzFogAmount(viewZ, skinnedPos.y, light.fog[2], light.fog[3]),
503
- );
504
- return output;
505
- }
506
-
507
- `;
508
-
509
- // ─── FS output struct ───────────────────────────────────────────────
510
- // Location 0: final radiance+alpha (blended into rg11b10ufloat; the HDR target
511
- // has no alpha channel, but the blend equation still uses the .a you write here
512
- // as the src-alpha factor that premultiplies rgb into the HDR target).
513
- // Location 1: auxiliary rgba8unorm carrying
514
- // .r = bloom mask (1 = contributes to bloom, 0 = skip — e.g. ground).
515
- // .g = accumulated canvas alpha — the channel that used to live in hdr.a
516
- // before the switch to rg11b10ufloat. Sampled by composite to
517
- // un-premultiply color for tonemap and to set the final drawable alpha
518
- // (needed for the `premultiplied` canvas alphaMode that blends the
519
- // WebGPU surface over the page background).
520
- // .b = subsurface strength ÷ 4 — what a graph's `subsurface` node set, 0 for
521
- // everything else. Read by the scattering pass (passes/subsurface.ts).
522
- // FS output at location 1 must be vec4f — the blend state references src.a.
523
- // Materials write mask = vec4f(1.0, 1.0, _rzSubsurface, color.a); ground writes
524
- // vec4f(0.0, 1.0, 0.0, edgeFade). With src.a coming from the 4th component and
525
- // src-alpha blending enabled:
526
- // out.r = mask_r · src.a + dst.r · (1-src.a) (bloom mask, weighted by alpha)
527
- // out.g = 1.0 · src.a + dst.g · (1-src.a) (canonical premultiplied alpha-over)
528
-
529
- // The struct itself comes from scene-contract, which owns what the scene pass's
530
- // attachments ARE — this is one of the two shaders that gains an output when
531
- // one is added, and the graph generator emits against this same declaration.
532
- //
533
- // A FUNCTION, and no longer part of the prelude constant below, because the id
534
- // attachment is a device capability probed at init: a struct baked at import
535
- // time would be built before the answer exists. The graph appends it where the
536
- // constant used to end, so the assembled module is unchanged.
537
- export function commonFsOutWgsl(): string {
538
- return `\n\n${sceneFsOutWgsl()}\n`;
539
- }
540
-
541
- // ─── Dissolve ───────────────────────────────────────────────────────
542
- /**
543
- * Whether a fragment survives the dissolve, and how close it is to the front.
544
- *
545
- * ONE implementation, shared by the colour pass and the depth prepass, and that
546
- * is the whole reason it lives here rather than in either of them. The prepass
547
- * claims depth for fragments the colour pass will shade; if the two disagreed
548
- * about which flakes are gone, the model would keep writing depth where it no
549
- * longer draws — holes that occlude the floor behind her and read as sky.
550
- *
551
- * OBJECT SPACE, off the bind-pose position, for the same reason the procedural
552
- * texture nodes use restPos: a world-space field would let the flakes swim
553
- * through her as she moves, and a screen-space one would leave them hanging in
554
- * the air while she turns. In object space the pattern is painted ON the
555
- * surface — the flakes stay where they were on her arm as the arm moves.
556
- *
557
- * The hash is value noise rather than a bare hash so the flakes come apart in
558
- * clumps of a few millimetres rather than as single-pixel snow, which at any
559
- * distance is just a fade.
560
- */
561
- export const DISSOLVE_WGSL = /* wgsl */ `
562
- /** Clump size, in object-space units — MMD's are roughly centimetres.
563
- *
564
- * Raised from 0.42: at that size the pieces are near enough to speckle that a
565
- * departure reads as a fade rather than as a body coming apart, which is the
566
- * thing the clumping exists to avoid. Hand-sized pieces are visible ones. */
567
- const RZ_DISSOLVE_GRAIN: f32 = 1.2;
568
- /** How much the clumps pull a fragment off its own grit value — the whole of
569
- * the LOOK, and none of the rate. See rz_dissolve_threshold. */
570
- const RZ_DISSOLVE_CLUMP: f32 = 0.6;
571
- /** Grit cell, as a fraction of a clump. See rz_dissolve_threshold: this is what
572
- * keeps a material SMALLER than a clump from having one threshold for all of
573
- * it, and it has to be smaller than the SMALLEST material a model carries —
574
- * an eye highlight, a button, a buckle — not merely small. Two and a half
575
- * millimetres on a normal model, which is under all of them. */
576
- const RZ_DISSOLVE_GRIT: f32 = 0.021;
577
- /** How wide the glowing front is, in threshold units. Thin: the front is a
578
- * rim, and a wide one lights whole limbs at once. */
579
- const RZ_DISSOLVE_EDGE: f32 = 0.11;
580
- /** What the front burns with. Emission, added after lighting and after the
581
- * graph — a colour that ramps or takes a shadow reads as paint, not as heat.
582
- * Above 1 on purpose: it is meant to reach the bloom pyramid. Blue-violet,
583
- * the same light the motes leaving her are drawn and lit with. */
584
- const RZ_BURN_COLOR: vec3f = vec3f(0.45, 0.62, 2.40);
585
-
586
- fn rz_dissolve_hash(p: vec3f) -> f32 {
587
- // INTEGER, for exactly the reason _hash33 in nodes.ts is, and its comment
588
- // says it: above 24 bits an f32 loses the low ones. The float hash this
589
- // replaces multiplied three terms into the hundreds of millions and took
590
- // fract() of the product — which past 2^24 is not noise, it is a quantised
591
- // staircase, and wherever that staircase landed on zero the threshold was
592
- // zero. A surface whose threshold is zero never crosses it: it stays behind
593
- // while the rest of her leaves, and it sits inside the burning front the
594
- // whole time she is gone. Those were the white pieces that would not go.
595
- //
596
- // Floored first, unlike _hash33: vec3i() truncates toward zero, so -0.5 and
597
- // +0.5 are the same cell, and half this model is at negative x.
598
- var h = vec3u(vec3i(floor(p)) + vec3i(32768));
599
- h = h * vec3u(1664525u, 1013904223u, 2654435761u);
600
- h = (h.yzx ^ h) * vec3u(2246822519u, 3266489917u, 668265263u);
601
- h = h ^ (h >> vec3u(16u));
602
- return f32((h.x ^ h.y ^ h.z) & 16777215u) * (1.0 / 16777216.0);
603
- }
604
-
605
- /** Value noise over that hash — smooth within a flake, uncorrelated between. */
606
- fn rz_dissolve_field(p: vec3f) -> f32 {
607
- let i = floor(p);
608
- let f = fract(p);
609
- let u = f * f * (3.0 - 2.0 * f);
610
- let c000 = rz_dissolve_hash(i);
611
- let c100 = rz_dissolve_hash(i + vec3f(1.0, 0.0, 0.0));
612
- let c010 = rz_dissolve_hash(i + vec3f(0.0, 1.0, 0.0));
613
- let c110 = rz_dissolve_hash(i + vec3f(1.0, 1.0, 0.0));
614
- let c001 = rz_dissolve_hash(i + vec3f(0.0, 0.0, 1.0));
615
- let c101 = rz_dissolve_hash(i + vec3f(1.0, 0.0, 1.0));
616
- let c011 = rz_dissolve_hash(i + vec3f(0.0, 1.0, 1.0));
617
- let c111 = rz_dissolve_hash(i + vec3f(1.0, 1.0, 1.0));
618
- let x00 = mix(c000, c100, u.x);
619
- let x10 = mix(c010, c110, u.x);
620
- let x01 = mix(c001, c101, u.x);
621
- let x11 = mix(c011, c111, u.x);
622
- return mix(mix(x00, x10, u.y), mix(x01, x11, u.y), u.z);
623
- }
624
-
625
- /**
626
- * The threshold this fragment is measured against.
627
- *
628
- * NOISE ALONE, so the whole body comes apart at once — a hand, a shoulder and
629
- * an ankle all thinning together rather than a line travelling up her. It was
630
- * tilted by height at first, on the argument that a sweep reads as something
631
- * happening TO her; what it actually reads as is a wipe, and a wipe has a
632
- * direction, an edge and a speed the rest of the effect knows nothing about.
633
- * Everywhere at once is also the honest match for what leaves: the motes are
634
- * shed from every limb in the same breath.
635
- *
636
- * TWO SCALES. Clumps alone meant every fragment of a material SMALLER than one
637
- * cell shared a single threshold: an eye highlight, a brow, a button, a hair
638
- * clip. All of it sat inside the glowing front at once, so the piece flashed
639
- * white as a whole and then popped — the two things a disintegration must never
640
- * do. The grit is a per-cell hash at a fraction of the clump, so a part a few
641
- * millimetres across still comes apart in pieces.
642
- *
643
- * THE GRIT IS THE BASE, though, and the clumps only push a fragment off it.
644
- * That ordering is what makes the dissolve smooth, and it is not obvious: the
645
- * two used to be WEIGHTED AND ADDED, and a sum is not uniformly distributed
646
- * however uniform each half is. It piles up in the middle, so most of the
647
- * surface had a threshold near a half — all of it went as the dissolve swept
648
- * through the middle, and what remained was the thin tail near zero. That tail
649
- * was the second stage everyone could see: a body that mostly vanished, then a
650
- * scatter of glowing scraps, then nothing.
651
- *
652
- * WRAPPED, not added. Offsetting a uniform value and taking fract() leaves it
653
- * EXACTLY uniform, where scaling a sum back into range only flattens the middle
654
- * — measured over four hundred thousand samples, the sum removed 12% of her per
655
- * step at the halfway mark and 0.1% at each end (a 110x swing), the scaled sum
656
- * still swung 89x, and the wrap is flat: 5.0% per step from the first flake to
657
- * the last, a ratio of 1.0.
658
- *
659
- * That flatness IS the smoothness. An uneven rate is what produced the two
660
- * stages you could see — a body that mostly vanished at once, then a scatter of
661
- * scraps that took as long again to follow.
662
- *
663
- * The clumping survives the wrap: neighbouring fragments share a clump value,
664
- * so the offset moves them together. What wraps past 1 comes back at 0 and goes
665
- * at the other end instead, which costs a little speckle in a region and buys
666
- * an even rate everywhere.
667
- */
668
- fn rz_dissolve_threshold(restPos: vec3f) -> f32 {
669
- let grit = rz_dissolve_hash(floor(restPos / (RZ_DISSOLVE_GRAIN * RZ_DISSOLVE_GRIT)));
670
- let clump = rz_dissolve_field(restPos / RZ_DISSOLVE_GRAIN) - 0.5;
671
- return fract(grit + clump * RZ_DISSOLVE_CLUMP);
672
- }
673
- `
674
-
675
- // ─── Convenience: full shared prelude ───────────────────────────────
676
- // Material files compose this as `${NODES_WGSL}${COMMON_MATERIAL_PRELUDE_WGSL}` to
677
- // pull in everything structural. Each material then adds its own constants + fs().
678
-
679
- // The FSOut struct is NOT in here any more — see commonFsOutWgsl above. Every
680
- // consumer of this constant appends it immediately, which is where it was.
681
- export const COMMON_MATERIAL_PRELUDE_WGSL =
682
- COMMON_BINDINGS_WGSL + WORLD_AMBIENT_WGSL + lightsApi(0, 6, "objectLight.layers.x", { binding: 9, sampler: "diffuseSampler" }) + SAMPLE_SHADOW_WGSL + COMMON_VS_WGSL
1
+ import { sceneFsOutWgsl } from "../passes/scene-contract"
2
+ import { lightsApi } from "../lights"
3
+ import { SHADOW_CASCADES } from "../../shadow-cascades"
4
+ import { sunShadowWgsl } from "../scene-light-api"
5
+ import { WORLD_AMBIENT_WGSL } from "../lights"
6
+
7
+ // Shared WGSL blocks concatenated by every material shader.
8
+ // Splits the boilerplate (uniform structs, bind group layout, skinning VS, PCF shadow)
9
+ // away from the per-material fragment code so each material file only contains what
10
+ // makes it visually distinct.
11
+ //
12
+ // Concat order in every material:
13
+ // NODES_WGSL (nodes.ts — math/noise/BSDF helpers)
14
+ // COMMON_BINDINGS_WGSL (uniform structs + @group/@binding declarations)
15
+ // SAMPLE_SHADOW_WGSL (3×3 PCF shadow sampler; reads bindings above)
16
+ // COMMON_VS_WGSL (skinning vertex shader; reads bindings above)
17
+ // <material's own constants + @fragment fn fs>
18
+ //
19
+ // WGSL is a whole-module compile — declaration order at module scope doesn't matter,
20
+ // but the readable order is: types → bindings → helpers → entry points.
21
+
22
+ // ─── Uniform structs + bind group layout ────────────────────────────
23
+ // Every material pipeline uses the same bind group layout, so the same bindings are
24
+ // declared here once. Groups:
25
+ // group(0): per-frame scene (camera, lights, shadow map, BRDF LUT via nodes.ts)
26
+ // group(1): per-model skinning
27
+ // group(2): per-material (diffuse texture + material uniforms)
28
+
29
+ /** The jelly eyes' vertex move (jelly-eyes.ts). Every pass that places model
30
+ * vertices takes it, or a pass that skips it draws the iris where it was —
31
+ * the shadow map then shades half the moved iris with its own unmoved copy.
32
+ * Reads `objectLight.jelly` and `material.materialId`, which the including
33
+ * module declares. */
34
+ export const JELLY_VERTEX_WGSL = /* wgsl */ `
35
+ fn _rzJellyTurn(q: vec2f, a: f32) -> vec2f {
36
+ let c = cos(a);
37
+ let s = sin(a);
38
+ return vec2f(c * q.x - s * q.y, s * q.x + c * q.y);
39
+ }
40
+
41
+ /**
42
+ * Where the jelly puts an iris vertex. The iris is the part of the eye the eye
43
+ * bones carry, so it is moved as a whole, in bind space before skinning:
44
+ * scaled about its centre (the CPU composes the blink's spring, the lid's
45
+ * press and her motion's knock into one scale), turned and drifted a hair on
46
+ * the spring, brought forward a hair, and rolled about the eye bone with a
47
+ * closing expression — inside the white, which stays where it is. A highlight
48
+ * layer (this draw's material is one of jelly[1].w's) takes the iris's move,
49
+ * then its own scale, turn and tremble, before the roll. Vertices take it by their weight on the eye bones
50
+ * (jelly[2].w, jelly[3].w), so nothing else on the face moves.
51
+ */
52
+ fn rzJellyVertex(p: vec3f, joints: vec4<u32>, nw: vec4f) -> vec3f {
53
+ let j = objectLight.jelly;
54
+ let ids = u32(j[1].w);
55
+ let mid = u32(material.materialId);
56
+ let hl = mid > 0u && (mid == (ids & 4095u) || mid == (ids >> 12u));
57
+ var out = p;
58
+ for (var e = 0u; e < 2u; e++) {
59
+ let bone = j[2u + e].w;
60
+ if (bone < 0.0) { continue; }
61
+ let b = u32(bone);
62
+ let w = dot(nw, select(vec4f(0.0), vec4f(1.0), joints == vec4<u32>(b)));
63
+ if (w <= 0.0) { continue; }
64
+ let c = j[e].xyz;
65
+ // A rig that carries both eyes on one bone: each vertex follows its own side.
66
+ if (j[2].w == j[3].w && e == 0u && distance(p.xy, j[1].xy) < distance(p.xy, j[0].xy)) { continue; }
67
+ if (j[2].w == j[3].w && e == 1u && distance(p.xy, j[0].xy) <= distance(p.xy, j[1].xy)) { continue; }
68
+ let t = j[4u + e];
69
+ let m = j[6u + e];
70
+ let h = j[10u + e];
71
+ var q = _rzJellyTurn((p.xy - c.xy) * t.xy, t.z) + m.xy;
72
+ // Forward is −Z (MMD faces −Z).
73
+ var push = h.z;
74
+ if (hl) {
75
+ // Sliding over the iris's dome on its own, a highlight sheet a hair in
76
+ // front of it would sink into it where the dome bulges more and the two
77
+ // fight for depth; so it comes forward by as far as it slid — a slope of
78
+ // one, steeper than the dome anywhere it draws.
79
+ let before = q;
80
+ q = _rzJellyTurn(q * h.xy, t.w) + m.zw;
81
+ push += length(q - before);
82
+ }
83
+ var moved = vec3f(c.xy + q, p.z - push);
84
+ let roll = j[8u + e];
85
+ if (roll.w != 0.0) {
86
+ let d = moved - roll.xyz;
87
+ let rd = _rzJellyTurn(d.yz, roll.w);
88
+ moved = roll.xyz + vec3f(d.x, rd.x, rd.y);
89
+ }
90
+ out = mix(p, moved, w);
91
+ }
92
+ return out;
93
+ }
94
+ `
95
+
96
+ /** A model's ObjectLight as WGSL declares it (see the layout below). One copy
97
+ * for every pass that binds it, so their layouts cannot drift. */
98
+ export const OBJECT_LIGHT_STRUCT_WGSL =
99
+ "struct ObjectLight { layers: vec4u, ambient: vec4f, sh: array<vec4f, 9>, fill: vec4f, jelly: array<vec4f, 12>, bloom: vec4f, xray: array<vec4f, 4>, xrayMask: array<vec4u, 16>, matLayers: array<vec4u, 128> }"
100
+
101
+ /**
102
+ * The see-through window (#xray): a rectangle on the frame, in pixels —
103
+ * xray[0] is (left, top, right, bottom), xray[3].x is 1 while a window is open
104
+ * on this model — and which of the model's materials it cuts: a bit a
105
+ * material, by its 1-based draw index (materialId), up to 512. Tested against
106
+ * the fragment's own position, so it sits where the lens is, whatever moves
107
+ * behind it. Declared after the pass's own `objectLight` binding.
108
+ */
109
+ export const XRAY_WGSL = /* wgsl */ `
110
+ fn rz_xray_inside(fp: vec4f) -> bool {
111
+ if (objectLight.xray[3].x < 0.5) { return false; }
112
+ let r = objectLight.xray[0];
113
+ return fp.x >= r.x && fp.y >= r.y && fp.x <= r.z && fp.y <= r.w;
114
+ }
115
+ fn rz_xray_cut(fp: vec4f, materialId: f32) -> bool {
116
+ let i = u32(materialId);
117
+ if (i >= 512u) { return false; }
118
+ let word = objectLight.xrayMask[i / 128u][(i / 32u) % 4u];
119
+ if (((word >> (i % 32u)) & 1u) == 0u) { return false; }
120
+ return rz_xray_inside(fp);
121
+ }
122
+ `
123
+
124
+ /**
125
+ * The rendering layers this draw is on: its material's own where the model
126
+ * gives it some (objectLight.matLayers, by the 1-based materialId, up to 511),
127
+ * else the model's. A game lights its renderers one by one — URP hands each
128
+ * object its own few lamps — and a converted stage is one model of many such
129
+ * renderers, so the bits a light is tested against have to be able to differ
130
+ * from material to material. Zero, which every model leaves there, is "the
131
+ * model's". Declared after the pass's own `objectLight` and `material` bindings.
132
+ */
133
+ export const DRAW_LAYERS_WGSL = /* wgsl */ `
134
+ fn rzDrawLayers() -> u32 {
135
+ let i = u32(material.materialId);
136
+ if (i >= 512u) { return objectLight.layers.x; }
137
+ let own = objectLight.matLayers[i / 4u][i % 4u];
138
+ return select(objectLight.layers.x, own, own != 0u);
139
+ }
140
+ `
141
+
142
+ export const COMMON_BINDINGS_WGSL = /* wgsl */ `
143
+
144
+ struct CameraUniforms {
145
+ view: mat4x4f,
146
+ projection: mat4x4f,
147
+ viewPos: vec3f,
148
+ /** Render-target height in device pixels. */
149
+ viewportHeight: f32,
150
+ /** The scene clock in seconds — what the time node reads. Paused with the
151
+ * transport and stepped exactly by an export, so an animated material lands
152
+ * in the file where it stood on screen. (No backticks in here: this WGSL
153
+ * lives in a template literal and one would end it.) */
154
+ time: f32,
155
+ // NOTHING AFTER THIS. A trailing vec3f aligns to 16 and pushes the struct to
156
+ // 176 bytes against a 160-byte buffer, which fails validation on every
157
+ // pipeline at once; ending on the f32 rounds the struct to exactly 160.
158
+ };
159
+
160
+ struct Light {
161
+ direction: vec4f,
162
+ color: vec4f,
163
+ };
164
+
165
+ struct LightUniforms {
166
+ ambientColor: vec4f,
167
+ lights: array<Light, 4>,
168
+ /** Irradiance SH of the HDRI world; [0].w is the on-flag. */
169
+ sh: array<vec4f, 9>,
170
+ /** The scene fog (Engine.setSceneFog): haze (colour, amount), (distance,
171
+ * height), then the second layer the same. Amount 0 is none. */
172
+ fog: array<vec4f, 4>,
173
+ /** The cast's shadow on a stage (Engine.setStageCastShadow): colour, amount;
174
+ * amount 0 is off. Then the view-projection its map was drawn with. */
175
+ castShadow: vec4f,
176
+ castVP: mat4x4f,
177
+ /** The rendering layers each directional light reaches, slot by slot — a
178
+ * draw is lit by the first whose bits it shares (rzMainLight). */
179
+ dirLayers: vec4u,
180
+ };
181
+
182
+ // Per-material uniforms. Every material binds this layout even if it ignores fields;
183
+ // the engine keeps one bind group layout across all material pipelines. The PMX
184
+ // classic-material fields (ambient/specular/shininess) are carried for graph nodes that
185
+ // want them; most graphs read only diffuseColor + alpha.
186
+ struct MaterialUniforms {
187
+ diffuseColor: vec3f, // PMX diffuse rgb — the material_diffuse node reads this
188
+ alpha: f32, // 0 → discard; <1 → transparent draw call
189
+ ambient: vec3f, // PMX ambient rgb
190
+ shininess: f32, // PMX specular power
191
+ specular: vec3f, // PMX specular rgb
192
+ sphereMode: f32, // 0 none · 1 multiply (sph) · 2 add (spa)
193
+ // Skeleton index of the 頭 (head) bone, or -1. Lets the eye shader gate
194
+ // the post-alpha-eye stencil by camera-vs-face hemisphere.
195
+ headBoneIndex: f32,
196
+ // The draw's identity, for the id attachment: which material, which object.
197
+ // They ride HERE, in padding this struct already carried, so the buffer's
198
+ // size and layout are untouched and the indirect-draw path keeps working —
199
+ // the ids arrive with the same per-draw uniform the material already binds,
200
+ // rather than needing a channel of their own. Zero while ids are off, and
201
+ // zero is the reserved "nothing" value, so reading them then is not wrong,
202
+ // just empty. f32 because the buffer is written as floats; the shader casts.
203
+ materialId: f32,
204
+ objectId: f32,
205
+ // How much of this material is still THERE: 1 whole, 0 gone. Rides the last
206
+ // of the padding this struct already carried, for the same reason the ids do
207
+ // — the buffer's size and layout are untouched, so the indirect-draw path and
208
+ // every existing pipeline keep working, and a material that never dissolves
209
+ // pays one float it was already paying.
210
+ //
211
+ // A material morph rebuilds this block from its base copy, which is why the
212
+ // engine writes the value into that copy as well as into the live buffer: a
213
+ // face morphing while she dissolves must not come back solid for those frames.
214
+ dissolve: f32,
215
+ };
216
+
217
+ struct VertexOutput {
218
+ // @invariant: the opaque depth prepass rasterises this same skinned position
219
+ // through a DIFFERENT shader module, and the colour pass then depth-tests
220
+ // less-equal against what it wrote. Without invariance a backend is free to
221
+ // optimise the two position computations differently, and a one-ulp
222
+ // disagreement is a pixel of missing character. Invariance pins both to the
223
+ // same result; it costs only that freedom.
224
+ @builtin(position) @invariant position: vec4f,
225
+ @location(0) normal: vec3f,
226
+ @location(1) uv: vec2f,
227
+ @location(2) worldPos: vec3f,
228
+ // Bind-pose object-space position (the raw pre-skin vertex attribute). Procedural
229
+ // textures (noise bump, sparkle, Generated-coord gradients) key off this instead of
230
+ // worldPos so the pattern rides with the surface — otherwise the mesh swims through a
231
+ // world-static noise field under any skinning deformation or root (センター) motion.
232
+ // At rest skinMats are identity so restPos == worldPos, which is why existing noise-
233
+ // scale constants stay valid without retuning.
234
+ @location(3) restPos: vec3f,
235
+ /** The scene fog's two amounts, computed PER VERTEX as the game does — see
236
+ * Engine.setSceneFog — and interpolated across the face. */
237
+ @location(5) fog: vec2f,
238
+ /** The vertex colour, RGBA — white on a mesh that carries none. A PMX keeps
239
+ * it in its first additional UV (what a converted game stage writes there:
240
+ * a plant's occlusion rides in its alpha). The attribute node reads it. */
241
+ @location(6) vcolor: vec4f,
242
+ /** The second UV set — a PMX's second additional UV (xy), else the first
243
+ * UV again. The uv_map node's uv2. */
244
+ @location(7) uv2: vec2f,
245
+ };
246
+
247
+ /** One fog layer's amount at a vertex of view depth d and world height y. */
248
+ fn _rzFogAmount(d: f32, y: f32, col: vec4f, p: vec4f) -> f32 {
249
+ if (col.w <= 0.0) { return 0.0; }
250
+ let f = clamp(d * p.x + p.y, 0.0, 1.0);
251
+ let h = clamp((p.z - y) / p.w, -1.0, 1.0);
252
+ return (1.0 - clamp(f - (1.0 - f) * h, 0.0, 1.0)) * col.w;
253
+ }
254
+
255
+ // One view-projection per shadow cascade, inner to outer — the volumes built
256
+ // by shadow-cascades.ts, in the same order.
257
+ struct LightVP { viewProj: array<mat4x4f, ${SHADOW_CASCADES.length}>, };
258
+
259
+ @group(0) @binding(0) var<uniform> camera: CameraUniforms;
260
+ @group(0) @binding(1) var<uniform> light: LightUniforms;
261
+ @group(0) @binding(2) var diffuseSampler: sampler;
262
+ // The sun's shadow atlas: every cascade in its own tile — see shadow-cascades.ts.
263
+ @group(0) @binding(3) var shadowAtlas: texture_depth_2d;
264
+ @group(0) @binding(4) var shadowSampler: sampler_comparison;
265
+ @group(0) @binding(5) var<uniform> lightVP: LightVP;
266
+ // The world's own sky, for a surface that REFLECTS it rather than merely being
267
+ // lit by it. Equirect, in the same layout and the same linear radiance the
268
+ // composite draws the dome from, and mipped — a rough surface reads a coarser
269
+ // level, which is what a prefiltered environment is for. A scene with no HDRI
270
+ // has the 1x1 fallback bound here; rzWorldSpecular checks the SH flag and
271
+ // answers with the flat ambient instead, so nothing samples the placeholder.
272
+ @group(0) @binding(8) var worldEnvTexture: texture_2d<f32>;
273
+ // The cast's own shadow map for a stage's floor — see _rzCastShadow.
274
+ @group(0) @binding(10) var castShadowMap: texture_depth_2d;
275
+
276
+ /** The stage's reflection probe (Engine.captureReflectionProbe): where it was
277
+ * captured (xyz) and its strength (w); the box it projects onto, min with the
278
+ * on-flag in w, then max with the local flag in w (1: outside the box the
279
+ * sky stands in). Off (boxMin.w 0) the sky stands in everywhere. */
280
+ struct ProbeUniforms {
281
+ center: vec4f,
282
+ boxMin: vec4f,
283
+ boxMax: vec4f,
284
+ };
285
+ // A cube, GGX-prefiltered down its mips — see rzProbeSpecular in nodes.ts.
286
+ @group(0) @binding(11) var probeCube: texture_cube<f32>;
287
+ @group(0) @binding(12) var<uniform> probe: ProbeUniforms;
288
+
289
+ /**
290
+ * How much of the cast stands between this point and the stage's shadow
291
+ * direction, 0–1 — setStageCastShadow. A 5×5 comparison filter at 1.5 texels:
292
+ * the game blurs its character shadow before laying it, and a single tap reads
293
+ * as a stencil.
294
+ */
295
+ fn _rzCastShadow(wp: vec3f) -> f32 {
296
+ if (light.castShadow.w <= 0.0) { return 0.0; }
297
+ let c = light.castVP * vec4f(wp, 1.0);
298
+ let ndc = c.xyz / c.w;
299
+ if (abs(ndc.x) >= 1.0 || abs(ndc.y) >= 1.0 || ndc.z <= 0.0 || ndc.z >= 1.0) { return 0.0; }
300
+ let uv = vec2f(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5);
301
+ let ts = 1.5 / f32(textureDimensions(castShadowMap).x);
302
+ var lit = 0.0;
303
+ for (var y = -2; y <= 2; y++) {
304
+ for (var x = -2; x <= 2; x++) {
305
+ lit += textureSampleCompareLevel(castShadowMap, shadowSampler, uv + vec2f(f32(x), f32(y)) * ts, ndc.z - 0.001);
306
+ }
307
+ }
308
+ return 1.0 - lit / 25.0;
309
+ }
310
+ @group(1) @binding(0) var<storage, read> skinMats: array<mat4x4f>;
311
+ // What this object's lighting is, apart from the scene's, as the game's
312
+ // pipeline gives each renderer its own:
313
+ // layers.x its rendering-layer bits, which decide the lights that reach it —
314
+ // a stage's daylight and the cast's key are two lights on two
315
+ // layers, as the game lights them;
316
+ // ambient.x 1 while it has an ambient of its own (Engine.setModelAmbient),
317
+ // 0 for the world's;
318
+ // sh that ambient's irradiance, folded as the world's (ibl.ts);
319
+ // fill.rgb its fill (Engine.setModelFill), added after its graph times its
320
+ // surface colour — zero for a model that has none.
321
+ // jelly its jelly eyes (Engine.setModelJellyEyes, jelly-eyes.ts), not
322
+ // lighting but per-model all the same, so it rides here:
323
+ // [0] left iris centre (bind space), strength — 0 is off
324
+ // [1] right iris centre, the highlight layers' materialIds
325
+ // (a + b·4096, 0 none)
326
+ // [2] left iris half extents, closure, eye bone (−1 none)
327
+ // [3] the right's
328
+ // [4] left scale x, y, twist, highlight turn (radians)
329
+ // [5] the right's
330
+ // [6] left drift x, y, highlight's own offset x, y (bind units)
331
+ // [7] the right's
332
+ // [8] left eye bone's head (the roll's pivot), roll (radians)
333
+ // [9] the right's
334
+ // [10] left highlight scale x, y, forward push (bind units), 0
335
+ // [11] the right's
336
+ // bloom.x 1 while it feeds the bloom, 0 when it is left out
337
+ // (Engine.setModelBloom): the bloom mask its surfaces and
338
+ // outlines write.
339
+ ${OBJECT_LIGHT_STRUCT_WGSL}
340
+ @group(1) @binding(1) var<uniform> objectLight: ObjectLight;
341
+ ${XRAY_WGSL}
342
+
343
+ ${JELLY_VERTEX_WGSL}
344
+ /** The light arriving at a surface of this object facing n: its own ambient
345
+ * where loaded data gave it one (a stage's probes, a character's), else the
346
+ * world's. The same polynomial rzWorldAmbient evaluates. */
347
+ fn rzObjectAmbient(n: vec3f) -> vec3f {
348
+ if (objectLight.ambient.x < 0.5) { return rzWorldAmbient(n); }
349
+ let s = objectLight.sh;
350
+ let c = s[0].xyz + s[1].xyz * n.y + s[2].xyz * n.z + s[3].xyz * n.x
351
+ + s[4].xyz * (n.x * n.y) + s[5].xyz * (n.y * n.z) + s[6].xyz * (3.0 * n.z * n.z - 1.0)
352
+ + s[7].xyz * (n.x * n.z) + s[8].xyz * (n.x * n.x - n.y * n.y);
353
+ return max(c, vec3f(0.0));
354
+ }
355
+
356
+ /** The directional light slot that lights this draw: a light kept to layers
357
+ * of its own that this draw is on (the cast's key, beside a stage's sun),
358
+ * else the first whose layers it shares, else the sun's. A light that
359
+ * reaches every layer stands in for nobody. */
360
+ fn rzMainLight() -> u32 {
361
+ let mine = rzDrawLayers();
362
+ for (var k = 1u; k < 4u; k++) {
363
+ if (light.dirLayers[k] != 0xffffffffu && (light.dirLayers[k] & mine) != 0u) { return k; }
364
+ }
365
+ for (var k = 0u; k < 4u; k++) {
366
+ if ((light.dirLayers[k] & mine) != 0u) { return k; }
367
+ }
368
+ return 0u;
369
+ }
370
+ @group(2) @binding(0) var diffuseTexture: texture_2d<f32>;
371
+ @group(2) @binding(1) var<uniform> material: MaterialUniforms;
372
+ // Reserved for future sphere/toon graph nodes; graphs that don't read them get the
373
+ // 1×1 white fallback bound here.
374
+ @group(2) @binding(2) var toonTexture: texture_2d<f32>;
375
+ @group(2) @binding(3) var sphereTexture: texture_2d<f32>;
376
+ // Extra maps supplied by the STYLE GROUP rather than by the PMX — the lightmap /
377
+ // ILM / ramp textures a Blender-authored look is built on. A PMX material carries
378
+ // exactly one image, and this whole family of shading encodes shadow thresholds,
379
+ // specular masks and material IDs in the channels of a second and third. Unset
380
+ // slots get the 1×1 white fallback, so a graph reading one that was never
381
+ // supplied sees white rather than garbage.
382
+ @group(2) @binding(5) var groupTexture0: texture_2d<f32>;
383
+ @group(2) @binding(6) var groupTexture1: texture_2d<f32>;
384
+ @group(2) @binding(7) var groupTexture2: texture_2d<f32>;
385
+ @group(2) @binding(8) var groupTexture3: texture_2d<f32>;
386
+
387
+ // Four-bone blended normals can cancel to ~zero on physics-driven parts
388
+ // (opposing bone rotations at 50/50 weights) — normalize(0) is 0/0 = NaN,
389
+ // which poisons the whole shading stack and flashes through bloom. Fall
390
+ // back to up for degenerate normals instead.
391
+ // A fragment's colour as it may leave the material: every channel finite. A NaN
392
+ // or Inf from any graph on any GPU is one pixel here, written as nothing; let
393
+ // through, it blooms into a block and the skin blur smears it into bars. Read
394
+ // off the exponent bits, which fast math cannot fold away.
395
+ fn rz_finite(c: vec4f) -> vec4f {
396
+ let e = bitcast<vec4u>(c) & vec4u(0x7f800000u);
397
+ return select(vec4f(0.0), c, e != vec4u(0x7f800000u));
398
+ }
399
+
400
+ fn safe_normal(nIn: vec3f) -> vec3f {
401
+ let l2 = dot(nIn, nIn);
402
+ if (l2 < 1e-12) { return vec3f(0.0, 1.0, 0.0); }
403
+ return nIn * inverseSqrt(l2);
404
+ }
405
+
406
+ `;
407
+
408
+ // ─── Shadow sampler (3×3 PCF, cascade-selected) ─────────────────────
409
+ // Normal-bias 0.08, depth-bias 0.001 NDC; the lookup is sunShadowWgsl in
410
+ // scene-light-api.ts, shared with the ground and effects.
411
+ //
412
+ // Selection: the first cascade whose box covers the point — with a margin that
413
+ // keeps the whole PCF kernel inside its tile — else LIT. Lit is a fix, not
414
+ // merely a default: past every cascade there is no occlusion information, and
415
+ // comparing against unrelated depths would silently shadow any stage deeper
416
+ // than the boxes.
417
+
418
+ const SAMPLE_SHADOW_WGSL = /* wgsl */ `
419
+ ${sunShadowWgsl("_rzSun", "shadowAtlas", "shadowSampler", "lightVP.viewProj")}
420
+
421
+ /** The sun's cast shadow alone, without sampleShadow's facing test: what a
422
+ * character's ramp is min'd with (its own N·L carries the terminator). */
423
+ fn rzSunOcclusion(worldPos: vec3f, n: vec3f) -> f32 {
424
+ let castAmt = light.lights[0].direction.w;
425
+ if (castAmt <= 0.0) { return 1.0; }
426
+ let a = _rzSunLocate(worldPos + n * 0.08);
427
+ if (a.w < 0.0) { return 1.0; }
428
+ return mix(1.0, _rzSunTaps(a), castAmt);
429
+ }
430
+
431
+ fn sampleShadow(worldPos: vec3f, n: vec3f) -> f32 {
432
+ // THE SCENE'S ONE SHADOW SWITCH, and it lives on the sun because the sun is
433
+ // the only thing that casts. Lit is the answer when it is off: returning 0
434
+ // would be "fully shadowed", the opposite of what a disabled shadow means.
435
+ let castAmt = light.lights[0].direction.w;
436
+ if (castAmt <= 0.0) { return 1.0; }
437
+ // A surface turned from the sun is in its own shade — when the sun is what
438
+ // keys it. Under a key of its own layer the atlas is only the occluders'
439
+ // shadow, and the key's N·L decides its terminator.
440
+ if (rzMainLight() == 0u && dot(n, -light.lights[0].direction.xyz) <= 0.0) { return 0.0; }
441
+ let a = _rzSunLocate(worldPos + n * 0.08);
442
+ if (a.w < 0.0) { return 1.0; }
443
+ return mix(1.0, _rzSunTaps(a), castAmt);
444
+ }
445
+
446
+ /**
447
+ * The cast's shadow on a stage surface where the stage ROOFS the cast from the
448
+ * sun, 0–1 — setStageCastShadow on a graph-drawn stage (a GLB's). Under open
449
+ * sky the sun's own map already lays the cast's shadow, and laying this one too
450
+ * doubled it; under a ceiling the sun reaches neither the floor nor her, the
451
+ * lamps cast nothing, and she stood on the floor with no shadow at all. So
452
+ * per pixel: find the point of the cast that throws this shadow (the cast
453
+ * map's nearest depth, walked back toward the light along the map's z row),
454
+ * step off her toward the light, and ask the sun's map whether it reaches
455
+ * there. Lit: the sun shadow has it, answer 0. Shadowed: this is the only
456
+ * shadow she gets. Zero on everything that is not a stage (objectLight
457
+ * layers.y).
458
+ */
459
+ fn rzRoofedCastShadow(wp: vec3f) -> f32 {
460
+ if (light.castShadow.w <= 0.0 || objectLight.layers.y == 0u) { return 0.0; }
461
+ let cover = _rzCastShadow(wp);
462
+ if (cover <= 0.0) { return 0.0; }
463
+ let ndc = (light.castVP * vec4f(wp, 1.0)).xyz;
464
+ let size = vec2i(textureDimensions(castShadowMap));
465
+ let px = vec2i(vec2f(ndc.x * 0.5 + 0.5, 0.5 - ndc.y * 0.5) * vec2f(size));
466
+ // The nearest of her over the filter's footprint: a penumbra texel's own
467
+ // depth may be the cleared 1.
468
+ var occ = 1.0;
469
+ for (var y = -2; y <= 2; y += 2) {
470
+ for (var x = -2; x <= 2; x += 2) {
471
+ occ = min(occ, textureLoad(castShadowMap, clamp(px + vec2i(x, y), vec2i(0), size - 1), 0));
472
+ }
473
+ }
474
+ if (occ >= ndc.z) { return 0.0; }
475
+ // Orthographic: depth grows away from the light at |g| per unit.
476
+ let g = vec3f(light.castVP[0].z, light.castVP[1].z, light.castVP[2].z);
477
+ let k = length(g);
478
+ let q = wp - (g / k) * ((ndc.z - occ) / k + 0.5);
479
+ return cover * (1.0 - rzSunOcclusion(q, vec3f(0.0)));
480
+ }
481
+
482
+ `;
483
+
484
+ // ─── Skinning vertex shader ─────────────────────────────────────────
485
+ // Four-bone linear blend skinning. Renormalizes weights when they don't sum to 1
486
+ // (PMX models occasionally ship with unnormalized weights on extras like hair tips).
487
+ // VS normalize on the outgoing normal is skipped — interpolation denormalizes it
488
+ // anyway and every fragment shader does `normalize(input.normal)` as its first line.
489
+
490
+ const COMMON_VS_WGSL = /* wgsl */ `
491
+
492
+ @vertex fn vs(
493
+ @location(0) position: vec3f,
494
+ @location(1) normal: vec3f,
495
+ @location(2) uv: vec2f,
496
+ @location(3) joints0: vec4<u32>,
497
+ @location(4) weights0: vec4<f32>,
498
+ // The extra stream (Engine: the model's attribute buffer, slot 4).
499
+ @location(5) vcolor: vec4<f32>,
500
+ @location(6) uv2: vec2<f32>
501
+ ) -> VertexOutput {
502
+ var output: VertexOutput;
503
+ output.vcolor = vcolor;
504
+ output.uv2 = uv2;
505
+ let weightSum = weights0.x + weights0.y + weights0.z + weights0.w;
506
+ let invWeightSum = select(1.0, 1.0 / weightSum, weightSum > 0.0001);
507
+ let nw = select(vec4f(1.0, 0.0, 0.0, 0.0), weights0 * invWeightSum, weightSum > 0.0001);
508
+ var pos4 = vec4f(position, 1.0);
509
+ if (objectLight.jelly[0].w > 0.0) { pos4 = vec4f(rzJellyVertex(position, joints0, nw), 1.0); }
510
+ var skinnedPos = vec4f(0.0);
511
+ var skinnedNrm = vec3f(0.0);
512
+ for (var i = 0u; i < 4u; i++) {
513
+ let m = skinMats[joints0[i]];
514
+ let w = nw[i];
515
+ skinnedPos += (m * pos4) * w;
516
+ skinnedNrm += (mat3x3f(m[0].xyz, m[1].xyz, m[2].xyz) * normal) * w;
517
+ }
518
+ output.position = camera.projection * camera.view * vec4f(skinnedPos.xyz, 1.0);
519
+ output.normal = skinnedNrm;
520
+ output.uv = uv;
521
+ output.worldPos = skinnedPos.xyz;
522
+ output.restPos = position;
523
+ let viewZ = (camera.view * vec4f(skinnedPos.xyz, 1.0)).z;
524
+ output.fog = vec2f(
525
+ _rzFogAmount(viewZ, skinnedPos.y, light.fog[0], light.fog[1]),
526
+ _rzFogAmount(viewZ, skinnedPos.y, light.fog[2], light.fog[3]),
527
+ );
528
+ return output;
529
+ }
530
+
531
+ `;
532
+
533
+ // ─── FS output struct ───────────────────────────────────────────────
534
+ // Location 0: final radiance+alpha (blended into rg11b10ufloat; the HDR target
535
+ // has no alpha channel, but the blend equation still uses the .a you write here
536
+ // as the src-alpha factor that premultiplies rgb into the HDR target).
537
+ // Location 1: auxiliary rgba8unorm carrying
538
+ // .r = bloom mask (1 = contributes to bloom, 0 = skip — e.g. ground).
539
+ // .g = accumulated canvas alpha — the channel that used to live in hdr.a
540
+ // before the switch to rg11b10ufloat. Sampled by composite to
541
+ // un-premultiply color for tonemap and to set the final drawable alpha
542
+ // (needed for the `premultiplied` canvas alphaMode that blends the
543
+ // WebGPU surface over the page background).
544
+ // .b = subsurface strength ÷ 4 — what a graph's `subsurface` node set, 0 for
545
+ // everything else. Read by the scattering pass (passes/subsurface.ts).
546
+ // FS output at location 1 must be vec4f — the blend state references src.a.
547
+ // Materials write mask = vec4f(1.0, 1.0, _rzSubsurface, color.a); ground writes
548
+ // vec4f(0.0, 1.0, 0.0, edgeFade). With src.a coming from the 4th component and
549
+ // src-alpha blending enabled:
550
+ // out.r = mask_r · src.a + dst.r · (1-src.a) (bloom mask, weighted by alpha)
551
+ // out.g = 1.0 · src.a + dst.g · (1-src.a) (canonical premultiplied alpha-over)
552
+
553
+ // The struct itself comes from scene-contract, which owns what the scene pass's
554
+ // attachments ARE — this is one of the two shaders that gains an output when
555
+ // one is added, and the graph generator emits against this same declaration.
556
+ //
557
+ // A FUNCTION, and no longer part of the prelude constant below, because the id
558
+ // attachment is a device capability probed at init: a struct baked at import
559
+ // time would be built before the answer exists. The graph appends it where the
560
+ // constant used to end, so the assembled module is unchanged.
561
+ export function commonFsOutWgsl(): string {
562
+ return `\n\n${sceneFsOutWgsl()}\n`;
563
+ }
564
+
565
+ // ─── Dissolve ───────────────────────────────────────────────────────
566
+ /**
567
+ * Whether a fragment survives the dissolve, and how close it is to the front.
568
+ *
569
+ * ONE implementation, shared by the colour pass and the depth prepass, and that
570
+ * is the whole reason it lives here rather than in either of them. The prepass
571
+ * claims depth for fragments the colour pass will shade; if the two disagreed
572
+ * about which flakes are gone, the model would keep writing depth where it no
573
+ * longer draws — holes that occlude the floor behind her and read as sky.
574
+ *
575
+ * OBJECT SPACE, off the bind-pose position, for the same reason the procedural
576
+ * texture nodes use restPos: a world-space field would let the flakes swim
577
+ * through her as she moves, and a screen-space one would leave them hanging in
578
+ * the air while she turns. In object space the pattern is painted ON the
579
+ * surface — the flakes stay where they were on her arm as the arm moves.
580
+ *
581
+ * The hash is value noise rather than a bare hash so the flakes come apart in
582
+ * clumps of a few millimetres rather than as single-pixel snow, which at any
583
+ * distance is just a fade.
584
+ */
585
+ export const DISSOLVE_WGSL = /* wgsl */ `
586
+ /** Clump size, in object-space units — MMD's are roughly centimetres.
587
+ *
588
+ * Raised from 0.42: at that size the pieces are near enough to speckle that a
589
+ * departure reads as a fade rather than as a body coming apart, which is the
590
+ * thing the clumping exists to avoid. Hand-sized pieces are visible ones. */
591
+ const RZ_DISSOLVE_GRAIN: f32 = 1.2;
592
+ /** How much the clumps pull a fragment off its own grit value — the whole of
593
+ * the LOOK, and none of the rate. See rz_dissolve_threshold. */
594
+ const RZ_DISSOLVE_CLUMP: f32 = 0.6;
595
+ /** Grit cell, as a fraction of a clump. See rz_dissolve_threshold: this is what
596
+ * keeps a material SMALLER than a clump from having one threshold for all of
597
+ * it, and it has to be smaller than the SMALLEST material a model carries —
598
+ * an eye highlight, a button, a buckle — not merely small. Two and a half
599
+ * millimetres on a normal model, which is under all of them. */
600
+ const RZ_DISSOLVE_GRIT: f32 = 0.021;
601
+ /** How wide the glowing front is, in threshold units. Thin: the front is a
602
+ * rim, and a wide one lights whole limbs at once. */
603
+ const RZ_DISSOLVE_EDGE: f32 = 0.11;
604
+ /** What the front burns with. Emission, added after lighting and after the
605
+ * graph — a colour that ramps or takes a shadow reads as paint, not as heat.
606
+ * Above 1 on purpose: it is meant to reach the bloom pyramid. Blue-violet,
607
+ * the same light the motes leaving her are drawn and lit with. */
608
+ const RZ_BURN_COLOR: vec3f = vec3f(0.45, 0.62, 2.40);
609
+
610
+ fn rz_dissolve_hash(p: vec3f) -> f32 {
611
+ // INTEGER, for exactly the reason _hash33 in nodes.ts is, and its comment
612
+ // says it: above 24 bits an f32 loses the low ones. The float hash this
613
+ // replaces multiplied three terms into the hundreds of millions and took
614
+ // fract() of the product — which past 2^24 is not noise, it is a quantised
615
+ // staircase, and wherever that staircase landed on zero the threshold was
616
+ // zero. A surface whose threshold is zero never crosses it: it stays behind
617
+ // while the rest of her leaves, and it sits inside the burning front the
618
+ // whole time she is gone. Those were the white pieces that would not go.
619
+ //
620
+ // Floored first, unlike _hash33: vec3i() truncates toward zero, so -0.5 and
621
+ // +0.5 are the same cell, and half this model is at negative x.
622
+ var h = vec3u(vec3i(floor(p)) + vec3i(32768));
623
+ h = h * vec3u(1664525u, 1013904223u, 2654435761u);
624
+ h = (h.yzx ^ h) * vec3u(2246822519u, 3266489917u, 668265263u);
625
+ h = h ^ (h >> vec3u(16u));
626
+ return f32((h.x ^ h.y ^ h.z) & 16777215u) * (1.0 / 16777216.0);
627
+ }
628
+
629
+ /** Value noise over that hash — smooth within a flake, uncorrelated between. */
630
+ fn rz_dissolve_field(p: vec3f) -> f32 {
631
+ let i = floor(p);
632
+ let f = fract(p);
633
+ let u = f * f * (3.0 - 2.0 * f);
634
+ let c000 = rz_dissolve_hash(i);
635
+ let c100 = rz_dissolve_hash(i + vec3f(1.0, 0.0, 0.0));
636
+ let c010 = rz_dissolve_hash(i + vec3f(0.0, 1.0, 0.0));
637
+ let c110 = rz_dissolve_hash(i + vec3f(1.0, 1.0, 0.0));
638
+ let c001 = rz_dissolve_hash(i + vec3f(0.0, 0.0, 1.0));
639
+ let c101 = rz_dissolve_hash(i + vec3f(1.0, 0.0, 1.0));
640
+ let c011 = rz_dissolve_hash(i + vec3f(0.0, 1.0, 1.0));
641
+ let c111 = rz_dissolve_hash(i + vec3f(1.0, 1.0, 1.0));
642
+ let x00 = mix(c000, c100, u.x);
643
+ let x10 = mix(c010, c110, u.x);
644
+ let x01 = mix(c001, c101, u.x);
645
+ let x11 = mix(c011, c111, u.x);
646
+ return mix(mix(x00, x10, u.y), mix(x01, x11, u.y), u.z);
647
+ }
648
+
649
+ /**
650
+ * The threshold this fragment is measured against.
651
+ *
652
+ * NOISE ALONE, so the whole body comes apart at once — a hand, a shoulder and
653
+ * an ankle all thinning together rather than a line travelling up her. It was
654
+ * tilted by height at first, on the argument that a sweep reads as something
655
+ * happening TO her; what it actually reads as is a wipe, and a wipe has a
656
+ * direction, an edge and a speed the rest of the effect knows nothing about.
657
+ * Everywhere at once is also the honest match for what leaves: the motes are
658
+ * shed from every limb in the same breath.
659
+ *
660
+ * TWO SCALES. Clumps alone meant every fragment of a material SMALLER than one
661
+ * cell shared a single threshold: an eye highlight, a brow, a button, a hair
662
+ * clip. All of it sat inside the glowing front at once, so the piece flashed
663
+ * white as a whole and then popped — the two things a disintegration must never
664
+ * do. The grit is a per-cell hash at a fraction of the clump, so a part a few
665
+ * millimetres across still comes apart in pieces.
666
+ *
667
+ * THE GRIT IS THE BASE, though, and the clumps only push a fragment off it.
668
+ * That ordering is what makes the dissolve smooth, and it is not obvious: the
669
+ * two used to be WEIGHTED AND ADDED, and a sum is not uniformly distributed
670
+ * however uniform each half is. It piles up in the middle, so most of the
671
+ * surface had a threshold near a half — all of it went as the dissolve swept
672
+ * through the middle, and what remained was the thin tail near zero. That tail
673
+ * was the second stage everyone could see: a body that mostly vanished, then a
674
+ * scatter of glowing scraps, then nothing.
675
+ *
676
+ * WRAPPED, not added. Offsetting a uniform value and taking fract() leaves it
677
+ * EXACTLY uniform, where scaling a sum back into range only flattens the middle
678
+ * — measured over four hundred thousand samples, the sum removed 12% of her per
679
+ * step at the halfway mark and 0.1% at each end (a 110x swing), the scaled sum
680
+ * still swung 89x, and the wrap is flat: 5.0% per step from the first flake to
681
+ * the last, a ratio of 1.0.
682
+ *
683
+ * That flatness IS the smoothness. An uneven rate is what produced the two
684
+ * stages you could see — a body that mostly vanished at once, then a scatter of
685
+ * scraps that took as long again to follow.
686
+ *
687
+ * The clumping survives the wrap: neighbouring fragments share a clump value,
688
+ * so the offset moves them together. What wraps past 1 comes back at 0 and goes
689
+ * at the other end instead, which costs a little speckle in a region and buys
690
+ * an even rate everywhere.
691
+ */
692
+ fn rz_dissolve_threshold(restPos: vec3f) -> f32 {
693
+ let grit = rz_dissolve_hash(floor(restPos / (RZ_DISSOLVE_GRAIN * RZ_DISSOLVE_GRIT)));
694
+ let clump = rz_dissolve_field(restPos / RZ_DISSOLVE_GRAIN) - 0.5;
695
+ return fract(grit + clump * RZ_DISSOLVE_CLUMP);
696
+ }
697
+ `
698
+
699
+ // ─── Convenience: full shared prelude ───────────────────────────────
700
+ // Material files compose this as `${NODES_WGSL}${COMMON_MATERIAL_PRELUDE_WGSL}` to
701
+ // pull in everything structural. Each material then adds its own constants + fs().
702
+
703
+ // The FSOut struct is NOT in here any more — see commonFsOutWgsl above. Every
704
+ // consumer of this constant appends it immediately, which is where it was.
705
+ export const COMMON_MATERIAL_PRELUDE_WGSL =
706
+ COMMON_BINDINGS_WGSL + DRAW_LAYERS_WGSL + WORLD_AMBIENT_WGSL + lightsApi(0, 6, "rzDrawLayers()", { binding: 9, sampler: "diffuseSampler" }) + SAMPLE_SHADOW_WGSL + COMMON_VS_WGSL