@wave3d/core 0.1.0

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.
Files changed (55) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +60 -0
  3. package/dist/_virtual/_rolldown/runtime.js +13 -0
  4. package/dist/config/model.d.ts +240 -0
  5. package/dist/config/model.js +496 -0
  6. package/dist/config/model.js.map +1 -0
  7. package/dist/core-loader.d.ts +10 -0
  8. package/dist/core-loader.js +12 -0
  9. package/dist/core-loader.js.map +1 -0
  10. package/dist/index.d.ts +4 -0
  11. package/dist/index.js +3 -0
  12. package/dist/presets.d.ts +8 -0
  13. package/dist/presets.js +544 -0
  14. package/dist/presets.js.map +1 -0
  15. package/dist/renderer/WaveGeometry.d.ts +31 -0
  16. package/dist/renderer/WaveGeometry.js +92 -0
  17. package/dist/renderer/WaveGeometry.js.map +1 -0
  18. package/dist/renderer/WaveRenderer.d.ts +232 -0
  19. package/dist/renderer/WaveRenderer.js +1118 -0
  20. package/dist/renderer/WaveRenderer.js.map +1 -0
  21. package/dist/renderer/heroPalette.d.ts +10 -0
  22. package/dist/renderer/heroPalette.js +34 -0
  23. package/dist/renderer/heroPalette.js.map +1 -0
  24. package/dist/renderer/index.d.ts +4 -0
  25. package/dist/renderer/index.js +4 -0
  26. package/dist/renderer/palette.d.ts +67 -0
  27. package/dist/renderer/palette.js +535 -0
  28. package/dist/renderer/palette.js.map +1 -0
  29. package/dist/renderer/shaders.js +545 -0
  30. package/dist/renderer/shaders.js.map +1 -0
  31. package/dist/shell/createWave.d.ts +58 -0
  32. package/dist/shell/createWave.js +161 -0
  33. package/dist/shell/createWave.js.map +1 -0
  34. package/dist/shell/poster.js +64 -0
  35. package/dist/shell/poster.js.map +1 -0
  36. package/dist/shell/probe.js +34 -0
  37. package/dist/shell/probe.js.map +1 -0
  38. package/dist/standalone/wave3d.standalone.js +13507 -0
  39. package/dist/standalone.d.ts +13 -0
  40. package/dist/standalone.js +17 -0
  41. package/dist/standalone.js.map +1 -0
  42. package/dist/studio/StudioWaveRenderer.d.ts +187 -0
  43. package/dist/studio/StudioWaveRenderer.js +905 -0
  44. package/dist/studio/StudioWaveRenderer.js.map +1 -0
  45. package/dist/studio/index.d.ts +3 -0
  46. package/dist/studio/index.js +3 -0
  47. package/dist/studio/randomize.d.ts +28 -0
  48. package/dist/studio/randomize.js +264 -0
  49. package/dist/studio/randomize.js.map +1 -0
  50. package/dist/util/base64.js +14 -0
  51. package/dist/util/base64.js.map +1 -0
  52. package/dist/util/math.js +18 -0
  53. package/dist/util/math.js.map +1 -0
  54. package/package.json +76 -0
  55. package/skills/wave3d/SKILL.md +158 -0
