/** * Zero-readback WebGPU 3D renderer for Soft Roam 3D (/softroam3d/). * * Reads ONLY the three GPU storage buffers in `Roam3dRenderSource` (`cells`, `floorFood`, `waterFood`): * no per-frame CPU readback and no per-frame CPU geometry construction. `waterFood` is read on the field grid * (`dims.fx, fy, fz`, voxels of `dims.fieldTiles` tiles), never on the 2-tile hash buckets (`cx, cy, cz`). * * Each frame is one command buffer: * 0. Prep (compute, skipped when `opts.dataVersion` has not changed since this source was last prepped): * - `prepVolume` writes `waterFood` into a renderer-owned `rgba16float` 3D texture of * `min(fx, 128) × min(fy, 128) × min(fz, 128)` texels (a box average when a field axis is longer than 128), * in units of a 2-tile voxel's food (the scale the haze was calibrated on) times `snowGain` (1 at fieldTiles 2, * see ROAM3D_SNOW_GAIN_EXP), and the max of every 8³-texel brick * with a 1-texel halo (so a brick at 0 means every trilinear sample inside it is exactly 0). * - `prepColumns` sums each `waterFood` column into `colSum` (one u32 per field column) for the floor shadow. * - `prepCompactCount` + `prepCompactScatter` (skipped when neither the data version nor the peel/slice planes have * changed) compact the cell slots into three index lists in strictly ascending slot order, one per instanced draw * (spheres, bonds, shadows), with the same tests the vertex shaders apply, and write the three `drawIndirect` * argument records. Two dispatches for all three lists: per-workgroup counts (512 slots each, so at most 256 * workgroups at `cap` 131,072), then a scatter that scans those counts in shared memory. Ascending slot order keeps * every draw's instance order (and so the blended shadows and depth ties) exactly as drawing every slot did. * 1. Opaque scene target (`rgba16float` + `depth32float`): * - Floor & soft column shadows: floor quad at y = 0 shaded by manual bilinear `floorFood`, a grid of 16-tile * squares, and the overhead `colSum` attenuation; then instanced soft radial cell shadows projected straight * down (none for cells more than 64 tiles up). * - Spheres & bonds: instanced sphere impostors (the compacted list, drawn indirect) with * exact perspective ray-sphere intersection and `frag_depth`, coloured by cell kind and a hash of the `root` * slot with `store` as brightness (radius optionally held to `opts.minPixelRadius` pixels); then instanced * camera-facing bond ribbons from each live cell to its `mother` slot (skipped when `mother < 0`, mother dead, * clipped, or crossing the x/z wrap seam). * 2. Volumetric composite to the output target (`format`): full-screen front-to-back raymarch through the volume * texture (hardware trilinear, repeat in x/z, clamped in y), composited against the opaque `sceneDepth` and * `sceneColor`, with analytic glass tank edges, Fresnel rim, and optional top peel / south slice planes. With * empty-space skipping on (default only when a texture side exceeds 64; `opts.skipEmpty` overrides) a step that * lands in an empty brick crosses the whole brick in one water-only segment. * * Per-world resources (volume texture, `colSum`, bricks, the three index lists, their workgroup sums and indirect * arguments, bind groups) are a set made by `stageSource`/`setSource`. * At most one staged set is held: staging again destroys the previous staged set, committing destroys the old active * set, and `destroy()` frees both. */ import { R3_RENDER_STRIDE, type Roam3dDims, type Roam3dRenderSource } from '@bl/softroam3d-ref'; import { Disposer } from '../volume3d/approaches/disposer.ts'; import { Roam3dCamera, type Roam3dCameraMatrices } from './camera.ts'; export interface Roam3dRenderOpts { /** Fraction of tank height peeled from the surface down, in [0, 0.95]. Default 0. */ peel?: number; /** Fraction of tank depth kept from the north wall (z = 0), in [0.05, 1]. Default 1. */ slice?: number; /** Volumetric marine-snow and water haze intensity, in [0, 1.5]. Default 0.75. */ haze?: number; /** Soft bioluminescent body glow and dual-scale HDR bloom intensity, in [0, 1.5]. Default 1.0. */ glow?: number; /** Continuous animation clock in seconds (drives cell breathing, jaw flexing, and nutrient pulses). Ignored (0) when `still` is true. */ time?: number; /** Draw glass tank edges and Fresnel rim. Default true. */ glass?: boolean; /** Raymarch samples per coarse voxel. Default 1.0. */ detail?: number; /** Cell radius multiplier (1.0 = exact 1024-unit diameter). Default 1.0. */ cellScale?: number; /** Disable per-frame raymarch jitter phase shift for deterministic captures/tests. Default false. */ still?: boolean; /** Optional offscreen output texture (used by headless Deno tests when canvasContext is null). */ target?: GPUTexture; /** * Version of the source's buffer contents. When given and equal to the version this source was last prepped at, * the frame skips `prepVolume` and `prepColumns` (camera-only redraws), and the instance compaction too unless the * peel or slice changed. Absent: prep and compact every frame. */ dataVersion?: number; /** Smallest on-screen cell radius in pixels (sphere billboard and ray-sphere radius both). Default 0 (off). */ minPixelRadius?: number; /** Empty-brick skipping in the haze raymarch. Default: on only when a volume texture side exceeds 64 texels. */ skipEmpty?: boolean; /** * Per-pass GPU timestamps: writes ROAM3D_TIMING_SLOTS queries from `first` (prep begin/end, opaque begin/end, haze * begin/end). The prep pass holds the volume/column prep and the instance compaction, whichever run; when neither * runs it writes nothing to its two slots. Needs a device with `timestamp-query`. */ timing?: { querySet: GPUQuerySet; first?: number }; } export interface Roam3dRenderer { render(camera: Roam3dCamera | Roam3dCameraMatrices, opts?: Roam3dRenderOpts): void; /** Rebind the renderer to a different `Roam3dRenderSource` (e.g. when switching CPU worker to GPU twin). */ setSource(source: Roam3dRenderSource): void; /** * Build bind groups for `source` without mutating active draw state; returns a commit function * that swaps them in only after caller-side WebGPU validation succeeds. */ stageSource?(source: Roam3dRenderSource): () => void; /** Free any staged source built by `stageSource` without swapping it in (e.g. on validation or OOM rollback). */ discardStagedSource?(): void; resize(w: number, h: number): void; destroy(): void; /** Returns WGSL compilation error messages across all shader modules (empty array when all are valid). */ checkShaders(): Promise; } /** * Display calibration scales against the real Phase A default aquarium (`defaultRoam3dConfig()`): * - `waterFood` non-zero voxels: fresh snow ~90–140, sinking plumes p50 ~5–16 / p90 ~34–53, peaks ~250–357. * - `floorFood` non-zero tiles: p50 ~2–11, p90 ~7–29, p99 ~35–42, peaks ~46–86. * - Cell `store`: `minStore = 16`, divides at `2 * birthStore = 200`, `cap4 = 400`, median ~150–160. */ export const ROAM3D_WATER_FOOD_SCALE = 120; export const ROAM3D_FLOOR_FOOD_SCALE = 32; export const ROAM3D_STORE_SCALE = 200; export const ROAM3D_MAX_RAY_STEPS = 256; /** * Haze gain on the volume texels in worlds with coarse fields (`fieldTiles > 2`): `(fieldTiles / 2) ** 3`, which undoes * `volScale`'s 2-tile-voxel dilution so a texel shows its field voxel's food as is. Every preset cube is a 64^3 field * grid, so a texel is 1/64 of the box side in each of them and the snow reads per screen volume alike: 8 at cube256, * 64 at cube512, 1 (unchanged) for the tank and cube128. Measured at step 3000 (seed 1, 640x480 oblique): the snow moved * the frame by a mean 0.16/255 in cube256 and 0.04/255 in cube512 before (0.55 in cube128), 0.87 and 1.72 with it. The * big cubes also hold less food per tile^3 than cube128 (about 12x less at cube512), which the gain does not hide: it * only stops the display from diluting it a second time. The floor column shadow (`colScale`, `opts.y`) is unchanged. */ export const ROAM3D_SNOW_GAIN_EXP = 3; /** Largest volume texture side; a longer field axis is box-averaged down by a power of two. */ export const ROAM3D_VOLUME_MAX_SIDE = 128; /** Side of an empty-space brick, in volume texels. */ export const ROAM3D_BRICK = 8; /** Timestamp queries `opts.timing` writes per frame. */ export const ROAM3D_TIMING_SLOTS = 6; /** Cell slots per instance-compaction workgroup (256 threads, two slots each). */ export const ROAM3D_COMPACT_PER_WG = 512; /** Largest `cap` the two-dispatch compaction scans: 256 workgroups of 512, whose sums fit one workgroup's scan. */ export const ROAM3D_COMPACT_MAX_CAP = 256 * ROAM3D_COMPACT_PER_WG; /** Byte offsets of the three `drawIndirect` records (vertexCount 6, instanceCount, 0, 0) in the indirect buffer. */ export const ROAM3D_INDIRECT = { sphere: 0, bond: 16, shadow: 32, bytes: 48 } as const; /** Workgroups of the instance compaction for `cap` slots (each scans ROAM3D_COMPACT_PER_WG). */ export function roam3dCompactGroups(cap: number): number { return Math.ceil(cap / ROAM3D_COMPACT_PER_WG); } /** The renderer's per-world grid sizes, derived from the field grid only. */ export interface Roam3dVolumeLayout { /** Volume texture size in texels. */ tex: [number, number, number]; /** Field voxels averaged into one texel along each axis (1 unless the field axis is longer than 128). */ factor: [number, number, number]; /** Bricks of ROAM3D_BRICK texels along each axis, and in all. */ bricks: [number, number, number]; brickCount: number; /** Field columns (fx * fz): `colSum` entries. */ columns: number; /** Texel = field food sum times this: averages the box and puts it in 2-tile-voxel units (1 at fieldTiles 2). */ volScale: number; /** Column sums are multiplied by this for the floor shadow: 2-tile-column units (1 at fieldTiles 2). */ colScale: number; /** Haze-only display gain on the texels (volume texture and bricks), 1 at fieldTiles 2: see ROAM3D_SNOW_GAIN_EXP. */ snowGain: number; /** Bytes of the volume texture (8 per rgba16float texel). */ textureBytes: number; } export function roam3dVolumeLayout(dims: Pick): Roam3dVolumeLayout { const tex: [number, number, number] = [ Math.min(dims.fx, ROAM3D_VOLUME_MAX_SIDE), Math.min(dims.fy, ROAM3D_VOLUME_MAX_SIDE), Math.min(dims.fz, ROAM3D_VOLUME_MAX_SIDE), ]; const factor: [number, number, number] = [dims.fx / tex[0], dims.fy / tex[1], dims.fz / tex[2]]; const bricks: [number, number, number] = [ Math.ceil(tex[0] / ROAM3D_BRICK), Math.ceil(tex[1] / ROAM3D_BRICK), Math.ceil(tex[2] / ROAM3D_BRICK), ]; const t = dims.fieldTiles / 2; return { tex, factor, bricks, brickCount: bricks[0] * bricks[1] * bricks[2], columns: dims.fx * dims.fz, volScale: 1 / (factor[0] * factor[1] * factor[2] * t * t * t), colScale: 1 / (t * t), snowGain: dims.fieldTiles > 2 ? Math.pow(t, ROAM3D_SNOW_GAIN_EXP) : 1, textureBytes: tex[0] * tex[1] * tex[2] * 8, }; } /** Default for `opts.skipEmpty`: on only when a volume texture side exceeds 64 texels (never for the tank). */ export function roam3dSkipEmptyDefault(layout: Pick): boolean { return Math.max(layout.tex[0], layout.tex[1], layout.tex[2]) > 64; } /** * Device limits the renderer needs for a world, named as WebGPU limits (everything else stays at the spec default): * the largest storage binding it reads (cells or the field), its storage buffers per stage, and the 3D texture side. */ export function roam3dRendererNeeds(dims: Roam3dDims): Record { const layout = roam3dVolumeLayout(dims); const biggest = Math.max(dims.cap * R3_RENDER_STRIDE * 4, dims.fieldCount * 4, dims.floorCount * 4); return { maxStorageBufferBindingSize: biggest, maxBufferSize: biggest, // The instance compaction reads cells and writes three index lists, the workgroup sums and the indirect args. maxStorageBuffersPerShaderStage: 6, maxTextureDimension3D: Math.max(...layout.tex), }; } /** Effective volumetric raymarch step length, ensuring `ROAM3D_MAX_RAY_STEPS` covers `spanLen` at every detail setting. */ export function raymarchStepLength(voxLen: number, detail: number, spanLen: number): number { const requested = Math.max(voxLen / Math.max(detail, 0.25), 0.004); return Math.max(requested, Math.max(0, spanLen) / (ROAM3D_MAX_RAY_STEPS - 1)); } const SCENE_COLOR_FORMAT: GPUTextureFormat = 'rgba16float'; const SCENE_DEPTH_FORMAT: GPUTextureFormat = 'depth32float'; const VOLUME_FORMAT: GPUTextureFormat = 'rgba16float'; const UNIFORM_BYTES = 84 * 4; // 336 bytes, strictly 16-byte aligned // WebGPU GPUShaderStage bit values (spec constants, safe to import in Node/Vitest without WebGPU globals). const STAGE_VERTEX = 0x1; const STAGE_FRAGMENT = 0x2; const STAGE_COMPUTE = 0x4; const STAGE_VF = STAGE_VERTEX | STAGE_FRAGMENT; // WebGPU usage bits (spec constants), so the renderer also builds against fake devices in Node. const BUF_STORAGE = 0x80; const BUF_COPY_DST = 0x8; const BUF_INDIRECT = 0x100; const TEX_TEXTURE_BINDING = 0x4; const TEX_STORAGE_BINDING = 0x8; /** Declared bind-group layouts per stage; exported so unit tests can audit them against WGSL sources. */ export const ROAM3D_BINDINGS = { /** 1 cells, 2 this draw's compacted slot list. */ cells: [ { binding: 0, visibility: STAGE_VF, buffer: { type: 'uniform' as const } }, { binding: 1, visibility: STAGE_VERTEX, buffer: { type: 'read-only-storage' as const } }, { binding: 2, visibility: STAGE_VERTEX, buffer: { type: 'read-only-storage' as const } }, ], /** 1 floorFood, 2 colSum. */ floor: [ { binding: 0, visibility: STAGE_VF, buffer: { type: 'uniform' as const } }, { binding: 1, visibility: STAGE_FRAGMENT, buffer: { type: 'read-only-storage' as const } }, { binding: 2, visibility: STAGE_FRAGMENT, buffer: { type: 'read-only-storage' as const } }, ], /** 1 bricks, 2 scene colour, 3 scene depth, 4 volume texture, 5 its trilinear sampler, 6-7 bloom mip textures, 8 bloom sampler. */ haze: [ { binding: 0, visibility: STAGE_FRAGMENT, buffer: { type: 'uniform' as const } }, { binding: 1, visibility: STAGE_FRAGMENT, buffer: { type: 'read-only-storage' as const } }, { binding: 2, visibility: STAGE_FRAGMENT, texture: { sampleType: 'unfilterable-float' as const } }, { binding: 3, visibility: STAGE_FRAGMENT, texture: { sampleType: 'depth' as const } }, { binding: 4, visibility: STAGE_FRAGMENT, texture: { sampleType: 'float' as const, viewDimension: '3d' as const } }, { binding: 5, visibility: STAGE_FRAGMENT, sampler: { type: 'filtering' as const } }, { binding: 6, visibility: STAGE_FRAGMENT, texture: { sampleType: 'float' as const } }, { binding: 7, visibility: STAGE_FRAGMENT, texture: { sampleType: 'float' as const } }, { binding: 8, visibility: STAGE_FRAGMENT, sampler: { type: 'filtering' as const } }, ], /** 0 source HDR texture, 1 linear clamp sampler (dual-scale separable glow bloom). */ bloom: [ { binding: 0, visibility: STAGE_FRAGMENT, texture: { sampleType: 'float' as const } }, { binding: 1, visibility: STAGE_FRAGMENT, sampler: { type: 'filtering' as const } }, ], /** 1 waterFood, 2 volume texture (write), 3 bricks (atomic max), 4 colSum. */ prep: [ { binding: 0, visibility: STAGE_COMPUTE, buffer: { type: 'uniform' as const } }, { binding: 1, visibility: STAGE_COMPUTE, buffer: { type: 'read-only-storage' as const } }, { binding: 2, visibility: STAGE_COMPUTE, storageTexture: { access: 'write-only' as const, format: 'rgba16float' as const, viewDimension: '3d' as const }, }, { binding: 3, visibility: STAGE_COMPUTE, buffer: { type: 'storage' as const } }, { binding: 4, visibility: STAGE_COMPUTE, buffer: { type: 'storage' as const } }, ], /** 1 cells, 2 sphere list, 3 bond list, 4 shadow list, 5 per-workgroup sums, 6 drawIndirect args. */ compact: [ { binding: 0, visibility: STAGE_COMPUTE, buffer: { type: 'uniform' as const } }, { binding: 1, visibility: STAGE_COMPUTE, buffer: { type: 'read-only-storage' as const } }, { binding: 2, visibility: STAGE_COMPUTE, buffer: { type: 'storage' as const } }, { binding: 3, visibility: STAGE_COMPUTE, buffer: { type: 'storage' as const } }, { binding: 4, visibility: STAGE_COMPUTE, buffer: { type: 'storage' as const } }, { binding: 5, visibility: STAGE_COMPUTE, buffer: { type: 'storage' as const } }, { binding: 6, visibility: STAGE_COMPUTE, buffer: { type: 'storage' as const } }, ], } as const; const COMMON_WGSL = /* wgsl */ ` struct Uniforms { viewProj: mat4x4, invViewProj: mat4x4, right: vec4, // xyz = camera right, w = viewport width px up: vec4, // xyz = camera up, w = viewport height px back: vec4, // xyz = camera back, w = world cell radius eye: vec4, // xyz = camera eye, w = frame index ext: vec4, // xyz = box extent (1, height/size, 1), w = 1 / spanXZ vis: vec4, // xyz = visible max (peel/slice), w = clipped flag (0 or 1) bg: vec4, // rgb = backdrop tint, w = glass on (0 or 1) opts: vec4, // x = haze strength, y = water food norm, z = floor food norm, w = detail dims0: vec4, // x = size, y = height, z = cap, w = spanXZ dims1: vec4, // xyz = volume texture texels, w = spanY dims2: vec4, // xyz = field voxels (fx, fy, fz), w = flags (bit 0: skip empty bricks) opts2: vec4, // x = min pixel radius, y = pixels per world unit at view depth 1, z = volume scale, w = column scale opts3: vec4, // x = body glow strength, y = animation time (seconds), zw = reserved }; @group(0) @binding(0) var u: Uniforms; const CELL_STRIDE: u32 = ${R3_RENDER_STRIDE}u; const SUN_DIR: vec3 = vec3(0.273861, 0.899830, 0.244519); // normalized (0.28, 0.92, 0.25) fn hashU32(x_in: u32) -> u32 { var h: u32 = (x_in ^ 0x9e3779b1u) * 0x85ebca6bu; h = h ^ (h >> 16u); h = h * 0x7feb352du; h = h ^ (h >> 15u); h = h * 0x846ca68bu; h = h ^ (h >> 16u); return h; } fn hsvToRgb(h: f32, s: f32, v: f32) -> vec3 { let k = vec3(1.0, 2.0 / 3.0, 1.0 / 3.0); let p = abs(fract(vec3(h) + k) * 6.0 - vec3(3.0)); return v * mix(vec3(1.0), clamp(p - vec3(1.0), vec3(0.0), vec3(1.0)), s); } fn bodyBaseColor(rootSlot: u32) -> vec3 { let h = hashU32(rootSlot + 17u); let hue = f32(h & 0xffffu) / 65536.0; let sat = 0.56 + 0.24 * (f32((h >> 16u) & 0xffu) / 255.0); let val = 0.78 + 0.16 * (f32((h >> 24u) & 0xffu) / 255.0); return hsvToRgb(hue, sat, val); } fn cellAlbedo(kind: u32, rootSlot: u32) -> vec3 { let body = bodyBaseColor(rootSlot); if (kind == 1u) { // Shell: pale bone armour softly tinted by body identity return mix(vec3(0.90, 0.88, 0.80), body, 0.16); } if (kind == 2u) { // Mouth: warm rose-crimson return mix(vec3(0.94, 0.34, 0.28), body, 0.18); } // Plain cell (Phase A has only kinds 0 plain, 1 shell, 2 mouth) return body; } `; export const SPHERE_WGSL = /* wgsl */ `${COMMON_WGSL} @group(0) @binding(1) var cells: array; @group(0) @binding(2) var indices: array; // this draw's compacted slots, ascending struct VOut { @builtin(position) clipPos: vec4, @location(0) worldPos: vec3, @location(1) @interpolate(flat) center: vec3, @location(2) @interpolate(flat) col: vec3, @location(3) @interpolate(flat) props: vec4, // x = radius, y = kind (0/1/2), z = brightness, w = energy @location(4) @interpolate(flat) axis: vec3, // unit anatomical forward axis (away from mother) @location(5) @interpolate(flat) anim: vec3, // x = cid phase [0, 2pi), y = projected px radius, z = hasMother (0/1) }; @vertex fn vs(@builtin(vertex_index) vi: u32, @builtin(instance_index) ii: u32) -> VOut { var out: VOut; out.clipPos = vec4(2.0, 2.0, 2.0, 1.0); out.worldPos = vec3(0.0); out.center = vec3(0.0); out.col = vec3(0.0); out.props = vec4(0.0); out.axis = vec3(0.0, 1.0, 0.0); out.anim = vec3(0.0); // The compaction already applied every test below; they stay so a list can only skip work, never add an instance. let slot = indices[ii]; if (slot >= u.dims0.z) { return out; } let base = slot * CELL_STRIDE; let flags = cells[base + 3u]; if ((flags & 1i) == 0i) { return out; } let ix = cells[base + 0u]; let iy = cells[base + 1u]; let iz = cells[base + 2u]; let center = vec3(f32(ix), f32(iy), f32(iz)) * u.ext.w; if (center.y > u.vis.y || center.z > u.vis.z) { return out; } let kind = (bitcast(flags) >> 8u) & 255u; let storeU = bitcast(cells[base + 4u]); let mother = cells[base + 5u]; let rootSlot = bitcast(cells[base + 6u]); let cidU = bitcast(cells[base + 7u]); let energy = clamp(f32(storeU) / ${ROAM3D_STORE_SCALE}.0, 0.0, 2.0); let bright = 0.44 + 0.72 * (1.0 - exp(-energy * 1.35)); // Derive stable anatomical forward axis: away from mother along the body, else hashed from persistent cid. let hA = hashU32(cidU * 37u + 11u); let az0 = (f32(hA & 0xffffu) / 65535.0) * 6.2831853; let el0 = (f32((hA >> 16u) & 0xffffu) / 65535.0) * 1.4 - 0.7; var axis = vec3(cos(el0) * sin(az0), sin(el0), cos(el0) * cos(az0)); var hasMother = 0.0; if (mother >= 0i && u32(mother) < u.dims0.z) { let mBase = u32(mother) * CELL_STRIDE; if ((cells[mBase + 3u] & 1i) != 0i) { let mx = cells[mBase + 0u]; let my = cells[mBase + 1u]; let mz = cells[mBase + 2u]; let halfSpan = i32(u.dims0.w >> 1u); if (abs(ix - mx) <= halfSpan && abs(iz - mz) <= halfSpan) { let dVec = vec3(f32(ix - mx), f32(iy - my), f32(iz - mz)); let dLen = length(dVec); if (dLen > 1e-4) { axis = dVec / dLen; hasMother = 1.0; } } } } let viewDepth = (u.viewProj * vec4(center, 1.0)).w; var rad = u.back.w; if (u.opts2.x > 0.0) { // Hold the projected radius at minPixelRadius: radius in pixels = rad * opts2.y / viewDepth. if (viewDepth > 1e-6) { rad = max(rad, u.opts2.x * viewDepth / max(u.opts2.y, 1e-6)); } } let pxRad = select(0.0, rad * u.opts2.y / max(viewDepth, 1e-6), viewDepth > 1e-6); var quad = array, 6>( vec2(-1.0, -1.0), vec2(1.0, -1.0), vec2(1.0, 1.0), vec2(-1.0, -1.0), vec2(1.0, 1.0), vec2(-1.0, 1.0), ); let q = quad[vi]; // Pad the billboard slightly more when sculpted 3D SDF detail (carapace ribs / flexing jaws) is active up close. let pad = select(1.36, 1.68, pxRad >= 3.5); let worldPos = center + (u.right.xyz * q.x + u.up.xyz * q.y) * (rad * pad); out.clipPos = u.viewProj * vec4(worldPos, 1.0); out.worldPos = worldPos; out.center = center; out.col = cellAlbedo(kind, rootSlot); out.props = vec4(rad, f32(kind), bright, energy); out.axis = axis; let cidPhase = (f32(hashU32(cidU + 53u) & 0xffffu) / 65535.0) * 6.2831853; out.anim = vec3(cidPhase, pxRad, hasMother); return out; } struct FOut { @location(0) color: vec4, @builtin(frag_depth) depth: f32, }; fn sMax(a: f32, b: f32, k: f32) -> f32 { let h = max(k - abs(a - b), 0.0) / k; return max(a, b) + h * h * k * 0.25; } // Sculpted local-space 3D cell SDF in unit radius coordinates (+z faces away from mother). // Returns vec2(signedDistance, materialAux): for shell aux = plate crevice mask; for mouth aux = inside-maw mask. fn cellSdf(q: vec3, kind: u32, t: f32, ph: f32, hasMother: f32) -> vec2 { if (kind == 1u) { // Armoured shell: ribbed 3D bone carapace with 6 sculpted armor plates and overlapping axial bands. let ang = atan2(q.y, q.x); let rib = abs(cos(ang * 3.0 + ph * 0.5)); let grooveA = smoothstep(0.0, 0.26, rib); let band = abs(cos(q.z * 4.2)); let grooveB = smoothstep(0.0, 0.24, band); let plate = grooveA * (0.65 + 0.35 * grooveB); let seam = 1.0 - grooveA * grooveB; let breath = 0.014 * sin(t * 1.5 + ph) * select(0.0, 1.0, t > 0.0); let r = 0.99 + breath + 0.095 * plate - 0.055 * seam; return vec2((length(q) - r) * 0.68, seam); } if (kind == 2u) { // Hunter mouth: forward-facing sculpted 3D predator maw with 5 pulsing radial jaws and a carved inner gullet. let chomp = 0.5 + 0.5 * sin(t * 4.2 + ph); let ang = atan2(q.y, q.x); let frontMask = smoothstep(-0.05, 0.72, q.z); let jawWave = max(cos(ang * 5.0 + 0.24 * sin(t * 2.1 + ph)), 0.0); let jaws = frontMask * (0.12 + 0.05 * chomp) * pow(jawWave, 1.35); let qHead = vec3(q.x, q.y, q.z * 0.92); let dBody = length(qHead) - (0.96 + 0.025 * chomp + jaws); let cavCenter = vec3(0.0, 0.0, 0.78 - 0.06 * chomp); let cavRad = 0.46 + 0.11 * chomp; let dCav = length(q - cavCenter) - cavRad; let d = sMax(dBody, -dCav, 0.13) * 0.72; let inMaw = smoothstep(0.18, -0.08, dCav) * smoothstep(0.15, 0.75, q.z); return vec2(d, inMaw); } // Plain living cell: gently elongated breathing membrane that undulates softly during live playback. let stretch = 1.0 + 0.14 * hasMother; let qS = vec3(q.x, q.y, q.z / stretch); var r = 0.96; if (t > 0.0) { let breath = 0.042 * sin(t * 2.5 + ph); let wob = 0.044 * sin(q.x * 3.6 + t * 1.9 + ph) * cos(q.y * 3.4 - t * 1.5 + ph * 1.7) * sin(q.z * 3.2 + t * 1.3); r = r + breath + wob; } return vec2((length(qS) - r) * 0.85, 0.0); } fn cellNormal(q: vec3, kind: u32, t: f32, ph: f32, hasMother: f32) -> vec3 { let e = 0.015; let k0 = vec3( 1.0, -1.0, -1.0); let k1 = vec3(-1.0, -1.0, 1.0); let k2 = vec3(-1.0, 1.0, -1.0); let k3 = vec3( 1.0, 1.0, 1.0); let n = k0 * cellSdf(q + k0 * e, kind, t, ph, hasMother).x + k1 * cellSdf(q + k1 * e, kind, t, ph, hasMother).x + k2 * cellSdf(q + k2 * e, kind, t, ph, hasMother).x + k3 * cellSdf(q + k3 * e, kind, t, ph, hasMother).x; let l = length(n); return select(normalize(q), n / l, l > 1e-5); } @fragment fn fs(in: VOut) -> FOut { let rad = in.props.x; let kind = u32(in.props.y + 0.5); let shell = select(0.0, 1.0, kind == 1u); let mouth = select(0.0, 1.0, kind == 2u); let bright = in.props.z; let energy = in.props.w; let ph = in.anim.x; let pxRad = in.anim.y; let hasMother = in.anim.z; let tAnim = u.opts3.y; let glowMix = min(clamp(u.opts3.x, 0.0, 1.5), 1.0); let ro = u.eye.xyz; let rd = normalize(in.worldPos - ro); let oc = ro - in.center; // Distance LOD: distant cells (< 3.5 px) use analytic ray-sphere for 900+ FPS on cube512 overview; // close-up cells raymarch their sculpted 3D SDF models (translucent nucleus, bone carapace, flexing jaws). if (pxRad < 3.5) { let b = dot(oc, rd); let c = dot(oc, oc) - rad * rad; let disc = b * b - c; if (disc < 0.0) { discard; } let t = -b - sqrt(disc); if (t <= 0.0) { discard; } let p = ro + rd * t; let n = normalize(p - in.center); let V = -rd; let clip = u.viewProj * vec4(p, 1.0); let depth = clip.z / clip.w; if (depth < 0.0 || depth > 1.0) { discard; } let pulse = 1.0 + select(0.0, 0.08 * sin(tAnim * 2.6 + ph) * glowMix, tAnim > 0.0); let depthFrac = clamp(p.y / max(u.ext.y, 1e-4), 0.0, 1.0); let waterLight = 0.42 + 0.58 * depthFrac; let wrap = clamp((dot(n, SUN_DIR) + 0.38) / 1.38, 0.0, 1.0); let hemi = mix(vec3(0.07, 0.11, 0.18), vec3(0.34, 0.44, 0.56), n.y * 0.5 + 0.5) * (0.45 + 0.55 * waterLight); var lit = in.col * bright * pulse * (vec3(1.10, 1.03, 0.92) * wrap * (0.35 + 0.65 * waterLight) + hemi * 0.72); let H = normalize(SUN_DIR + V); let specPow = mix(24.0, 48.0, shell); let spec = pow(max(dot(n, H), 0.0), specPow) * mix(0.22, 0.48, shell) * (0.4 + 0.6 * waterLight); lit += vec3(0.98, 0.96, 0.90) * spec; let ndv = max(dot(n, V), 0.0); let core = pow(ndv, 1.45); lit += in.col * bright * pulse * (0.20 + 0.16 * core) * glowMix; lit += vec3(0.48, 0.08, 0.05) * (mouth * bright * 0.65 * glowMix); let rim = pow(1.0 - ndv, 2.5); let rimPlain = mix(in.col * 0.9 + vec3(0.12), in.col * 0.78 + vec3(0.22), glowMix); let rimCol = mix(rimPlain, vec3(0.96, 0.92, 0.78), shell * mix(0.72, 0.88, glowMix)); let rimGain = (0.28 + 0.24 * shell) + (0.18 + 0.12 * shell) * glowMix * bright; lit += rimCol * rim * rimGain; let bloomW = clamp(0.45 + 0.35 * bright + 0.35 * mouth, 0.0, 1.15); var out: FOut; out.color = vec4(lit, bloomW); out.depth = depth; return out; } // Sculpted 3D SDF close-up path inside bounding sphere of radius 1.32 * rad (fits full jaw extension cleanly). let boundR = rad * 1.32; let bB = dot(oc, rd); let cB = dot(oc, oc) - boundR * boundR; let discB = bB * bB - cB; if (discB < 0.0) { discard; } let sqB = sqrt(discB); let tStart = max(0.0, -bB - sqB); let tEnd = -bB + sqB; if (tEnd <= 0.0) { discard; } let F = normalize(in.axis); let refUp = select(vec3(0.0, 1.0, 0.0), vec3(1.0, 0.0, 0.0), abs(F.y) > 0.92); let T = normalize(cross(refUp, F)); let B = cross(F, T); let ocL = oc / rad; let roL = vec3(dot(ocL, T), dot(ocL, B), dot(ocL, F)); let rdL = vec3(dot(rd, T), dot(rd, B), dot(rd, F)); var tLoc = 0.0; var qHit = vec3(0.0); var n = vec3(0.0); var p = vec3(0.0); var aux = 0.0; if (kind == 0u && tAnim == 0.0 && hasMother < 0.5) { // Exact world-space analytic sphere hit for static solo plain cells (bit-for-bit depth ties independent of cid). let rS = rad * 0.96; let cS = dot(oc, oc) - rS * rS; let discS = bB * bB - cS; if (discS < 0.0) { discard; } let tW = -bB - sqrt(discS); if (tW <= 0.0) { discard; } tLoc = tW / rad; p = ro + rd * tW; n = normalize(p - in.center); qHit = roL + rdL * tLoc; } else { tLoc = tStart / rad; let tMaxLoc = tEnd / rad; var hit = false; for (var it: i32 = 0; it < 24; it = it + 1) { let q = roL + rdL * tLoc; let res = cellSdf(q, kind, tAnim, ph, hasMother); if (res.x < 0.008) { hit = true; aux = res.y; break; } tLoc += max(res.x, 0.012); if (tLoc > tMaxLoc) { break; } } if (!hit || tLoc <= 0.0) { discard; } qHit = roL + rdL * tLoc; let nL = cellNormal(qHit, kind, tAnim, ph, hasMother); n = normalize(T * nL.x + B * nL.y + F * nL.z); p = ro + rd * (tLoc * rad); } let V = -rd; let clip = u.viewProj * vec4(p, 1.0); let depth = clip.z / clip.w; if (depth < 0.0 || depth > 1.0) { discard; } let depthFrac = clamp(p.y / max(u.ext.y, 1e-4), 0.0, 1.0); let waterLight = 0.42 + 0.58 * depthFrac; let wrap = clamp((dot(n, SUN_DIR) + 0.42) / 1.42, 0.0, 1.0); let hemi = mix(vec3(0.07, 0.11, 0.18), vec3(0.34, 0.44, 0.56), n.y * 0.5 + 0.5) * (0.45 + 0.55 * waterLight); let H = normalize(SUN_DIR + V); let ndv = max(dot(n, V), 0.0); let rim = pow(1.0 - ndv, 2.35); var lit = vec3(0.0); var bloomW = clamp(0.45 + 0.35 * bright, 0.0, 1.15); if (kind == 1u) { // Armoured bone carapace: warm ivory plates with crisp sheen, darkened amber crevices, subtle inner body glow in seams. let seam = clamp(aux, 0.0, 1.0); let ao = mix(1.0, 0.42, seam); let plateCol = mix(vec3(0.97, 0.91, 0.76), in.col, 0.16); let baseCol = mix(plateCol, in.col * 0.55 + vec3(0.24, 0.18, 0.11), seam * 0.60); lit = baseCol * bright * ao * (vec3(1.12, 1.05, 0.94) * wrap * (0.38 + 0.62 * waterLight) + hemi * 0.72); let spec = pow(max(dot(n, H), 0.0), 56.0) * (0.58 * (1.0 - seam * 0.8)) * (0.45 + 0.55 * waterLight); lit += vec3(1.0, 0.97, 0.88) * spec; // Living bioluminescent warmth peeking from the seams + bone rim light. lit += in.col * (0.32 * seam * bright * glowMix); lit += vec3(0.96, 0.92, 0.78) * rim * ((0.44 + 0.22 * glowMix) * (1.0 - 0.5 * seam)); bloomW = clamp(0.38 + 0.25 * bright, 0.0, 0.95); } else if (kind == 2u) { // Sculpted predator mouth: rose-crimson outer mantle, pulsing radial jaws, and fiery glowing inner gullet. let inMaw = clamp(aux, 0.0, 1.0); let chomp = 0.5 + 0.5 * sin(tAnim * 4.2 + ph); let backBlend = smoothstep(0.25, -0.85, qHit.z); let outerCol = mix(vec3(0.92, 0.26, 0.24), in.col, backBlend * 0.55); let jawTip = smoothstep(0.35, 0.85, qHit.z) * (1.0 - inMaw); let surfaceCol = mix(outerCol, vec3(1.0, 0.44, 0.32), jawTip * 0.45); let mawAo = mix(1.0, 0.28, inMaw); lit = surfaceCol * bright * mawAo * (vec3(1.10, 1.02, 0.92) * wrap * (0.35 + 0.65 * waterLight) + hemi * 0.68); let spec = pow(max(dot(n, H), 0.0), 32.0) * (0.30 * (1.0 - inMaw * 0.7)) * (0.4 + 0.6 * waterLight); lit += vec3(1.0, 0.88, 0.82) * spec; // Fiery bioluminescent inner gullet glowing out of the carved 3D mouth opening. let deepGlow = inMaw * (0.85 + 0.45 * chomp); lit += vec3(1.55, 0.25, 0.08) * deepGlow * (0.75 + 0.45 * glowMix); lit += vec3(0.98, 0.32, 0.22) * rim * (0.36 + 0.26 * glowMix * bright); bloomW = clamp(0.65 + 0.45 * bright + 0.55 * deepGlow, 0.0, 1.45); } else { // Translucent living plain cell: breathing cytoplasm gel with a visible pulsing inner nucleus. let pulse = 1.0 + select(0.0, 0.08 * sin(tAnim * 3.1 + ph), tAnim > 0.0); // Soft subsurface wrap lighting + organic micro-mottling across cytoplasm. let mottle = 0.92 + 0.08 * sin(qHit.x * 7.5 + ph) * cos(qHit.y * 7.5 - ph) * sin(qHit.z * 7.5); let gelCol = in.col * mottle; lit = gelCol * bright * (vec3(1.06, 1.02, 0.94) * wrap * (0.36 + 0.64 * waterLight) + hemi * 0.68); let spec = pow(max(dot(n, H), 0.0), 30.0) * 0.28 * (0.4 + 0.6 * waterLight); lit += vec3(0.96, 0.97, 1.0) * spec; // Translucent inner glowing nucleus seen through the membrane (size & warmth driven by energy store). let nucOff = select( vec3(0.0), vec3(0.06 * sin(tAnim * 1.7 + ph), 0.06 * cos(tAnim * 1.4 + ph), 0.05 * sin(tAnim * 1.1 + ph * 2.0)), tAnim > 0.0, ); let relNuc = nucOff - roL; let projNuc = dot(relNuc, rdL); let closestNuc = roL + rdL * projNuc - nucOff; let nucRad = 0.26 + 0.22 * clamp(energy, 0.0, 1.0); let dNuc = length(closestNuc) / nucRad; let nucCore = exp(-dNuc * dNuc * 2.1) * (0.48 + 0.58 * clamp(energy, 0.0, 1.35)) * pulse; let nucTint = mix(in.col, vec3(1.0, 0.96, 0.86), 0.45); lit += nucTint * nucCore * (0.35 + 0.55 * glowMix); // Translucent glowing cell membrane rim. let rimCol = mix(in.col * 0.9 + vec3(0.12), in.col * 0.72 + vec3(0.28), glowMix); lit += rimCol * rim * (0.34 + 0.26 * glowMix * bright); bloomW = clamp(0.42 + 0.36 * bright + 0.28 * nucCore, 0.0, 1.2); } var out: FOut; out.color = vec4(lit, bloomW); out.depth = depth; return out; } `; export const BOND_WGSL = /* wgsl */ `${COMMON_WGSL} @group(0) @binding(1) var cells: array; @group(0) @binding(2) var indices: array; // this draw's compacted slots, ascending struct VOut { @builtin(position) clipPos: vec4, @location(0) worldPos: vec3, @location(1) uv: vec2, @location(2) @interpolate(flat) col: vec3, @location(3) @interpolate(flat) halfW: f32, @location(4) @interpolate(flat) flow: vec4, // x = flow dir (+1 A->B, -1 B->A), y = flow strength, z = cid phase, w = body luma }; @vertex fn vs(@builtin(vertex_index) vi: u32, @builtin(instance_index) ii: u32) -> VOut { var out: VOut; out.clipPos = vec4(2.0, 2.0, 2.0, 1.0); out.worldPos = vec3(0.0); out.uv = vec2(0.0); out.col = vec3(0.0); out.halfW = 0.0; out.flow = vec4(0.0); // The compaction already applied every test below; they stay so a list can only skip work, never add an instance. let slot = indices[ii]; if (slot >= u.dims0.z) { return out; } let base = slot * CELL_STRIDE; let flags = cells[base + 3u]; if ((flags & 1i) == 0i) { return out; } let mother = cells[base + 5u]; if (mother < 0i) { return out; } let mSlot = u32(mother); if (mSlot >= u.dims0.z) { return out; } let mBase = mSlot * CELL_STRIDE; let mFlags = cells[mBase + 3u]; if ((mFlags & 1i) == 0i) { return out; } let ax = cells[base + 0u]; let ay = cells[base + 1u]; let az = cells[base + 2u]; let bx = cells[mBase + 0u]; let by = cells[mBase + 1u]; let bz = cells[mBase + 2u]; // Skip bonds whose two endpoints lie on opposite sides of the periodic x or z wrap seam. let halfSpan = i32(u.dims0.w >> 1u); if (abs(ax - bx) > halfSpan || abs(az - bz) > halfSpan) { return out; } let pA = vec3(f32(ax), f32(ay), f32(az)) * u.ext.w; let pB = vec3(f32(bx), f32(by), f32(bz)) * u.ext.w; if (pA.y > u.vis.y || pA.z > u.vis.z || pB.y > u.vis.y || pB.z > u.vis.z) { return out; } let t = select(0.0, 1.0, vi == 1u || vi == 2u || vi == 4u); let s = select(-1.0, 1.0, vi == 2u || vi == 4u || vi == 5u); // Organic tissue bridge width that tapers smoothly in the fragment shader to weld joined cells into one living body. let halfW = u.back.w * 0.66; let p = mix(pA, pB, t); let rootSlot = bitcast(cells[base + 6u]); let cidU = bitcast(cells[base + 7u]); let bodyCol = bodyBaseColor(rootSlot); let storeA = f32(bitcast(cells[base + 4u])); let storeB = f32(bitcast(cells[mBase + 4u])); let avgBright = 0.55 + 0.55 * clamp(0.5 * (storeA + storeB) / ${ROAM3D_STORE_SCALE}.0, 0.0, 1.2); let flowDir = select(-1.0, 1.0, storeA >= storeB); let flowStr = clamp(abs(storeA - storeB) / 140.0, 0.16, 1.0); let cidPhase = (f32(hashU32(cidU + 91u) & 0xffffu) / 65535.0) * 6.2831853; out.col = bodyCol * avgBright; out.uv = vec2(t, s); out.halfW = halfW; out.flow = vec4(flowDir, flowStr, cidPhase, avgBright); let c = u.viewProj * vec4(p, 1.0); let ca = u.viewProj * vec4(pA, 1.0); let cb = u.viewProj * vec4(pB, 1.0); let vp = vec2(u.right.w, u.up.w); if (ca.w > 1e-4 && cb.w > 1e-4 && c.w > 1e-4 && vp.x > 0.0 && vp.y > 0.0) { let cu = u.viewProj * vec4(p + u.up.xyz * halfW, 1.0); if (cu.w > 1e-4) { let px = 0.5 * vp; let sd = (cb.xy / cb.w - ca.xy / ca.w) * px; let sl = length(sd); let perp = select(vec2(1.0, 0.0), vec2(-sd.y, sd.x) / max(sl, 1e-6), sl > 1e-4); let hpx = max(length((cu.xy / cu.w - c.xy / c.w) * px), 0.9); out.worldPos = p; out.clipPos = vec4(c.xy + (perp * s * hpx / px) * c.w, c.z, c.w); return out; } } var side = cross(pB - pA, u.eye.xyz - 0.5 * (pA + pB)); let sl = length(side); side = select(u.right.xyz, side / max(sl, 1e-6), sl > 1e-5); let wp = p + side * s * halfW; out.worldPos = wp; out.clipPos = u.viewProj * vec4(wp, 1.0); return out; } struct FOut { @location(0) color: vec4, @builtin(frag_depth) depth: f32, }; @fragment fn fs(in: VOut) -> FOut { // Smooth organic hourglass waist: wide where the tissue meets each cell, gently pinched in the middle. let endDist = abs(in.uv.x * 2.0 - 1.0); let waist = 0.56 + 0.44 * pow(endDist, 1.5); let rNorm = in.uv.y / waist; let radial2 = 1.0 - rNorm * rNorm; if (radial2 <= 0.0) { discard; } let radial = sqrt(radial2); let viewDir = normalize(u.eye.xyz - in.worldPos); let pSurf = in.worldPos + viewDir * (radial * in.halfW * waist * 0.72); let clip = u.viewProj * vec4(pSurf, 1.0); let depth = clip.z / clip.w; if (depth < 0.0 || depth > 1.0) { discard; } let glowMix = min(clamp(u.opts3.x, 0.0, 1.5), 1.0); let depthFrac = clamp(pSurf.y / max(u.ext.y, 1e-4), 0.0, 1.0); let waterLight = 0.45 + 0.55 * depthFrac; // Soft translucent tissue shading with a luminous rim and an animated inner nutrient vein. let rim = pow(1.0 - radial, 2.0); var col = in.col * (0.42 + 0.52 * radial) * waterLight; col += (in.col * 0.72 + vec3(0.24)) * rim * (0.28 + 0.22 * glowMix); let coreVein = exp(-rNorm * rNorm * 6.5); let phase = in.uv.x * 9.424778 - in.flow.x * u.opts3.y * 3.8 + in.flow.z; let pulse = 0.35 + 0.65 * pow(0.5 + 0.5 * sin(phase), 3.0); let strandCol = mix(vec3(0.96, 0.92, 0.74), in.col + vec3(0.25), 0.32); col += strandCol * coreVein * in.flow.y * pulse * (0.45 + 0.55 * glowMix); var out: FOut; out.color = vec4(col, 0.52 + 0.35 * coreVein * in.flow.y); out.depth = depth; return out; } `; export const FLOOR_WGSL = /* wgsl */ `${COMMON_WGSL} @group(0) @binding(1) var floorFood: array; @group(0) @binding(2) var colSum: array; struct VOut { @builtin(position) clipPos: vec4, @location(0) uv: vec2, }; @vertex fn vs(@builtin(vertex_index) vi: u32) -> VOut { // CCW when seen from +y so back-face culling lets the camera look up from below y = 0. var verts = array, 6>( vec2(0.0, 0.0), vec2(0.0, 1.0), vec2(1.0, 1.0), vec2(0.0, 0.0), vec2(1.0, 1.0), vec2(1.0, 0.0), ); let q = verts[vi]; let worldXZ = vec2(q.x * u.vis.x, q.y * u.vis.z); var out: VOut; out.uv = worldXZ; out.clipPos = u.viewProj * vec4(worldXZ.x, 0.0, worldXZ.y, 1.0); return out; } fn sampleFloorFood(uv: vec2) -> f32 { let sz = u.dims0.x; let mask = i32(sz - 1u); let p = uv * f32(sz) - vec2(0.5); let i0 = vec2(floor(p)); let f = fract(p); let x0 = u32(i0.x & mask); let x1 = u32((i0.x + 1i) & mask); let z0 = u32(i0.y & mask); let z1 = u32((i0.y + 1i) & mask); let c00 = f32(floorFood[z0 * sz + x0]); let c10 = f32(floorFood[z0 * sz + x1]); let c01 = f32(floorFood[z1 * sz + x0]); let c11 = f32(floorFood[z1 * sz + x1]); return mix(mix(c00, c10, f.x), mix(c01, c11, f.x), f.y); } // The waterFood column over this floor point, summed once per data version by prepColumns. fn waterColumnShadow(uv: vec2) -> f32 { let fx = u.dims2.x; let fz = u.dims2.z; let vx = u32(i32(floor(uv.x * f32(fx))) & i32(fx - 1u)); let vz = u32(i32(floor(uv.y * f32(fz))) & i32(fz - 1u)); let sum = colSum[vz * fx + vx]; let density = f32(sum) * u.opts.y * 0.06 * u.opts2.w; return exp(-density * 0.55); } @fragment fn fs(in: VOut) -> @location(0) vec4 { // Compute derivatives in uniform control flow before any conditional logic. // One grid square per 16 tiles in every world (8 across the 128-tile tank). let gridCoord = in.uv * (f32(u.dims0.x) / 16.0); let fw = max(fwidth(gridCoord), vec2(0.001)); let g = abs(fract(gridCoord - 0.5) - 0.5) / fw; let line = 1.0 - min(min(g.x, g.y), 1.0); let foodRaw = sampleFloorFood(in.uv); let food = 1.0 - exp(-foodRaw * u.opts.z); var col = vec3(0.024, 0.040, 0.060); col += vec3(0.06, 0.24, 0.34) * food + vec3(0.10, 0.36, 0.32) * (food * food); col = mix(col, vec3(0.24, 0.38, 0.54), line * 0.13); // Overhead marine-snow column shadow onto the floor. let colShade = mix(0.58, 1.0, waterColumnShadow(in.uv)); col *= colShade; // Subtle bright floor rim at tank edges. let edgeDist = min(in.uv, vec2(1.0) - in.uv); let rim = 1.0 - smoothstep(0.0, 0.007, min(edgeDist.x, edgeDist.y)); col = mix(col, vec3(0.34, 0.54, 0.74), rim * 0.36); // Bare floor and grid stay unbloomed (alpha 0); concentrated floor food gets a soft cyan bloom weight. return vec4(col, 0.22 * food * food); } `; export const SHADOW_WGSL = /* wgsl */ `${COMMON_WGSL} @group(0) @binding(1) var cells: array; @group(0) @binding(2) var indices: array; // this draw's compacted slots, ascending struct VOut { @builtin(position) clipPos: vec4, @location(0) uv: vec2, @location(1) worldXZ: vec2, @location(2) @interpolate(flat) alpha: f32, }; @vertex fn vs(@builtin(vertex_index) vi: u32, @builtin(instance_index) ii: u32) -> VOut { var out: VOut; out.clipPos = vec4(2.0, 2.0, 2.0, 1.0); out.uv = vec2(0.0); out.worldXZ = vec2(-1.0); out.alpha = 0.0; // The compaction already applied every test below; they stay so a list can only skip work, never add an instance. let slot = indices[ii]; if (slot >= u.dims0.z) { return out; } let base = slot * CELL_STRIDE; let flags = cells[base + 3u]; if ((flags & 1i) == 0i) { return out; } let center = vec3(f32(cells[base + 0u]), f32(cells[base + 1u]), f32(cells[base + 2u])) * u.ext.w; if (center.y > u.vis.y || center.z > u.vis.z) { return out; } // CCW when seen from +y so shadows also back-face cull when viewing from below. var quad = array, 6>( vec2(-1.0, -1.0), vec2(-1.0, 1.0), vec2(1.0, 1.0), vec2(-1.0, -1.0), vec2(1.0, 1.0), vec2(1.0, -1.0), ); // Height in tiles: shadows fade over the first 32 tiles (the tank's full depth) and stop past 64. let hTiles = center.y * f32(u.dims0.x); if (hTiles > 64.0) { return out; } let q = quad[vi]; let hNorm = clamp(hTiles / 32.0, 0.0, 1.0); let r = u.back.w * (1.35 + 1.45 * hNorm); let p = vec3(center.x + q.x * r, 0.00025, center.z + q.y * r); out.clipPos = u.viewProj * vec4(p, 1.0); out.uv = q; out.worldXZ = p.xz; out.alpha = 0.28 * (1.0 - 0.55 * hNorm); return out; } @fragment fn fs(in: VOut) -> @location(0) vec4 { if (in.worldXZ.x < 0.0 || in.worldXZ.x > u.vis.x || in.worldXZ.y < 0.0 || in.worldXZ.y > u.vis.z) { discard; } let r2 = dot(in.uv, in.uv); if (r2 > 1.0) { discard; } let soft = 1.0 - r2; return vec4(0.004, 0.008, 0.016, soft * soft * in.alpha); } `; export const HAZE_WGSL = /* wgsl */ `${COMMON_WGSL} @group(0) @binding(1) var bricks: array; @group(0) @binding(2) var sceneCol: texture_2d; @group(0) @binding(3) var sceneDep: texture_depth_2d; @group(0) @binding(4) var volTex: texture_3d; @group(0) @binding(5) var volSamp: sampler; @group(0) @binding(6) var bloom1: texture_2d; @group(0) @binding(7) var bloom2: texture_2d; @group(0) @binding(8) var bloomSamp: sampler; @vertex fn vs(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { var p = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0)); return vec4(p[vi], 0.0, 1.0); } const WATER_COL: vec3 = vec3(0.045, 0.165, 0.255); const FOOD_COL: vec3 = vec3(0.24, 0.72, 0.86); fn ign(p: vec2) -> f32 { return fract(52.9829189 * fract(dot(p, vec2(0.06711056, 0.00583715)))); } fn worldFromNdc(x: f32, y: f32, z: f32) -> vec3 { let h = u.invViewProj * vec4(x, y, z, 1.0); return h.xyz / h.w; } fn boxSpan(ro: vec3, rd: vec3, hi: vec3) -> vec2 { let d = select(rd, vec3(1e-6), abs(rd) < vec3(1e-6)); let t0 = (vec3(0.0) - ro) / d; let t1 = (hi - ro) / d; return vec2( max(max(min(t0.x, t1.x), min(t0.y, t1.y)), min(t0.z, t1.z)), min(min(max(t0.x, t1.x), max(t0.y, t1.y)), max(t0.z, t1.z)), ); } // Hardware trilinear read of the volume texture (repeat in x/z, clamped in y), in 2-tile-voxel food units. fn sampleWaterFood(p: vec3) -> f32 { let uvw = p / max(u.ext.xyz, vec3(1e-4)); return textureSampleLevel(volTex, volSamp, uvw, 0.0).r; } fn brickGrid() -> vec3 { return (u.dims1.xyz + vec3(${ROAM3D_BRICK - 1}u)) / ${ROAM3D_BRICK}u; } // The brick holding p (in bricks along each axis). fn brickOf(p: vec3) -> vec3 { let uvw = clamp(p / max(u.ext.xyz, vec3(1e-4)), vec3(0.0), vec3(1.0)); let s = uvw * vec3(u.dims1.xyz) / ${ROAM3D_BRICK}.0; return min(vec3(s), brickGrid() - vec3(1u)); } fn brickEmpty(b: vec3) -> bool { let nb = brickGrid(); return bricks[(b.y * nb.z + b.z) * nb.x + b.x] == 0u; } // Distance along rd from p to where the ray leaves brick b. fn brickExit(p: vec3, rd: vec3, b: vec3) -> f32 { let tex = vec3(u.dims1.xyz); let lo = vec3(b) * ${ROAM3D_BRICK}.0 / tex * u.ext.xyz; let hi = min(vec3(b + vec3(1u)) * ${ROAM3D_BRICK}.0 / tex, vec3(1.0)) * u.ext.xyz; let d = select(rd, vec3(1e-6), abs(rd) < vec3(1e-6)); let tt = select((lo - p) / d, (hi - p) / d, d > vec3(0.0)); return max(min(tt.x, min(tt.y, tt.z)), 0.0); } fn boxEdgeFactor(p: vec3, hi: vec3, width: f32) -> f32 { let d = max(min(p, hi - p), vec3(0.0)); let m0 = min(d.x, min(d.y, d.z)); let m2 = max(d.x, max(d.y, d.z)); let second = (d.x + d.y + d.z) - m0 - m2; return 1.0 - smoothstep(0.0, width, second); } fn glassRim(p: vec3, rd: vec3, hi: vec3, tDist: f32) -> vec3 { let halfExt = max(0.5 * hi, vec3(1e-4)); let q = (p - halfExt) / halfExt; let aq = abs(q); var n = vec3(0.0, 0.0, sign(q.z)); if (aq.x >= aq.y && aq.x >= aq.z) { n = vec3(sign(q.x), 0.0, 0.0); } else if (aq.y >= aq.z) { n = vec3(0.0, sign(q.y), 0.0); } let fres = pow(1.0 - clamp(abs(dot(n, rd)), 0.0, 1.0), 3.0); let spec = pow(max(dot(reflect(rd, n), SUN_DIR), 0.0), 42.0); let edgeW = max(0.0022, tDist * 0.0024); let edge = boxEdgeFactor(p, hi, edgeW); let topSheen = select(0.0, 0.045, n.y > 0.5); return vec3(0.44, 0.70, 0.90) * (fres * 0.22 + edge * 0.42 + topSheen) + vec3(1.0, 0.94, 0.80) * spec * 0.30; } fn applyBloom(c: vec3, uv: vec2) -> vec3 { let glowStrength = clamp(u.opts3.x, 0.0, 1.5); if (glowStrength <= 0.0) { return c; } let gTight = textureSampleLevel(bloom1, bloomSamp, uv, 0.0).rgb; let gWide = textureSampleLevel(bloom2, bloomSamp, uv, 0.0).rgb; // Keep bloom richly coloured into dark water around bodies while compressing softly over dense bright swarms. let gRaw = gTight * 0.36 + gWide * 0.38; let gLuma = dot(gRaw, vec3(0.2126, 0.7152, 0.0722)); let gSat = max(mix(vec3(gLuma), gRaw, 1.32), vec3(0.0)); let gSoft = gSat / (1.0 + gLuma * 1.15); let baseLuma = dot(max(c, vec3(0.0)), vec3(0.2126, 0.7152, 0.0722)); let headroom = 1.0 / (1.0 + baseLuma * 0.85); return c + gSoft * (glowStrength * headroom); } fn toneFinish(c: vec3) -> vec4 { let mapped = vec3(1.0) - exp(-max(c, vec3(0.0)) * 1.25); return vec4(pow(clamp(mapped, vec3(0.0), vec3(1.0)), vec3(1.0 / 2.2)), 1.0); } @fragment fn fs(@builtin(position) fp: vec4) -> @location(0) vec4 { let texSize = vec2(textureDimensions(sceneCol)); let px = vec2(fp.xy); let screenUv = fp.xy / texSize; let ndc = vec2(screenUv.x * 2.0 - 1.0, 1.0 - screenUv.y * 2.0); let ro = u.eye.xyz; let rd = normalize(worldFromNdc(ndc.x, ndc.y, 1.0) - worldFromNdc(ndc.x, ndc.y, 0.0)); let gradT = clamp(1.0 - screenUv.y, 0.0, 1.0); let bgCol = pow(u.bg.rgb, vec3(2.2)) * (0.72 + 0.55 * gradT); let d = textureLoad(sceneDep, px, 0); let hit = d < 1.0; var tHit = 1e9; if (hit) { tHit = dot(worldFromNdc(ndc.x, ndc.y, d) - ro, rd); } let behind = select(bgCol, textureLoad(sceneCol, px, 0).rgb, hit); let full = boxSpan(ro, rd, u.ext.xyz); let s0 = boxSpan(ro, rd, u.vis.xyz); let span = vec2(max(s0.x, 0.0), min(s0.y, tHit)); let glass = u.bg.w > 0.5; let clipped = u.vis.w > 0.5; if (span.y <= span.x) { var out = behind; if (glass && full.y > max(full.x, 0.0)) { if (full.x > 0.0 && full.x < tHit) { out += glassRim(ro + rd * full.x, rd, u.ext.xyz, full.x) * 0.75; } if (full.y < tHit) { out += glassRim(ro + rd * full.y, rd, u.ext.xyz, full.y) * 0.45; } } return toneFinish(applyBloom(out, screenUv)); } let voxLen = min(u.ext.x / f32(u.dims1.x), min(u.ext.y / f32(u.dims1.y), u.ext.z / f32(u.dims1.z))); let skipEmpty = (u.dims2.w & 1u) != 0u; let detail = max(u.opts.w, 0.25); let spanLen = span.y - span.x; let h = max(max(voxLen / detail, 0.004), spanLen / f32(${ROAM3D_MAX_RAY_STEPS - 1}u)); let hazeStrength = max(u.opts.x, 0.0); let waterAbs = 0.04 + 0.26 * hazeStrength; let foodSig = 3.2 * hazeStrength; var col = vec3(0.0); var T = 1.0; let jitter = ign(fp.xy + vec2(fract(u.eye.w * 0.6180339) * 64.0)); var t = span.x + jitter * h; var first = true; for (var it: i32 = 0; it < ${ROAM3D_MAX_RAY_STEPS}; it = it + 1) { if (t >= span.y || T < 0.025) { break; } let p = ro + rd * t; if (skipEmpty) { let b = brickOf(p); if (brickEmpty(b)) { // Every trilinear sample in this brick is 0: cross it in one water-only segment (light taken mid-way). let segE = min(max(brickExit(p, rd, b) + 1e-5, 1e-4), span.y - t); let yMid = clamp((p.y + 0.5 * rd.y * segE) / max(u.ext.y, 1e-4), 0.0, 1.0); let litE = 0.22 + 0.78 * yMid * yMid; let scatE = WATER_COL * waterAbs * (0.14 + 1.55 * litE); let trE = exp(-waterAbs * segE * 1.15); col += T * scatE * (1.0 - trE) / max(waterAbs, 1e-4); T *= trE; t += segE; first = false; continue; } } let seg = min(h, span.y - t); let rawFood = sampleWaterFood(p); let food = 1.0 - exp(-rawFood * u.opts.y); let yFrac = clamp(p.y / max(u.ext.y, 1e-4), 0.0, 1.0); let lit = 0.22 + 0.78 * yFrac * yFrac; let sig = waterAbs + foodSig * food; let scat = WATER_COL * waterAbs * (0.14 + 1.55 * lit) + FOOD_COL * foodSig * food * (0.45 + 0.85 * lit); let tr = exp(-sig * seg * 1.15); col += T * scat * (1.0 - tr) / max(sig, 1e-4); T *= tr; t += seg; if (first) { t = span.x + seg; } first = false; } var out = col + T * behind; if (glass) { if (full.x > 0.0 && full.x < tHit) { out += glassRim(ro + rd * full.x, rd, u.ext.xyz, full.x); } if (full.y > 0.0 && full.y < tHit) { out += T * glassRim(ro + rd * full.y, rd, u.ext.xyz, full.y) * 0.52; } if (clipped && s0.x > 0.0 && s0.x < tHit) { let cutEdge = boxEdgeFactor(ro + rd * s0.x, u.vis.xyz, max(0.0024, s0.x * 0.0026)); out += vec3(0.92, 0.74, 0.38) * cutEdge * 0.55; } } return toneFinish(applyBloom(out, screenUv)); } `; /** * Dual-scale separable HDR bloom for the Soft Roam bioluminescent glow look. * - `fsExtract`: reads 2x2 pixels of `sceneCol`, masks by `sceneCol.a` (cells/bonds > 0, bare floor/bg = 0), and * blends average + peak so 1-pixel organisms on cube512 keep strong radiance through downsampling. * - `fsDown`: 4-tap bilinear downsample from half-res to quarter-res with gentle peak preservation. * - `fsBlurH` / `fsBlurV`: 5-tap bilinear 9-tap Gaussian blur along X and Y (same size as source). */ export const BLOOM_WGSL = /* wgsl */ ` @group(0) @binding(0) var srcTex: texture_2d; @group(0) @binding(1) var srcSamp: sampler; @vertex fn vs(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4 { var p = array, 3>(vec2(-1.0, -1.0), vec2(3.0, -1.0), vec2(-1.0, 3.0)); return vec4(p[vi], 0.0, 1.0); } fn maskedSample(coord: vec2, maxCoord: vec2) -> vec3 { let s = textureLoad(srcTex, clamp(coord, vec2(0), maxCoord), 0); return max(s.rgb, vec3(0.0)) * max(s.a, 0.0); } @fragment fn fsExtract(@builtin(position) fp: vec4) -> @location(0) vec4 { let maxCoord = vec2(textureDimensions(srcTex)) - vec2(1); let p = vec2(fp.xy) * 2; let c00 = maskedSample(p + vec2(0, 0), maxCoord); let c10 = maskedSample(p + vec2(1, 0), maxCoord); let c01 = maskedSample(p + vec2(0, 1), maxCoord); let c11 = maskedSample(p + vec2(1, 1), maxCoord); let avg = (c00 + c10 + c01 + c11) * 0.25; let peak = max(max(c00, c10), max(c01, c11)); return vec4(mix(avg, peak, 0.28), 1.0); } @fragment fn fsDown(@builtin(position) fp: vec4) -> @location(0) vec4 { let dim = max(vec2(textureDimensions(srcTex)), vec2(1.0)); let inv = vec2(1.0) / dim; let uv = (fp.xy * 2.0) * inv; let off = inv * 0.75; let c00 = textureSampleLevel(srcTex, srcSamp, clamp(uv + vec2(-off.x, -off.y), vec2(0.0), vec2(1.0)), 0.0).rgb; let c10 = textureSampleLevel(srcTex, srcSamp, clamp(uv + vec2( off.x, -off.y), vec2(0.0), vec2(1.0)), 0.0).rgb; let c01 = textureSampleLevel(srcTex, srcSamp, clamp(uv + vec2(-off.x, off.y), vec2(0.0), vec2(1.0)), 0.0).rgb; let c11 = textureSampleLevel(srcTex, srcSamp, clamp(uv + vec2( off.x, off.y), vec2(0.0), vec2(1.0)), 0.0).rgb; let avg = (c00 + c10 + c01 + c11) * 0.25; let peak = max(max(c00, c10), max(c01, c11)); return vec4(mix(avg, peak, 0.15), 1.0); } fn blurAxis(fp: vec4, axis: vec2) -> vec4 { let dim = max(vec2(textureDimensions(srcTex)), vec2(1.0)); let uv = fp.xy / dim; let step = axis / dim; var sum = textureSampleLevel(srcTex, srcSamp, uv, 0.0).rgb * 0.227027027; sum += textureSampleLevel(srcTex, srcSamp, uv + step * 1.38461538, 0.0).rgb * 0.316216216; sum += textureSampleLevel(srcTex, srcSamp, uv - step * 1.38461538, 0.0).rgb * 0.316216216; sum += textureSampleLevel(srcTex, srcSamp, uv + step * 3.23076923, 0.0).rgb * 0.070270270; sum += textureSampleLevel(srcTex, srcSamp, uv - step * 3.23076923, 0.0).rgb * 0.070270270; return vec4(sum, 1.0); } @fragment fn fsBlurH(@builtin(position) fp: vec4) -> @location(0) vec4 { return blurAxis(fp, vec2(1.0, 0.0)); } @fragment fn fsBlurV(@builtin(position) fp: vec4) -> @location(0) vec4 { return blurAxis(fp, vec2(0.0, 1.0)); } `; export const PREP_WGSL = /* wgsl */ `${COMMON_WGSL} @group(0) @binding(1) var waterFood: array; @group(0) @binding(2) var volOut: texture_storage_3d; @group(0) @binding(3) var brickMax: array>; @group(0) @binding(4) var colSum: array; const F16_MAX: f32 = 65504.0; // One texel per thread: the box average of its field voxels, then its max into every brick whose trilinear samples // can read it (its own, plus the neighbour across a face it touches: wrapping in x and z, none past the floor or // surface in y). @compute @workgroup_size(4, 4, 4) fn prepVolume(@builtin(global_invocation_id) g: vec3) { let tex = u.dims1.xyz; if (g.x >= tex.x || g.y >= tex.y || g.z >= tex.z) { return; } let f = u.dims2.xyz; let k = f / tex; var sum = 0.0; for (var dz: u32 = 0u; dz < k.z; dz = dz + 1u) { for (var dy: u32 = 0u; dy < k.y; dy = dy + 1u) { for (var dx: u32 = 0u; dx < k.x; dx = dx + 1u) { let idx = ((g.y * k.y + dy) * f.z + (g.z * k.z + dz)) * f.x + (g.x * k.x + dx); sum = sum + f32(waterFood[idx]); } } } let v = min(sum * u.opts2.z, F16_MAX); textureStore(volOut, g, vec4(v, 0.0, 0.0, 1.0)); if (v <= 0.0) { return; } let m = max(1u, u32(ceil(v))); let nb = (tex + vec3(${ROAM3D_BRICK - 1}u)) / ${ROAM3D_BRICK}u; let b = vec3(g / ${ROAM3D_BRICK}u); let r = g % ${ROAM3D_BRICK}u; var lo = vec3(0); var hi = vec3(0); if (r.x == 0u && nb.x > 1u) { lo.x = -1; } if (r.x == ${ROAM3D_BRICK - 1}u && nb.x > 1u) { hi.x = 1; } if (r.z == 0u && nb.z > 1u) { lo.z = -1; } if (r.z == ${ROAM3D_BRICK - 1}u && nb.z > 1u) { hi.z = 1; } if (r.y == 0u && b.y > 0i) { lo.y = -1; } if (r.y == ${ROAM3D_BRICK - 1}u && u32(b.y) + 1u < nb.y) { hi.y = 1; } let n = vec3(nb); for (var oz = lo.z; oz <= hi.z; oz = oz + 1i) { let bz = (b.z + oz + n.z) % n.z; for (var oy = lo.y; oy <= hi.y; oy = oy + 1i) { let by = b.y + oy; for (var ox = lo.x; ox <= hi.x; ox = ox + 1i) { let bx = (b.x + ox + n.x) % n.x; atomicMax(&brickMax[u32((by * n.z + bz) * n.x + bx)], m); } } } } // One field column per thread: the u32 sum of waterFood from the floor to the surface (what the floor shader read // per fragment before, so the floor shadow is unchanged). @compute @workgroup_size(64) fn prepColumns(@builtin(global_invocation_id) g: vec3) { let f = u.dims2.xyz; let i = g.x; if (i >= f.x * f.z) { return; } let strideY = f.z * f.x; var idx = i; var sum: u32 = 0u; for (var vy: u32 = 0u; vy < f.y; vy = vy + 1u) { sum = sum + waterFood[idx]; idx = idx + strideY; } colSum[i] = sum; } `; /** * Instance compaction: three slot lists (spheres, bonds, shadows) in strictly ascending slot order and their * `drawIndirect` records, in two dispatches of ceil(cap / 512) workgroups. Every test is the vertex shaders' own, in the * same f32 arithmetic. No thread returns before a barrier: slots at or past `cap` give an empty mask. */ export const COMPACT_WGSL = /* wgsl */ `${COMMON_WGSL} @group(0) @binding(1) var cells: array; @group(0) @binding(2) var sphereIdx: array; @group(0) @binding(3) var bondIdx: array; @group(0) @binding(4) var shadowIdx: array; @group(0) @binding(5) var wgSums: array>; @group(0) @binding(6) var drawArgs: array; const WG: u32 = 256u; const PER_WG: u32 = ${ROAM3D_COMPACT_PER_WG}u; var blk: array, 256>; var loc: array, 256>; // Bit 0: the sphere draw keeps this slot, bit 1: the bond draw, bit 2: the shadow draw. fn instanceMask(slot: u32) -> u32 { if (slot >= u.dims0.z) { return 0u; } let base = slot * CELL_STRIDE; let flags = cells[base + 3u]; if ((flags & 1i) == 0i) { return 0u; } let ax = cells[base + 0u]; let ay = cells[base + 1u]; let az = cells[base + 2u]; let center = vec3(f32(ax), f32(ay), f32(az)) * u.ext.w; if (center.y > u.vis.y || center.z > u.vis.z) { return 0u; } var m = 1u; let hTiles = center.y * f32(u.dims0.x); if (!(hTiles > 64.0)) { m = m | 4u; } let mother = cells[base + 5u]; if (mother >= 0i && u32(mother) < u.dims0.z) { let mBase = u32(mother) * CELL_STRIDE; if ((cells[mBase + 3u] & 1i) != 0i) { let bx = cells[mBase + 0u]; let by = cells[mBase + 1u]; let bz = cells[mBase + 2u]; let halfSpan = i32(u.dims0.w >> 1u); if (!(abs(ax - bx) > halfSpan || abs(az - bz) > halfSpan)) { let pB = vec3(f32(bx), f32(by), f32(bz)) * u.ext.w; if (!(pB.y > u.vis.y || pB.z > u.vis.z)) { m = m | 2u; } } } } return m; } fn maskCounts(m: u32) -> vec4 { return vec4(m & 1u, (m >> 1u) & 1u, (m >> 2u) & 1u, 0u); } // Pass 1: each workgroup counts what its 512 slots give each list. @compute @workgroup_size(256) fn prepCompactCount(@builtin(local_invocation_index) lid: u32, @builtin(workgroup_id) wid: vec3) { let s0 = wid.x * PER_WG + 2u * lid; blk[lid] = maskCounts(instanceMask(s0)) + maskCounts(instanceMask(s0 + 1u)); workgroupBarrier(); for (var stride = WG / 2u; stride > 0u; stride = stride >> 1u) { if (lid < stride) { blk[lid] = blk[lid] + blk[lid + stride]; } workgroupBarrier(); } if (lid == 0u) { wgSums[wid.x] = blk[0]; } } // Pass 2: scan the (at most 256) workgroup counts and this workgroup's per-thread counts in shared memory, then write // each kept slot at its rank. Workgroup 0 also writes the three drawIndirect records. @compute @workgroup_size(256) fn prepCompactScatter(@builtin(local_invocation_index) lid: u32, @builtin(workgroup_id) wid: vec3) { let groups = (u.dims0.z + PER_WG - 1u) / PER_WG; let s0 = wid.x * PER_WG + 2u * lid; let m0 = instanceMask(s0); let m1 = instanceMask(s0 + 1u); let mine = maskCounts(m0) + maskCounts(m1); var g = vec4(0u); if (lid < groups) { g = wgSums[lid]; } blk[lid] = g; loc[lid] = mine; workgroupBarrier(); // Inclusive Hillis-Steele scans of both arrays. for (var off = 1u; off < WG; off = off << 1u) { var addB = vec4(0u); var addL = vec4(0u); if (lid >= off) { addB = blk[lid - off]; addL = loc[lid - off]; } workgroupBarrier(); blk[lid] = blk[lid] + addB; loc[lid] = loc[lid] + addL; workgroupBarrier(); } var p = loc[lid] - mine; if (wid.x > 0u) { p = p + blk[wid.x - 1u]; } if ((m0 & 1u) != 0u) { sphereIdx[p.x] = s0; p.x = p.x + 1u; } if ((m0 & 2u) != 0u) { bondIdx[p.y] = s0; p.y = p.y + 1u; } if ((m0 & 4u) != 0u) { shadowIdx[p.z] = s0; p.z = p.z + 1u; } if ((m1 & 1u) != 0u) { sphereIdx[p.x] = s0 + 1u; } if ((m1 & 2u) != 0u) { bondIdx[p.y] = s0 + 1u; } if ((m1 & 4u) != 0u) { shadowIdx[p.z] = s0 + 1u; } if (wid.x == 0u && lid == 0u) { let total = blk[WG - 1u]; drawArgs[${ROAM3D_INDIRECT.sphere / 4}] = 6u; drawArgs[${ROAM3D_INDIRECT.sphere / 4 + 1}] = total.x; drawArgs[${ROAM3D_INDIRECT.sphere / 4 + 2}] = 0u; drawArgs[${ROAM3D_INDIRECT.sphere / 4 + 3}] = 0u; drawArgs[${ROAM3D_INDIRECT.bond / 4}] = 6u; drawArgs[${ROAM3D_INDIRECT.bond / 4 + 1}] = total.y; drawArgs[${ROAM3D_INDIRECT.bond / 4 + 2}] = 0u; drawArgs[${ROAM3D_INDIRECT.bond / 4 + 3}] = 0u; drawArgs[${ROAM3D_INDIRECT.shadow / 4}] = 6u; drawArgs[${ROAM3D_INDIRECT.shadow / 4 + 1}] = total.z; drawArgs[${ROAM3D_INDIRECT.shadow / 4 + 2}] = 0u; drawArgs[${ROAM3D_INDIRECT.shadow / 4 + 3}] = 0u; } } `; export const ROAM3D_SHADERS = { sphere: SPHERE_WGSL, bond: BOND_WGSL, floor: FLOOR_WGSL, shadow: SHADOW_WGSL, haze: HAZE_WGSL, bloom: BLOOM_WGSL, prep: PREP_WGSL, compact: COMPACT_WGSL, } as const; /** Which bind-group layout of ROAM3D_BINDINGS each shader of ROAM3D_SHADERS is built against. */ export const ROAM3D_SHADER_LAYOUTS: Record = { sphere: 'cells', bond: 'cells', shadow: 'cells', floor: 'floor', haze: 'haze', bloom: 'bloom', prep: 'prep', compact: 'compact', }; /** One world's renderer resources: bound to one `Roam3dRenderSource`, destroyed together. */ interface WorldSet { readonly source: Roam3dRenderSource; readonly layout: Roam3dVolumeLayout; readonly owned: Disposer; readonly bricks: GPUBuffer; readonly prepGroup: GPUBindGroup; /** One cells bind group per instanced draw, each with that draw's compacted slot list. */ readonly sphereGroup: GPUBindGroup; readonly bondGroup: GPUBindGroup; readonly shadowGroup: GPUBindGroup; readonly compactGroup: GPUBindGroup; /** The three drawIndirect records the compaction writes (ROAM3D_INDIRECT offsets). */ readonly indirect: GPUBuffer; readonly floorGroup: GPUBindGroup; readonly volView: GPUTextureView; hazeGroup: GPUBindGroup | null; /** The scene colour view `hazeGroup` was built with (it is rebuilt when the targets are resized). */ hazeFor: GPUTextureView | null; /** Whether prep has run since this set was made, and at which data version (undefined: none was given). */ prepped: boolean; preppedVersion: number | undefined; /** Whether the instance lists were compacted since this set was made, at which data version and visible box. */ compacted: boolean; compactedVersion: number | undefined; compactedVis: [number, number]; destroyed: boolean; } export function createRoam3dRenderer( device: GPUDevice, canvasContext: GPUCanvasContext | null, format: GPUTextureFormat, source: Roam3dRenderSource, ): Roam3dRenderer { const owned = new Disposer(); const sized = new Disposer(); if (canvasContext) { canvasContext.configure({ device, format, alphaMode: 'opaque' }); } const cellLayout = device.createBindGroupLayout({ label: 'softroam3d-cell-bgl', entries: [...ROAM3D_BINDINGS.cells], }); const floorLayout = device.createBindGroupLayout({ label: 'softroam3d-floor-bgl', entries: [...ROAM3D_BINDINGS.floor], }); const hazeLayout = device.createBindGroupLayout({ label: 'softroam3d-haze-bgl', entries: [...ROAM3D_BINDINGS.haze], }); const bloomLayout = device.createBindGroupLayout({ label: 'softroam3d-bloom-bgl', entries: [...ROAM3D_BINDINGS.bloom], }); const prepLayout = device.createBindGroupLayout({ label: 'softroam3d-prep-bgl', entries: [...ROAM3D_BINDINGS.prep], }); const compactLayout = device.createBindGroupLayout({ label: 'softroam3d-compact-bgl', entries: [...ROAM3D_BINDINGS.compact], }); const mSphere = device.createShaderModule({ label: 'softroam3d-sphere', code: SPHERE_WGSL }); const mBond = device.createShaderModule({ label: 'softroam3d-bond', code: BOND_WGSL }); const mFloor = device.createShaderModule({ label: 'softroam3d-floor', code: FLOOR_WGSL }); const mShadow = device.createShaderModule({ label: 'softroam3d-shadow', code: SHADOW_WGSL }); const mHaze = device.createShaderModule({ label: 'softroam3d-haze', code: HAZE_WGSL }); const mBloom = device.createShaderModule({ label: 'softroam3d-bloom', code: BLOOM_WGSL }); const mPrep = device.createShaderModule({ label: 'softroam3d-prep', code: PREP_WGSL }); const mCompact = device.createShaderModule({ label: 'softroam3d-compact', code: COMPACT_WGSL }); const modules: readonly [string, GPUShaderModule][] = [ ['sphere', mSphere], ['bond', mBond], ['floor', mFloor], ['shadow', mShadow], ['haze', mHaze], ['bloom', mBloom], ['prep', mPrep], ['compact', mCompact], ]; const cellPipeLayout = device.createPipelineLayout({ bindGroupLayouts: [cellLayout] }); const floorPipeLayout = device.createPipelineLayout({ bindGroupLayouts: [floorLayout] }); const hazePipeLayout = device.createPipelineLayout({ bindGroupLayouts: [hazeLayout] }); const bloomPipeLayout = device.createPipelineLayout({ bindGroupLayouts: [bloomLayout] }); const prepPipeLayout = device.createPipelineLayout({ bindGroupLayouts: [prepLayout] }); const compactPipeLayout = device.createPipelineLayout({ bindGroupLayouts: [compactLayout] }); const pPrepVolume = device.createComputePipeline({ label: 'softroam3d-prep-volume', layout: prepPipeLayout, compute: { module: mPrep, entryPoint: 'prepVolume' }, }); const pPrepColumns = device.createComputePipeline({ label: 'softroam3d-prep-columns', layout: prepPipeLayout, compute: { module: mPrep, entryPoint: 'prepColumns' }, }); const pCompactCount = device.createComputePipeline({ label: 'softroam3d-compact-count', layout: compactPipeLayout, compute: { module: mCompact, entryPoint: 'prepCompactCount' }, }); const pCompactScatter = device.createComputePipeline({ label: 'softroam3d-compact-scatter', layout: compactPipeLayout, compute: { module: mCompact, entryPoint: 'prepCompactScatter' }, }); const pFloor = device.createRenderPipeline({ label: 'softroam3d-floor', layout: floorPipeLayout, vertex: { module: mFloor, entryPoint: 'vs' }, fragment: { module: mFloor, entryPoint: 'fs', targets: [{ format: SCENE_COLOR_FORMAT }] }, primitive: { topology: 'triangle-list', frontFace: 'ccw', cullMode: 'back' }, depthStencil: { format: SCENE_DEPTH_FORMAT, depthWriteEnabled: true, depthCompare: 'less' }, }); const pShadow = device.createRenderPipeline({ label: 'softroam3d-shadow', layout: cellPipeLayout, vertex: { module: mShadow, entryPoint: 'vs' }, fragment: { module: mShadow, entryPoint: 'fs', targets: [{ format: SCENE_COLOR_FORMAT, blend: { color: { srcFactor: 'src-alpha', dstFactor: 'one-minus-src-alpha' }, // Preserve the floor's bloom weight in alpha while darkening RGB under shadows. alpha: { srcFactor: 'zero', dstFactor: 'one' }, }, }], }, primitive: { topology: 'triangle-list', frontFace: 'ccw', cullMode: 'back' }, depthStencil: { format: SCENE_DEPTH_FORMAT, depthWriteEnabled: false, depthCompare: 'less-equal' }, }); const pSphere = device.createRenderPipeline({ label: 'softroam3d-sphere', layout: cellPipeLayout, vertex: { module: mSphere, entryPoint: 'vs' }, fragment: { module: mSphere, entryPoint: 'fs', targets: [{ format: SCENE_COLOR_FORMAT }] }, primitive: { topology: 'triangle-list', cullMode: 'none' }, depthStencil: { format: SCENE_DEPTH_FORMAT, depthWriteEnabled: true, depthCompare: 'less' }, }); const pBond = device.createRenderPipeline({ label: 'softroam3d-bond', layout: cellPipeLayout, vertex: { module: mBond, entryPoint: 'vs' }, fragment: { module: mBond, entryPoint: 'fs', targets: [{ format: SCENE_COLOR_FORMAT }] }, primitive: { topology: 'triangle-list', cullMode: 'none' }, depthStencil: { format: SCENE_DEPTH_FORMAT, depthWriteEnabled: true, depthCompare: 'less' }, }); const pHaze = device.createRenderPipeline({ label: 'softroam3d-haze', layout: hazePipeLayout, vertex: { module: mHaze, entryPoint: 'vs' }, fragment: { module: mHaze, entryPoint: 'fs', targets: [{ format }] }, primitive: { topology: 'triangle-list' }, }); const makeBloomPipe = (name: string, entryPoint: string) => device.createRenderPipeline({ label: `softroam3d-bloom-${name}`, layout: bloomPipeLayout, vertex: { module: mBloom, entryPoint: 'vs' }, fragment: { module: mBloom, entryPoint, targets: [{ format: SCENE_COLOR_FORMAT }] }, primitive: { topology: 'triangle-list' }, }); const pBloomExtract = makeBloomPipe('extract', 'fsExtract'); const pBloomDown = makeBloomPipe('down', 'fsDown'); const pBloomBlurH = makeBloomPipe('blur-h', 'fsBlurH'); const pBloomBlurV = makeBloomPipe('blur-v', 'fsBlurV'); const ubo = owned.add(device.createBuffer({ label: 'softroam3d-uniforms', size: UNIFORM_BYTES, usage: GPUBufferUsage.UNIFORM | GPUBufferUsage.COPY_DST, })); // Repeat across the horizontal torus (x = U, z = W), clamped through the depth (y = V). const volSampler = device.createSampler({ label: 'softroam3d-volume-sampler', addressModeU: 'repeat', addressModeV: 'clamp-to-edge', addressModeW: 'repeat', magFilter: 'linear', minFilter: 'linear', mipmapFilter: 'nearest', }); const bloomSampler = device.createSampler({ label: 'softroam3d-bloom-sampler', addressModeU: 'clamp-to-edge', addressModeV: 'clamp-to-edge', magFilter: 'linear', minFilter: 'linear', mipmapFilter: 'nearest', }); let active: WorldSet | null = null; let pending: WorldSet | null = null; let colView: GPUTextureView | null = null; let depView: GPUTextureView | null = null; let bloomA1View: GPUTextureView | null = null; let bloomB1View: GPUTextureView | null = null; let bloomA2View: GPUTextureView | null = null; let bloomB2View: GPUTextureView | null = null; let bgBloomExtract: GPUBindGroup | null = null; let bgBloomA1: GPUBindGroup | null = null; let bgBloomB1: GPUBindGroup | null = null; let bgBloomA2: GPUBindGroup | null = null; let bgBloomB2: GPUBindGroup | null = null; let targetW = 0; let targetH = 0; let frameNo = 0; let destroyed = false; const uboBuf = new ArrayBuffer(UNIFORM_BYTES); const uboF32 = new Float32Array(uboBuf); const uboU32 = new Uint32Array(uboBuf); function buildHazeGroup(set: WorldSet): void { if (!colView || !depView || !bloomA1View || !bloomA2View) { set.hazeGroup = null; set.hazeFor = null; return; } set.hazeGroup = device.createBindGroup({ label: 'softroam3d-haze-bg', layout: hazeLayout, entries: [ { binding: 0, resource: { buffer: ubo } }, { binding: 1, resource: { buffer: set.bricks } }, { binding: 2, resource: colView }, { binding: 3, resource: depView }, { binding: 4, resource: set.volView }, { binding: 5, resource: volSampler }, { binding: 6, resource: bloomA1View }, { binding: 7, resource: bloomA2View }, { binding: 8, resource: bloomSampler }, ], }); set.hazeFor = colView; } /** Make every per-world resource for `src`; on a throw, whatever was made is destroyed and nothing else changes. */ function buildSet(src: Roam3dRenderSource): WorldSet { const d = src.dims; if (d.cap > ROAM3D_COMPACT_MAX_CAP) { throw new Error(`softroam3d: cap ${d.cap} is above the renderer's ${ROAM3D_COMPACT_MAX_CAP} slots`); } const layout = roam3dVolumeLayout(d); const setOwned = new Disposer(); try { const vol = setOwned.add(device.createTexture({ label: 'softroam3d-volume', dimension: '3d', size: layout.tex, format: VOLUME_FORMAT, usage: TEX_TEXTURE_BINDING | TEX_STORAGE_BINDING, })); const volView = vol.createView({ label: 'softroam3d-volume-view', dimension: '3d' }); const colSum = setOwned.add(device.createBuffer({ label: 'softroam3d-col-sum', size: Math.max(16, layout.columns * 4), usage: BUF_STORAGE, })); const bricks = setOwned.add(device.createBuffer({ label: 'softroam3d-bricks', size: Math.max(16, layout.brickCount * 4), usage: BUF_STORAGE | BUF_COPY_DST, })); const prepGroup = device.createBindGroup({ label: 'softroam3d-prep-bg', layout: prepLayout, entries: [ { binding: 0, resource: { buffer: ubo } }, { binding: 1, resource: { buffer: src.waterFood } }, { binding: 2, resource: volView }, { binding: 3, resource: { buffer: bricks } }, { binding: 4, resource: { buffer: colSum } }, ], }); const listBytes = Math.max(16, d.cap * 4); const list = (name: string) => setOwned.add(device.createBuffer({ label: `softroam3d-${name}-idx`, size: listBytes, usage: BUF_STORAGE, })); const sphereIdx = list('sphere'); const bondIdx = list('bond'); const shadowIdx = list('shadow'); const wgSums = setOwned.add(device.createBuffer({ label: 'softroam3d-wg-sums', size: Math.max(16, roam3dCompactGroups(d.cap) * 16), usage: BUF_STORAGE, })); const indirect = setOwned.add(device.createBuffer({ label: 'softroam3d-indirect', size: ROAM3D_INDIRECT.bytes, usage: BUF_INDIRECT | BUF_STORAGE | BUF_COPY_DST, })); const compactGroup = device.createBindGroup({ label: 'softroam3d-compact-bg', layout: compactLayout, entries: [ { binding: 0, resource: { buffer: ubo } }, { binding: 1, resource: { buffer: src.cells } }, { binding: 2, resource: { buffer: sphereIdx } }, { binding: 3, resource: { buffer: bondIdx } }, { binding: 4, resource: { buffer: shadowIdx } }, { binding: 5, resource: { buffer: wgSums } }, { binding: 6, resource: { buffer: indirect } }, ], }); const drawGroup = (name: string, idx: GPUBuffer) => device.createBindGroup({ label: `softroam3d-${name}-bg`, layout: cellLayout, entries: [ { binding: 0, resource: { buffer: ubo } }, { binding: 1, resource: { buffer: src.cells } }, { binding: 2, resource: { buffer: idx } }, ], }); const sphereGroup = drawGroup('sphere', sphereIdx); const bondGroup = drawGroup('bond', bondIdx); const shadowGroup = drawGroup('shadow', shadowIdx); const floorGroup = device.createBindGroup({ label: 'softroam3d-floor-bg', layout: floorLayout, entries: [ { binding: 0, resource: { buffer: ubo } }, { binding: 1, resource: { buffer: src.floorFood } }, { binding: 2, resource: { buffer: colSum } }, ], }); const set: WorldSet = { source: src, layout, owned: setOwned, bricks, prepGroup, sphereGroup, bondGroup, shadowGroup, compactGroup, indirect, floorGroup, volView, hazeGroup: null, hazeFor: null, prepped: false, preppedVersion: undefined, compacted: false, compactedVersion: undefined, compactedVis: [Number.NaN, Number.NaN], destroyed: false, }; buildHazeGroup(set); return set; } catch (err) { setOwned.disposeAll(); throw err; } } function destroySet(set: WorldSet | null): void { if (!set || set.destroyed) return; set.destroyed = true; set.hazeGroup = null; set.owned.disposeAll(); } active = buildSet(source); function ensureTargets(w: number, h: number): void { const rw = Math.max(1, Math.floor(w)); const rh = Math.max(1, Math.floor(h)); if (colView && rw === targetW && rh === targetH) return; sized.disposeAll(); targetW = rw; targetH = rh; const usage = GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.TEXTURE_BINDING; colView = sized.add(device.createTexture({ label: 'softroam3d-scene-color', size: [rw, rh], format: SCENE_COLOR_FORMAT, usage, })).createView(); depView = sized.add(device.createTexture({ label: 'softroam3d-scene-depth', size: [rw, rh], format: SCENE_DEPTH_FORMAT, usage, })).createView(); const w1 = Math.max(1, (rw + 1) >> 1); const h1 = Math.max(1, (rh + 1) >> 1); const w2 = Math.max(1, (w1 + 1) >> 1); const h2 = Math.max(1, (h1 + 1) >> 1); const makeBloomTex = (label: string, bw: number, bh: number) => sized.add(device.createTexture({ label, size: [bw, bh], format: SCENE_COLOR_FORMAT, usage, })).createView(); bloomA1View = makeBloomTex('softroam3d-bloom-a1', w1, h1); bloomB1View = makeBloomTex('softroam3d-bloom-b1', w1, h1); bloomA2View = makeBloomTex('softroam3d-bloom-a2', w2, h2); bloomB2View = makeBloomTex('softroam3d-bloom-b2', w2, h2); const makeBloomBg = (label: string, view: GPUTextureView) => device.createBindGroup({ label, layout: bloomLayout, entries: [ { binding: 0, resource: view }, { binding: 1, resource: bloomSampler }, ], }); bgBloomExtract = makeBloomBg('softroam3d-bloom-extract-bg', colView); bgBloomA1 = makeBloomBg('softroam3d-bloom-a1-bg', bloomA1View); bgBloomB1 = makeBloomBg('softroam3d-bloom-b1-bg', bloomB1View); bgBloomA2 = makeBloomBg('softroam3d-bloom-a2-bg', bloomA2View); bgBloomB2 = makeBloomBg('softroam3d-bloom-b2-bg', bloomB2View); if (active) buildHazeGroup(active); } return { stageSource(nextSource: Roam3dRenderSource): () => void { if (destroyed) return () => {}; // Hold at most one staged set: a new stage supersedes (and frees) the previous one, whose commit becomes a no-op. const prevPending = pending; pending = null; destroySet(prevPending); const staged = buildSet(nextSource); pending = staged; return () => { if (destroyed || pending !== staged || staged.destroyed) return; pending = null; const old = active; active = staged; if (staged.hazeFor !== colView) buildHazeGroup(staged); destroySet(old); }; }, discardStagedSource(): void { const stale = pending; pending = null; destroySet(stale); }, setSource(nextSource: Roam3dRenderSource): void { if (destroyed) return; const next = buildSet(nextSource); const old = active; // A direct bind supersedes any staged set: its commit becomes a no-op instead of replacing this source later. const stale = pending; pending = null; active = next; destroySet(stale); destroySet(old); }, resize(w: number, h: number): void { if (destroyed) return; ensureTargets(w, h); }, render(camera: Roam3dCamera | Roam3dCameraMatrices, opts: Roam3dRenderOpts = {}): void { if (destroyed || !active) return; const outTex = opts.target ?? canvasContext?.getCurrentTexture(); if (!outTex) { throw new Error('softroam3d: render requires either a configured GPUCanvasContext or opts.target'); } const w = outTex.width; const h = outTex.height; ensureTargets(w, h); const set = active; if (!colView || !depView) return; if (!set.hazeGroup || set.hazeFor !== colView) buildHazeGroup(set); if (!set.hazeGroup) return; const d = set.source.dims; const lay = set.layout; const cam = camera instanceof Roam3dCamera ? camera.matrices(w / h) : camera; const extX = 1.0; const extY = d.height / d.size; const extZ = 1.0; const peel = Math.max(0, Math.min(0.95, opts.peel ?? 0)); const slice = Math.max(0.05, Math.min(1, opts.slice ?? 1)); const visY = extY * (1 - peel); const visZ = extZ * slice; const clipped = peel > 1e-4 || slice < 1 - 1e-4 ? 1 : 0; const cellScale = Math.max(0.25, Math.min(2.5, opts.cellScale ?? 1.0)); const cellRad = (0.5 / d.size) * cellScale; const haze = opts.haze ?? 0.75; const glow = Math.max(0, Math.min(1.5, opts.glow ?? 1.0)); const animTime = opts.still ? 0 : (Number.isFinite(opts.time) && opts.time! > 0 ? opts.time! : 0); const glass = opts.glass ?? true; const detail = opts.detail ?? 1.0; const jitterFrame = opts.still ? 0 : frameNo++; const minPx = Math.max(0, Number.isFinite(opts.minPixelRadius) ? opts.minPixelRadius! : 0); // Pixels per world unit at view depth 1: half the target height times the projection's y scale. const pxPerUnit = 0.5 * h * (cam.proj[5] ?? 1); const skipEmpty = opts.skipEmpty ?? roam3dSkipEmptyDefault(lay); uboF32.set(cam.viewProj, 0); uboF32.set(cam.invViewProj, 16); uboF32[32] = cam.right[0]; uboF32[33] = cam.right[1]; uboF32[34] = cam.right[2]; uboF32[35] = w; uboF32[36] = cam.up[0]; uboF32[37] = cam.up[1]; uboF32[38] = cam.up[2]; uboF32[39] = h; uboF32[40] = cam.back[0]; uboF32[41] = cam.back[1]; uboF32[42] = cam.back[2]; uboF32[43] = cellRad; uboF32[44] = cam.eye[0]; uboF32[45] = cam.eye[1]; uboF32[46] = cam.eye[2]; uboF32[47] = jitterFrame; uboF32[48] = extX; uboF32[49] = extY; uboF32[50] = extZ; uboF32[51] = 1 / d.spanXZ; uboF32[52] = extX; uboF32[53] = visY; uboF32[54] = visZ; uboF32[55] = clipped; // Deep marine dark-jar backdrop (matches --field look). uboF32[56] = 0.032; uboF32[57] = 0.058; uboF32[58] = 0.095; uboF32[59] = glass ? 1 : 0; uboF32[60] = haze; uboF32[61] = 1 / ROAM3D_WATER_FOOD_SCALE; uboF32[62] = 1 / ROAM3D_FLOOR_FOOD_SCALE; uboF32[63] = detail; uboU32[64] = d.size; uboU32[65] = d.height; uboU32[66] = d.cap; uboU32[67] = d.spanXZ; uboU32[68] = lay.tex[0]; uboU32[69] = lay.tex[1]; uboU32[70] = lay.tex[2]; uboU32[71] = d.spanY; uboU32[72] = d.fx; uboU32[73] = d.fy; uboU32[74] = d.fz; uboU32[75] = skipEmpty ? 1 : 0; uboF32[76] = minPx; uboF32[77] = pxPerUnit; uboF32[78] = lay.volScale * lay.snowGain; uboF32[79] = lay.colScale; uboF32[80] = glow; uboF32[81] = animTime; uboF32[82] = 0; uboF32[83] = 0; device.queue.writeBuffer(ubo, 0, uboBuf); const timing = opts.timing; const t0 = timing?.first ?? 0; const stamps = (begin: number) => timing ? { timestampWrites: { querySet: timing.querySet, beginningOfPassWriteIndex: t0 + begin, endOfPassWriteIndex: t0 + begin + 1 } } : {}; const enc = device.createCommandEncoder({ label: 'softroam3d-frame' }); // Stage 0: rebuild the volume texture, its bricks and the column sums when the data may have changed, and the // three instance lists when the data or the visible box (peel/slice) may have changed. const fresh = opts.dataVersion !== undefined && set.prepped && set.preppedVersion === opts.dataVersion; const listsFresh = opts.dataVersion !== undefined && set.compacted && set.compactedVersion === opts.dataVersion && set.compactedVis[0] === visY && set.compactedVis[1] === visZ; const compact = d.cap > 0 && !listsFresh; if (!fresh) enc.clearBuffer(set.bricks); if (!fresh || compact) { const prep = enc.beginComputePass({ label: 'softroam3d-prep', ...stamps(0) }); if (!fresh) { prep.setPipeline(pPrepVolume); prep.setBindGroup(0, set.prepGroup); prep.dispatchWorkgroups(Math.ceil(lay.tex[0] / 4), Math.ceil(lay.tex[1] / 4), Math.ceil(lay.tex[2] / 4)); prep.setPipeline(pPrepColumns); prep.dispatchWorkgroups(Math.ceil(lay.columns / 64)); set.prepped = true; set.preppedVersion = opts.dataVersion; } if (compact) { const groups = roam3dCompactGroups(d.cap); prep.setPipeline(pCompactCount); prep.setBindGroup(0, set.compactGroup); prep.dispatchWorkgroups(groups); prep.setPipeline(pCompactScatter); prep.dispatchWorkgroups(groups); set.compacted = true; set.compactedVersion = opts.dataVersion; set.compactedVis = [visY, visZ]; } prep.end(); } // Stage 1 (floor + shadows, then spheres + bonds) into offscreen HDR colour + depth. const opaquePass = enc.beginRenderPass({ label: 'softroam3d-opaque', colorAttachments: [{ view: colView, loadOp: 'clear', storeOp: 'store', clearValue: { r: 0, g: 0, b: 0, a: 0 }, }], depthStencilAttachment: { view: depView, depthClearValue: 1.0, depthLoadOp: 'clear', depthStoreOp: 'store', }, ...stamps(2), }); // Floor plane shaded by floorFood + overhead water column shadow, plus projected cell shadows. opaquePass.setPipeline(pFloor); opaquePass.setBindGroup(0, set.floorGroup); opaquePass.draw(6); if (d.cap > 0) { // Each draw covers only its compacted list (instance counts written by the compaction). opaquePass.setPipeline(pShadow); opaquePass.setBindGroup(0, set.shadowGroup); opaquePass.drawIndirect(set.indirect, ROAM3D_INDIRECT.shadow); // Instanced sphere impostors and mother-daughter bond ribbons. opaquePass.setPipeline(pSphere); opaquePass.setBindGroup(0, set.sphereGroup); opaquePass.drawIndirect(set.indirect, ROAM3D_INDIRECT.sphere); opaquePass.setPipeline(pBond); opaquePass.setBindGroup(0, set.bondGroup); opaquePass.drawIndirect(set.indirect, ROAM3D_INDIRECT.bond); } opaquePass.end(); // Stage 1.5: dual-scale separable HDR bloom on glowing cells/bonds (skipped when glow == 0). if (glow > 0 && bloomA1View && bloomB1View && bloomA2View && bloomB2View && bgBloomExtract && bgBloomA1 && bgBloomB1 && bgBloomA2 && bgBloomB2) { const runBloom = (label: string, pipe: GPURenderPipeline, bg: GPUBindGroup, dst: GPUTextureView) => { const pass = enc.beginRenderPass({ label, colorAttachments: [{ view: dst, loadOp: 'clear', storeOp: 'store', clearValue: { r: 0, g: 0, b: 0, a: 1 } }], }); pass.setPipeline(pipe); pass.setBindGroup(0, bg); pass.draw(3); pass.end(); }; runBloom('softroam3d-bloom-extract', pBloomExtract, bgBloomExtract, bloomA1View); runBloom('softroam3d-bloom-h1', pBloomBlurH, bgBloomA1, bloomB1View); runBloom('softroam3d-bloom-v1', pBloomBlurV, bgBloomB1, bloomA1View); runBloom('softroam3d-bloom-down', pBloomDown, bgBloomA1, bloomA2View); runBloom('softroam3d-bloom-h2', pBloomBlurH, bgBloomA2, bloomB2View); runBloom('softroam3d-bloom-v2', pBloomBlurV, bgBloomB2, bloomA2View); } // Stage 2: front-to-back volumetric raymarch + glass tank edges + glow bloom composited over sceneDepth. const hazePass = enc.beginRenderPass({ label: 'softroam3d-haze', colorAttachments: [{ view: outTex.createView(), loadOp: 'clear', storeOp: 'store', clearValue: { r: 0, g: 0, b: 0, a: 1 }, }], ...stamps(4), }); hazePass.setPipeline(pHaze); hazePass.setBindGroup(0, set.hazeGroup); hazePass.draw(3); hazePass.end(); device.queue.submit([enc.finish()]); }, async checkShaders(): Promise { const errors: string[] = []; for (const [name, mod] of modules) { const info = await mod.getCompilationInfo(); for (const msg of info.messages) { if (msg.type === 'error') { errors.push(`${name}:${msg.lineNum}:${msg.linePos}: ${msg.message}`); } } } return errors; }, destroy(): void { if (destroyed) return; destroyed = true; const a = active; const p = pending; active = null; pending = null; destroySet(p); destroySet(a); colView = null; depView = null; bloomA1View = null; bloomB1View = null; bloomA2View = null; bloomB2View = null; bgBloomExtract = null; bgBloomA1 = null; bgBloomB1 = null; bgBloomA2 = null; bgBloomB2 = null; targetW = 0; targetH = 0; if (canvasContext) { try { canvasContext.unconfigure(); } catch { /* context already lost */ } } sized.disposeAll(); owned.disposeAll(); }, }; }