import { useEffect, useRef } from "react"; type Brush = { x: number; y: number; size: number; r: number; g: number; b: number; alpha: number; energy: number; curve: number; gx: number; gy: number; }; type FieldSample = { width: number; height: number; rgba: Uint8ClampedArray; fieldRgba: Uint8ClampedArray; luma: Float32Array; alpha: Float32Array; analysis: Float32Array; flowX: Float32Array; flowY: Float32Array; fieldStrength: Float32Array; }; type PyramidLevel = { width: number; height: number; values: Float32Array; energy: Float32Array; gx: Float32Array; gy: Float32Array; curve: Float32Array; }; const FIELD_SIZE = 256; const MAX_DEPTH = 6; const MIN_BRUSH_SIZE = 4; const ENERGY_SPLIT_THRESHOLD = 0.038; const PARTICLE_COUNT = new URLSearchParams(globalThis.location?.search ?? "").has("smoke") ? 24_576 : 196_608; const PARTICLE_STRIDE_FLOATS = 12; const MAX_NODE_ENVELOPES = 96; type NodeEnvelope = { id: string; x: number; y: number; radius: number; strength: number; }; type GraphViewportTransform = { x: number; y: number; scale: number; bounds: { x: number; y: number; width: number; height: number; }; }; const gpuParticleComputeShader = /* wgsl */ ` struct Particle { position: vec2f, velocity: vec2f, color: vec4f, seed: f32, size: f32, life: f32, pad: f32, }; struct SimUniforms { time: f32, dt: f32, width: f32, height: f32, particleCount: f32, flowGain: f32, alpha: f32, detail: f32, envelopeCount: f32, nodeGain: f32, worldX: f32, worldY: f32, worldWidth: f32, worldHeight: f32, viewX: f32, viewY: f32, viewScale: f32, pad1: f32, }; @group(0) @binding(0) var particles: array; @group(0) @binding(1) var uniforms: SimUniforms; @group(0) @binding(2) var fieldSampler: sampler; @group(0) @binding(3) var fieldTexture: texture_2d; @group(0) @binding(4) var nodeEnvelopes: array; fn hash(value: f32) -> f32 { return fract(sin(value * 12.9898) * 43758.5453); } fn hash2(cell: vec2f) -> f32 { return hash(dot(cell, vec2f(127.1, 311.7))); } fn wrap2(value: vec2f, size: vec2f) -> vec2f { return fract(value / size) * size; } fn proceduralCurl(point: vec2f, seed: f32) -> vec2f { let angle = sin(point.x * 0.011 + uniforms.time * 0.23 + seed * 6.28318) + cos(point.y * 0.017 - uniforms.time * 0.19 + seed * 4.71) + sin((point.x + point.y) * 0.006 + uniforms.time * 0.11) + sin(point.x * 0.041 + point.y * -0.032 + uniforms.time * 0.37 + seed); return vec2f(cos(angle * 3.14159), sin(angle * 3.14159)); } fn samplePacked(uv: vec2f) -> vec4f { return textureSampleLevel(fieldTexture, fieldSampler, clamp(uv, vec2f(0.001), vec2f(0.999)), 0.0); } fn channelGradient(uv: vec2f, channel: u32) -> vec2f { let step = vec2f(1.0 / 256.0, 1.0 / 256.0) / max(uniforms.detail, 1.0); let left = samplePacked(uv - vec2f(step.x, 0.0)); let right = samplePacked(uv + vec2f(step.x, 0.0)); let up = samplePacked(uv - vec2f(0.0, step.y)); let down = samplePacked(uv + vec2f(0.0, step.y)); if (channel == 2u) { return vec2f(right.b - left.b, down.b - up.b); } return vec2f(right.a - left.a, down.a - up.a); } @compute @workgroup_size(128) fn updateParticles(@builtin(global_invocation_id) id: vec3u) { let index = id.x; if (index >= u32(uniforms.particleCount)) { return; } var particle = particles[index]; let canvasSize = vec2f(max(uniforms.width, 1.0), max(uniforms.height, 1.0)); var position = particle.position * canvasSize; var uv = clamp(particle.position, vec2f(0.001), vec2f(0.999)); var packed = samplePacked(uv); let detail = clamp(uniforms.detail, 0.65, 4.0); let strengthGradient = channelGradient(uv, 3u); let curvatureGradient = channelGradient(uv, 2u); let tangent = normalize(vec2f(-curvatureGradient.y, curvatureGradient.x) + vec2f(0.001, 0.0)); let inward = normalize(strengthGradient + vec2f(0.001, 0.0)); let fieldVector = packed.rg * 2.0 - vec2f(1.0); let fieldVelocity = fieldVector * uniforms.flowGain * (0.34 + packed.a * 2.25) * detail; let turbulence = proceduralCurl(position * (0.82 + packed.b * 0.9), particle.seed) * (9.0 + packed.b * 36.0 + packed.a * 18.0) * detail; let ridgeSlip = tangent * (packed.b * 30.0 + packed.a * 18.0) * detail; let channelPull = inward * (packed.a * 24.0 + packed.b * 8.0); let cell = floor(position / max(12.0, 38.0 / detail)); let jitter = vec2f(hash2(cell + particle.seed), hash2(cell + vec2f(7.0, 13.0) + particle.seed)) - vec2f(0.5); var nodePush = vec2f(0.0); var nodeHeat = 0.0; for (var envelopeIndex = 0u; envelopeIndex < ${MAX_NODE_ENVELOPES}u; envelopeIndex = envelopeIndex + 1u) { if (f32(envelopeIndex) >= uniforms.envelopeCount) { break; } let envelope = nodeEnvelopes[envelopeIndex]; let delta = uv - envelope.xy; let radius = max(envelope.z, 0.008); let normalized = dot(delta, delta) / (radius * radius); let edge = exp(-4.0); let gaussian = exp(-4.0 * normalized); let influence = pow(clamp((gaussian - edge) / max(1.0 - edge, 0.000001), 0.0, 1.0), 0.78) * envelope.w * uniforms.nodeGain; let away = normalize(delta + vec2f(0.0001, 0.0)); let swirl = vec2f(-away.y, away.x); nodePush += (swirl * 34.0 + away * 18.0) * influence; nodeHeat += influence; } let velocity = fieldVelocity + turbulence + ridgeSlip + channelPull + nodePush + jitter * (5.0 + packed.a * 18.0) * detail; position = wrap2(position + velocity * uniforms.dt, canvasSize); uv = position / canvasSize; packed = samplePacked(uv); let density = clamp(packed.a * 0.76 + packed.b * 0.54, 0.0, 1.0); let die = hash(particle.seed * 91.7 + floor(uniforms.time * (7.0 + detail * 5.0))); if (density < 0.10 && die > density + 0.34) { let respawnSeed = particle.seed + uniforms.time * 0.071 + f32(index) * 0.000013; let angle = respawnSeed * 6.28318; let radius = sqrt(hash(respawnSeed * 31.0)) * (0.46 - min(packed.a, 0.32) * 0.28); let center = vec2f(0.5) + vec2f(cos(angle), sin(angle)) * radius; let micro = vec2f(hash(respawnSeed * 47.0), hash(respawnSeed * 59.0)) - vec2f(0.5); uv = clamp(center + micro * (0.18 / detail), vec2f(0.001), vec2f(0.999)); position = uv * canvasSize; packed = samplePacked(uv); } particle.position = uv; particle.velocity = velocity; particle.life = fract(particle.life + uniforms.dt * (0.08 + packed.a * 0.18 + packed.b * 0.11 + hash(particle.seed * 23.0) * 0.07) * detail); let speed = clamp(length(velocity) / (96.0 + detail * 26.0), 0.0, 1.0); let flowAxis = abs(fieldVector.x - fieldVector.y); let heat = clamp(packed.a * 0.92 + packed.b * 0.86 + speed * 0.48 + nodeHeat * 0.62, 0.0, 1.0); let brass = clamp((packed.b - packed.a * 0.32) * 1.35 + flowAxis * 0.18, 0.0, 1.0); let cyan = vec3f(0.08 + heat * 0.28, 0.44 + heat * 0.46, 0.52 + heat * 0.62); let gold = vec3f(0.86, 0.58, 0.22); let deep = vec3f(0.02, 0.10, 0.12); let rgb = mix(mix(deep, cyan, 0.42 + heat * 0.58), gold, brass * 0.32); particle.color = vec4f( rgb, uniforms.alpha * (0.004 + heat * 0.018 + density * 0.012 + nodeHeat * 0.014) * (0.72 + detail * 0.11) ); particle.size = (0.52 + hash(particle.seed * 19.0) * 1.85) * (0.58 + packed.a * 1.25 + packed.b * 0.62 + nodeHeat * 0.44) * (0.92 + detail * 0.12) * (1.0 - abs(particle.life - 0.5) * 0.42); particles[index] = particle; } `; const gpuParticleRenderShader = /* wgsl */ ` struct Particle { position: vec2f, velocity: vec2f, color: vec4f, seed: f32, size: f32, life: f32, pad: f32, }; struct SimUniforms { time: f32, dt: f32, width: f32, height: f32, particleCount: f32, flowGain: f32, alpha: f32, detail: f32, envelopeCount: f32, nodeGain: f32, worldX: f32, worldY: f32, worldWidth: f32, worldHeight: f32, viewX: f32, viewY: f32, viewScale: f32, pad1: f32, }; @group(0) @binding(0) var renderParticles: array; @group(0) @binding(1) var renderUniforms: SimUniforms; struct VertexOut { @builtin(position) position: vec4f, @location(0) color: vec4f, @location(1) local: vec2f, }; @vertex fn vertexMain(@builtin(vertex_index) vertexIndex: u32, @builtin(instance_index) instanceIndex: u32) -> VertexOut { let corners = array( vec2f(-1.0, -1.0), vec2f(1.0, -1.0), vec2f(-1.0, 1.0), vec2f(-1.0, 1.0), vec2f(1.0, -1.0), vec2f(1.0, 1.0) ); let particle = renderParticles[instanceIndex]; let local = corners[vertexIndex]; let direction = normalize(particle.velocity + vec2f(0.001, 0.0)); let tangent = vec2f(-direction.y, direction.x); let stretch = clamp(length(particle.velocity) / 92.0, 0.0, 2.1); let ellipse = direction * local.x * particle.size * (1.0 + stretch * 0.48) + tangent * local.y * particle.size * (0.74 + renderUniforms.detail * 0.035); let world = vec2f(renderUniforms.worldX, renderUniforms.worldY) + particle.position * vec2f(renderUniforms.worldWidth, renderUniforms.worldHeight); let viewScale = max(renderUniforms.viewScale, 0.05); let basePosition = vec2f(renderUniforms.viewX, renderUniforms.viewY) + world * viewScale; let pixelPosition = basePosition + ellipse * sqrt(viewScale); var out: VertexOut; out.position = vec4f((pixelPosition.x / renderUniforms.width) * 2.0 - 1.0, 1.0 - (pixelPosition.y / renderUniforms.height) * 2.0, 0.0, 1.0); out.color = particle.color * (1.0 - abs(particle.life - 0.5) * 0.44); out.local = local; return out; } @fragment fn fragmentMain(input: VertexOut) -> @location(0) vec4f { let radius2 = dot(input.local, input.local); let falloff = 5.1 + renderUniforms.detail * 0.52; let edge = exp(-falloff); let gaussian = exp(-falloff * radius2); let compact = pow(clamp((gaussian - edge) / max(1.0 - edge, 0.000001), 0.0, 1.0), 0.72); let core = exp(-radius2 * 18.0) * 0.42; return vec4f(input.color.rgb * (compact * 1.52 + core), input.color.a * compact); } `; type HuginnFieldCanvasProps = { imageUrl: string; fieldUrl: string; }; export function HuginnFieldCanvas({ imageUrl, fieldUrl }: HuginnFieldCanvasProps) { const canvasRef = useRef(null); useEffect(() => { const canvas = canvasRef.current; if (!canvas) { return; } let cancelled = false; const render = async () => { try { const [image, fieldImage] = await Promise.all([ loadImage(imageUrl), loadImage(fieldUrl), ]); if (cancelled) { return; } const sample = sampleImage(image, fieldImage); const gpuCleanup = await startGpuParticleField(canvas, sample); if (gpuCleanup) { console.info("Huginn WebGPU particle field active."); return gpuCleanup; } console.info("Huginn WebGPU unavailable; using canvas field fallback."); const pyramid = buildCurvaturePyramid(sample); const brushes = buildBrushes(sample, pyramid); const observer = new ResizeObserver(() => drawFieldFallback(canvas, brushes, sample)); observer.observe(canvas); drawFieldFallback(canvas, brushes, sample); return () => observer.disconnect(); } catch { return; } }; let cleanup: (() => void) | undefined; void render().then((nextCleanup) => { cleanup = nextCleanup; }); return () => { cancelled = true; cleanup?.(); }; }, [fieldUrl, imageUrl]); return