Branchwell

PulseCanvas / app · pulsecanvas.ai / Sources / PulseCanvas / Resources / NativeExpansionCommon.metal

Raw 19.8 KB on 1cf89eeacc946d122aba3a62ada6cb1600fbf757
1#include <metal_stdlib>
2using namespace metal;
3
4// Preserve highlight intensity and coverage when projecting colored effects to grayscale.
5static float monochromeIntensity(float3 color) { return max(color.r, max(color.g, color.b)); }
6
7// PulseCanvas native effect prelude. Original procedural code: no external images,
8// preset equations or third-party shader sources. Classic mathematical forms are
9// implemented from their definitions. This file is prepended to every Native*.metal
10// effect file when the renderer compiles the native library.
11//
12// Layout matches NativeUniforms in VisualizerRenderer.swift. The first fields match
13// SpatialFrame so every native pass shares one uniform block.
14struct NativeFrame {
15 float2 resolution; float time; int scene;
16 float4 rhythm; // attack, drive, attack swell, raw treble (Chaos-scaled)
17 float4 style; // brightness, size, fog, camera zoom
18 float4 camera; // rotation, Chaos, detail, zoom speed
19 float4 colors[5];
20 float4 bands; // smoothed low, low-mid, high-mid, high (Chaos-scaled)
21 float4 motion; // zoom travel, music clock, procedural time, smoothed energy
22};
23
24// Everything an effect needs, already normalized. Every audio term is zero at zero Chaos.
25struct Ctx {
26 float2 uv; // centred, y up; the shorter canvas edge spans [-1, 1]
27 float2 screen; // 0...1 across the canvas
28 float2 extent; // half-size of the canvas in uv units (>= 1 on each axis)
29 float px; // one pixel in uv units
30 float t; // procedural time plus integrated percussion motion (Chaos-scaled)
31 float m; // music clock: advances faster in energetic passages
32 float e; // smoothed musical energy, 0...~1
33 float hit; // short attack envelope
34 float4 b; // smoothed bands: low, low-mid, high-mid, high
35 float travel; // integrated forward zoom distance
36 float size; // size control, 1 at default
37 float fog; // depth control, 0...1
38 float detail; // detail control, 0...1
39};
40
41constant float PI = 3.14159265;
42constant float TAU = 6.2831853;
43
44// ---------------------------------------------------------------- hashing / noise
45// Deterministic integer seeds authored for this catalog. Floating coordinates are
46// treated as IEEE-754 bits; +/- zero share one identity. The three independently
47// mixed coordinate words supply decorrelated channels without floating hash recipes.
48uint canvasSeed(uint word) {
49 word ^= word >> 13;
50 word *= 0xA3B19535u;
51 word ^= word >> 17;
52 word *= 0xD74F739Du;
53 word ^= word >> 11;
54 return word;
55}
56uint canvasWord(float coordinate) { return coordinate == 0 ? 0u : as_type<uint>(coordinate); }
57float canvasUnit(uint word) { return float(canvasSeed(word) >> 8) * (1.f / 16777216.f); }
58uint canvasPair(float2 p) { return canvasSeed(canvasWord(p.x) ^ 0x13A17C9Bu) ^ canvasWord(p.y); }
59uint canvasTriple(float3 p) { return canvasSeed(canvasPair(p.xy) ^ 0x7259B43Fu) ^ canvasWord(p.z); }
60float hash11(float p) { return canvasUnit(canvasWord(p) ^ 0x4B7CA815u); }
61float hash21(float2 p) { return canvasUnit(canvasPair(p)); }
62float2 hash22(float2 p) { uint seed = canvasPair(p); return float2(canvasUnit(seed), canvasUnit(seed ^ 0xF195ED47u)); }
63float3 hash33(float3 p) { uint seed = canvasTriple(p); return float3(canvasUnit(seed), canvasUnit(seed ^ 0xF195ED47u), canvasUnit(seed ^ 0x2DB67189u)); }
64float hash31(float3 p) { return canvasUnit(canvasTriple(p)); }
65
66float noise2(float2 p) {
67 float2 i = floor(p), f = fract(p), u = f * f * (3 - 2 * f);
68 return mix(mix(hash21(i), hash21(i + float2(1, 0)), u.x), mix(hash21(i + float2(0, 1)), hash21(i + 1), u.x), u.y);
69}
70float noise3(float3 p) {
71 float3 i = floor(p), f = fract(p), u = f * f * (3 - 2 * f);
72 float a = hash31(i), b = hash31(i + float3(1, 0, 0)), c = hash31(i + float3(0, 1, 0)), d = hash31(i + float3(1, 1, 0));
73 float e = hash31(i + float3(0, 0, 1)), g = hash31(i + float3(1, 0, 1)), h = hash31(i + float3(0, 1, 1)), k = hash31(i + 1);
74 return mix(mix(mix(a, b, u.x), mix(c, d, u.x), u.y), mix(mix(e, g, u.x), mix(h, k, u.x), u.y), u.z);
75}
76float fbm2(float2 p, int octaves) {
77 float sum = 0, amplitude = .5;
78 for (int i = 0; i < octaves; ++i) { sum += amplitude * noise2(p); p = float2(p.x * 1.6 - p.y * 1.2, p.x * 1.2 + p.y * 1.6) + 3.1; amplitude *= .5; }
79 return sum;
80}
81float fbm3(float3 p, int octaves) {
82 float sum = 0, amplitude = .5;
83 for (int i = 0; i < octaves; ++i) { sum += amplitude * noise3(p); p = p * 2.03 + float3(1.7, -3.1, 2.3); amplitude *= .5; }
84 return sum;
85}
86// Smooth divergence-free-looking flow from a noise potential.
87float2 curl2(float2 p) {
88 const float e = .05;
89 float a = noise2(p + float2(0, e)), b = noise2(p - float2(0, e));
90 float c = noise2(p + float2(e, 0)), d = noise2(p - float2(e, 0));
91 return float2(a - b, d - c) / (2 * e);
92}
93// Voronoi: x = nearest distance, y = second distance, zw = nearest cell id.
94float4 voronoi(float2 p, float jitter, float phase) {
95 float2 cell = floor(p), f = fract(p);
96 float first = 8, second = 8; float2 winner = 0;
97 for (int y = -1; y <= 1; ++y) for (int x = -1; x <= 1; ++x) {
98 float2 g = float2(x, y), seed = hash22(cell + g);
99 float2 site = g + .5 + jitter * .5 * sin(phase + seed * TAU);
100 float d = length(site - f);
101 if (d < first) { second = first; first = d; winner = cell + g; } else second = min(second, d);
102 }
103 return float4(first, second, winner);
104}
105
106// ---------------------------------------------------------------- geometry
107float2 rot(float2 p, float a) { float c = cos(a), s = sin(a); return float2(c * p.x - s * p.y, s * p.x + c * p.y); }
108float smin(float a, float b, float k) { float h = clamp(.5 + .5 * (b - a) / k, 0.f, 1.f); return mix(b, a, h) - k * h * (1 - h); }
109float smax(float a, float b, float k) { return -smin(-a, -b, k); }
110float sdBox(float3 p, float3 b) { float3 q = abs(p) - b; return length(max(q, 0.f)) + min(max(q.x, max(q.y, q.z)), 0.f); }
111float sdBox2(float2 p, float2 b) { float2 q = abs(p) - b; return length(max(q, 0.f)) + min(max(q.x, q.y), 0.f); }
112float sdTorus(float3 p, float2 t) { return length(float2(length(p.xz) - t.x, p.y)) - t.y; }
113float sdCapsule(float3 p, float3 a, float3 b, float r) { float3 pa = p - a, ba = b - a; float h = clamp(dot(pa, ba) / dot(ba, ba), 0.f, 1.f); return length(pa - ba * h) - r; }
114float sdSegment(float2 p, float2 a, float2 b) { float2 pa = p - a, ba = b - a; float h = clamp(dot(pa, ba) / max(dot(ba, ba), 1e-6f), 0.f, 1.f); return length(pa - ba * h); }
115float sdHex(float2 p, float r) { const float3 k = float3(-.8660254, .5, .57735); p = abs(p); p -= 2 * min(dot(k.xy, p), 0.f) * k.xy; p -= float2(clamp(p.x, -k.z * r, k.z * r), r); return length(p) * sign(p.y); }
116// Hexagonal tiling: xy = local offset, zw = cell id.
117float4 hexCell(float2 p) {
118 const float2 s = float2(1, 1.7320508);
119 float2 a = p - s * floor(p / s + .5), b = p - s * (floor((p - s * .5) / s + .5) + .5);
120 return dot(a, a) < dot(b, b) ? float4(a, round(p / s)) : float4(b, round((p - s * .5) / s) + .5);
121}
122// Repeat with a stable cell index.
123float repeatId(float x, float period) { return floor(x / period + .5); }
124
125// ---------------------------------------------------------------- shading
126float3 paint(float phase, constant NativeFrame &f) {
127 float cycle = phase - floor(phase * .5) * 2;
128 float x = (cycle < 1 ? cycle : 2 - cycle) * 4;
129 int i = min(3, int(x));
130 return mix(f.colors[i].rgb, f.colors[i + 1].rgb, x - float(i));
131}
132float3 deep(float phase, constant NativeFrame &f) { return paint(phase, f) * paint(phase + .5, f); }
133float glow(float d, float width) { return width * width / (width * width + d * d); }
134float line(float d, float width, float px) { return 1 - smoothstep(width - px, width + px, abs(d)); }
135float fill(float d, float px) { return 1 - smoothstep(-px, px, d); }
136float3 hsvTint(float3 color, float amount) { float l = dot(color, float3(.299, .587, .114)); return mix(float3(l), color, amount); }
137// Thin-film interference tint, used for soap, oil and opal colors; blended with the palette.
138float3 filmColor(float thickness, constant NativeFrame &f) {
139 float3 rainbow = .5 + .5 * cos(TAU * (thickness + float3(0, .33, .67)));
140 return mix(paint(thickness, f), rainbow * paint(thickness * .5 + .2, f) * 2, .45);
141}
142
143// ---------------------------------------------------------------- raymarch helpers
144float3 cameraRay(float2 uv, float3 forward, float3 up, float lens) {
145 float3 w = normalize(forward), u = normalize(cross(up, w)), v = cross(w, u);
146 return normalize(uv.x * u + uv.y * v + lens * w);
147}
148// Slot k (back to front) of a forward-moving stack of n layers. x = phase (0 far, 1 at
149// the viewer), y = a stable layer id that survives the wrap, so layers never pop.
150float2 layerSlot(int k, int n, float travel) {
151 float shift = travel * float(n);
152 return float2((float(k) + fract(shift)) / float(n), float(k) - floor(shift));
153}
154float layerFade(float phase) { return smoothstep(0.f, .22f, phase) * (1 - smoothstep(.8f, 1.f, phase)); }
155// Magnification for a layer: far layers are small and dense, near layers large.
156float layerScale(float phase, float range) { return exp2((1 - phase) * range); }
157// Seamless scale-space zoom for self-similar patterns: two octaves crossfade at weight 0.
158float2 octaveZoom(float travel, int octave) {
159 float z = fract(travel);
160 float weight = octave == 0 ? 1 - smoothstep(0.f, 1.f, z) : smoothstep(0.f, 1.f, z);
161 return float2(exp2(float(octave) - z), weight);
162}
163// Oblique camera over a ground plane; the horizon sits above the canvas so the plane
164// fills every aspect ratio. Returns ground x, forward distance and view distance.
165float3 groundView(float2 uv, float2 extent, float height, float margin) {
166 float horizon = extent.y + margin;
167 float depth = height / max(horizon - uv.y, 1e-3f);
168 return float3(uv.x * depth, depth, depth * length(float2(1, uv.x)));
169}
170
171// ---------------------------------------------------------------- context / output
172Ctx makeContext(float2 position, constant NativeFrame &f) {
173 Ctx c;
174 float2 res = max(f.resolution, float2(1));
175 float shortSide = min(res.x, res.y);
176 c.screen = position / res;
177 c.extent = res / shortSide;
178 float2 uv = (position - res * .5) / (shortSide * .5);
179 uv.y = -uv.y;
180 float zoom = clamp(f.style.w, .3f, 2.f);
181 c.uv = rot(uv, f.camera.x) / zoom;
182 c.extent /= zoom;
183 c.px = 2 / (shortSide * zoom);
184 c.travel = f.motion.x;
185 c.m = f.motion.y;
186 // Integrate measured percussion energy; never multiply absolute time by a
187 // changing amplitude, which would jump or reverse the animation on each beat.
188 c.t = f.motion.z + c.m * 3;
189 c.e = clamp(f.motion.w, 0.f, 1.5f);
190 c.hit = clamp(f.rhythm.x, 0.f, 1.f);
191 c.b = clamp(f.bands, 0.f, 1.f);
192 c.size = sqrt(clamp(f.style.y, .3f, 6.f));
193 c.fog = clamp(f.style.z, 0.f, 1.f);
194 c.detail = clamp(f.camera.z, 0.f, 1.f);
195 return c;
196}
197
198// Music moves each design's elements, never the picture as a whole. Every design gets one of
199// three motion styles for its family, so neighbouring designs move differently:
200// tunnels 0 wobble (the tube flexes in lobes that roll around it)
201// 1 twist (rings at different depths turn, so lines wind into spirals; all of 310–319)
202// 2 ripple (rings wave in and out as waves run down the bore)
203// flights 0 slither (lanes bend sideways in an S that runs toward the viewer)
204// 1 swell (the ground rolls in waves across the lanes)
205// 2 churn (turbulent ground)
206// fields 0 eddies, 1 rolling waves, 2 liquid flow
207// The attack swell keeps each beat moving for about a quarter second and the music's momentum
208// keeps everything moving between beats. All of it is zero at zero Chaos or in silence; higher
209// Chaos also raises the gain, so the slider reads as "more chaotic", not just "louder".
210// Second versions (370–389) and Coaster versions move exactly like the designs they come from.
211constant short secondVersionSources[20] = {336, 337, 339, 340, 341, 342, 343, 345, 346, 347, 348, 349, 351, 352, 353, 354, 355, 357, 358, 359};
212Ctx rhythmicSurface(Ctx c, constant NativeFrame &f, int design) {
213 int scene = design >= 370 && design <= 389 ? int(secondVersionSources[design - 370]) : design;
214 float variant = float((scene - 100) % 7);
215 // Material-lined tunnels (310–319) twist: their fine weaves and scales read best turning,
216 // and the encoder keeps their detail; everything else spreads across the three styles.
217 int style = scene >= 310 && scene <= 319 ? 1 : scene % 3;
218 float2 p = c.uv;
219 float chaos = clamp(f.camera.y, 0.f, 1.f);
220 float gain = .55 + chaos;
221 float beat = min(1.f, c.hit * .7 + clamp(f.rhythm.z, 0.f, 1.f) * .6);
222 float energy = c.e;
223 float bass = c.b.x, body = c.b.y, fine = .5 * (c.b.z + c.b.w);
224 // Slow turbulence shared by every style; its strength follows the music's energy.
225 float2 drift = curl2(p * 1.4 + float2(c.t * .05, -c.t * .04) + variant) * .3;
226 bool tunnel = (scene >= 245 && scene <= 279) || (scene >= 300 && scene <= 319) || (scene >= 360 && scene <= 369);
227 bool drive = (scene >= 200 && scene <= 209) || (scene >= 220 && scene <= 244) || (scene >= 330 && scene <= 339);
228 if (tunnel) {
229 float r = length(p), a = atan2(p.y, p.x);
230 float depth = log(max(r, 1e-3f));
231 float reach = smoothstep(.04f, .35f, r);
232 float2 radial = p / max(r, 1e-5f);
233 float push = 0, turn = 0;
234 if (style == 0) {
235 push = (beat * .5 + bass * .16 + energy * .1) * sin(a * (3 + variant) + depth * 2 - c.t * .45);
236 } else if (style == 1) {
237 turn = (beat * 1.1 + bass * .32 + energy * .25) * sin(depth * (3.5 + variant * .4) + beat * 6 - c.t * .4);
238 } else {
239 push = (beat * .32 + bass * .14 + energy * .08) * sin(depth * 6 - c.t * 1.6 + variant);
240 turn = body * .2 * sin(a * 3 - depth * 4 + c.t * .5);
241 }
242 turn += (body * .16 + fine * .1) * sin(a * 4 - depth * 6 + c.t * .6);
243 float2 q = rot(p, turn * gain * reach);
244 q += radial * push * gain * r / (1 + r);
245 c.uv = q + drift * energy * gain * .35 * reach;
246 } else if (drive) {
247 float lane = p.x * (2.4 + variant * .2);
248 if (style == 0) {
249 c.uv.x += (beat * .24 + bass * .1 + energy * .06) * gain * sin(p.y * 4 + beat * 6 + c.t * .5 + variant);
250 } else if (style == 1) {
251 c.uv.y += (beat * .2 + bass * .1 + energy * .05) * gain * sin(lane + p.y * 3 - c.t * .5);
252 } else {
253 c.uv += drift * (beat * .35 + bass * .12 + energy * .1) * gain;
254 }
255 c.uv.x += (body * .1 + fine * .1) * gain * sin(p.y * 5 + lane * .5 + c.t * .4);
256 c.uv += drift * energy * gain * .25;
257 } else {
258 if (style == 0) {
259 float2 q = p * (1.2 + variant * .1) + float2(c.t * .06, -c.t * .045);
260 c.uv += curl2(q) * .45 * (beat * .55 + bass * .18 + body * .12 + energy * .1) * gain;
261 } else if (style == 1) {
262 float2 wave = float2(sin(p.y * (3.2 + variant * .2) + p.x * 1.7 + c.t * .6),
263 cos(p.x * (3.8 + variant * .2) - p.y * 2.1 - c.t * .5));
264 c.uv += wave * float2(beat * .3 + bass * .12 + energy * .05, beat * .22 + body * .16 + energy * .05) * gain;
265 } else {
266 float2 flow = float2(fbm2(p * 1.3 + c.t * .08, 3), fbm2(p * 1.3 + 5.2 - c.t * .07, 3)) - .5;
267 c.uv += flow * (beat * .5 + bass * .2 + body * .14 + energy * .15) * gain;
268 }
269 c.uv += fine * .055 * gain * float2(sin(p.y * 13 - c.t), cos(p.x * 11 + c.t));
270 c.uv += drift * energy * gain * .3;
271 }
272 return c;
273}
274
275// ---------------------------------------------------------------- roller-coaster course
276// Coaster versions ride a real tube that winds through space instead of a straight bore. Each
277// pixel's ray is traced against a tube whose centreline bends away ahead of the camera; the design
278// is handed the wall's own coordinates (the angle around the tube and the depth along it) as
279// the uv a straight tunnel has there. The walls stay rigid: they sweep past while the far end
280// swings away around each bend and drops behind the wall on tight turns, the track climbs and
281// dives, and the camera banks into each turn. Mirrored in NativeCommon.metal.
282float2 coasterPath(float z, float seed) {
283 return float2(1.5 * sin(z * .3 + seed) + .6 * sin(z * .55 + seed * 2.3),
284 1.1 * sin(z * .26 + seed * 1.7 + 1.1) + .5 * sin(z * .5 + seed * .6));
285}
286float2 coasterSlope(float z, float seed) {
287 return float2(.45 * cos(z * .3 + seed) + .33 * cos(z * .55 + seed * 2.3),
288 .286 * cos(z * .26 + seed * 1.7 + 1.1) + .25 * cos(z * .5 + seed * .6));
289}
290// Distance from the tube's axis across its section: round, or square for box corridors.
291float coasterRadius(float2 q, bool square) { return square ? max(fabs(q.x), fabs(q.y)) : length(q); }
292// Where the ray is across the tube's section at depth z, relative to the bending centreline.
293float2 coasterLateral(float2 ray, float z, float along, float2 origin, float2 slope, float seed) {
294 return ray * z - (coasterPath(along + z, seed) - origin - slope * z);
295}
296Ctx coasterTube(Ctx c, float seed, float along, bool square) {
297 // The camera rides the centreline. Its view lags the track a little, so each turn swings
298 // the outer wall into view before the far end goes round it, and it banks into the turn.
299 float2 origin = coasterPath(along, seed), slope = coasterSlope(along - 1.2, seed);
300 float2 ray = rot(c.uv, -.3 * (coasterSlope(along + 4, seed).x - slope.x));
301 float spread = length(ray);
302 float z = .05, inside = .05, gap = 1;
303 float2 lateral = ray * z;
304 for (int i = 0; i < 40; ++i) {
305 lateral = coasterLateral(ray, z, along, origin, slope, seed);
306 gap = 1 - coasterRadius(lateral, square);
307 if (gap < 0) break;
308 inside = z;
309 if (gap < .002 || z > 60) break;
310 z += gap * .85 / (spread + min(2.f, .4f * z + .6f));
311 }
312 // A step can cross the wall: bisect between the last depth inside and the first outside.
313 if (gap < 0) {
314 float outside = z;
315 for (int i = 0; i < 6; ++i) {
316 z = .5 * (inside + outside);
317 lateral = coasterLateral(ray, z, along, origin, slope, seed);
318 if (coasterRadius(lateral, square) < 1) inside = z; else outside = z;
319 }
320 }
321 float2 uv = lateral / max(coasterRadius(lateral, square), 1e-4f) / z;
322 // Pixel footprint for anti-aliasing: walls bunch up on the inside of a turn.
323 c.px = clamp(max(length(dfdx(uv)), length(dfdy(uv))), c.px * .25f, c.px * 6);
324 c.uv = uv;
325 return c;
326}
327// The Coaster versions (390–455) ride the track of the design they come from.
328Ctx coasterRide(Ctx c, int source, bool box) { return coasterTube(c, float(source) * 1.37, c.travel * 2.4 + c.m * .8, box); }
329
330float4 finish(float3 color, float2 position, constant NativeFrame &f) {
331 color = max(color, float3(0)) * max(0.f, f.style.x);
332 color = 1 - exp(-color * 1.55);
333 // Static ordered dither keeps smooth gradients from banding in 8-bit video.
334 float dither = (hash21(floor(position)) - .5) / 255;
335 return float4(float3(monochromeIntensity(saturate(color + dither))), 1);
336}
337
338// Each effect is `float3 name(Ctx c, constant NativeFrame &f)`; this emits its fragment.
339#define NATIVE_EFFECT(name) \
340fragment float4 name##Fragment(float4 position [[position]], constant NativeFrame &f [[buffer(0)]]) { \
341 Ctx c = rhythmicSurface(makeContext(position.xy, f), f, f.scene); \
342 return finish(name(c, f), position.xy, f); \
343}
344// A design's Coaster version: the same design riding the roller-coaster course (box: square tube).
345#define NATIVE_COASTER(name, source, box) \
346fragment float4 name##CoasterFragment(float4 position [[position]], constant NativeFrame &f [[buffer(0)]]) { \
347 Ctx c = rhythmicSurface(coasterRide(makeContext(position.xy, f), source, box), f, source); \
348 return finish(name(c, f), position.xy, f); \
349}
350
351vertex float4 nativeVertex(uint id [[vertex_id]]) {
352 const float2 p[3] = {float2(-1, -1), float2(3, -1), float2(-1, 3)};
353 return float4(p[id], 0, 1);
354}