// Headless WebGPU verification for the Soft Roam 3D renderer (apps/lab/src/softroam3d/render.ts). // Compiles all WGSL modules, verifies zero compilation errors via getCompilationInfo(), creates all // pipelines, renders the real Phase A integer physics kernel (`foundRoam3d(defaultRoam3dConfig())` // stepped 200 steps) into an offscreen RGBA8 texture (both full and peeled/sliced), verifies // `renderer.setSource()` source switching, asserts frames are non-blank, and measures render FPS. // Then the three preset cubes (`cube128`, `cube256`, `cube512`, founded and stepped on the CPU reference and uploaded): // non-blank frames with visible cells, the one-pixel cell floor at 512, empty-brick skipping against the plain march, // prep skipped on an unchanged `dataVersion`, a GPU twin parity frame on cube128, and a per-pass render benchmark // (`timestamp-query` when the adapter has it, wall clock otherwise) for every world. Every instanced draw goes through // the renderer's slot-order instance compaction, so the round-trip and parity checks above cover it; the dataVersion // block also checks the lists follow peel/slice changes. `--bench-populated` adds a steady-state benchmark: every preset // world warmed on the GPU twin to step 3000 (BL_RENDER_WARM_STEPS), timed per pass at 768x576 and 1920x1080, with the // waterFood distribution and how far the snow moves the pixels. // // deno run -A --no-lock tests/deno/softroam3d_render.ts // BL_RENDER_BENCH_FRAMES=120 deno run -A --no-lock tests/deno/softroam3d_render.ts // deno run -A --no-lock tests/deno/softroam3d_render.ts --bench-populated import { defaultRoam3dConfig, foundRoam3d, foundRoam3dWorld, packRenderCells, R3_NONE, R3_RENDER_STRIDE, roam3dDims, type Roam3dDims, type Roam3dRenderSource, type Roam3dWorld, type Roam3dWorldId, } from "../../packages/softroam3d-ref/src/index.ts"; import { Roam3dGpu } from "../../packages/softroam3d-gpu/src/index.ts"; import { Roam3dCamera } from "../../apps/lab/src/softroam3d/camera.ts"; import { createDemoProvider } from "../../apps/lab/src/softroam3d/demo.ts"; import { createRoam3dRenderer, type Roam3dRenderOpts, ROAM3D_TIMING_SLOTS, roam3dSkipEmptyDefault, roam3dVolumeLayout, } from "../../apps/lab/src/softroam3d/render.ts"; import { createRoam3dBufferSource } from "../../apps/lab/src/softroam3d/source.ts"; function assert(cond: unknown, msg: string): asserts cond { if (!cond) throw new Error(`softroam3d_render: ${msg}`); } const adapter = await navigator.gpu?.requestAdapter({ powerPreference: "high-performance" }); assert(adapter, "no WebGPU adapter available"); const hasTimestamps = adapter.features.has("timestamp-query"); const device = await adapter.requestDevice(hasTimestamps ? { requiredFeatures: ["timestamp-query"] } : undefined); device.pushErrorScope("validation"); const world = foundRoam3d(defaultRoam3dConfig()); for (let i = 0; i < 200; i++) world.stepOnce(); const census = world.census(); assert(census.residual === 0, `expected residual 0, got ${census.residual}`); assert(census.cells > 160, `expected real world growth, got ${census.cells} cells`); const packedCells = new Int32Array(world.dims.cap * R3_RENDER_STRIDE); packRenderCells(world.cells, world.dims.cap, packedCells); const source = createRoam3dBufferSource(device, world.dims); source.uploadCells(packedCells); source.uploadFloor(world.fields.floorFood); source.uploadWater(world.fields.waterFood); const format: GPUTextureFormat = "rgba8unorm"; const renderer = createRoam3dRenderer(device, null, format, source); const shaderErrors = await renderer.checkShaders(); assert(shaderErrors.length === 0, `WGSL compilation errors:\n ${shaderErrors.join("\n ")}`); console.log("WGSL modules compiled with 0 errors."); const W = 256; const H = 256; const outTex = device.createTexture({ label: "softroam3d-test-target", size: [W, H], format, usage: GPUTextureUsage.RENDER_ATTACHMENT | GPUTextureUsage.COPY_SRC, }); const bytesPerRow = W * 4; // 1024, multiple of 256 const readBuf = device.createBuffer({ label: "softroam3d-test-readback", size: bytesPerRow * H, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ, }); async function renderAndRead( dims = world.dims, opts: Omit = {}, ): Promise { const cam = new Roam3dCamera("oblique", dims); renderer.render(cam, { target: outTex, still: true, ...opts }); const enc = device.createCommandEncoder(); enc.copyTextureToBuffer({ texture: outTex }, { buffer: readBuf, bytesPerRow }, [W, H]); device.queue.submit([enc.finish()]); await readBuf.mapAsync(GPUMapMode.READ); const copy = new Uint8Array(readBuf.getMappedRange()).slice(); readBuf.unmap(); return copy; } const fullPixels = await renderAndRead(); let nonZeroAlpha = 0; let brightPixels = 0; let minLuma = 255; let maxLuma = 0; const uniqueColors = new Set(); for (let i = 0; i < fullPixels.length; i += 4) { const r = fullPixels[i]!; const g = fullPixels[i + 1]!; const b = fullPixels[i + 2]!; const a = fullPixels[i + 3]!; if (a > 0) nonZeroAlpha++; const luma = Math.round(0.299 * r + 0.587 * g + 0.114 * b); if (luma < minLuma) minLuma = luma; if (luma > maxLuma) maxLuma = luma; if (luma >= 90) brightPixels++; uniqueColors.add(((r >> 3) << 10) | ((g >> 3) << 5) | (b >> 3)); } assert(nonZeroAlpha === W * H, `expected opaque output, got ${nonZeroAlpha}/${W * H}`); assert(maxLuma - minLuma >= 60, `frame looks flat/blank (luma range ${minLuma}..${maxLuma})`); assert(brightPixels >= 50, `expected visible lit cells/floor/edges, got only ${brightPixels} bright pixels`); assert(uniqueColors.size >= 40, `expected varied scene colours, got only ${uniqueColors.size} quantized colours`); console.log( `Full real-kernel frame ${W}x${H} (step ${census.step}, ${census.cells} cells, ${census.bodies} bodies): luma ${minLuma}..${maxLuma}, brightPx=${brightPixels}, quantizedColors=${uniqueColors.size}`, ); const slicedPixels = await renderAndRead(world.dims, { peel: 0.45, slice: 0.65 }); let diffPixels = 0; for (let i = 0; i < fullPixels.length; i += 4) { if ( Math.abs(fullPixels[i]! - slicedPixels[i]!) + Math.abs(fullPixels[i + 1]! - slicedPixels[i + 1]!) + Math.abs(fullPixels[i + 2]! - slicedPixels[i + 2]!) > 12 ) { diffPixels++; } } assert(diffPixels >= 200, `peel/slice had negligible visual effect (${diffPixels} differing pixels)`); console.log(`Peel/slice frame differs in ${diffPixels} pixels.`); // Verify live source switching (`setSource`) from real kernel source to demo source and back. const demo = createDemoProvider(); demo.start(1); demo.step(10); const demoPacked = demo.pack(); const demoSource = createRoam3dBufferSource(device, demo.dims); demoSource.uploadCells(demoPacked.cells); demoSource.uploadFloor(demoPacked.floorFood); demoSource.uploadWater(demoPacked.waterFood); renderer.setSource(demoSource); const demoPixels = await renderAndRead(demo.dims); let sourceDiff = 0; for (let i = 0; i < fullPixels.length; i += 4) { if ( Math.abs(fullPixels[i]! - demoPixels[i]!) + Math.abs(fullPixels[i + 1]! - demoPixels[i + 1]!) + Math.abs(fullPixels[i + 2]! - demoPixels[i + 2]!) > 12 ) { sourceDiff++; } } assert(sourceDiff >= 200, `setSource() did not change rendered frame (${sourceDiff} differing pixels)`); renderer.setSource(source); const restoredPixels = await renderAndRead(world.dims); let restoreDiffBytes = 0; for (let i = 0; i < fullPixels.length; i++) { if (fullPixels[i] !== restoredPixels[i]) restoreDiffBytes++; } assert( restoreDiffBytes === 0, `setSource(source) return switch did not restore original frame (${restoreDiffBytes} differing bytes)`, ); console.log(`setSource() round-trip verified (${sourceDiff} differing pixels on switch, 0 differing bytes on return).`); // Render one frame straight from `Roam3dGpu.renderSource()` after stepping 50 steps and assert it // matches the frame rendered from CPU-uploaded buffers at the exact same step pixel for pixel. const parityCfg = defaultRoam3dConfig(); const cpu50 = foundRoam3d(parityCfg); const gpu50 = await Roam3dGpu.create(device, parityCfg); gpu50.upload(cpu50); gpu50.step(50); cpu50.advance(50); const gpuDigest50 = await gpu50.digest(); const cpuDigest50 = cpu50.digest(); assert(gpuDigest50 === cpuDigest50, `GPU/CPU state digest mismatch at step 50: gpu=${gpuDigest50}, cpu=${cpuDigest50}`); renderer.setSource(gpu50.renderSource()); const gpu50Pixels = await renderAndRead(gpu50.dims); const cpu50Packed = new Int32Array(cpu50.dims.cap * R3_RENDER_STRIDE); packRenderCells(cpu50.cells, cpu50.dims.cap, cpu50Packed); const cpu50Source = createRoam3dBufferSource(device, cpu50.dims); cpu50Source.uploadCells(cpu50Packed); cpu50Source.uploadFloor(cpu50.fields.floorFood); cpu50Source.uploadWater(cpu50.fields.waterFood); renderer.setSource(cpu50Source); const cpu50Pixels = await renderAndRead(cpu50.dims); let parityDiffPixels = 0; let parityMaxChannelDiff = 0; for (let i = 0; i < gpu50Pixels.length; i += 4) { const dr = Math.abs(gpu50Pixels[i]! - cpu50Pixels[i]!); const dg = Math.abs(gpu50Pixels[i + 1]! - cpu50Pixels[i + 1]!); const db = Math.abs(gpu50Pixels[i + 2]! - cpu50Pixels[i + 2]!); const da = Math.abs(gpu50Pixels[i + 3]! - cpu50Pixels[i + 3]!); const m = Math.max(dr, dg, db, da); if (m > 0) parityDiffPixels++; if (m > parityMaxChannelDiff) parityMaxChannelDiff = m; } assert( parityDiffPixels === 0, `GPU renderSource() vs CPU-uploaded frame differed at step 50 (${parityDiffPixels} pixels, max channel diff ${parityMaxChannelDiff})`, ); console.log( `GPU renderSource() vs CPU-uploaded parity at step 50: exact pixel-for-pixel match (${W}x${H}, digest ${gpuDigest50}).`, ); renderer.setSource(source); cpu50Source.destroy(); gpu50.destroy(); // Verify cell diameter is independent of store at default cellScale while brightness still responds to store. const singleDims = roam3dDims({ size: 32, height: 16, cap: 256 }); const singleSource = createRoam3dBufferSource(device, singleDims); const emptyFloor = new Uint32Array(singleDims.floorCount); const emptyWater = new Uint32Array(singleDims.fieldCount); singleSource.uploadFloor(emptyFloor); singleSource.uploadWater(emptyWater); renderer.setSource(singleSource); const renderSingleCell = async (store: number, glow = 0): Promise => { const buf = new Int32Array(singleDims.cap * R3_RENDER_STRIDE); if (store >= 0) { buf[0] = singleDims.spanXZ >>> 1; buf[1] = singleDims.spanY >>> 1; buf[2] = singleDims.spanXZ >>> 1; buf[3] = 1; // alive, plain kind 0 buf[4] = store; buf[5] = R3_NONE; buf[6] = 0; // root buf[7] = 1; // cid } singleSource.uploadCells(buf); return await renderAndRead(singleDims, { haze: 0, glass: false, glow }); }; const bgOnly = await renderSingleCell(-1, 0); const lowStorePx = await renderSingleCell(16, 0); const highStorePx = await renderSingleCell(200, 0); const highGlowPx = await renderSingleCell(200, 1); let lowCount = 0; let highCount = 0; let lowLumaSum = 0; let highLumaSum = 0; for (let i = 0; i < bgOnly.length; i += 4) { const lowDiff = Math.abs(lowStorePx[i]! - bgOnly[i]!) + Math.abs(lowStorePx[i + 1]! - bgOnly[i + 1]!) + Math.abs(lowStorePx[i + 2]! - bgOnly[i + 2]!); const highDiff = Math.abs(highStorePx[i]! - bgOnly[i]!) + Math.abs(highStorePx[i + 1]! - bgOnly[i + 1]!) + Math.abs(highStorePx[i + 2]! - bgOnly[i + 2]!); // Filter to pixels clearly on the elevated sphere (above floor shadow noise). if (lowDiff > 24 && lowStorePx[i]! + lowStorePx[i + 1]! + lowStorePx[i + 2]! > bgOnly[i]! + bgOnly[i + 1]! + bgOnly[i + 2]!) { lowCount++; lowLumaSum += 0.299 * lowStorePx[i]! + 0.587 * lowStorePx[i + 1]! + 0.114 * lowStorePx[i + 2]!; } if (highDiff > 24 && highStorePx[i]! + highStorePx[i + 1]! + highStorePx[i + 2]! > bgOnly[i]! + bgOnly[i + 1]! + bgOnly[i + 2]!) { highCount++; highLumaSum += 0.299 * highStorePx[i]! + 0.587 * highStorePx[i + 1]! + 0.114 * highStorePx[i + 2]!; } } assert(lowCount > 5 && highCount > 5, `expected visible cell silhouette (low=${lowCount}, high=${highCount})`); assert( Math.abs(lowCount - highCount) <= 2, `cell silhouette size should not depend on store (low=${lowCount}, high=${highCount})`, ); assert( highLumaSum / highCount > lowLumaSum / lowCount + 10, `higher store should render brighter (low=${(lowLumaSum / lowCount).toFixed(1)}, high=${(highLumaSum / highCount).toFixed(1)})`, ); console.log( `Cell store invariance verified: low(16)=${lowCount}px avgLuma=${(lowLumaSum / lowCount).toFixed(1)}, high(200)=${highCount}px avgLuma=${(highLumaSum / highCount).toFixed(1)}.`, ); // Verify body glow produces a visible luminous halo around the cell compared to glow: 0. let glowHaloPx = 0; for (let i = 0; i < bgOnly.length; i += 4) { const dNoGlow = Math.abs(highStorePx[i]! - bgOnly[i]!) + Math.abs(highStorePx[i + 1]! - bgOnly[i + 1]!) + Math.abs(highStorePx[i + 2]! - bgOnly[i + 2]!); const dGlow = Math.abs(highGlowPx[i]! - bgOnly[i]!) + Math.abs(highGlowPx[i + 1]! - bgOnly[i + 1]!) + Math.abs(highGlowPx[i + 2]! - bgOnly[i + 2]!); if (dNoGlow <= 6 && dGlow > 12) glowHaloPx++; } assert(glowHaloPx >= 20, `expected visible glow halo outside sphere, got only ${glowHaloPx} halo pixels`); console.log(`Body glow halo verified: ${glowHaloPx} luminous halo pixels outside bare sphere silhouette.`); renderer.setSource(source); singleSource.destroy(); // 60-frame render benchmark at 768x576 (typical lab canvas resolution) on the real kernel buffers. const BW = 768; const BH = 576; const benchTex = device.createTexture({ label: "softroam3d-bench-target", size: [BW, BH], format, usage: GPUTextureUsage.RENDER_ATTACHMENT, }); const benchCam = new Roam3dCamera("oblique", world.dims); renderer.render(benchCam, { target: benchTex }); await device.queue.onSubmittedWorkDone(); const N = 60; const t0 = performance.now(); for (let f = 0; f < N; f++) { benchCam.orbit(0.02, 0); renderer.render(benchCam, { target: benchTex }); } await device.queue.onSubmittedWorkDone(); const elapsedMs = performance.now() - t0; const msPerFrame = elapsedMs / N; const fps = 1000 / msPerFrame; console.log( `Benchmark ${BW}x${BH} (real kernel: ${census.cells} live cells, cap ${world.dims.cap}): ${msPerFrame.toFixed(2)} ms/frame (${fps.toFixed(1)} FPS)`, ); // ---- The preset cubes ---- /** Pixels whose max channel differs by more than `tol`, and the mean absolute channel difference. */ function diffStats(a: Uint8Array, b: Uint8Array, tol = 12): { pixels: number; meanAbs: number; maxAbs: number } { let pixels = 0, sum = 0, maxAbs = 0; for (let i = 0; i < a.length; i += 4) { let m = 0; for (let k = 0; k < 3; k++) { const d = Math.abs(a[i + k]! - b[i + k]!); sum += d; if (d > m) m = d; } if (m > tol) pixels++; if (m > maxAbs) maxAbs = m; } return { pixels, meanAbs: sum / ((a.length / 4) * 3), maxAbs }; } function frameStats(px: Uint8Array): { minLuma: number; maxLuma: number; colors: number; opaque: number } { let minLuma = 255, maxLuma = 0, opaque = 0; const colors = new Set(); for (let i = 0; i < px.length; i += 4) { const luma = Math.round(0.299 * px[i]! + 0.587 * px[i + 1]! + 0.114 * px[i + 2]!); if (luma < minLuma) minLuma = luma; if (luma > maxLuma) maxLuma = luma; if (px[i + 3]! > 0) opaque++; colors.add(((px[i]! >> 3) << 10) | ((px[i + 1]! >> 3) << 5) | (px[i + 2]! >> 3)); } return { minLuma, maxLuma, colors: colors.size, opaque }; } function uploadWorld(w: Roam3dWorld) { const src = createRoam3dBufferSource(device, w.dims); const packed = new Int32Array(w.dims.cap * R3_RENDER_STRIDE); packRenderCells(w.cells, w.dims.cap, packed); src.uploadCells(packed); src.uploadFloor(w.fields.floorFood); assert(w.fields.waterFood.length === w.dims.fieldCount, `waterFood has ${w.fields.waterFood.length} entries, fieldCount ${w.dims.fieldCount}`); src.uploadWater(w.fields.waterFood); return { src, packed }; } interface WorldCase { id: Roam3dWorldId; steps: number } const CUBES: WorldCase[] = [{ id: "cube128", steps: 30 }, { id: "cube256", steps: 8 }, { id: "cube512", steps: 8 }]; const cubeWorlds = new Map }>(); for (const c of CUBES) { const t0c = performance.now(); const w = foundRoam3dWorld(c.id, 1); w.advance(c.steps); const wc = w.census(); assert(wc.residual === 0, `${c.id}: residual ${wc.residual}`); const { src } = uploadWorld(w); cubeWorlds.set(c.id, { world: w, source: src }); const lay = roam3dVolumeLayout(w.dims); renderer.setSource(src); const minPx = w.dims.size > 128 ? 1 : 0; const px = await renderAndRead(w.dims, { minPixelRadius: minPx }); const st = frameStats(px); assert(st.opaque === W * H, `${c.id}: expected opaque output`); assert(st.maxLuma - st.minLuma >= 40, `${c.id}: frame looks flat (luma ${st.minLuma}..${st.maxLuma})`); assert(st.colors >= 30, `${c.id}: only ${st.colors} quantized colours`); // Cells are visible: the same frame with every cell slot cleared differs. const noCells = new Int32Array(w.dims.cap * R3_RENDER_STRIDE); src.uploadCells(noCells); const pxEmpty = await renderAndRead(w.dims, { minPixelRadius: minPx }); const cellDiff = diffStats(px, pxEmpty); const packedAgain = new Int32Array(w.dims.cap * R3_RENDER_STRIDE); packRenderCells(w.cells, w.dims.cap, packedAgain); src.uploadCells(packedAgain); assert(cellDiff.pixels >= 20, `${c.id}: cells are not visible (${cellDiff.pixels} differing pixels)`); // The one-pixel floor shows more cell pixels than true size in the big cubes. let minPxNote = ""; if (minPx > 0) { const pxTrue = await renderAndRead(w.dims, { minPixelRadius: 0 }); const d = diffStats(px, pxTrue); assert(d.pixels > 0, `${c.id}: minPixelRadius 1 changed nothing`); minPxNote = `, minPixelRadius 1 vs 0 differs in ${d.pixels} px`; } // Empty-brick skipping against the plain march: the water-only segments are integrated in one step, so the frames // are close, not equal. const pxSkip = await renderAndRead(w.dims, { minPixelRadius: minPx, skipEmpty: true }); const pxPlain = await renderAndRead(w.dims, { minPixelRadius: minPx, skipEmpty: false }); const sk = diffStats(pxSkip, pxPlain, 6); assert(sk.meanAbs < 3, `${c.id}: skipping changes the frame too much (mean ${sk.meanAbs.toFixed(2)}, max ${sk.maxAbs})`); // The snow shows: the same frame with the water drained differs. Food is drawn per 2-tile volume (volScale), and a // world unit spans `size` tiles, so the same snow is fainter the bigger the cube; this prints how much it shows. src.uploadWater(new Uint32Array(w.dims.fieldCount)); const pxDry = await renderAndRead(w.dims, { minPixelRadius: minPx }); src.uploadWater(w.fields.waterFood); const snow = diffStats(px, pxDry, 0); assert(snow.pixels > 0, `${c.id}: the water food does not show at all`); // Verify the close-up and inside-the-cube presets render non-blank frames and glow changes cube512 visibly. if (c.id === "cube512") { const pxNoGlow = await renderAndRead(w.dims, { minPixelRadius: minPx, glow: 0 }); const glowDiff = diffStats(px, pxNoGlow, 4); assert(glowDiff.pixels >= 40, `cube512: glow had negligible effect (${glowDiff.pixels} differing pixels)`); for (const preset of ["close", "inside", "floor"] as const) { const pCam = new Roam3dCamera(preset, w.dims); renderer.render(pCam, { target: outTex, still: true, minPixelRadius: minPx }); const enc = device.createCommandEncoder(); enc.copyTextureToBuffer({ texture: outTex }, { buffer: readBuf, bytesPerRow }, [W, H]); device.queue.submit([enc.finish()]); await readBuf.mapAsync(GPUMapMode.READ); const pPx = new Uint8Array(readBuf.getMappedRange()).slice(); readBuf.unmap(); const pst = frameStats(pPx); assert(pst.opaque === W * H, `cube512 ${preset}: expected opaque output`); assert(pst.maxLuma - pst.minLuma >= 15, `cube512 ${preset}: frame looks flat (${pst.minLuma}..${pst.maxLuma})`); } console.log(` cube512 glow diff vs glow=0: ${glowDiff.pixels} px (mean ${glowDiff.meanAbs.toFixed(2)}/255, max ${glowDiff.maxAbs}); close/inside/floor presets OK.`); } console.log( `${c.id} (${w.dims.size}x${w.dims.size}x${w.dims.height}, fieldTiles ${w.dims.fieldTiles}, volume ${lay.tex.join("x")}, skip default ${roam3dSkipEmptyDefault(lay)}) step ${wc.step}: ${wc.cells} cells, ${wc.bodies} bodies; luma ${st.minLuma}..${st.maxLuma}, colours ${st.colors}; cells differ in ${cellDiff.pixels} px${minPxNote}; snow shows in ${snow.pixels} px (mean ${snow.meanAbs.toFixed(3)}, max ${snow.maxAbs}); skip vs plain mean ${sk.meanAbs.toFixed(3)} max ${sk.maxAbs} (${sk.pixels} px over 6) [${((performance.now() - t0c) / 1000).toFixed(1)} s]`, ); } // An unchanged dataVersion reuses the prepped volume: the frame is byte-identical to a freshly prepped one. { const { world: w, source: src } = cubeWorlds.get("cube128")!; renderer.setSource(src); const prepped = await renderAndRead(w.dims, { dataVersion: 41 }); const reused = await renderAndRead(w.dims, { dataVersion: 41 }); assert(diffStats(prepped, reused, 0).pixels === 0, "cube128: frame with prep skipped differs from the prepped frame"); // Change the water without bumping the version: the skipped prep keeps the old volume (so the frame still matches). const drained = new Uint32Array(w.dims.fieldCount); src.uploadWater(drained); const stale = await renderAndRead(w.dims, { dataVersion: 41 }); const fresh = await renderAndRead(w.dims, { dataVersion: 42 }); src.uploadWater(w.fields.waterFood); assert(diffStats(prepped, stale, 0).pixels === 0, "cube128: an unchanged dataVersion re-prepped"); assert(diffStats(stale, fresh).pixels > 0 || diffStats(stale, fresh, 0).pixels > 0, "cube128: a new dataVersion did not re-prep"); // The instance lists follow the peel/slice planes under one version: peeled then full must equal a version-less full // frame (a stale peeled list would drop every cell above the old planes), and peeled must equal a version-less peel. const peelOpts = { peel: 0.55, slice: 0.45 }; const peeledV = await renderAndRead(w.dims, { dataVersion: 43, ...peelOpts }); const fullV = await renderAndRead(w.dims, { dataVersion: 43 }); const peeledV2 = await renderAndRead(w.dims, { dataVersion: 43, ...peelOpts }); const fullPlain = await renderAndRead(w.dims); const peeledPlain = await renderAndRead(w.dims, peelOpts); assert(diffStats(fullV, fullPlain, 0).pixels === 0, "cube128: full frame after a peeled one under one dataVersion kept the peeled lists"); assert(diffStats(peeledV, peeledPlain, 0).pixels === 0 && diffStats(peeledV2, peeledPlain, 0).pixels === 0, "cube128: peeled frame under a dataVersion differs"); assert(diffStats(fullPlain, peeledPlain).pixels > 0, "cube128: peel/slice changed nothing"); console.log("dataVersion: prep skipped on an unchanged version (byte-identical), redone on a new one; instance lists re-compacted on a peel/slice change."); } // The instance lists keep ascending slot order across compaction workgroups (512 slots each): pairs of identical spheres // in different colours share a position, one slot each side of a workgroup boundary (and far apart). With depth test // `less` the first drawn wins every tie, so the frame must equal the one with only the lower slot of each pair, and // differ from the one with only the higher. Cells sit 100 tiles up (no shadows), carry no bonds, and are drawn at least // 8 px in radius. { const dims = roam3dDims({ size: 128, height: 128, cap: 32768 }); const tieSrc = createRoam3dBufferSource(device, dims); tieSrc.uploadFloor(new Uint32Array(dims.floorCount)); tieSrc.uploadWater(new Uint32Array(dims.fieldCount)); renderer.setSource(tieSrc); const pairs: Array<[number, number]> = [[511, 512], [1023, 1536], [5, 30000], [4095, 4096], [32766, 32767]]; const fill = (lower: boolean, higher: boolean) => { const buf = new Int32Array(dims.cap * R3_RENDER_STRIDE); pairs.forEach(([lo, hi], k) => { for (const [slot, on, root] of [[lo, lower, lo], [hi, higher, hi]] as const) { if (!on) continue; const o = slot * R3_RENDER_STRIDE; buf[o] = ((20 + 20 * k) * dims.spanXZ / 128) | 0; buf[o + 1] = 100 * 1024; buf[o + 2] = ((30 + 15 * k) * dims.spanXZ / 128) | 0; buf[o + 3] = 1; buf[o + 4] = 150; buf[o + 5] = R3_NONE; buf[o + 6] = root; buf[o + 7] = slot + 1; } }); tieSrc.uploadCells(buf); }; const tieOpts = { haze: 0, glass: false, minPixelRadius: 8 }; fill(true, false); const lowOnly = await renderAndRead(dims, tieOpts); fill(false, true); const highOnly = await renderAndRead(dims, tieOpts); fill(true, true); const both = await renderAndRead(dims, tieOpts); const vsLow = diffStats(both, lowOnly, 0); const lowVsHigh = diffStats(lowOnly, highOnly, 0); assert(lowVsHigh.pixels > 50, `tie test: the two colours are not told apart (${lowVsHigh.pixels} px)`); assert(vsLow.pixels === 0, `instance order: a higher slot won a depth tie across a compaction workgroup (${vsLow.pixels} px)`); console.log(`Instance order across compaction workgroups: lower slot wins every depth tie (${pairs.length} pairs, ${lowVsHigh.pixels} px tell the colours apart).`); renderer.setSource(source); tieSrc.destroy(); } // GPU twin parity on cube128: renderSource() after a few steps draws the same frame as the CPU state uploaded. { const cfg = foundRoam3dWorld("cube128", 2); const gpuCube = await Roam3dGpu.create(device, cfg.cfg); gpuCube.upload(cfg); gpuCube.step(5); cfg.advance(5); const gd = await gpuCube.digest(); const cd = cfg.digest(); assert(gd === cd, `cube128 GPU/CPU digest mismatch at step 5: gpu=${gd}, cpu=${cd}`); // The page's census path: the GPU reduction reports largestBody, equal to the CPU census. const gc = await gpuCube.census(); const cc = cfg.census(); assert(Number.isFinite(gc.largestBody) && gc.largestBody === cc.largest, `cube128 GPU census largestBody ${gc.largestBody} vs CPU ${cc.largest}`); assert(gc.cells === cc.cells && gc.bodies === cc.bodies && gc.residual === cc.residual, `cube128 GPU census ${JSON.stringify(gc)} vs CPU ${JSON.stringify(cc)}`); renderer.setSource(gpuCube.renderSource()); const gpx = await renderAndRead(cfg.dims, { dataVersion: 1 }); const { src } = uploadWorld(cfg); renderer.setSource(src); const cpx = await renderAndRead(cfg.dims, { dataVersion: 1 }); const d = diffStats(gpx, cpx, 0); assert(d.pixels === 0, `cube128 GPU renderSource() vs CPU upload differ in ${d.pixels} px (max ${d.maxAbs})`); console.log(`cube128 GPU renderSource() vs CPU upload at step 5: exact match (digest ${gd}); GPU census equals CPU (largest body ${gc.largestBody}).`); src.destroy(); gpuCube.destroy(); } // ---- Per-pass render benchmark across worlds ---- const BENCH_FRAMES = Math.max(4, Number(Deno.env.get("BL_RENDER_BENCH_FRAMES") ?? 60)); const queryBytes = ROAM3D_TIMING_SLOTS * BENCH_FRAMES * 8; const queryResolve = hasTimestamps ? device.createBuffer({ size: queryBytes, usage: GPUBufferUsage.QUERY_RESOLVE | GPUBufferUsage.COPY_SRC }) : null; const queryRead = hasTimestamps ? device.createBuffer({ size: queryBytes, usage: GPUBufferUsage.MAP_READ | GPUBufferUsage.COPY_DST }) : null; interface BenchRow { world: string; mode: string; wallMs: number; prepMs: number | null; opaqueMs: number | null; hazeMs: number | null } async function benchRender( label: string, mode: string, src: Roam3dRenderSource, dims: Roam3dDims, opts: (f: number) => Omit, target: GPUTexture = benchTex, ): Promise { renderer.setSource(src); // A fresh query set per run: a pass a run skips (prep) must read as unwritten, not as an earlier run's stamps. const querySet = hasTimestamps ? device.createQuerySet({ type: "timestamp", count: ROAM3D_TIMING_SLOTS * BENCH_FRAMES }) : null; const cam = new Roam3dCamera("oblique", dims); renderer.render(cam, { target, ...opts(-1) }); await device.queue.onSubmittedWorkDone(); const t0b = performance.now(); for (let f = 0; f < BENCH_FRAMES; f++) { cam.orbit(0.02, 0); renderer.render(cam, { target, ...opts(f), timing: querySet ? { querySet, first: f * ROAM3D_TIMING_SLOTS } : undefined, }); } await device.queue.onSubmittedWorkDone(); const wallMs = (performance.now() - t0b) / BENCH_FRAMES; if (!querySet || !queryResolve || !queryRead) { querySet?.destroy(); return { world: label, mode, wallMs, prepMs: null, opaqueMs: null, hazeMs: null }; } const enc = device.createCommandEncoder(); enc.resolveQuerySet(querySet, 0, ROAM3D_TIMING_SLOTS * BENCH_FRAMES, queryResolve, 0); enc.copyBufferToBuffer(queryResolve, 0, queryRead, 0, queryBytes); device.queue.submit([enc.finish()]); await queryRead.mapAsync(GPUMapMode.READ); const ts = new BigUint64Array(queryRead.getMappedRange().slice(0)); queryRead.unmap(); const span = (f: number, k: number): number | null => { const a = ts[f * ROAM3D_TIMING_SLOTS + k]!, b = ts[f * ROAM3D_TIMING_SLOTS + k + 1]!; return a > 0n && b >= a ? Number(b - a) / 1e6 : null; }; const avg = (k: number): number | null => { let sum = 0, n = 0; for (let f = 0; f < BENCH_FRAMES; f++) { const v = span(f, k); if (v !== null) { sum += v; n++; } } return n > 0 ? sum / n : null; }; querySet.destroy(); return { world: label, mode, wallMs, prepMs: avg(0), opaqueMs: avg(2), hazeMs: avg(4) }; } const rows: BenchRow[] = []; const tankSrc = source; rows.push(await benchRender("tank", "prep every frame", tankSrc, world.dims, () => ({}))); rows.push(await benchRender("tank", "prep skipped (camera only)", tankSrc, world.dims, () => ({ dataVersion: 1 }))); for (const c of CUBES) { const { world: w, source: src } = cubeWorlds.get(c.id)!; const minPixelRadius = w.dims.size > 128 ? 1 : 0; rows.push(await benchRender(c.id, "prep every frame", src, w.dims, () => ({ minPixelRadius }))); rows.push(await benchRender(c.id, "prep skipped, skip off", src, w.dims, () => ({ minPixelRadius, dataVersion: 1, skipEmpty: false }))); rows.push(await benchRender(c.id, "prep skipped, skip on", src, w.dims, () => ({ minPixelRadius, dataVersion: 1, skipEmpty: true }))); } const fmt = (v: number | null) => (v === null ? " - " : v.toFixed(3).padStart(6)); console.log(`Render benchmark ${BW}x${BH}, ${BENCH_FRAMES} frames, oblique orbit (${hasTimestamps ? "GPU timestamps" : "no timestamp-query: wall clock only"}):`); console.log(" world mode wall ms fps prep opaque haze (GPU ms)"); for (const r of rows) { console.log( ` ${r.world.padEnd(8)} ${r.mode.padEnd(28)} ${r.wallMs.toFixed(2).padStart(7)} ${(1000 / r.wallMs).toFixed(0).padStart(5)} ${fmt(r.prepMs)} ${fmt(r.opaqueMs)} ${fmt(r.hazeMs)}`, ); } // ---- Populated steady state (opt in: --bench-populated or BL_RENDER_BENCH_POPULATED=1) ---- // Every preset world warmed on the GPU twin to step BL_RENDER_WARM_STEPS (default 3000), drawn straight from // `renderSource()`, timed per pass at 768x576 and 1920x1080. "no cells" draws a copy of the same floor and water with // every cell slot empty, so `camera only` opaque minus `no cells` opaque is what drawing the cells costs. The snow line // is the waterFood distribution and how far the snow moves the pixels (the same frame with the water drained). if (Deno.args.includes("--bench-populated") || Deno.env.get("BL_RENDER_BENCH_POPULATED") === "1") { const WARM = Math.max(0, Number(Deno.env.get("BL_RENDER_WARM_STEPS") ?? 3000)); const sizes: Array<[number, number]> = [[768, 576], [1920, 1080]]; const targets = sizes.map(([w, h]) => device.createTexture({ label: `softroam3d-bench-${w}x${h}`, size: [w, h], format, usage: GPUTextureUsage.RENDER_ATTACHMENT }) ); const prow: Array = []; const snowLines: string[] = []; const pct = (sorted: Uint32Array, q: number) => (sorted.length ? sorted[Math.min(sorted.length - 1, Math.floor(q * sorted.length))]! : 0); for (const id of ["tank", "cube128", "cube256", "cube512"] as const) { const w = foundRoam3dWorld(id, 1); const g = await Roam3dGpu.create(device, w.cfg); g.upload(w); const tw = performance.now(); for (let s = 0; s < WARM; s += 50) { g.step(Math.min(50, WARM - s), 16); await device.queue.onSubmittedWorkDone(); } const warmMs = performance.now() - tw; const c = await g.census(); const live = g.renderSource(); const dims = live.dims; const minPixelRadius = dims.size > 128 ? 1 : 0; // A copy of the floor and water with no cells, and (for the snow line) a copy of everything. const copy = createRoam3dBufferSource(device, dims); const empty = createRoam3dBufferSource(device, dims); const waterRead = device.createBuffer({ size: dims.fieldCount * 4, usage: GPUBufferUsage.COPY_DST | GPUBufferUsage.MAP_READ }); { const e = device.createCommandEncoder(); e.copyBufferToBuffer(live.cells, 0, copy.cells, 0, dims.cap * R3_RENDER_STRIDE * 4); e.copyBufferToBuffer(live.floorFood, 0, copy.floorFood, 0, dims.floorCount * 4); e.copyBufferToBuffer(live.waterFood, 0, copy.waterFood, 0, dims.fieldCount * 4); e.copyBufferToBuffer(live.floorFood, 0, empty.floorFood, 0, dims.floorCount * 4); e.copyBufferToBuffer(live.waterFood, 0, empty.waterFood, 0, dims.fieldCount * 4); e.copyBufferToBuffer(live.waterFood, 0, waterRead, 0, dims.fieldCount * 4); device.queue.submit([e.finish()]); } empty.uploadCells(new Int32Array(dims.cap * R3_RENDER_STRIDE)); await waterRead.mapAsync(GPUMapMode.READ); const water = new Uint32Array(waterRead.getMappedRange().slice(0)); waterRead.unmap(); waterRead.destroy(); const lay = roam3dVolumeLayout(dims); let total = 0; const nz: number[] = []; for (const v of water) { total += v; if (v > 0) nz.push(v); } const sorted = Uint32Array.from(nz).sort(); renderer.setSource(copy); const withSnow = await renderAndRead(dims, { minPixelRadius }); // At haze 0 the food adds nothing to the haze, so what still moves is the floor's column shadow alone. const withSnowNoHaze = await renderAndRead(dims, { minPixelRadius, haze: 0 }); copy.uploadWater(new Uint32Array(dims.fieldCount)); const dry = await renderAndRead(dims, { minPixelRadius }); const dryNoHaze = await renderAndRead(dims, { minPixelRadius, haze: 0 }); const snow = diffStats(withSnow, dry, 0); const floorOnly = diffStats(withSnowNoHaze, dryNoHaze, 0); snowLines.push( ` ${id.padEnd(8)} fieldTiles ${dims.fieldTiles} volScale ${lay.volScale}: waterFood total ${total}, nonzero ${nz.length}/${dims.fieldCount} voxels, p50 ${pct(sorted, 0.5)} p90 ${pct(sorted, 0.9)} p99 ${pct(sorted, 0.99)} max ${pct(sorted, 1)} (p90 x volScale ${(pct(sorted, 0.9) * lay.volScale).toFixed(2)}); snow moves ${snow.pixels} px, mean ${snow.meanAbs.toFixed(3)}/255, max ${snow.maxAbs} (floor column shadow alone: mean ${floorOnly.meanAbs.toFixed(3)}/255)`, ); for (let k = 0; k < sizes.length; k++) { const res = `${sizes[k]![0]}x${sizes[k]![1]}`; const t = targets[k]!; const label = `${id} ${c.cells}c`; prow.push({ res, ...await benchRender(label, "prep every frame", live, dims, () => ({ minPixelRadius }), t) }); prow.push({ res, ...await benchRender(label, "camera only", live, dims, () => ({ minPixelRadius, dataVersion: 1 }), t) }); prow.push({ res, ...await benchRender(label, "camera only, no cells", empty, dims, () => ({ minPixelRadius, dataVersion: 1 }), t) }); } console.log(`Warmed ${id} to step ${c.step} on the GPU in ${(warmMs / 1000).toFixed(1)} s: ${c.cells} cells, ${c.bodies} bodies, largest ${c.largestBody}, residual ${c.residual}.`); renderer.setSource(source); copy.destroy(); empty.destroy(); g.destroy(); } console.log(`Populated render benchmark (step ${WARM}, ${BENCH_FRAMES} frames, oblique orbit, ${hasTimestamps ? "GPU timestamps" : "wall clock only"}):`); console.log(" res world mode wall ms fps prep opaque haze cells (GPU ms)"); for (let i = 0; i < prow.length; i += 3) { const cellsMs = prow[i + 1]!.opaqueMs !== null && prow[i + 2]!.opaqueMs !== null ? prow[i + 1]!.opaqueMs! - prow[i + 2]!.opaqueMs! : null; for (let k = 0; k < 3; k++) { const r = prow[i + k]!; console.log( ` ${r.res.padEnd(10)} ${r.world.padEnd(16)} ${r.mode.padEnd(22)} ${r.wallMs.toFixed(2).padStart(7)} ${(1000 / r.wallMs).toFixed(0).padStart(5)} ${fmt(r.prepMs)} ${fmt(r.opaqueMs)} ${fmt(r.hazeMs)} ${k === 1 ? fmt(cellsMs) : ""}`, ); } } console.log(`Snow at step ${WARM} (256x256 oblique, default haze):`); for (const l of snowLines) console.log(l); for (const t of targets) t.destroy(); } queryResolve?.destroy(); queryRead?.destroy(); renderer.setSource(source); for (const { source: src } of cubeWorlds.values()) src.destroy(); const validationErr = await device.popErrorScope(); assert(validationErr === null, `WebGPU validation error: ${validationErr?.message}`); benchTex.destroy(); outTex.destroy(); readBuf.destroy(); renderer.destroy(); demoSource.destroy(); source.destroy(); device.destroy(); console.log("PASS softroam3d_render");