@@ -0,0 +1,545 @@
1
+ import "../config/model.js";
2
+ //#region src/renderer/shaders.ts
3
+ /**
4
+ * The wave shaders. Vertex: a flat plane is Y-displaced by simplex noise, then
5
+ * twisted by three axis-rotations `freq * expStep(uv, power)` where
6
+ * `expStep(x,n) = exp2(-exp2(n)*pow(x,n))` is a falloff (rotation concentrated at
7
+ * the uv=0 edge), with diagonal axes + an animated X wobble. Fragment: uses NO
8
+ * normal-based lighting — "thickness" comes from `crease`, a foreshorten/fold
9
+ * detector built from `dFdy(uv)`, used to lift flat areas toward white
10
+ * (`col += (1-crease)*0.25`) and to localise the striations. Striations are subtle
11
+ * high-frequency simplex noise ADDED to the colour, colour-matched via (1-blue)
12
+ * and end-weighted via a parabola — so they blend rather than form hard lines.
13
+ * Our additions: gradient stops/types for colour, and an optional additive light
14
+ * layer (kept gentle so the default look is preserved).
15
+ */
16
+ const simplex2d = `
17
+ float xxhash(vec2 x){
18
+ uvec2 t = floatBitsToUint(x);
19
+ uint h = 0xc2b2ae3du * t.x + 0x165667b9u;
20
+ h = (h << 17u | h >> 15u) * 0x27d4eb2fu;
21
+ h += 0xc2b2ae3du * t.y;
22
+ h = (h << 17u | h >> 15u) * 0x27d4eb2fu;
23
+ h ^= h >> 15u;
24
+ h *= 0x85ebca77u;
25
+ h ^= h >> 13u;
26
+ h *= 0xc2b2ae3du;
27
+ h ^= h >> 16u;
28
+ return uintBitsToFloat(h >> 9u | 0x3f800000u) - 1.0;
29
+ }
30
+ vec2 hash(vec2 x){
31
+ float k = 6.283185307 * xxhash(x);
32
+ return vec2(cos(k), sin(k));
33
+ }
34
+ float simplexNoise(in vec2 p){
35
+ const float K1 = 0.366025404; // (sqrt(3)-1)/2
36
+ const float K2 = 0.211324865; // (3-sqrt(3))/6
37
+ vec2 i = floor(p + (p.x + p.y) * K1);
38
+ vec2 a = p - i + (i.x + i.y) * K2;
39
+ float m = step(a.y, a.x);
40
+ vec2 o = vec2(m, 1.0 - m);
41
+ vec2 b = a - o + K2;
42
+ vec2 c = a - 1.0 + 2.0 * K2;
43
+ vec3 h = max(0.5 - vec3(dot(a, a), dot(b, b), dot(c, c)), 0.0);
44
+ vec3 n = h * h * h * vec3(dot(a, hash(i + 0.0)), dot(b, hash(i + o)), dot(c, hash(i + 1.0)));
45
+ return dot(n, vec3(32.99)); // analytic factor (= 2916*sqrt(2)/125)
46
+ }
47
+ `;
48
+ const colorUniforms = `
49
+ uniform vec3 uColors[MAX_COLORS];
50
+ uniform float uColorPos[MAX_COLORS];
51
+ uniform int uColorCount;
52
+ uniform int uGradType;
53
+ uniform float uGradAngle;
54
+ uniform float uGradShift;
55
+ uniform vec2 uMeshPointPos[MAX_MESH_POINTS];
56
+ uniform vec3 uMeshPointColor[MAX_MESH_POINTS];
57
+ uniform float uMeshPointInfluence[MAX_MESH_POINTS];
58
+ uniform int uMeshPointCount;
59
+ uniform float uMeshSoftness;
60
+ uniform sampler2D uPalette; // baked 2D palette texture
61
+ uniform float uUsePalette; // >0.5 = sample the texture; else procedural grad()
62
+ uniform float uPaletteRaw; // >0.5 = sample palette by raw (uv.x,uv.y), not gradCoord
63
+ uniform vec2 uPaletteScale;
64
+ uniform vec2 uPaletteOffset;
65
+ uniform float uPaletteRotation;
66
+ uniform float uHueShift;
67
+ uniform float uContrast;
68
+ uniform float uSaturation;
69
+ uniform float uOpacity;
70
+ uniform float uSquared; // 1 = square the output colour (the deep "squared" hero look)
71
+ `;
72
+ const colorFns = `
73
+ vec3 contrastFn(vec3 v, float a){ return (v - 0.5) * a + 0.5; }
74
+ vec3 desaturate(vec3 color, float factor){
75
+ vec3 gray = vec3(dot(vec3(0.299, 0.587, 0.114), color));
76
+ return mix(color, gray, factor);
77
+ }
78
+ vec3 hueShift(vec3 color, float shift){
79
+ vec3 g = vec3(0.57735);
80
+ vec3 proj = g * dot(g, color);
81
+ vec3 U = color - proj;
82
+ vec3 W = cross(g, U);
83
+ return U * cos(shift) + W * sin(shift) + proj;
84
+ }
85
+
86
+ // Our gradient: interpolate stops by their positions (uColorPos sorted ascending).
87
+ vec3 grad(float u){
88
+ u = clamp(u, 0.0, 1.0);
89
+ vec3 col = uColors[0];
90
+ for (int i = 0; i < MAX_COLORS - 1; i++){
91
+ if (i >= uColorCount - 1) break;
92
+ float p0 = uColorPos[i];
93
+ float p1 = uColorPos[i + 1];
94
+ if (u >= p0){
95
+ float t = clamp((u - p0) / max(p1 - p0, 1e-5), 0.0, 1.0);
96
+ col = mix(uColors[i], uColors[i + 1], t);
97
+ }
98
+ }
99
+ return col;
100
+ }
101
+
102
+ // iOS-style 2D colour field. Each control point contributes an inverse-distance
103
+ // weight; normalising the sum fills the whole surface without dark seams.
104
+ vec3 meshGradient(vec2 uv){
105
+ vec3 colorSum = vec3(0.0);
106
+ float weightSum = 0.0;
107
+ float exponent = mix(4.8, 1.35, clamp(uMeshSoftness, 0.0, 1.0));
108
+ for (int i = 0; i < MAX_MESH_POINTS; i++){
109
+ if (i >= uMeshPointCount) break;
110
+ float influence = max(uMeshPointInfluence[i], 0.05);
111
+ float distanceFromPoint = length(uv - uMeshPointPos[i]) / influence;
112
+ float weight = 1.0 / (pow(max(distanceFromPoint, 0.012), exponent) + 0.002);
113
+ colorSum += uMeshPointColor[i] * weight;
114
+ weightSum += weight;
115
+ }
116
+ return colorSum / max(weightSum, 0.0001);
117
+ }
118
+
119
+ // Map a surface uv to the 0–1 gradient coordinate per gradient type. uGradShift
120
+ // adds a low-frequency simplex warp so the colour varies in 2D (along the length
121
+ // as well as across the width) — a 2D palette feel instead
122
+ // of flat 1-D bands.
123
+ float gradCoord(vec2 uv){
124
+ float warp = uGradShift * simplexNoise(uv * 1.6 + 4.0);
125
+ if (uGradType == 1){ return clamp(length(uv - 0.5) * 2.0 + warp, 0.0, 1.0); } // radial
126
+ if (uGradType == 2){ return fract(atan(uv.y - 0.5, uv.x - 0.5) / (2.0 * PI) + 0.5 + warp); } // conic
127
+ vec2 dir = vec2(sin(uGradAngle), cos(uGradAngle)); // linear, angled
128
+ return clamp(dot(uv - 0.5, dir) + 0.5 + warp, 0.0, 1.0);
129
+ }
130
+
131
+ // One base-colour sample for the whole surface: rotate/scale/offset the raw-palette uv,
132
+ // then pick the mesh field / baked 2D texture / procedural stops by mode. The raw palette
133
+ // is sampled by (uv.x, uv.y) directly; the stops-generated texture is sampled via
134
+ // gradCoord so its angle/type/warp still apply.
135
+ vec3 waveBaseColor(vec2 uv){
136
+ float gc = gradCoord(uv);
137
+ vec2 mediaUv = uv - 0.5;
138
+ float mediaCos = cos(uPaletteRotation);
139
+ float mediaSin = sin(uPaletteRotation);
140
+ mediaUv = vec2(
141
+ mediaCos * mediaUv.x + mediaSin * mediaUv.y,
142
+ -mediaSin * mediaUv.x + mediaCos * mediaUv.y
143
+ );
144
+ mediaUv = mediaUv * uPaletteScale + 0.5 + uPaletteOffset;
145
+ vec2 puv = uPaletteRaw > 0.5
146
+ ? clamp(mediaUv, 0.0, 1.0)
147
+ : vec2(gc, clamp(uv.y, 0.0, 1.0));
148
+ return uGradType == 3
149
+ ? meshGradient(uv)
150
+ : (uUsePalette > 0.5 ? texture2D(uPalette, puv).rgb : grad(gc));
151
+ }
152
+
153
+ // The shared colour grade: contrast → desaturate → hue rotate (degrees).
154
+ vec3 applyColorGrade(vec3 c){
155
+ c = contrastFn(c, uContrast);
156
+ c = desaturate(c, 1.0 - uSaturation);
157
+ return hueShift(c, radians(uHueShift));
158
+ }
159
+ `;
160
+ const vertexShader = `
161
+ ${simplex2d}
162
+
163
+ uniform float uTime, uSpeed, uSeed;
164
+ uniform float uDispFreqX, uDispFreqZ, uDispAmount;
165
+ uniform float uDetailFreq, uDetailAmount; // 2nd displacement octave (only read under DETAIL_OCTAVE)
166
+ uniform float uTwFreqX, uTwFreqY, uTwFreqZ, uTwPowX, uTwPowY, uTwPowZ;
167
+ uniform float uLoopSeconds; // seamless-loop period (only read under LOOP_MOTION)
168
+
169
+ varying vec2 vUv;
170
+ varying vec3 vWorldPos;
171
+ varying vec3 vViewDir;
172
+ varying vec4 vClipPosition; // = gl_Position, for the wireframe theme's depth fade
173
+
174
+ // expStep: a falloff from 1 (at x=0) toward 0, sharpness set by n. The
175
+ // max() guards pow(0, n) (= Infinity → NaN) so negative n is safe — negative n
176
+ // just concentrates the twist toward the OTHER end instead.
177
+ float expStep(float x, float n){ return exp2(-exp2(n) * pow(max(x, 1.0e-3), n)); }
178
+
179
+ // rotationMatrix (mat4), used row-vector style: pos = (vec4(pos,1) * R).xyz
180
+ mat4 rotationMatrix(vec3 axis, float angle){
181
+ axis = normalize(axis);
182
+ float s = sin(angle), c = cos(angle), oc = 1.0 - c;
183
+ return mat4(
184
+ oc*axis.x*axis.x + c, oc*axis.x*axis.y - axis.z*s, oc*axis.z*axis.x + axis.y*s, 0.0,
185
+ oc*axis.x*axis.y + axis.z*s, oc*axis.y*axis.y + c, oc*axis.y*axis.z - axis.x*s, 0.0,
186
+ oc*axis.z*axis.x - axis.y*s, oc*axis.y*axis.z + axis.x*s, oc*axis.z*axis.z + c, 0.0,
187
+ 0.0, 0.0, 0.0, 1.0
188
+ );
189
+ }
190
+
191
+ void main(){
192
+ vUv = uv;
193
+ #ifndef LOOP_MOTION
194
+ float t = uTime * uSpeed + uSeed;
195
+ #endif
196
+
197
+ #ifdef LOOP_MOTION
198
+ // Seamless loop: rather than scrolling the noise field linearly by t (which never repeats),
199
+ // sample it on a circle of radius loopR at angle loopTheta — exactly periodic with period
200
+ // uLoopSeconds. The tangential speed loopR·dθ/dt equals uSpeed, so the looped motion advances
201
+ // at the same rate as the linear drift, just curved into a closed orbit (it orbits rather than
202
+ // drifts — the trade-off for a seamless loop, hence opt-in). uSeed offsets the phase so stacked
203
+ // waves keep their relative motion while sharing the single period.
204
+ float loopTheta = uTime * (6.28318530718 / uLoopSeconds) + uSeed;
205
+ float loopR = uSpeed * uLoopSeconds * 0.159154943092; // = uSpeed·uLoopSeconds / (2π)
206
+ vec2 loopOff = loopR * vec2(cos(loopTheta), sin(loopTheta));
207
+ #endif
208
+
209
+ // The base geometry is already a baked hairpin fold. On top of it we deform the
210
+ // vertices: a displacement lifts Y by simplex noise of the (x,z) position, then
211
+ // three axis-rotations twist the strip.
212
+ vec3 pos = position;
213
+ #ifdef LOOP_MOTION
214
+ pos.y += uDispAmount * simplexNoise(vec2(pos.x * uDispFreqX, pos.z * uDispFreqZ) + loopOff);
215
+ #else
216
+ pos.y += uDispAmount * simplexNoise(vec2(pos.x * uDispFreqX + t, pos.z * uDispFreqZ + t));
217
+ #endif
218
+ #ifdef DETAIL_OCTAVE
219
+ // A second, finer octave riding on the broad swell — fine ripples on top of the big shape, a
220
+ // shape vocabulary single-octave displacement can't reach. Shares the loop orbit so it stays
221
+ // periodic when looping.
222
+ #ifdef LOOP_MOTION
223
+ pos.y += uDetailAmount * simplexNoise(vec2(pos.x * uDetailFreq, pos.z * uDetailFreq) + loopOff);
224
+ #else
225
+ pos.y += uDetailAmount * simplexNoise(vec2(pos.x * uDetailFreq + t, pos.z * uDetailFreq + t));
226
+ #endif
227
+ #endif
228
+
229
+ // The X-twist frequency feeding rotB. Two modes: by default uTwFreqX is used
230
+ // directly; the variant (used by the Wave 4 preset) modulates it with
231
+ // simplex noise indexed along the ribbon (uv.y) so the twist breathes over time.
232
+ // We gate the wobble with a #define so the compiled program is unchanged when off.
233
+ float twistXFreq = uTwFreqX;
234
+ #ifdef TWIST_MOTION
235
+ #ifdef LOOP_MOTION
236
+ float twistXNoise = simplexNoise(vec2(vUv.y * 2.0, 0.0) + loopOff);
237
+ #else
238
+ float twistXNoise = simplexNoise(vec2(vUv.y * 2.0, t));
239
+ #endif
240
+ twistXFreq = uTwFreqX - twistXNoise * 0.1;
241
+ #endif
242
+
243
+ // Three-axis twist: expStep falloff sets how
244
+ // sharply each rotation concentrates toward an edge. rotA keys off uv.x, rotB/rotC
245
+ // off uv.y; axes (0.5,0,0.5) and (0,0.5,0.5) are normalised inside rotationMatrix.
246
+ mat4 rotA = rotationMatrix(vec3(0.5, 0.0, 0.5), uTwFreqY * expStep(uv.x, uTwPowY));
247
+ mat4 rotB = rotationMatrix(vec3(0.0, 0.5, 0.5), twistXFreq * expStep(uv.y, uTwPowX));
248
+ mat4 rotC = rotationMatrix(vec3(0.5, 0.0, 0.5), uTwFreqZ * expStep(uv.y, uTwPowZ));
249
+ pos = (vec4(pos, 1.0) * rotA).xyz;
250
+ pos = (vec4(pos, 1.0) * rotB).xyz;
251
+ pos = (vec4(pos, 1.0) * rotC).xyz;
252
+
253
+ // The scale / rotation / position transform lives on the mesh (modelMatrix), so the
254
+ // orientation matches THREE's Euler-XYZ rather than an in-shader rotation order.
255
+ vec4 world = modelMatrix * vec4(pos, 1.0);
256
+ vWorldPos = world.xyz;
257
+ vViewDir = cameraPosition - world.xyz;
258
+ gl_Position = projectionMatrix * viewMatrix * world;
259
+ vClipPosition = gl_Position;
260
+ }
261
+ `;
262
+ const fragmentShader = `
263
+ #define MAX_COLORS 8
264
+ #define MAX_MESH_POINTS 8
265
+ #define MAX_LIGHTS 8
266
+ #define MAX_NOISE_BANDS 4
267
+ #define PI 3.14159265359
268
+
269
+ ${simplex2d}
270
+
271
+ ${colorUniforms}
272
+ uniform float uDebug; // dev: 1 = show crease, 2 = show derivative normal
273
+ uniform float uSheen; // white-lift on the flat (low-crease) areas (1 = full)
274
+ uniform float uRoundness; // pose-robust normal-based roundness/thickness strength
275
+ uniform float uIridescence; // thin-film hue shift with view angle (0 = off)
276
+ uniform float uFiberCount;
277
+ uniform float uFiberStrength;
278
+ uniform float uTexture;
279
+ uniform float uCreaseLight;
280
+ uniform float uCreaseSharpness;
281
+ uniform float uCreaseSoftness;
282
+ uniform float uEdgeFade;
283
+ uniform vec2 uResolution;
284
+ uniform float uAmbient;
285
+ uniform int uNumLights;
286
+ uniform vec3 uLightPos[MAX_LIGHTS];
287
+ uniform vec3 uLightColor[MAX_LIGHTS];
288
+ uniform float uLightIntensity[MAX_LIGHTS];
289
+ uniform int uNumNoiseBands;
290
+ uniform vec4 uNoiseBandBounds[MAX_NOISE_BANDS]; // (startX, endX, startY, endY)
291
+ uniform vec4 uNoiseBandParams[MAX_NOISE_BANDS]; // (feather, strength, frequency, colorAttenuation)
292
+ uniform float uNoiseBandParaPow[MAX_NOISE_BANDS];
293
+
294
+ varying vec2 vUv;
295
+ varying vec3 vWorldPos;
296
+ varying vec3 vViewDir;
297
+ #ifdef DEPTH_TINT
298
+ uniform float uDepthTint;
299
+ uniform vec3 uDepthTintColor;
300
+ varying vec4 vClipPosition; // clip-space depth (written by the vertex shader for both programs)
301
+ #endif
302
+ #ifdef EDGE_FEATHER
303
+ uniform float uEdgeFeather; // ribbon long-edge softness (only when it differs from the 0.1 default)
304
+ #endif
305
+
306
+ // Cheap value hash for the optional grain overlay (distinct from the simplex hash).
307
+ float grainHash(vec2 p){ return fract(sin(dot(p, vec2(12.9898, 78.233))) * 43758.5453); }
308
+
309
+ float parabola(float x, float k){ return pow(4.0 * x * (1.0 - x), k); }
310
+ float mapLinear(float v, float a, float b, float c, float d){ return c + (v - a) * (d - c) / (b - a); }
311
+
312
+ ${colorFns}
313
+
314
+ // Striations: a subtle high-frequency simplex-noise grain ADDED to the
315
+ // colour — colour-matched (weaker where blue is high), only near folds (crease), and
316
+ // concentrated toward the ends (parabola). Blends in rather than reading as hard lines.
317
+ vec3 surfaceStreaks(vec2 uv, vec3 color, float crease){
318
+ float strength = uFiberStrength; // default 0.2
319
+ float freq = uFiberCount; // default 600
320
+ float colorAtten = 0.9;
321
+ float paraPow = 3.0;
322
+ // Noise bands: inside each rectangular uv region the
323
+ // fiber params are overridden, so the streaks vary per region instead of uniform.
324
+ for (int i = 0; i < MAX_NOISE_BANDS; i++) {
325
+ if (i >= uNumNoiseBands) break;
326
+ vec4 b = uNoiseBandBounds[i];
327
+ vec4 prm = uNoiseBandParams[i];
328
+ float feather = max(prm.x, 1.0e-4);
329
+ float blend =
330
+ smoothstep(b.x - feather, b.x, uv.x) * (1.0 - smoothstep(b.y, b.y + feather, uv.x)) *
331
+ smoothstep(b.z - feather, b.z, uv.y) * (1.0 - smoothstep(b.w, b.w + feather, uv.y));
332
+ strength = mix(strength, prm.y, blend);
333
+ freq = mix(freq, prm.z, blend);
334
+ colorAtten = mix(colorAtten, prm.w, blend);
335
+ paraPow = mix(paraPow, uNoiseBandParaPow[i], blend);
336
+ }
337
+ // The high frequency runs along uv.x (the ribbon's length) so the streaks read as
338
+ // fine lengthwise fibers; end-weighted by 1 - parabola(uv.x).
339
+ float p = 1.0 - parabola(uv.x, paraPow);
340
+ float n0 = simplexNoise(vec2(uv.x * 0.1, uv.y * 0.5));
341
+ float n1 = simplexNoise(vec2(uv.x * (freq + freq * 0.5 * n0), uv.y * 4.0 * n0));
342
+ n1 = mapLinear(n1, -1.0, 1.0, 0.0, 1.0);
343
+ color += n1 * strength * (1.0 - color.b * colorAtten) * crease * p;
344
+ return color;
345
+ }
346
+
347
+ void main(){
348
+ // crease: a foreshortening / fold detector from the screen-space uv derivative.
349
+ // It drives BOTH the roundness shading and where the streaks appear — this is what
350
+ // gives the wave its thickness without any normal-based lighting.
351
+ float crease = dFdy(vUv).y * uResolution.y * uCreaseLight;
352
+ crease = clamp(mapLinear(crease, -1.0, 1.0, 0.0, 1.0), 0.0, 1.0);
353
+ crease = pow(crease, uCreaseSharpness);
354
+ crease = clamp(smoothstep(0.0, uCreaseSoftness, crease), 0.0, 1.0);
355
+
356
+ // Debug visualisations (dev): 1 = crease value, 2 = derivative surface normal.
357
+ if (uDebug > 0.5) {
358
+ if (uDebug < 1.5) { gl_FragColor = vec4(vec3(crease), 1.0); return; }
359
+ vec3 dn = normalize(cross(dFdx(vWorldPos), dFdy(vWorldPos)));
360
+ gl_FragColor = vec4(dn * 0.5 + 0.5, 1.0); return;
361
+ }
362
+
363
+ // Colour: sample the baked 2D palette texture, or fall back to the procedural 1-D
364
+ // gradient (see waveBaseColor).
365
+ vec3 col = waveBaseColor(vUv);
366
+ col = surfaceStreaks(vUv, col, crease);
367
+ col = applyColorGrade(col);
368
+
369
+ // Iridescence: a thin-film / holographic hue that shifts with view angle. Reuses the same
370
+ // camera-facing ratio as roundness (recomputed here, since roundness may be off): grazing parts
371
+ // of the ribbon (low facing) shift hue most, so the colour flows as the ribbon curves. Skipped
372
+ // at 0, so the compiled result is unchanged when off.
373
+ if (uIridescence > 0.001) {
374
+ vec3 iridN = normalize(cross(dFdx(vWorldPos), dFdy(vWorldPos)));
375
+ float iridFacing = abs(dot(iridN, normalize(vViewDir)));
376
+ col = hueShift(col, (1.0 - iridFacing) * uIridescence * PI);
377
+ }
378
+
379
+ // Sheen: lift the flat (low-crease) areas toward white. This is
380
+ // pose-dependent (it keys off dFdy(uv.y)), so we keep it gentle and add a robust term.
381
+ col += (1.0 - crease) * 0.25 * uSheen;
382
+
383
+ // Pose-robust roundness: shade by the camera-facing ratio of the derivative surface
384
+ // normal so the ribbon reads as a rounded, grabbable solid from any angle. Grazing
385
+ // edges darken into shadow (defining the rounded form), the body keeps its full colour,
386
+ // and the most face-on sliver catches a soft highlight. uRoundness = strength.
387
+ if (uRoundness > 0.001) {
388
+ vec3 volN = normalize(cross(dFdx(vWorldPos), dFdy(vWorldPos)));
389
+ float facing = abs(dot(volN, normalize(vViewDir))); // 1 = facing camera, 0 = edge-on
390
+ col *= mix(1.0 - 0.6 * uRoundness, 1.0, facing); // deepen grazing edges → solid form
391
+ col += smoothstep(0.65, 1.0, facing) * uRoundness * 0.18; // soft highlight on the facing body
392
+ }
393
+
394
+ // Optional positionable lights (our feature) — additive & gentle, on top of the
395
+ // base shading so the default look is preserved. A finely-subdivided mesh
396
+ // keeps this derivative normal smooth.
397
+ if (uNumLights > 0) {
398
+ vec3 N = normalize(cross(dFdx(vWorldPos), dFdy(vWorldPos)));
399
+ vec3 Vd = normalize(vViewDir);
400
+ if (dot(N, Vd) < 0.0) N = -N;
401
+ for (int i = 0; i < MAX_LIGHTS; i++) {
402
+ if (i >= uNumLights) break;
403
+ vec3 L = normalize(uLightPos[i] - vWorldPos);
404
+ vec3 lc = uLightColor[i] * uLightIntensity[i];
405
+ float diff = max(dot(N, L), 0.0);
406
+ float spec = pow(max(dot(N, normalize(L + Vd)), 0.0), 28.0);
407
+ col += col * diff * lc * 0.16 + spec * lc * 0.10;
408
+ }
409
+ }
410
+ col *= 0.55 + clamp(uAmbient, 0.0, 1.0); // overall level; default 0.45 => x1.0 (neutral)
411
+
412
+ #ifdef DEPTH_TINT
413
+ // Depth tint: fade far fragments toward a colour so a multi-wave stack gains atmospheric
414
+ // separation — near strands keep their colour, far ones recede. Reuses the clip-space depth the
415
+ // wireframe theme fades with (clamp(z*6), where 1 = far).
416
+ col = mix(col, uDepthTintColor, clamp(vClipPosition.z * 6.0, 0.0, 1.0) * uDepthTint);
417
+ #endif
418
+
419
+ if (uTexture > 0.001) col *= 1.0 + (grainHash(vUv * 850.0) - 0.5) * uTexture * 0.25;
420
+
421
+ // Soft long edges + optional viewport-edge fade. The edge softness is the hardcoded 0.1 by
422
+ // default (literal branch → byte-identical); EDGE_FEATHER swaps in the uEdgeFeather knob only
423
+ // when it differs, so razor-crisp or vapor-soft edges are both reachable.
424
+ #ifdef EDGE_FEATHER
425
+ float ribEdge =
426
+ smoothstep(0.0, uEdgeFeather, vUv.y) * (1.0 - smoothstep(1.0 - uEdgeFeather, 1.0, vUv.y));
427
+ #else
428
+ float ribEdge = smoothstep(0.0, 0.1, vUv.y) * (1.0 - smoothstep(0.9, 1.0, vUv.y));
429
+ #endif
430
+ float alpha = uOpacity * ribEdge;
431
+ if (uEdgeFade > 0.001) {
432
+ vec2 sc = gl_FragCoord.xy / max(uResolution, vec2(1.0));
433
+ float vig =
434
+ smoothstep(0.0, uEdgeFade, sc.x) * (1.0 - smoothstep(1.0 - uEdgeFade, 1.0, sc.x)) *
435
+ smoothstep(0.0, uEdgeFade, sc.y) * (1.0 - smoothstep(1.0 - uEdgeFade, 1.0, sc.y));
436
+ alpha *= vig;
437
+ }
438
+
439
+ // Deep "squared" hero colour: formerly done by a framebuffer-squaring blend that REPLACED the
440
+ // destination (punching holes at soft edges / where waves overlap). Squaring here + normal
441
+ // premultiplied compositing (see applyBlendMode) keeps the deep colour and blends correctly.
442
+ col = clamp(col, 0.0, 1.0);
443
+ // Square colour AND alpha so the soft ribbon edges keep the crisp, thin feather of the original
444
+ // squared-blend look — but now composited (premultiplied) rather than replace-blended, so they
445
+ // no longer punch holes. Over an opaque background alpha² still resolves to fully opaque.
446
+ if (uSquared > 0.5) { col *= col; alpha *= alpha; }
447
+ gl_FragColor = vec4(col, alpha);
448
+ #ifdef PREMULTIPLIED_ALPHA
449
+ gl_FragColor.rgb *= gl_FragColor.a;
450
+ #endif
451
+ }
452
+ `;
453
+ const lineFragmentShader = `
454
+ #define MAX_COLORS 8
455
+ #define MAX_MESH_POINTS 8
456
+ #define PI 3.14159265359
457
+
458
+ ${simplex2d}
459
+
460
+ ${colorUniforms}
461
+ uniform float uLineAmount; // default 425
462
+ uniform float uLineThickness; // default 1
463
+ uniform float uLineDerivativePower; // default 0.95
464
+ uniform float uMaxWidth; // default 1232
465
+ uniform vec3 uClearColor; // = page background colour (shown between the lines)
466
+
467
+ varying vec2 vUv;
468
+ varying vec4 vClipPosition;
469
+
470
+ ${colorFns}
471
+
472
+ void main(){
473
+ // Same 2D palette sample + colour ops as the solid theme.
474
+ vec3 color = applyColorGrade(waveBaseColor(vUv));
475
+
476
+ // Carve into fine vertical lines; thickness from the screen-space uv derivative.
477
+ vec2 dy = dFdy(vUv);
478
+ float lineThickness = uLineThickness * pow(abs(dy.x * uMaxWidth), uLineDerivativePower);
479
+ float a = abs(sin(vUv.x * uLineAmount));
480
+ a = smoothstep(lineThickness, 0.0, a);
481
+
482
+ // Depth fade: the wave recedes into the background colour with depth. Watch the
483
+ // argument order: clamp(0.0, 1.0, z*6) is a swapped-args trap — it clamps the
484
+ // constant 0.0 into [1.0, z*6], i.e. min(1.0, z*6), which (with our ortho clip.z
485
+ // range) collapses the whole wave to the background. The correct clamp(z*6, 0, 1)
486
+ // gives the proper subtle far-end fade and thin-line look.
487
+ float depthFade = clamp(vClipPosition.z * 6.0, 0.0, 1.0);
488
+ color = mix(uClearColor, color, a * (1.0 - depthFade));
489
+ if (uSquared > 0.5) color *= color; // deep "squared" look, now composited not replace-blended
490
+ gl_FragColor = vec4(color, uOpacity);
491
+ #ifdef PREMULTIPLIED_ALPHA
492
+ gl_FragColor.rgb *= gl_FragColor.a;
493
+ #endif
494
+ }
495
+ `;
496
+ const postVertexShader = `
497
+ varying vec2 vUv;
498
+ void main(){
499
+ vUv = uv;
500
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
501
+ }
502
+ `;
503
+ const postFragmentShader = `
504
+ uniform sampler2D tDiffuse;
505
+ uniform vec2 uResolution;
506
+ uniform float uBlurAmount;
507
+ uniform int uBlurSamples;
508
+ uniform float uGrainAmount;
509
+ uniform float uTime;
510
+ varying vec2 vUv;
511
+
512
+ float random2(vec2 st){ return fract(sin(dot(st.xy, vec2(12.9898, 78.233))) * 43758.5453); }
513
+
514
+ // Angular (spin) blur: rotate the sample coord around the centre and
515
+ // accumulate — a tangential smear that grows toward the edges. Carries alpha so a
516
+ // transparent background survives the post pass.
517
+ vec4 blurAngular(sampler2D tex, vec2 uv, float angle, int samples){
518
+ vec4 total = vec4(0.0);
519
+ vec2 coord = uv - 0.5;
520
+ float dist = 1.0 / float(samples);
521
+ vec2 dir = vec2(cos(angle * dist), sin(angle * dist));
522
+ mat2 rot = mat2(dir.x, dir.y, -dir.y, dir.x);
523
+ for (int i = 0; i < 64; i++){
524
+ if (i >= samples) break;
525
+ total += texture2D(tex, coord + 0.5);
526
+ coord = coord * rot; // row-vector order (coord * rot) sets the spin direction
527
+ }
528
+ return total * dist;
529
+ }
530
+
531
+ void main(){
532
+ vec4 sceneColor = texture2D(tDiffuse, vUv);
533
+ vec4 blurColor = blurAngular(tDiffuse, vUv, uBlurAmount, uBlurSamples);
534
+ // blurPower: keep a sharp band weighted to the middle, blurring toward top & bottom.
535
+ float blurPower = smoothstep(0.0, 0.7, vUv.y) - smoothstep(0.2, 1.0, vUv.y);
536
+ vec4 color = mix(blurColor, sceneColor, blurPower);
537
+ // Static film grain: keyed off gl_FragCoord only (no uTime), so it doesn't flicker.
538
+ color.rgb += mix(uGrainAmount, -uGrainAmount, random2(gl_FragCoord.xy * 0.01)) * (4.0 / 255.0);
539
+ gl_FragColor = color; // preserve alpha → transparent background works
540
+ }
541
+ `;
542
+ //#endregion
543
+ export { fragmentShader, lineFragmentShader, postFragmentShader, postVertexShader, vertexShader };
544
+
545
+ //# sourceMappingURL=shaders.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shaders.js","names":[],"sources":["../../src/renderer/shaders.ts"],"sourcesContent":["import { MAX_COLORS, MAX_LIGHTS, MAX_MESH_POINTS, MAX_NOISE_BANDS } from \"../config/model\";\n\n/**\n * The wave shaders. Vertex: a flat plane is Y-displaced by simplex noise, then\n * twisted by three axis-rotations `freq * expStep(uv, power)` where\n * `expStep(x,n) = exp2(-exp2(n)*pow(x,n))` is a falloff (rotation concentrated at\n * the uv=0 edge), with diagonal axes + an animated X wobble. Fragment: uses NO\n * normal-based lighting — \"thickness\" comes from `crease`, a foreshorten/fold\n * detector built from `dFdy(uv)`, used to lift flat areas toward white\n * (`col += (1-crease)*0.25`) and to localise the striations. Striations are subtle\n * high-frequency simplex noise ADDED to the colour, colour-matched via (1-blue)\n * and end-weighted via a parabola — so they blend rather than form hard lines.\n * Our additions: gradient stops/types for colour, and an optional additive light\n * layer (kept gentle so the default look is preserved).\n */\n\n// Noise function: xxHash-seeded unit-vector gradients + a Gustavson simplex. It uses\n// GLSL ES 3.00 integer ops (floatBitsToUint, unsigned bit-shifts) — available with no\n// glslVersion change because three compiles non-raw ShaderMaterials as \"#version 300 es\"\n// already. `hash` returns a vec2 here — the cheap grain hash in the fragment is named\n// `grainHash` to avoid clashing with it.\nconst simplex2d = /* glsl */ `\nfloat xxhash(vec2 x){\n uvec2 t = floatBitsToUint(x);\n uint h = 0xc2b2ae3du * t.x + 0x165667b9u;\n h = (h << 17u | h >> 15u) * 0x27d4eb2fu;\n h += 0xc2b2ae3du * t.y;\n h = (h << 17u | h >> 15u) * 0x27d4eb2fu;\n h ^= h >> 15u;\n h *= 0x85ebca77u;\n h ^= h >> 13u;\n h *= 0xc2b2ae3du;\n h ^= h >> 16u;\n return uintBitsToFloat(h >> 9u | 0x3f800000u) - 1.0;\n}\nvec2 hash(vec2 x){\n float k = 6.283185307 * xxhash(x);\n return vec2(cos(k), sin(k));\n}\nfloat simplexNoise(in vec2 p){\n const float K1 = 0.366025404; // (sqrt(3)-1)/2\n const float K2 = 0.211324865; // (3-sqrt(3))/6\n vec2 i = floor(p + (p.x + p.y) * K1);\n vec2 a = p - i + (i.x + i.y) * K2;\n float m = step(a.y, a.x);\n vec2 o = vec2(m, 1.0 - m);\n vec2 b = a - o + K2;\n vec2 c = a - 1.0 + 2.0 * K2;\n vec3 h = max(0.5 - vec3(dot(a, a), dot(b, b), dot(c, c)), 0.0);\n vec3 n = h * h * h * vec3(dot(a, hash(i + 0.0)), dot(b, hash(i + o)), dot(c, hash(i + 1.0)));\n return dot(n, vec3(32.99)); // analytic factor (= 2916*sqrt(2)/125)\n}\n`;\n\n// Uniforms shared by BOTH fragment shaders (solid + wireframe line): the palette/gradient\n// inputs and the colour-grade knobs. Each shader declares its theme-specific uniforms beside\n// this block. Requires MAX_COLORS / MAX_MESH_POINTS #defines.\nconst colorUniforms = /* glsl */ `\nuniform vec3 uColors[MAX_COLORS];\nuniform float uColorPos[MAX_COLORS];\nuniform int uColorCount;\nuniform int uGradType;\nuniform float uGradAngle;\nuniform float uGradShift;\nuniform vec2 uMeshPointPos[MAX_MESH_POINTS];\nuniform vec3 uMeshPointColor[MAX_MESH_POINTS];\nuniform float uMeshPointInfluence[MAX_MESH_POINTS];\nuniform int uMeshPointCount;\nuniform float uMeshSoftness;\nuniform sampler2D uPalette; // baked 2D palette texture\nuniform float uUsePalette; // >0.5 = sample the texture; else procedural grad()\nuniform float uPaletteRaw; // >0.5 = sample palette by raw (uv.x,uv.y), not gradCoord\nuniform vec2 uPaletteScale;\nuniform vec2 uPaletteOffset;\nuniform float uPaletteRotation;\nuniform float uHueShift;\nuniform float uContrast;\nuniform float uSaturation;\nuniform float uOpacity;\nuniform float uSquared; // 1 = square the output colour (the deep \"squared\" hero look)\n`;\n\n// Colour helpers + the palette/gradient sampler shared by both fragment shaders.\n// Interpolate AFTER ${\"simplex2d\"} and ${\"colorUniforms\"} (gradCoord needs both) and a PI define.\nconst colorFns = /* glsl */ `\nvec3 contrastFn(vec3 v, float a){ return (v - 0.5) * a + 0.5; }\nvec3 desaturate(vec3 color, float factor){\n vec3 gray = vec3(dot(vec3(0.299, 0.587, 0.114), color));\n return mix(color, gray, factor);\n}\nvec3 hueShift(vec3 color, float shift){\n vec3 g = vec3(0.57735);\n vec3 proj = g * dot(g, color);\n vec3 U = color - proj;\n vec3 W = cross(g, U);\n return U * cos(shift) + W * sin(shift) + proj;\n}\n\n// Our gradient: interpolate stops by their positions (uColorPos sorted ascending).\nvec3 grad(float u){\n u = clamp(u, 0.0, 1.0);\n vec3 col = uColors[0];\n for (int i = 0; i < MAX_COLORS - 1; i++){\n if (i >= uColorCount - 1) break;\n float p0 = uColorPos[i];\n float p1 = uColorPos[i + 1];\n if (u >= p0){\n float t = clamp((u - p0) / max(p1 - p0, 1e-5), 0.0, 1.0);\n col = mix(uColors[i], uColors[i + 1], t);\n }\n }\n return col;\n}\n\n// iOS-style 2D colour field. Each control point contributes an inverse-distance\n// weight; normalising the sum fills the whole surface without dark seams.\nvec3 meshGradient(vec2 uv){\n vec3 colorSum = vec3(0.0);\n float weightSum = 0.0;\n float exponent = mix(4.8, 1.35, clamp(uMeshSoftness, 0.0, 1.0));\n for (int i = 0; i < MAX_MESH_POINTS; i++){\n if (i >= uMeshPointCount) break;\n float influence = max(uMeshPointInfluence[i], 0.05);\n float distanceFromPoint = length(uv - uMeshPointPos[i]) / influence;\n float weight = 1.0 / (pow(max(distanceFromPoint, 0.012), exponent) + 0.002);\n colorSum += uMeshPointColor[i] * weight;\n weightSum += weight;\n }\n return colorSum / max(weightSum, 0.0001);\n}\n\n// Map a surface uv to the 0–1 gradient coordinate per gradient type. uGradShift\n// adds a low-frequency simplex warp so the colour varies in 2D (along the length\n// as well as across the width) — a 2D palette feel instead\n// of flat 1-D bands.\nfloat gradCoord(vec2 uv){\n float warp = uGradShift * simplexNoise(uv * 1.6 + 4.0);\n if (uGradType == 1){ return clamp(length(uv - 0.5) * 2.0 + warp, 0.0, 1.0); } // radial\n if (uGradType == 2){ return fract(atan(uv.y - 0.5, uv.x - 0.5) / (2.0 * PI) + 0.5 + warp); } // conic\n vec2 dir = vec2(sin(uGradAngle), cos(uGradAngle)); // linear, angled\n return clamp(dot(uv - 0.5, dir) + 0.5 + warp, 0.0, 1.0);\n}\n\n// One base-colour sample for the whole surface: rotate/scale/offset the raw-palette uv,\n// then pick the mesh field / baked 2D texture / procedural stops by mode. The raw palette\n// is sampled by (uv.x, uv.y) directly; the stops-generated texture is sampled via\n// gradCoord so its angle/type/warp still apply.\nvec3 waveBaseColor(vec2 uv){\n float gc = gradCoord(uv);\n vec2 mediaUv = uv - 0.5;\n float mediaCos = cos(uPaletteRotation);\n float mediaSin = sin(uPaletteRotation);\n mediaUv = vec2(\n mediaCos * mediaUv.x + mediaSin * mediaUv.y,\n -mediaSin * mediaUv.x + mediaCos * mediaUv.y\n );\n mediaUv = mediaUv * uPaletteScale + 0.5 + uPaletteOffset;\n vec2 puv = uPaletteRaw > 0.5\n ? clamp(mediaUv, 0.0, 1.0)\n : vec2(gc, clamp(uv.y, 0.0, 1.0));\n return uGradType == 3\n ? meshGradient(uv)\n : (uUsePalette > 0.5 ? texture2D(uPalette, puv).rgb : grad(gc));\n}\n\n// The shared colour grade: contrast → desaturate → hue rotate (degrees).\nvec3 applyColorGrade(vec3 c){\n c = contrastFn(c, uContrast);\n c = desaturate(c, 1.0 - uSaturation);\n return hueShift(c, radians(uHueShift));\n}\n`;\n\nexport const vertexShader = /* glsl */ `\n${simplex2d}\n\nuniform float uTime, uSpeed, uSeed;\nuniform float uDispFreqX, uDispFreqZ, uDispAmount;\nuniform float uDetailFreq, uDetailAmount; // 2nd displacement octave (only read under DETAIL_OCTAVE)\nuniform float uTwFreqX, uTwFreqY, uTwFreqZ, uTwPowX, uTwPowY, uTwPowZ;\nuniform float uLoopSeconds; // seamless-loop period (only read under LOOP_MOTION)\n\nvarying vec2 vUv;\nvarying vec3 vWorldPos;\nvarying vec3 vViewDir;\nvarying vec4 vClipPosition; // = gl_Position, for the wireframe theme's depth fade\n\n// expStep: a falloff from 1 (at x=0) toward 0, sharpness set by n. The\n// max() guards pow(0, n) (= Infinity → NaN) so negative n is safe — negative n\n// just concentrates the twist toward the OTHER end instead.\nfloat expStep(float x, float n){ return exp2(-exp2(n) * pow(max(x, 1.0e-3), n)); }\n\n// rotationMatrix (mat4), used row-vector style: pos = (vec4(pos,1) * R).xyz\nmat4 rotationMatrix(vec3 axis, float angle){\n axis = normalize(axis);\n float s = sin(angle), c = cos(angle), oc = 1.0 - c;\n return mat4(\n oc*axis.x*axis.x + c, oc*axis.x*axis.y - axis.z*s, oc*axis.z*axis.x + axis.y*s, 0.0,\n oc*axis.x*axis.y + axis.z*s, oc*axis.y*axis.y + c, oc*axis.y*axis.z - axis.x*s, 0.0,\n oc*axis.z*axis.x - axis.y*s, oc*axis.y*axis.z + axis.x*s, oc*axis.z*axis.z + c, 0.0,\n 0.0, 0.0, 0.0, 1.0\n );\n}\n\nvoid main(){\n vUv = uv;\n#ifndef LOOP_MOTION\n float t = uTime * uSpeed + uSeed;\n#endif\n\n#ifdef LOOP_MOTION\n // Seamless loop: rather than scrolling the noise field linearly by t (which never repeats),\n // sample it on a circle of radius loopR at angle loopTheta — exactly periodic with period\n // uLoopSeconds. The tangential speed loopR·dθ/dt equals uSpeed, so the looped motion advances\n // at the same rate as the linear drift, just curved into a closed orbit (it orbits rather than\n // drifts — the trade-off for a seamless loop, hence opt-in). uSeed offsets the phase so stacked\n // waves keep their relative motion while sharing the single period.\n float loopTheta = uTime * (6.28318530718 / uLoopSeconds) + uSeed;\n float loopR = uSpeed * uLoopSeconds * 0.159154943092; // = uSpeed·uLoopSeconds / (2π)\n vec2 loopOff = loopR * vec2(cos(loopTheta), sin(loopTheta));\n#endif\n\n // The base geometry is already a baked hairpin fold. On top of it we deform the\n // vertices: a displacement lifts Y by simplex noise of the (x,z) position, then\n // three axis-rotations twist the strip.\n vec3 pos = position;\n#ifdef LOOP_MOTION\n pos.y += uDispAmount * simplexNoise(vec2(pos.x * uDispFreqX, pos.z * uDispFreqZ) + loopOff);\n#else\n pos.y += uDispAmount * simplexNoise(vec2(pos.x * uDispFreqX + t, pos.z * uDispFreqZ + t));\n#endif\n#ifdef DETAIL_OCTAVE\n // A second, finer octave riding on the broad swell — fine ripples on top of the big shape, a\n // shape vocabulary single-octave displacement can't reach. Shares the loop orbit so it stays\n // periodic when looping.\n#ifdef LOOP_MOTION\n pos.y += uDetailAmount * simplexNoise(vec2(pos.x * uDetailFreq, pos.z * uDetailFreq) + loopOff);\n#else\n pos.y += uDetailAmount * simplexNoise(vec2(pos.x * uDetailFreq + t, pos.z * uDetailFreq + t));\n#endif\n#endif\n\n // The X-twist frequency feeding rotB. Two modes: by default uTwFreqX is used\n // directly; the variant (used by the Wave 4 preset) modulates it with\n // simplex noise indexed along the ribbon (uv.y) so the twist breathes over time.\n // We gate the wobble with a #define so the compiled program is unchanged when off.\n float twistXFreq = uTwFreqX;\n#ifdef TWIST_MOTION\n#ifdef LOOP_MOTION\n float twistXNoise = simplexNoise(vec2(vUv.y * 2.0, 0.0) + loopOff);\n#else\n float twistXNoise = simplexNoise(vec2(vUv.y * 2.0, t));\n#endif\n twistXFreq = uTwFreqX - twistXNoise * 0.1;\n#endif\n\n // Three-axis twist: expStep falloff sets how\n // sharply each rotation concentrates toward an edge. rotA keys off uv.x, rotB/rotC\n // off uv.y; axes (0.5,0,0.5) and (0,0.5,0.5) are normalised inside rotationMatrix.\n mat4 rotA = rotationMatrix(vec3(0.5, 0.0, 0.5), uTwFreqY * expStep(uv.x, uTwPowY));\n mat4 rotB = rotationMatrix(vec3(0.0, 0.5, 0.5), twistXFreq * expStep(uv.y, uTwPowX));\n mat4 rotC = rotationMatrix(vec3(0.5, 0.0, 0.5), uTwFreqZ * expStep(uv.y, uTwPowZ));\n pos = (vec4(pos, 1.0) * rotA).xyz;\n pos = (vec4(pos, 1.0) * rotB).xyz;\n pos = (vec4(pos, 1.0) * rotC).xyz;\n\n // The scale / rotation / position transform lives on the mesh (modelMatrix), so the\n // orientation matches THREE's Euler-XYZ rather than an in-shader rotation order.\n vec4 world = modelMatrix * vec4(pos, 1.0);\n vWorldPos = world.xyz;\n vViewDir = cameraPosition - world.xyz;\n gl_Position = projectionMatrix * viewMatrix * world;\n vClipPosition = gl_Position;\n}\n`;\n\nexport const fragmentShader = /* glsl */ `\n#define MAX_COLORS ${MAX_COLORS}\n#define MAX_MESH_POINTS ${MAX_MESH_POINTS}\n#define MAX_LIGHTS ${MAX_LIGHTS}\n#define MAX_NOISE_BANDS ${MAX_NOISE_BANDS}\n#define PI 3.14159265359\n\n${simplex2d}\n\n${colorUniforms}\nuniform float uDebug; // dev: 1 = show crease, 2 = show derivative normal\nuniform float uSheen; // white-lift on the flat (low-crease) areas (1 = full)\nuniform float uRoundness; // pose-robust normal-based roundness/thickness strength\nuniform float uIridescence; // thin-film hue shift with view angle (0 = off)\nuniform float uFiberCount;\nuniform float uFiberStrength;\nuniform float uTexture;\nuniform float uCreaseLight;\nuniform float uCreaseSharpness;\nuniform float uCreaseSoftness;\nuniform float uEdgeFade;\nuniform vec2 uResolution;\nuniform float uAmbient;\nuniform int uNumLights;\nuniform vec3 uLightPos[MAX_LIGHTS];\nuniform vec3 uLightColor[MAX_LIGHTS];\nuniform float uLightIntensity[MAX_LIGHTS];\nuniform int uNumNoiseBands;\nuniform vec4 uNoiseBandBounds[MAX_NOISE_BANDS]; // (startX, endX, startY, endY)\nuniform vec4 uNoiseBandParams[MAX_NOISE_BANDS]; // (feather, strength, frequency, colorAttenuation)\nuniform float uNoiseBandParaPow[MAX_NOISE_BANDS];\n\nvarying vec2 vUv;\nvarying vec3 vWorldPos;\nvarying vec3 vViewDir;\n#ifdef DEPTH_TINT\nuniform float uDepthTint;\nuniform vec3 uDepthTintColor;\nvarying vec4 vClipPosition; // clip-space depth (written by the vertex shader for both programs)\n#endif\n#ifdef EDGE_FEATHER\nuniform float uEdgeFeather; // ribbon long-edge softness (only when it differs from the 0.1 default)\n#endif\n\n// Cheap value hash for the optional grain overlay (distinct from the simplex hash).\nfloat grainHash(vec2 p){ return fract(sin(dot(p, vec2(12.9898, 78.233))) * 43758.5453); }\n\nfloat parabola(float x, float k){ return pow(4.0 * x * (1.0 - x), k); }\nfloat mapLinear(float v, float a, float b, float c, float d){ return c + (v - a) * (d - c) / (b - a); }\n\n${colorFns}\n\n// Striations: a subtle high-frequency simplex-noise grain ADDED to the\n// colour — colour-matched (weaker where blue is high), only near folds (crease), and\n// concentrated toward the ends (parabola). Blends in rather than reading as hard lines.\nvec3 surfaceStreaks(vec2 uv, vec3 color, float crease){\n float strength = uFiberStrength; // default 0.2\n float freq = uFiberCount; // default 600\n float colorAtten = 0.9;\n float paraPow = 3.0;\n // Noise bands: inside each rectangular uv region the\n // fiber params are overridden, so the streaks vary per region instead of uniform.\n for (int i = 0; i < MAX_NOISE_BANDS; i++) {\n if (i >= uNumNoiseBands) break;\n vec4 b = uNoiseBandBounds[i];\n vec4 prm = uNoiseBandParams[i];\n float feather = max(prm.x, 1.0e-4);\n float blend =\n smoothstep(b.x - feather, b.x, uv.x) * (1.0 - smoothstep(b.y, b.y + feather, uv.x)) *\n smoothstep(b.z - feather, b.z, uv.y) * (1.0 - smoothstep(b.w, b.w + feather, uv.y));\n strength = mix(strength, prm.y, blend);\n freq = mix(freq, prm.z, blend);\n colorAtten = mix(colorAtten, prm.w, blend);\n paraPow = mix(paraPow, uNoiseBandParaPow[i], blend);\n }\n // The high frequency runs along uv.x (the ribbon's length) so the streaks read as\n // fine lengthwise fibers; end-weighted by 1 - parabola(uv.x).\n float p = 1.0 - parabola(uv.x, paraPow);\n float n0 = simplexNoise(vec2(uv.x * 0.1, uv.y * 0.5));\n float n1 = simplexNoise(vec2(uv.x * (freq + freq * 0.5 * n0), uv.y * 4.0 * n0));\n n1 = mapLinear(n1, -1.0, 1.0, 0.0, 1.0);\n color += n1 * strength * (1.0 - color.b * colorAtten) * crease * p;\n return color;\n}\n\nvoid main(){\n // crease: a foreshortening / fold detector from the screen-space uv derivative.\n // It drives BOTH the roundness shading and where the streaks appear — this is what\n // gives the wave its thickness without any normal-based lighting.\n float crease = dFdy(vUv).y * uResolution.y * uCreaseLight;\n crease = clamp(mapLinear(crease, -1.0, 1.0, 0.0, 1.0), 0.0, 1.0);\n crease = pow(crease, uCreaseSharpness);\n crease = clamp(smoothstep(0.0, uCreaseSoftness, crease), 0.0, 1.0);\n\n // Debug visualisations (dev): 1 = crease value, 2 = derivative surface normal.\n if (uDebug > 0.5) {\n if (uDebug < 1.5) { gl_FragColor = vec4(vec3(crease), 1.0); return; }\n vec3 dn = normalize(cross(dFdx(vWorldPos), dFdy(vWorldPos)));\n gl_FragColor = vec4(dn * 0.5 + 0.5, 1.0); return;\n }\n\n // Colour: sample the baked 2D palette texture, or fall back to the procedural 1-D\n // gradient (see waveBaseColor).\n vec3 col = waveBaseColor(vUv);\n col = surfaceStreaks(vUv, col, crease);\n col = applyColorGrade(col);\n\n // Iridescence: a thin-film / holographic hue that shifts with view angle. Reuses the same\n // camera-facing ratio as roundness (recomputed here, since roundness may be off): grazing parts\n // of the ribbon (low facing) shift hue most, so the colour flows as the ribbon curves. Skipped\n // at 0, so the compiled result is unchanged when off.\n if (uIridescence > 0.001) {\n vec3 iridN = normalize(cross(dFdx(vWorldPos), dFdy(vWorldPos)));\n float iridFacing = abs(dot(iridN, normalize(vViewDir)));\n col = hueShift(col, (1.0 - iridFacing) * uIridescence * PI);\n }\n\n // Sheen: lift the flat (low-crease) areas toward white. This is\n // pose-dependent (it keys off dFdy(uv.y)), so we keep it gentle and add a robust term.\n col += (1.0 - crease) * 0.25 * uSheen;\n\n // Pose-robust roundness: shade by the camera-facing ratio of the derivative surface\n // normal so the ribbon reads as a rounded, grabbable solid from any angle. Grazing\n // edges darken into shadow (defining the rounded form), the body keeps its full colour,\n // and the most face-on sliver catches a soft highlight. uRoundness = strength.\n if (uRoundness > 0.001) {\n vec3 volN = normalize(cross(dFdx(vWorldPos), dFdy(vWorldPos)));\n float facing = abs(dot(volN, normalize(vViewDir))); // 1 = facing camera, 0 = edge-on\n col *= mix(1.0 - 0.6 * uRoundness, 1.0, facing); // deepen grazing edges → solid form\n col += smoothstep(0.65, 1.0, facing) * uRoundness * 0.18; // soft highlight on the facing body\n }\n\n // Optional positionable lights (our feature) — additive & gentle, on top of the\n // base shading so the default look is preserved. A finely-subdivided mesh\n // keeps this derivative normal smooth.\n if (uNumLights > 0) {\n vec3 N = normalize(cross(dFdx(vWorldPos), dFdy(vWorldPos)));\n vec3 Vd = normalize(vViewDir);\n if (dot(N, Vd) < 0.0) N = -N;\n for (int i = 0; i < MAX_LIGHTS; i++) {\n if (i >= uNumLights) break;\n vec3 L = normalize(uLightPos[i] - vWorldPos);\n vec3 lc = uLightColor[i] * uLightIntensity[i];\n float diff = max(dot(N, L), 0.0);\n float spec = pow(max(dot(N, normalize(L + Vd)), 0.0), 28.0);\n col += col * diff * lc * 0.16 + spec * lc * 0.10;\n }\n }\n col *= 0.55 + clamp(uAmbient, 0.0, 1.0); // overall level; default 0.45 => x1.0 (neutral)\n\n#ifdef DEPTH_TINT\n // Depth tint: fade far fragments toward a colour so a multi-wave stack gains atmospheric\n // separation — near strands keep their colour, far ones recede. Reuses the clip-space depth the\n // wireframe theme fades with (clamp(z*6), where 1 = far).\n col = mix(col, uDepthTintColor, clamp(vClipPosition.z * 6.0, 0.0, 1.0) * uDepthTint);\n#endif\n\n if (uTexture > 0.001) col *= 1.0 + (grainHash(vUv * 850.0) - 0.5) * uTexture * 0.25;\n\n // Soft long edges + optional viewport-edge fade. The edge softness is the hardcoded 0.1 by\n // default (literal branch → byte-identical); EDGE_FEATHER swaps in the uEdgeFeather knob only\n // when it differs, so razor-crisp or vapor-soft edges are both reachable.\n#ifdef EDGE_FEATHER\n float ribEdge =\n smoothstep(0.0, uEdgeFeather, vUv.y) * (1.0 - smoothstep(1.0 - uEdgeFeather, 1.0, vUv.y));\n#else\n float ribEdge = smoothstep(0.0, 0.1, vUv.y) * (1.0 - smoothstep(0.9, 1.0, vUv.y));\n#endif\n float alpha = uOpacity * ribEdge;\n if (uEdgeFade > 0.001) {\n vec2 sc = gl_FragCoord.xy / max(uResolution, vec2(1.0));\n float vig =\n smoothstep(0.0, uEdgeFade, sc.x) * (1.0 - smoothstep(1.0 - uEdgeFade, 1.0, sc.x)) *\n smoothstep(0.0, uEdgeFade, sc.y) * (1.0 - smoothstep(1.0 - uEdgeFade, 1.0, sc.y));\n alpha *= vig;\n }\n\n // Deep \"squared\" hero colour: formerly done by a framebuffer-squaring blend that REPLACED the\n // destination (punching holes at soft edges / where waves overlap). Squaring here + normal\n // premultiplied compositing (see applyBlendMode) keeps the deep colour and blends correctly.\n col = clamp(col, 0.0, 1.0);\n // Square colour AND alpha so the soft ribbon edges keep the crisp, thin feather of the original\n // squared-blend look — but now composited (premultiplied) rather than replace-blended, so they\n // no longer punch holes. Over an opaque background alpha² still resolves to fully opaque.\n if (uSquared > 0.5) { col *= col; alpha *= alpha; }\n gl_FragColor = vec4(col, alpha);\n#ifdef PREMULTIPLIED_ALPHA\n gl_FragColor.rgb *= gl_FragColor.a;\n#endif\n}\n`;\n\n// ---- Wireframe \"thin-line\" theme ----\n// The same wave geometry, but instead of a solid surface the colour is carved into fine\n// vertical lines (abs(sin(uv.x * lineAmount))) whose thickness scales with the screen-\n// space uv derivative, then mixed line<->background with a depth fade. Used by the dark\n// hero preset. hueShift takes degrees (radians() here) to match the light shader.\nexport const lineFragmentShader = /* glsl */ `\n#define MAX_COLORS ${MAX_COLORS}\n#define MAX_MESH_POINTS ${MAX_MESH_POINTS}\n#define PI 3.14159265359\n\n${simplex2d}\n\n${colorUniforms}\nuniform float uLineAmount; // default 425\nuniform float uLineThickness; // default 1\nuniform float uLineDerivativePower; // default 0.95\nuniform float uMaxWidth; // default 1232\nuniform vec3 uClearColor; // = page background colour (shown between the lines)\n\nvarying vec2 vUv;\nvarying vec4 vClipPosition;\n\n${colorFns}\n\nvoid main(){\n // Same 2D palette sample + colour ops as the solid theme.\n vec3 color = applyColorGrade(waveBaseColor(vUv));\n\n // Carve into fine vertical lines; thickness from the screen-space uv derivative.\n vec2 dy = dFdy(vUv);\n float lineThickness = uLineThickness * pow(abs(dy.x * uMaxWidth), uLineDerivativePower);\n float a = abs(sin(vUv.x * uLineAmount));\n a = smoothstep(lineThickness, 0.0, a);\n\n // Depth fade: the wave recedes into the background colour with depth. Watch the\n // argument order: clamp(0.0, 1.0, z*6) is a swapped-args trap — it clamps the\n // constant 0.0 into [1.0, z*6], i.e. min(1.0, z*6), which (with our ortho clip.z\n // range) collapses the whole wave to the background. The correct clamp(z*6, 0, 1)\n // gives the proper subtle far-end fade and thin-line look.\n float depthFade = clamp(vClipPosition.z * 6.0, 0.0, 1.0);\n color = mix(uClearColor, color, a * (1.0 - depthFade));\n if (uSquared > 0.5) color *= color; // deep \"squared\" look, now composited not replace-blended\n gl_FragColor = vec4(color, uOpacity);\n#ifdef PREMULTIPLIED_ALPHA\n gl_FragColor.rgb *= gl_FragColor.a;\n#endif\n}\n`;\n\n// ---- Post pass: viewport-edge soft-focus blur + dither grain ----\n\nexport const postVertexShader = /* glsl */ `\nvarying vec2 vUv;\nvoid main(){\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n`;\n\nexport const postFragmentShader = /* glsl */ `\nuniform sampler2D tDiffuse;\nuniform vec2 uResolution;\nuniform float uBlurAmount;\nuniform int uBlurSamples;\nuniform float uGrainAmount;\nuniform float uTime;\nvarying vec2 vUv;\n\nfloat random2(vec2 st){ return fract(sin(dot(st.xy, vec2(12.9898, 78.233))) * 43758.5453); }\n\n// Angular (spin) blur: rotate the sample coord around the centre and\n// accumulate — a tangential smear that grows toward the edges. Carries alpha so a\n// transparent background survives the post pass.\nvec4 blurAngular(sampler2D tex, vec2 uv, float angle, int samples){\n vec4 total = vec4(0.0);\n vec2 coord = uv - 0.5;\n float dist = 1.0 / float(samples);\n vec2 dir = vec2(cos(angle * dist), sin(angle * dist));\n mat2 rot = mat2(dir.x, dir.y, -dir.y, dir.x);\n for (int i = 0; i < 64; i++){\n if (i >= samples) break;\n total += texture2D(tex, coord + 0.5);\n coord = coord * rot; // row-vector order (coord * rot) sets the spin direction\n }\n return total * dist;\n}\n\nvoid main(){\n vec4 sceneColor = texture2D(tDiffuse, vUv);\n vec4 blurColor = blurAngular(tDiffuse, vUv, uBlurAmount, uBlurSamples);\n // blurPower: keep a sharp band weighted to the middle, blurring toward top & bottom.\n float blurPower = smoothstep(0.0, 0.7, vUv.y) - smoothstep(0.2, 1.0, vUv.y);\n vec4 color = mix(blurColor, sceneColor, blurPower);\n // Static film grain: keyed off gl_FragCoord only (no uTime), so it doesn't flicker.\n color.rgb += mix(uGrainAmount, -uGrainAmount, random2(gl_FragCoord.xy * 0.01)) * (4.0 / 255.0);\n gl_FragColor = color; // preserve alpha → transparent background works\n}\n`;\n"],"mappings":";;;;;;;;;;;;;;;AAqBA,MAAM,YAAuB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoC7B,MAAM,gBAA2B;;;;;;;;;;;;;;;;;;;;;;;;AA2BjC,MAAM,WAAsB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyF5B,MAAa,eAA0B;EACrC,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsGZ,MAAa,iBAA4B;;;;;;;EAOvC,UAAU;;EAEV,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAyCd,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmJX,MAAa,qBAAgC;;;;;EAK3C,UAAU;;EAEV,cAAc;;;;;;;;;;EAUd,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;AA6BX,MAAa,mBAA8B;;;;;;;AAQ3C,MAAa,qBAAgC"}
@@ -0,0 +1,58 @@
1
+ import { StudioConfig } from "../config/model.js";
2
+ import { WaveRenderer } from "../renderer/WaveRenderer.js";
3
+ import { core_loader_d_exports } from "../core-loader.js";
4
+
5
+ //#region src/shell/createWave.d.ts
6
+ /** Why the shell showed the poster instead of a live wave. */
7
+ type FallbackReason = "no-webgl" | "reduced-motion" | "save-data" | "context-lost" | "load-error";
8
+ /** poster → loading → running, or → fallback (permanent poster). */
9
+ type WaveState = "poster" | "loading" | "running" | "fallback";
10
+ /** The heavy module fetched on upgrade. */
11
+ type CoreModule = typeof core_loader_d_exports;
12
+ interface WaveOptions {
13
+ /** Poster URL / data-URI. Defaults to adopting the container's `<img data-wave3d-poster>` (SSR). */
14
+ poster?: string;
15
+ /** Wait until the container nears the viewport before fetching the engine. Default true. */
16
+ lazy?: boolean;
17
+ /** IntersectionObserver margin for the lazy trigger. Default "200px". */
18
+ rootMargin?: string;
19
+ /** "auto" probes WebGL (with failIfMajorPerformanceCaveat); "force" skips the probe; "off" stays a poster. */
20
+ webgl?: "auto" | "force" | "off";
21
+ /** Forward prefers-reduced-motion to the renderer (freezes to a full static frame). Default true. */
22
+ respectReducedMotion?: boolean;
23
+ /** With reduced motion: "static" upgrades to a frozen frame; "poster" stays a poster. Default "static". */
24
+ reducedMotionBehavior?: "static" | "poster";
25
+ /** Keep a permanent poster when the user has Save-Data on. Default true. */
26
+ respectSaveData?: boolean;
27
+ /** Poster→canvas crossfade duration (ms). Default 300. */
28
+ fadeMs?: number;
29
+ /** Start paused. */
30
+ paused?: boolean;
31
+ onReady?(renderer: WaveRenderer): void;
32
+ onFallback?(reason: FallbackReason): void;
33
+ onStateChange?(state: WaveState): void;
34
+ /** Seam for the standalone/CDN build to supply the core synchronously (three already bundled). */
35
+ loadCore?(): Promise<CoreModule>;
36
+ }
37
+ interface WaveHandle {
38
+ readonly state: WaveState;
39
+ readonly renderer: WaveRenderer | null;
40
+ /** Merge a partial config. Staged before upgrade; after, setConfig() then refreshPlayback(). */
41
+ set(config: Partial<StudioConfig>): void;
42
+ play(): void;
43
+ pause(): void;
44
+ /** Safe to call in any state (aborts a pending upgrade, disposes a live renderer, removes the poster). */
45
+ destroy(): void;
46
+ }
47
+ /**
48
+ * Mount a self-optimizing wave into a container: shows a poster immediately, then — lazily, and only
49
+ * when the browser can actually run it — fetches the engine, builds the renderer, and crossfades in.
50
+ * Falls back to the poster on no-WebGL / save-data / reduced-motion / context-loss / load errors.
51
+ * No static three import: the engine arrives via a dynamic import, so the shell stays tiny.
52
+ */
53
+ declare function createWave(container: HTMLElement, config?: Partial<StudioConfig>, options?: WaveOptions): WaveHandle;
54
+ /** The drop-in embed contract: an alias of {@link createWave}. */
55
+ declare const mountWave: typeof createWave;
56
+ //#endregion
57
+ export { FallbackReason, WaveHandle, WaveOptions, WaveState, createWave, mountWave };
58
+ //# sourceMappingURL=createWave.d.ts.map