app: cherry-pick rune's pause and sound fixes onto the checkout

Rune comes from app/vendor/rune now, a checkout of 63ad0209 on branch
ported, carrying the four commits of upstream issues 1320 (a pause while
a clip is layered holds the layer's picture and time) and 1325 (a video's
sound is read ahead of the clock and leads it). Both were written against
eb9f1104 and ported across the refactors since. The faults are the first
two and the third in docs/rune-upstream.md; the app's workarounds in
review.rs stay until the fixes arrive upstream.
This commit is contained in:
vhaudiquet committed 2026-11-22 22:16:30 +01:00
1 parent 80fef698ce
commit 5bf262b82b
3795 files changed
+663463 -28

No files matched your search

+50
View File
@@ -0,0 +1,50 @@
[package]
name = "rune-light"
version = "0.0.1"
edition.workspace = true
license.workspace = true
description = "Real-time lighting for Rune UIs: SDF soft shadows, bevel normals, god rays and radiance-cascade GI over the frame's analytic primitives."
autotests = false
[features]
# Live GPU resource counters (`Device::get_internal_counters`) for the bind-group test and `frame_bench`.
test-gpu-counters = ["wgpu/counters"]
[dependencies]
rune-staging = { workspace = true }
wgpu = { workspace = true, features = ["std", "parking_lot", "wgsl"] }
bytemuck = { workspace = true }
[target.'cfg(target_vendor = "apple")'.dependencies]
wgpu = { workspace = true, features = ["metal", "custom"] }
[target.'cfg(target_os = "windows")'.dependencies]
wgpu = { workspace = true, features = ["dx12"] }
[target.'cfg(all(not(target_vendor = "apple"), not(target_arch = "wasm32"), not(target_os = "windows")))'.dependencies]
wgpu = { workspace = true, features = ["vulkan"] }
[target.'cfg(target_arch = "wasm32")'.dependencies]
wgpu = { workspace = true, features = ["webgpu"] }
[dev-dependencies]
rune = { workspace = true, default-features = true }
rune-fx = { workspace = true }
pollster = { workspace = true }
winit = { workspace = true, features = ["rwh_06", "x11", "wayland", "wayland-dlopen", "wayland-csd-adwaita-notitle"] }
[[example]]
name = "frame_bench"
required-features = ["test-gpu-counters"]
[[test]]
name = "builtin_shaders"
[[test]]
name = "continuous_corners"
[[test]]
name = "targets"
[lints]
workspace = true
+155
View File
@@ -0,0 +1,155 @@
# rune-light
Real-time lighting for Rune UIs. You place a light and the UI casts soft shadows from it, catches it on bevelled
edges and specular highlights, and glowing elements light the cards around them. It runs as passes over the frame
Rune already draws.
Every Rune element is an analytic rounded rect, so the frame is already an exact 2D distance field. rune-light
treats the elements you mark as occluders as short slabs standing on the UI plane, gives lights a 3D position
(height above the UI) and a physical source radius, and sphere traces through that field.
```rust
use rune_light::{Light, LightRenderer, Prim, Scene, Settings};
let lamp = Light::point(x, y, 58.0 * s) // device px; z = height above the UI
.color([1.0, 0.58, 0.27]).intensity(2.1) // linear colour; 1.0 = irradiance 1 at 200 px
.radius(11.0 * s) // source size → penumbra width and highlight size
.range(900.0 * s) // windowed inverse square
.bulb(0.9); // show the source as a soft bloom
let bubble = Prim::from_rune(inst.rect, inst.radii)
.raised(7.0 * s) // casts shadows
.bevel(6.0 * s, 2.0 * s) // SDF bevel → normals → rim light and highlights
.gloss(0.55, 0.42);
let mut lights = LightRenderer::new(&device, &queue, w, h, surface_format);
let drew = lights.render(&device, &queue, &mut encoder,
&Scene { prims: &prims, lights: &[lamp], settings: Settings::default() },
&ui_without_text, &text_layer, &target);
// drew == false → no lights and no emitters: nothing was recorded; present the UI as usual.
```
Run the demos, the benchmark and the CPU check (headless, offscreen; outputs land in `demo/light/`):
```sh
cargo build --release -p rune-light --example light
target/release/examples/light all # chat, flashlight, emissive, raised, godrays: PNG, strip, MP4
target/release/examples/light verify # GPU shadow texels vs. CPU estimator and brute-force ground truth
```
The benchmark (GPU timestamps per pass → `demo/light/bench.json`) needs the perf profile:
```sh
cargo build --profile perf -p rune-light --example light
target/perf/examples/light bench
```
`examples/reel/` renders a radiance-cascades reel that steps through the real GI buffers
(`reel render`, `reel stills T1,T2`, `reel bench`; outputs land in `demo/reel/`).
`examples/live.rs` puts the flashlight and chat demos in a window (`cargo run --release -p rune-light --example live`;
`live --snap out.png` renders one frame headless).
## Integration contract
**Inputs, per frame**
| Input | Form | Notes |
|---|---|---|
| Primitives | `&[Prim]`, device px, in draw order | Rune's instance rect and radii plus `z` (bottom, top, bevel width, bevel height), `gloss`/`roughness`, flags `OCCLUDER` / `EMISSIVE` / `RAISED`, emitted radiance, albedo. Painter's order decides which surface owns a pixel. |
| Lights | `&[Light]`, up to 8 | position + height, linear colour × intensity, source radius, range, optional torch cone (`spot`), `shafts`, `bulb`, `specular`, `softness`. Animate any field with Rune springs; fade a light out with `scaled(k)` (lights cool, never cut). |
| UI colour | `base`: the frame without text (linear, filterable; Rgba16Float works) | Used as albedo. |
| Text | `text`: glyphs only, premultiplied linear, transparent elsewhere | Lit like the surface beneath, clamped by `TextPolicy { floor, ceiling }`, so shadows never crush it and highlights never wash it out. `lit: 0` leaves text unlit. |
| Settings | ambient, exposure, `TextPolicy`, `Option<Gi>`, contact AO, rim, background gloss, `time`, `seed` | |
**Output:** the lit frame in `target`. If the target format isn't sRGB, the composite encodes sRGB itself and adds
±1 LSB interleaved-gradient dither (a fixed per-pixel pattern, so nothing crawls between frames).
**Guarantees**
- Deterministic: output is a pure function of the inputs, `time` and `seed`. There's no history, jitter or
accumulation, so frames never shimmer and a replay is exact.
- Zero cost with no lights and no emitters: `render` returns `false` and records no passes.
- Text contrast: text never drops below `floor` × its design colour, whatever the shadows do.
- Reduced motion: lights shouldn't travel. Cross-fade between positions with two `Light`s and `scaled(k)` over
0.15–0.2 s. The demos script motion with Rune `Track`s (springs sampled at absolute time).
**Rune integration (next step, not done here):** `Runtime` would mark nodes as occluders/emitters (a `light`
modifier on `El`), split glyph instances into their own target (it already knows `KIND_GLYPH`), and call `render`
between the uber pass and present. The demos do exactly this by hand with Rune's own `Renderer` and `TextSystem`.
## Techniques and why
| Pass | Res | Technique | Why |
|---|---|---|---|
| Surface | full | Instanced quads; the topmost primitive writes its own SDF, outward gradient, top z and id | Exact per-pixel bevel normals and receiver height, no texture SDF error at edges |
| Field | ½ | Brute-force union SDF of occluders, box-distance early-out, plus nearest slab z range and a GI distance | Exact for rounded rects, no jump flood needed. JFA would only be needed for arbitrary shapes (text, vectors) |
| Soft shadows | ½ | Sphere tracing the slab field from each receiver to the light, Quílez penumbra with Aaltonen's closest-approach fix, clearance measured against the cone to a spherical source (`0.5 + 0.5·h/(t·θ)`, smoothstep, as in an earlier lighting prototype's capsule shadows) | Physically sized penumbrae that harden toward contact for free; early exit once the ray clears the tallest card |
| Upsample | full | Joint bilateral on receiver height | Shadows never bleed from the floor onto a card top |
| Shading | full | Lambert + GGX (viewer overhead) with Karis sphere-light widening, a rim hairline on edges facing the light, contact AO from the field, an earlier lighting prototype's windowed inverse square and torch beam profile | Cards read as raised; highlights sweep; the torch has a hot core and spill, not a flat disc |
| God rays | ½ | A light behind the UI: each pixel integrates the light's glow, masked by the field (prefiltered to the sample spacing), along its path to the light (Mitchell, GPU Gems 3), plus distance falloff | Shafts through every gap and no banding, with the same field |
| GI | ⅛ | 2D radiance cascades: 5 cascades, 4·4ⁿ directions, Sannikov's bilinear fix, emitters glow, cards absorb only rays from lower probes (light reaches a card from things standing on it), one bounce from direct light on cards. The media are built from the analytic primitives with box-filtered sub-texel coverage and sampled bilinearly, so an emitter moving by a fraction of a texel changes the light by that fraction (no popping). Rays skip empty space using the distance to emitters and to the occluder boundary | Every emitter lights its neighbours with soft occlusion at a cost fixed by the grid, not the emitter count |
| Extra emission | ⅛ | An optional output-resolution emission texture (effect layers such as rune-fx electric arcs) enters the GI as glowing medium; `Prim::gi_hint` rects tell the tracer where it can be | Effects light the UI too |
| Glass | full | `GlassRenderer`: thick slabs over the lit frame. Snell refraction in and out (n = 1.5), exact unpolarised Fresnel, total internal reflection off the bottom face, Beer–Lambert tint, 8-wavelength dispersion from a Cauchy fit, frost from a 13-tap prefiltered pyramid read at the refracted cone's footprint, GGX highlights from emissive elements with normal-variance specular AA, GI fluence scattered into the bevel, smooth-union morphs | Glass that reads as glass: the UI bends at the rim, fringes in colour and mirrors at grazing angles |
Prior art reused from an earlier lighting prototype:
- `packages/kit/gpu/shadows/capsule-shadows.ts:508-527` (cone-relative soft visibility),
- `packages/kit/gpu/lights/physical.ts:142-163` (windowed inverse square, Karis widening),
- `packages/kit/gpu/lights/beam.ts:71-83` (torch profile),
- `packages/kit/gpu/gi/plan-bounce.ts:345-399` (cone gather, which radiance cascades generalise),
- `docs/rendering-techniques.md:396` (radiance cascades plan: pull-cord-lamp, GM Shaders),
- the blog's `flashlight.wgsl` (interleaved-gradient noise, light that reveals content without punching a hole).
## GPU cost
Measured on an Apple M5 Max (under other load) at 1280×800 pt × 2 = 2560×1600 device px, with 100 raised,
bevelled occluders. Compute passes are timed with wgpu timestamp queries (medians of 60 frames). Render-pass
timestamps aren't ordered against compute on tile GPUs, so the whole frame is also measured as the wall clock of
120 back-to-back frames with no readback. That's GPU-bound and an upper bound that includes submission
(`light bench` → `demo/light/bench.json`):
| Config | Field | Shadows | GI | Whole lighting frame |
|---|---|---|---|---|
| 1 light | 0.16 | 0.17 | n/a | 0.94 |
| **4 lights** | **0.07** | **0.31** | n/a | **1.04** |
| 8 lights | 0.06 | 0.57 | n/a | 1.65 |
| 4 lights, all with god rays | 0.06 | 1.38 | n/a | 2.20 |
| GI only (11 emitters) | 0.07 | 0.02 | 2.27 | 2.69 |
| 4 lights + GI bounce | 0.06 | 0.30 | 2.49 | 3.44 |
All times in ms. The fast path (field + soft shadows for 4 lights) costs about 0.4 ms. The remaining ~0.6 ms of the
1 ms frame is the full-resolution surface buffer and composite at 4 Mpx. The soft-shadow cost scales with lights
× half-res pixels, and rays stop early once they clear the tallest card. God rays cost ~0.27 ms per shaft light
(48 masked samples). GI costs ~2.3 ms at ⅛ resolution (320×200 probes, 5 cascades with the bilinear fix), and
that cost doesn't change with the number of emitters. It's for hero moments, not every frame of every screen.
The field pass is exact. Distances are clamped to 128 px, which is further than any tracer step, so each 16×16 tile
culls primitives into workgroup memory first. That took it from 1.3 ms (brute force) to 0.07 ms.
## Verification
`light verify` reads back the GPU visibility texture over a 64×40 grid and compares it with the CPU estimator over
the exact analytic field (`src/cpu.rs`). The mean difference is 0.0002. The worst texel is off by 0.48, on a
penumbra boundary where the half-res bilinear field and the exact field disagree by a fraction of a pixel. The
check also compares against brute-force ground truth (400 rays across the source's disc, exact 3D slab SDF): in the
116 penumbra texels the mean error is 0.06 and the worst is 0.35. That worst case is the known bias of the
Quílez/Aaltonen estimator where the ray grazes two occluders. It's never wrong in umbra or full light.
## Gaps
- GI uses the same field but no history, so it's deterministic. Small, very bright emitters can still ring faintly.
- Occluders are slabs of rounded rects. Text, icons and vector paths don't cast shadows yet. That needs a
jump-flood field over their coverage.
- Nested occluders: the field keeps the nearest slab's z range, so a raised button on a raised card shadows as
the nearer of the two.
- `examples/light.rs` drives `crates/rune` and `crates/rune-light` directly; `examples/lab` drives the lights from a
live `rune::Runtime` through the compositor hook (marked elements become occluders).
- `LightRenderer::inspect()` exposes every intermediate GI buffer (field, media, each cascade merged and, with
`inspect = true`, unmerged) and `Timings` has per-cascade GPU times; `examples/reel/` visualises them.
- GI is 2–3 ms for sparse layouts and more for dense ones: the bilinear fix traces four rays per direction, and C3's
rays cross many card edges where the field is small (`reel bench`). Halving the cascade-0 directions, or temporal
amortisation (which breaks strict determinism), are
the next levers.
- The surface buffer is a second full-resolution raster of the primitives. Rune's uber pass could write it as an
extra target for free.
@@ -0,0 +1,133 @@
//! CPU cost of recording rune-light and rune-fx frames, headless. Prints one line per measure: the median in µs over
//! its samples (and, for `gi off textures`, the textures a renderer holds after a frame without GI). It leaves out GPU
//! execution, upload and presentation.
//!
//! cargo run -p rune-light --profile perf --example frame_bench
use rune_fx::{Fx, FxFrame, FxOptions, FxRenderer, GlowParams, LensParams, Shape};
use rune_light::{Gi, Glass, GlassRenderer, GlassSettings, Light, LightRenderer, Prim, Scene, Settings};
const W: u32 = 2560;
const H: u32 = 1600;
const FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8Unorm;
fn main() {
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())).expect("adapter");
let (device, queue) = pollster::block_on(adapter.request_device(&Default::default())).expect("device");
let view = |format| {
device
.create_texture(&wgpu::TextureDescriptor {
label: None,
size: wgpu::Extent3d { width: W, height: H, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
})
.create_view(&Default::default())
};
let (base, text, target, out) = (view(wgpu::TextureFormat::Rgba16Float), view(wgpu::TextureFormat::Rgba16Float), view(FORMAT), view(FORMAT));
let lights = [Light::point(400.0, 300.0, 200.0), Light::point(1800.0, 900.0, 160.0)];
let prims = |n: usize| -> Vec<Prim> {
(0..n).map(|i| Prim::rect((i % 20) as f32 * 120.0, (i / 20) as f32 * 60.0, 100.0, 44.0).radius(10.0).raised(6.0)).collect()
};
let small = prims(16);
let big = prims(300);
let scene = |prims, gi| Scene { prims, lights: &lights, settings: Settings { gi, ..Settings::default() }, emission: None };
let finish = |encoder: wgpu::CommandEncoder| {
queue.submit([encoder.finish()]);
device.poll(wgpu::PollType::wait_indefinitely()).expect("poll");
};
let median = |mut v: Vec<f64>| {
v.sort_by(f64::total_cmp);
v[v.len() / 2]
};
// A frame that outgrows the 256-prim buffer, on a fresh renderer each sample.
let mut grow = Vec::new();
for _ in 0..30 {
let mut light = LightRenderer::new(&device, &queue, W, H, FORMAT);
let mut encoder = device.create_command_encoder(&Default::default());
light.render(&device, &queue, &mut encoder, &scene(&small, None), &base, &text, &target);
finish(encoder);
let mut encoder = device.create_command_encoder(&Default::default());
let t = rune::time::now();
light.render(&device, &queue, &mut encoder, &scene(&big, None), &base, &text, &target);
grow.push(t.elapsed().as_secs_f64() * 1e6);
finish(encoder);
}
println!("grow past 256 prims {:8.1} us", median(grow));
let before = device.get_internal_counters().hal.textures.read();
let mut light = LightRenderer::new(&device, &queue, W, H, FORMAT);
let mut encoder = device.create_command_encoder(&Default::default());
light.render(&device, &queue, &mut encoder, &scene(&small, None), &base, &text, &target);
finish(encoder);
println!("gi off textures {:8}", device.get_internal_counters().hal.textures.read() - before);
let mut glass = GlassRenderer::new(&device, W, H, FORMAT);
let panes = [Glass::rounded(200.0, 200.0, 600.0, 400.0, 40.0), Glass::rounded(1200.0, 600.0, 500.0, 300.0, 30.0)];
for (name, gi) in [("light steady gi off", None), ("light steady gi on", Some(Gi::default()))] {
let (mut l, mut g) = (Vec::new(), Vec::new());
for frame in 0..320 {
let mut encoder = device.create_command_encoder(&Default::default());
let t = rune::time::now();
light.render(&device, &queue, &mut encoder, &scene(&small, gi), &base, &text, &target);
let lit = t.elapsed().as_secs_f64() * 1e6;
let fluence = light.inspect().fluence.clone();
let t = rune::time::now();
glass.render(&device, &queue, &mut encoder, &panes, &[], GlassSettings::default(), &target, &fluence, &out);
let glassed = t.elapsed().as_secs_f64() * 1e6;
finish(encoder);
if frame >= 20 {
l.push(lit);
g.push(glassed);
}
}
println!("{name:<20} {:8.1} us", median(l));
println!("glass steady ({}) {:8.1} us", if gi.is_some() { "gi on " } else { "gi off" }, median(g));
}
let mut fx = FxRenderer::new(&device, FORMAT, FxOptions::default());
let layers: Vec<_> = (0..16)
.map(|i| {
let shape = Shape::rounded(100.0 + (i % 4) as f32 * 300.0, 100.0 + (i / 4) as f32 * 200.0, 200.0, 120.0, 20.0);
let fx = if i % 4 == 0 { Fx::lens(LensParams { frost: 0.6, ..Default::default() }) } else { Fx::glow(GlowParams { radius: 12.0, intensity: 0.8, ..Default::default() }) };
fx.on(shape).at(0.5)
})
.collect();
let mut f = Vec::new();
for frame in 0..320 {
let mut encoder = device.create_command_encoder(&Default::default());
let t = rune::time::now();
fx.prepare(&device, &queue, &FxFrame { viewport: [W, H], scale: 1.0, layers: &layers, backdrop: Some(&base), sources: &[] });
for i in (0..layers.len()).step_by(4) {
fx.blur_backdrop(&device, &queue, &mut encoder, &base, i);
}
{
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: None,
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &target,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations { load: wgpu::LoadOp::Load, store: wgpu::StoreOp::Store },
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
fx.draw_all(&mut pass, &layers, None);
}
let us = t.elapsed().as_secs_f64() * 1e6;
finish(encoder);
if frame >= 20 {
f.push(us);
}
}
println!("fx steady 16 layers {:8.1} us", median(f));
}
+539
View File
@@ -0,0 +1,539 @@
//! rune-light demos, bench and CPU reference check. Headless: renders offscreen, writes PNGs, frame strips and
//! MP4s (raw frames piped to ffmpeg) under `demo/light/`.
//!
//! light all | chat | flashlight | emissive | raised | godrays | bench | verify [--out DIR] [--frames N]
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
pub use rune::Spring;
use rune::color::{Color, oklch, oklcha, srgb_decode, srgb_encode};
use rune::render::{Gpu, Instance, KIND_GLYPH, KIND_RECT, NO_CLIP, Offscreen, Renderer, write_png};
use rune::text::TextSystem;
use rune::tok::TextStyle;
use rune_light::{Gi, Light, LightRenderer, Prim, Scene, Settings, TextPolicy, cpu};
thread_local! {
static SCALE: std::cell::Cell<f32> = const { std::cell::Cell::new(2.0) };
}
/// Device px per point (2 for the headless renders; the live window sets its own).
pub fn sc() -> f32 {
SCALE.with(|c| c.get())
}
pub fn set_scale(k: f32) {
SCALE.with(|c| c.set(k));
}
const W: u32 = 2560;
const H: u32 = 1600;
const FPS: u32 = 60;
// ---------------------------------------------------------------- springs
pub struct Track {
t0: f64,
x0: f32,
v0: f32,
pub target: f32,
spring: Spring,
}
impl Track {
pub fn at(v: f32) -> Track {
Track { t0: 0.0, x0: v, v0: 0.0, target: v, spring: Spring::new(0.3, 0.0) }
}
pub fn sample(&self, t: f64) -> (f32, f32) {
self.spring.sample(self.x0, self.v0, self.target, (t - self.t0).max(0.0) as f32)
}
pub fn value(&self, t: f64) -> f32 {
self.sample(t).0
}
pub fn retarget(&mut self, t: f64, target: f32, spring: Spring) {
let (x, v) = self.sample(t);
*self = Track { t0: t, x0: x, v0: v, target, spring };
}
}
// ---------------------------------------------------------------- UI building
struct Ui<'a> {
ts: &'a mut TextSystem,
base: Vec<Instance>,
text: Vec<Instance>,
prims: Vec<Prim>,
clear: Color,
}
fn inst(rect: [f32; 4], r: f32, fill: Color, border: Option<(Color, f32)>) -> Instance {
let (bc, bw) = border.unwrap_or((Color::TRANSPARENT, 0.0));
Instance {
rect,
radii: [r; 4],
fill: fill.premul(1.0),
border: if bw > 0.0 { bc.premul(1.0) } else { [0.0; 4] },
params: [bw, KIND_RECT, 0.0, 1.0],
uv: [0.0; 4],
clip: NO_CLIP,
fade: [0; 4],
}
}
impl<'a> Ui<'a> {
fn new(ts: &'a mut TextSystem, clear: Color) -> Self {
Ui { ts, base: Vec::new(), text: Vec::new(), prims: Vec::new(), clear }
}
/// A rect in points. `light` configures its lighting primitive; return `None` to skip it (pure decoration).
fn rect(&mut self, x: f32, y: f32, w: f32, h: f32, r: f32, fill: Color, border: Option<(Color, f32)>, light: impl FnOnce(Prim) -> Prim) {
let rect = [x * sc(), y * sc(), w * sc(), h * sc()];
self.base.push(inst(rect, r * sc(), fill, border.map(|(c, bw)| (c, bw * sc()))));
self.prims.push(light(Prim::from_rune(rect, [r * sc(); 4]).albedo([fill.r, fill.g, fill.b])));
}
/// Paint only (no lighting primitive): hairlines, icons.
fn paint(&mut self, x: f32, y: f32, w: f32, h: f32, r: f32, fill: Color) {
self.base.push(inst([x * sc(), y * sc(), w * sc(), h * sc()], r * sc(), fill, None));
}
fn text(&mut self, x: f32, y: f32, s: &str, size: f32, weight: f32, color: Color) -> f32 {
let style = TextStyle::new(size, weight);
let mut quads = Vec::new();
self.ts.glyphs(s, style, sc(), [(x * sc()).round(), (y * sc()).round()], &mut quads);
for q in quads {
self.text.push(Instance {
rect: q.rect,
radii: [0.0; 4],
fill: color.premul(1.0),
border: [0.0; 4],
params: [0.0, KIND_GLYPH, 0.0, 1.0],
uv: [q.uv[0], q.uv[1], 0.0, 0.0],
clip: NO_CLIP,
fade: [0; 4],
});
}
self.ts.measure(s, style, sc()).0
}
fn lines(&mut self, x: f32, y: f32, lh: f32, lines: &[&str], size: f32, weight: f32, color: Color) {
for (i, l) in lines.iter().enumerate() {
self.text(x, y + i as f32 * lh, l, size, weight, color);
}
}
fn measure(&mut self, s: &str, size: f32, weight: f32) -> f32 {
self.ts.measure(s, TextStyle::new(size, weight), sc()).0
}
}
// ---------------------------------------------------------------- GPU context
struct Ctx {
device: wgpu::Device,
queue: wgpu::Queue,
rune: Renderer,
ts: TextSystem,
light: LightRenderer,
base: wgpu::TextureView,
text: wgpu::TextureView,
out: Offscreen,
timestamps: bool,
}
impl Ctx {
fn new() -> Ctx {
let Gpu { adapter, device, queue, .. } = Gpu::headless();
let timestamps = device.features().contains(wgpu::Features::TIMESTAMP_QUERY);
eprintln!("adapter: {:?}, timestamps: {timestamps}", adapter.get_info().name);
let mk = |label| {
device
.create_texture(&wgpu::TextureDescriptor {
label: Some(label),
size: wgpu::Extent3d { width: W, height: H, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba16Float,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
})
.create_view(&Default::default())
};
let base = mk("ui base");
let text = mk("ui text");
let out = Offscreen::with_format(&device, W, H, wgpu::TextureFormat::Rgba8Unorm);
let rune = Renderer::new(&device, wgpu::TextureFormat::Rgba16Float);
let light = LightRenderer::new(&device, &queue, W, H, wgpu::TextureFormat::Rgba8Unorm);
Ctx { device, queue, rune, ts: TextSystem::default(), light, base, text, out, timestamps }
}
fn draw_ui(&mut self, base: &[Instance], text: &[Instance], clear: Color) {
self.rune.prepare(&self.device, &self.queue, &mut self.ts.atlas, base, (W, H));
let mut enc = self.device.create_command_encoder(&Default::default());
self.rune.draw(&mut enc, &self.base, [clear.r, clear.g, clear.b, 1.0]);
self.queue.submit([enc.finish()]);
self.rune.prepare(&self.device, &self.queue, &mut self.ts.atlas, text, (W, H));
let mut enc = self.device.create_command_encoder(&Default::default());
self.rune.draw(&mut enc, &self.text, [0.0; 4]);
self.queue.submit([enc.finish()]);
}
/// Lights the UI already drawn; returns sRGB RGBA8 pixels.
fn light_frame(&mut self, prims: &[Prim], lights: &[Light], settings: Settings, read: bool) -> Option<Vec<u8>> {
let mut enc = self.device.create_command_encoder(&Default::default());
let scene = Scene { prims, lights, settings, emission: None };
self.light.render(&self.device, &self.queue, &mut enc, &scene, &self.base, &self.text, &self.out.view);
if read {
self.out.copy(&mut enc);
}
self.queue.submit([enc.finish()]);
read.then(|| self.out.read(&self.device))
}
}
fn downscale(src: &[u8], w: u32, h: u32, k: u32) -> Vec<u8> {
let (ow, oh) = (w / k, h / k);
let mut out = vec![0u8; (ow * oh * 4) as usize];
for y in 0..oh {
for x in 0..ow {
let mut acc = [0f32; 3];
for dy in 0..k {
for dx in 0..k {
let i = (((y * k + dy) * w + x * k + dx) * 4) as usize;
for c in 0..3 {
acc[c] += srgb_decode(src[i + c] as f32 / 255.0);
}
}
}
let o = ((y * ow + x) * 4) as usize;
for c in 0..3 {
out[o + c] = (srgb_encode(acc[c] / (k * k) as f32) * 255.0).round() as u8;
}
out[o + 3] = 255;
}
}
out
}
#[path = "light_demos/mod.rs"]
mod demos;
pub use demos::{DOT_HUES, DOT0, Frame, Hit, N_CTL, Panel, SLIDER, TOGGLE0, accent_for, chat_scene, flashlight_scene, lin};
use demos::Demo;
// ---------------------------------------------------------------- driver
fn render_demo(ctx: &mut Ctx, demo: &mut dyn Demo, out: &Path, frames: Option<u32>) {
let name = demo.name();
let still_frame = (demo.still() * FPS as f32).round() as u32;
if frames == Some(0) {
let t = still_frame as f32 / FPS as f32;
let (prims, base, text, clear, lights, mut s) = demo.frame(&mut ctx.ts, t);
s.seed = 0.0;
ctx.draw_ui(&base, &text, clear);
let px = ctx.light_frame(&prims, &lights, s, true).unwrap();
write_png(&out.join(format!("{name}.png")), W, H, &px).unwrap();
return;
}
let n = frames.unwrap_or((demo.seconds() * FPS as f32).round() as u32);
let mp4 = out.join(format!("{name}.mp4"));
let mut ff = Command::new("ffmpeg")
.args(["-y", "-loglevel", "error", "-f", "rawvideo", "-pix_fmt", "rgba", "-s", &format!("{W}x{H}"), "-framerate", &FPS.to_string(), "-i", "-"])
.args(["-vf", "scale=out_color_matrix=bt709:out_range=tv", "-c:v", "libx264", "-preset", "medium", "-crf", "18", "-pix_fmt", "yuv420p"])
.args(["-colorspace", "bt709", "-color_primaries", "bt709", "-color_trc", "bt709", "-movflags", "+faststart"])
.arg(&mp4)
.stdin(Stdio::piped())
.spawn()
.expect("ffmpeg");
let stdin = ff.stdin.as_mut().unwrap();
let strip_at: Vec<u32> = (0..5).map(|i| (i * n) / 5 + n / 10).collect();
let mut strip: Vec<Vec<u8>> = Vec::new();
let t0 = rune::time::now();
for f in 0..n {
let t = f as f32 / FPS as f32;
let (prims, base, text, clear, lights, mut s) = demo.frame(&mut ctx.ts, t);
s.seed = 0.0;
ctx.draw_ui(&base, &text, clear);
let px = ctx.light_frame(&prims, &lights, s, true).unwrap();
if f == still_frame {
write_png(&out.join(format!("{name}.png")), W, H, &px).unwrap();
}
if strip_at.contains(&f) {
strip.push(downscale(&px, W, H, 4));
}
stdin.write_all(&px).expect("ffmpeg write");
}
drop(ff.stdin.take());
ff.wait().expect("ffmpeg");
let (sw, sh) = (W / 4, H / 4);
let gap = 8;
let tw = sw * strip.len() as u32 + gap * (strip.len() as u32 - 1);
let mut img = vec![12u8; (tw * sh * 4) as usize];
for (k, fr) in strip.iter().enumerate() {
let ox = k as u32 * (sw + gap);
for y in 0..sh {
let src = &fr[(y * sw * 4) as usize..((y + 1) * sw * 4) as usize];
let d = ((y * tw + ox) * 4) as usize;
img[d..d + src.len()].copy_from_slice(src);
}
}
for i in (3..img.len()).step_by(4) {
img[i] = 255;
}
write_png(&out.join(format!("{name}-strip.png")), tw, sh, &img).unwrap();
eprintln!("{name}: {n} frames in {:.1}s → {}", t0.elapsed().as_secs_f32(), mp4.display());
}
fn median(v: &mut [f64]) -> f64 {
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
v[v.len() / 2]
}
fn bench(ctx: &mut Ctx, out: &Path) {
if !ctx.timestamps {
eprintln!("no TIMESTAMP_QUERY on this adapter");
return;
}
// 1280×800 pt at 2×: ~100 raised occluders (a dense chat + sidebar), 4 lights.
let mut ts = TextSystem::default();
let mut ui = Ui::new(&mut ts, oklch(0.17, 0.006, 265.0));
let card = oklch(0.235, 0.007, 265.0);
for i in 0..10 {
for j in 0..10 {
let x = 30.0 + j as f32 * 124.0;
let y = 20.0 + i as f32 * 78.0;
ui.rect(x, y, 104.0 + (i * 7 % 13) as f32, 56.0, 14.0, card, None, |p| p.raised(7.0 * sc()).bevel(6.0 * sc(), 2.0 * sc()).gloss(0.5, 0.4));
ui.text(x + 12.0, y + 18.0, "Message", 13.0, 400.0, oklch(0.9, 0.0, 0.0));
}
}
let (prims, base, text, clear) = (ui.prims, ui.base, ui.text, ui.clear);
ctx.draw_ui(&base, &text, clear);
let cfgs: Vec<(&str, usize, bool, bool)> = vec![
("1 light", 1, false, false),
("4 lights", 4, false, false),
("8 lights", 8, false, false),
("4 lights + shafts", 4, true, false),
("GI only (emitters)", 0, false, true),
("4 lights + GI bounce", 4, false, true),
];
let mut report = String::from("{\n");
for (ci, (label, nl, shafts, gi)) in cfgs.iter().enumerate() {
let mut runs: Vec<[f64; 6]> = Vec::new();
for f in 0..90 {
let t = f as f32 / 60.0;
let lights: Vec<Light> = (0..*nl)
.map(|k| {
let a = t * 0.8 + k as f32 * 1.7;
let l = Light::point((640.0 + 420.0 * a.cos()) * sc(), (400.0 + 260.0 * a.sin()) * sc(), 60.0 * sc())
.intensity(1.5)
.radius(10.0 * sc())
.range(1200.0 * sc());
if *shafts { l.shafts(0.4) } else { l }
})
.collect();
let mut p = prims.clone();
if *gi {
for (k, pr) in p.iter_mut().enumerate() {
if k % 9 == 0 {
*pr = pr.emissive([2.0, 0.6, 0.3]);
}
}
}
let s = Settings {
gi: gi.then(|| Gi { bounce: if *nl > 0 { 0.25 } else { 0.0 }, ..Default::default() }),
..Default::default()
};
ctx.light_frame(&p, &lights, s, false);
if let Some(tm) = ctx.light.read_timings(&ctx.device) {
if f >= 30 {
runs.push([tm.field, tm.shadows, tm.gi, tm.raster, tm.total, 0.0]);
}
}
}
// Wall clock of 120 back-to-back frames with no readback: GPU-bound, an upper bound on the whole lighting pass
// (surface + field + shadows + GI + composite), since render-pass timestamps aren't ordered on tile GPUs.
let wall = {
let lights: Vec<Light> = (0..*nl)
.map(|k| {
let l = Light::point((300.0 + k as f32 * 90.0) * sc(), 400.0 * sc(), 60.0 * sc()).intensity(1.5).radius(10.0 * sc()).range(1200.0 * sc());
if *shafts { l.shafts(0.4) } else { l }
})
.collect();
let mut p = prims.clone();
if *gi {
for (k, pr) in p.iter_mut().enumerate() {
if k % 9 == 0 {
*pr = pr.emissive([2.0, 0.6, 0.3]);
}
}
}
let s = Settings { gi: gi.then(|| Gi { bounce: if *nl > 0 { 0.25 } else { 0.0 }, ..Default::default() }), ..Default::default() };
ctx.light_frame(&p, &lights, s, false);
ctx.device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
let t0 = rune::time::now();
for _ in 0..120 {
ctx.light_frame(&p, &lights, s, false);
}
ctx.device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
t0.elapsed().as_secs_f64() * 1000.0 / 120.0
};
let col = |i: usize| median(&mut runs.iter().map(|r| r[i]).collect::<Vec<_>>());
let (fi, sh, gi_t) = (col(0), col(1), col(2));
println!("{label:>24}: field {fi:.3} shadows {sh:.3} gi {gi_t:.3} ms (timestamps) whole lighting frame {wall:.3} ms (wall, GPU-bound) ({} prims)", prims.len());
report += &format!(
" \"{label}\": {{\"field\": {fi:.4}, \"shadows\": {sh:.4}, \"gi\": {gi_t:.4}, \"frame_wall\": {wall:.4}}}{}\n",
if ci + 1 < cfgs.len() { "," } else { "" }
);
}
report += "}\n";
std::fs::write(out.join("bench.json"), report).unwrap();
}
fn f16(h: u16) -> f32 {
let s = if h & 0x8000 != 0 { -1.0 } else { 1.0 };
let e = ((h >> 10) & 0x1f) as i32;
let m = (h & 0x3ff) as f32;
if e == 0 {
s * m * 2f32.powi(-24)
} else if e == 31 {
s * f32::INFINITY
} else {
s * (1.0 + m / 1024.0) * 2f32.powi(e - 15)
}
}
fn verify(ctx: &mut Ctx) {
// Two raised cards and a floating popover; one light low and to the side, so the floor has long penumbrae.
let prims = vec![
Prim::rect(600.0, 500.0, 400.0, 200.0).radius(28.0).raised(14.0),
Prim::rect(1200.0, 650.0, 300.0, 300.0).radius(60.0).raised(24.0),
Prim::rect(1500.0, 300.0, 360.0, 160.0).radius(20.0).floating(40.0, 48.0),
];
let light = Light::point(400.0, 420.0, 120.0).intensity(1.5).radius(24.0).range(6000.0);
let mut ts = TextSystem::default();
let ui = Ui::new(&mut ts, oklch(0.2, 0.0, 0.0));
let (base, text, clear) = (ui.base, ui.text, ui.clear);
ctx.draw_ui(&base, &text, clear);
ctx.light_frame(&prims, &[light], Settings::default(), false);
// Read back layer 0 of the visibility texture.
let (fw, fh) = ctx.light.field_size();
let row = (fw * 8).div_ceil(256) * 256;
let buf = ctx.device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: (row * fh) as u64,
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
});
let mut enc = ctx.device.create_command_encoder(&Default::default());
enc.copy_texture_to_buffer(
wgpu::TexelCopyTextureInfo { texture: ctx.light.visibility_texture(), mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
wgpu::TexelCopyBufferInfo { buffer: &buf, layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(row), rows_per_image: Some(fh) } },
wgpu::Extent3d { width: fw, height: fh, depth_or_array_layers: 1 },
);
ctx.queue.submit([enc.finish()]);
let slice = buf.slice(..);
slice.map_async(wgpu::MapMode::Read, |_| {});
ctx.device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
let data = slice.get_mapped_range().unwrap().to_vec();
let gpu = |x: u32, y: u32| {
let i = (y * row + x * 8) as usize;
f16(u16::from_le_bytes([data[i], data[i + 1]]))
};
// A grid of field texels over the whole frame: the estimator must match the GPU everywhere; in penumbrae
// (ground truth strictly between 0 and 1) we report how far the fast estimate is from brute force.
let top_z = |p: [f32; 2]| {
prims.iter().rev().find(|pr| cpu::field(&[(**pr).raised(1.0).floating(pr.z[0], pr.z[1])], p)[0] < 0.0).map_or(0.0, |pr| pr.z[1])
};
let (mut max_est, mut sum_est, mut n_all) = (0.0f32, 0.0f32, 0u32);
let (mut sum_pen, mut n_pen, mut max_pen) = (0.0f32, 0u32, 0.0f32);
let mut rows = Vec::new();
let mut worst = String::new();
for gy in 0..40u32 {
for gx in 0..64u32 {
let (x, y) = (gx * fw / 64 + 3, gy * fh / 40 + 5);
let pxy = [(x as f32 + 0.5) * 2.0, (y as f32 + 0.5) * 2.0];
let z = top_z(pxy);
// Skip receivers within 3 px of an edge (the receiver height is ambiguous there by construction).
if prims.iter().any(|pr| (cpu::field(std::slice::from_ref(pr), pxy)[0]).abs() < 3.0) {
continue;
}
let p = [pxy[0], pxy[1], z + 0.35];
let g = gpu(x, y);
let e = cpu::estimate(&prims, &light, p);
if (g - e).abs() > max_est {
worst = format!("worst texel ({x},{y}) z {z}: gpu {g:.3} vs cpu {e:.3}");
}
max_est = max_est.max((g - e).abs());
sum_est += (g - e).abs();
n_all += 1;
let gt = cpu::ground_truth(&prims, &light, p, 20);
if gt > 0.02 && gt < 0.98 {
sum_pen += (g - gt).abs();
max_pen = max_pen.max((g - gt).abs());
n_pen += 1;
if rows.len() < 12 {
rows.push(format!(" ({x:4},{y:4}) z {z:4.1} gpu {g:.3} cpu-est {e:.3} ground-truth {gt:.3}"));
}
}
}
}
for r in &rows {
println!("{r}");
}
println!("{worst}");
println!(
"{n_all} texels: max |gpu − cpu estimator| = {max_est:.4}, mean {:.5}; {n_pen} penumbra texels: mean |gpu − ground truth| = {:.3}, max {max_pen:.3}",
sum_est / n_all.max(1) as f32,
sum_pen / n_pen.max(1) as f32
);
}
fn main() {
let args: Vec<String> = std::env::args().collect();
let cmd = args.get(1).map(String::as_str).unwrap_or("all");
let mut out = PathBuf::from("demo/light");
let mut frames = None;
let mut i = 2;
while i < args.len() {
match args[i].as_str() {
"--out" => {
out = PathBuf::from(&args[i + 1]);
i += 1;
}
"--frames" => {
frames = args[i + 1].parse().ok();
i += 1;
}
_ => {}
}
i += 1;
}
std::fs::create_dir_all(&out).unwrap();
let mut ctx = Ctx::new();
let mut demos = demos::all_demos();
match cmd {
"bench" => bench(&mut ctx, &out),
"verify" => verify(&mut ctx),
"all" => {
for d in demos.iter_mut() {
render_demo(&mut ctx, d.as_mut(), &out, frames);
}
}
name => {
let d = demos.iter_mut().find(|d| d.name() == name).unwrap_or_else(|| panic!("unknown demo {name}"));
render_demo(&mut ctx, d.as_mut(), &out, frames);
}
}
}
/// Appends a line of text (points) to a built frame's text layer.
pub fn caption(ts: &mut TextSystem, f: &mut Frame, x: f32, y: f32, s: &str, color: Color) {
let mut ui = Ui::new(ts, f.3);
ui.text(x, y, s, 12.0, 500.0, color);
f.2.extend(ui.text);
}
@@ -0,0 +1,708 @@
use super::*;
// ---------------------------------------------------------------- demos
pub type Frame = (Vec<Prim>, Vec<Instance>, Vec<Instance>, Color, Vec<Light>, Settings);
pub(super) trait Demo {
fn name(&self) -> &'static str;
fn seconds(&self) -> f32 {
4.0
}
fn still(&self) -> f32;
fn frame(&mut self, ts: &mut TextSystem, t: f32) -> Frame;
}
fn finish(ui: Ui<'_>, lights: Vec<Light>, s: Settings) -> Frame {
(ui.prims, ui.base, ui.text, ui.clear, lights, s)
}
/// Linear colour from a colour temperature-ish triplet in sRGB.
pub fn lin(r: f32, g: f32, b: f32) -> [f32; 3] {
[srgb_decode(r), srgb_decode(g), srgb_decode(b)]
}
/// A smooth closed path through `pts` (Catmull–Rom), u in [0, 1).
fn loop_path(pts: &[[f32; 2]], u: f32) -> [f32; 2] {
let n = pts.len();
let x = u.rem_euclid(1.0) * n as f32;
let i = x.floor() as usize;
let f = x - i as f32;
let p = |k: isize| pts[((i as isize + k).rem_euclid(n as isize)) as usize];
let (p0, p1, p2, p3) = (p(-1), p(0), p(1), p(2));
let cr = |a: f32, b: f32, c: f32, d: f32| {
0.5 * ((2.0 * b) + (-a + c) * f + (2.0 * a - 5.0 * b + 4.0 * c - d) * f * f + (-a + 3.0 * b - 3.0 * c + d) * f * f * f)
};
[cr(p0[0], p1[0], p2[0], p3[0]), cr(p0[1], p1[1], p2[1], p3[1])]
}
/// A dragged light: waypoints the "hand" jumps between, followed by springs (Kit's palette "calm" .4/0 → softer .7/0
/// for a heavy lamp), sampled at absolute time so frames are deterministic.
struct Drag {
x: Track,
y: Track,
stops: Vec<(f32, [f32; 2])>,
next: usize,
spring: Spring,
}
impl Drag {
fn new(stops: Vec<(f32, [f32; 2])>, spring: Spring) -> Drag {
let p0 = stops[0].1;
Drag { x: Track::at(p0[0]), y: Track::at(p0[1]), stops, next: 1, spring }
}
pub fn at(&mut self, t: f32) -> [f32; 2] {
while self.next < self.stops.len() && self.stops[self.next].0 <= t {
let (ts, p) = self.stops[self.next];
self.x.retarget(ts as f64, p[0], self.spring);
self.y.retarget(ts as f64, p[1], self.spring);
self.next += 1;
}
[self.x.value(t as f64), self.y.value(t as f64)]
}
}
// 1. Chat timeline lit by a lamp ------------------------------------------------
struct Chat {
drag: Drag,
}
impl Chat {
fn new() -> Chat {
let stops = vec![
(0.0, [1085.0, 250.0]),
(0.2, [1060.0, 268.0]),
(0.9, [928.0, 382.0]),
(1.6, [1100.0, 530.0]),
(2.35, [905.0, 657.0]),
(3.0, [560.0, 658.0]),
(3.55, [1085.0, 250.0]),
];
Chat { drag: Drag::new(stops, Spring::new(0.85, 0.0)) }
}
}
fn bubble_text(ui: &mut Ui, x: f32, y: f32, lines: &[&str], color: Color) {
ui.lines(x, y, 21.0, lines, 14.0, 400.0, color);
}
impl Demo for Chat {
fn name(&self) -> &'static str {
"chat"
}
fn still(&self) -> f32 {
1.6
}
fn frame(&mut self, ts: &mut TextSystem, t: f32) -> Frame {
let p = self.drag.at(t);
chat_scene(ts, t, p)
}
}
/// The chat timeline with the warm lamp at `p` (points).
pub fn chat_scene(ts: &mut TextSystem, t: f32, p: [f32; 2]) -> Frame {
{
let bg = oklch(0.17, 0.006, 265.0);
let mut ui = Ui::new(ts, bg);
let side = oklch(0.195, 0.006, 265.0);
let txt = oklch(0.93, 0.004, 265.0);
let txt2 = oklch(0.66, 0.01, 265.0);
let txt3 = oklch(0.52, 0.01, 265.0);
let hair = oklcha(1.0, 0.0, 0.0, 0.06);
let card = oklch(0.235, 0.007, 265.0);
let user = oklch(0.3, 0.045, 258.0);
let code = oklch(0.195, 0.008, 265.0);
let accent = oklch(0.72, 0.15, 255.0);
// Sidebar: flat, it receives light but doesn't stand proud.
ui.rect(0.0, 0.0, 268.0, 800.0, 0.0, side, None, |p| p);
ui.paint(268.0, 0.0, 1.0, 800.0, 0.0, hair);
ui.text(24.0, 22.0, "OpenCode", 15.0, 600.0, txt);
ui.rect(20.0, 58.0, 228.0, 34.0, 9.0, card, Some((hair, 1.0)), |p| p.raised(3.0 * sc()).bevel(3.0 * sc(), 1.2 * sc()).gloss(0.5, 0.45));
ui.text(36.0, 66.0, "+ New session", 13.0, 500.0, txt);
ui.text(24.0, 116.0, "TODAY", 11.0, 600.0, txt3);
let sessions = [
"rune-light: lighting for UIs",
"Scroll momentum on iOS",
"Theme tokens codegen",
"Hex settings screen",
"Slug text spike",
"Radiance cascades notes",
"Motion blur from tracks",
];
for (i, s) in sessions.iter().enumerate() {
let y = 138.0 + i as f32 * 36.0;
if i == 0 {
ui.rect(14.0, y - 7.0, 240.0, 32.0, 8.0, oklcha(1.0, 0.0, 0.0, 0.06), None, |p| p);
}
ui.text(26.0, y, s, 13.0, if i == 0 { 500.0 } else { 400.0 }, if i == 0 { txt } else { txt2 });
}
// Header
ui.text(300.0, 22.0, "rune-light: lighting for UIs", 14.0, 600.0, txt);
let chip = "claude-opus-5.5";
let cw = ui.measure(chip, 12.0, 500.0);
ui.rect(1240.0 - cw - 24.0, 16.0, cw + 24.0, 28.0, 14.0, card, Some((hair, 1.0)), |p| p.raised(2.0 * sc()).bevel(4.0 * sc(), 1.0 * sc()).gloss(0.5, 0.4));
ui.text(1240.0 - cw - 12.0, 22.0, chip, 12.0, 500.0, txt2);
ui.paint(269.0, 60.0, 1011.0, 1.0, 0.0, hair);
let raise = |p: Prim| p.raised(7.0 * sc()).bevel(6.0 * sc(), 2.0 * sc()).gloss(0.55, 0.42);
// User bubble
let l1 = ["what if lighting effects. like you could put a light and", "it would raytrace around the ui elements…"];
ui.rect(800.0, 88.0, 440.0, 68.0, 16.0, user, Some((oklcha(1.0, 0.0, 0.0, 0.08), 1.0)), raise);
bubble_text(&mut ui, 818.0, 101.0, &l1, txt);
// Assistant
ui.rect(300.0, 182.0, 600.0, 152.0, 16.0, card, Some((hair, 1.0)), raise);
bubble_text(
&mut ui,
322.0,
198.0,
&[
"Every Rune element is an analytic rounded rect, so the frame is",
"already an exact distance field. A light can sphere-trace soft",
"shadows straight through it: contact-hard near each bubble,",
"wide and soft where the light is far.",
],
txt,
);
for (i, chipt) in ["Read shader.wgsl", "Edit rune-light/src/lib.rs", "Run bench"].iter().enumerate() {
let x = 322.0 + [0.0, 140.0, 330.0][i];
let w = ui.measure(chipt, 12.0, 500.0) + 22.0;
ui.rect(x, 292.0, w, 26.0, 13.0, oklch(0.27, 0.008, 265.0), Some((hair, 1.0)), |p| p.on(7.0 * sc()).raised(2.5 * sc()).bevel(4.0 * sc(), 1.0 * sc()).gloss(0.4, 0.4));
ui.text(x + 11.0, 297.0, chipt, 12.0, 500.0, txt2);
}
// User
ui.rect(960.0, 360.0, 280.0, 44.0, 16.0, user, Some((oklcha(1.0, 0.0, 0.0, 0.08), 1.0)), raise);
bubble_text(&mut ui, 980.0, 372.0, &["MAKE THIS SOOO GOOOD"], txt);
// Assistant with code
ui.rect(300.0, 430.0, 640.0, 196.0, 16.0, card, Some((hair, 1.0)), raise);
bubble_text(&mut ui, 322.0, 446.0, &["Here's the API: lights are springs like everything else."], txt);
ui.rect(318.0, 480.0, 604.0, 126.0, 10.0, code, Some((hair, 1.0)), |p| p.on(7.0 * sc()).gloss(0.2, 0.5));
let mono = oklch(0.8, 0.06, 200.0);
ui.lines(
336.0,
494.0,
20.0,
&[
"let lamp = Light::point(x, y, 60.0)",
" .color(WARM).intensity(1.6).radius(10.0);",
"",
"lights.render(&scene, &[lamp], target);",
"",
],
13.0,
400.0,
mono,
);
// Composer
ui.rect(300.0, 690.0, 940.0, 78.0, 18.0, card, Some((oklcha(1.0, 0.0, 0.0, 0.09), 1.0)), |p| {
p.raised(10.0 * sc()).bevel(7.0 * sc(), 2.5 * sc()).gloss(0.6, 0.38)
});
ui.text(322.0, 708.0, "Ask anything…", 14.0, 400.0, txt3);
ui.rect(1192.0, 724.0, 32.0, 32.0, 16.0, accent, None, |p| p.on(10.0 * sc()).raised(4.0 * sc()).bevel(10.0 * sc(), 3.0 * sc()).gloss(0.8, 0.3));
ui.paint(1203.0, 739.0, 10.0, 2.0, 1.0, oklch(0.2, 0.02, 255.0));
let lamp = Light::point(p[0] * sc(), p[1] * sc(), 40.0 * sc())
.color(lin(1.0, 0.78, 0.55))
.intensity(2.6)
.radius(11.0 * sc())
.range(1100.0 * sc())
.bulb(0.75)
.specular(1.2);
let fill = Light::point(-300.0 * sc(), -200.0 * sc(), 900.0 * sc())
.color(lin(0.55, 0.65, 1.0))
.intensity(0.35)
.radius(220.0 * sc())
.range(6000.0 * sc())
.specular(0.4);
let s = Settings {
ambient: [0.62, 0.63, 0.7],
albedo_floor: 0.07,
gi: None,
rim: 0.9,
contact_ao: 0.45,
time: t,
..Default::default()
};
finish(ui, vec![lamp, fill], s)
}
}
// 2. Cursor flashlight ------------------------------------------------------------
struct Flashlight;
/// Control ids for hit-testing: 5 toggles, 5 accent dots, the volume slider, 7 press buttons
/// (Dark pill, ⌥ Space chip, ⌘ ⇧ K keycaps, Reset, Record shortcut).
pub const TOGGLE0: usize = 0;
pub const DOT0: usize = 5;
pub const SLIDER: usize = 10;
pub const BUTTON0: usize = 11;
pub const N_CTL: usize = 18;
pub const DOT_HUES: [f32; 5] = [255.0, 300.0, 350.0, 40.0, 150.0];
pub fn accent_for(hue: f32) -> Color {
oklch(0.7, 0.15, hue)
}
/// Sampled (already animated) state of the settings panel. `Panel::default()` is the headless demo.
#[derive(Clone)]
pub struct Panel {
/// Toggle knob positions, 0 off … 1 on.
pub toggles: [f32; 5],
pub accent: Color,
pub selected: usize,
/// Opacity of the ring around the selected accent dot (0 in the headless demo).
pub ring: f32,
pub volume: f32,
pub hover: [f32; N_CTL],
pub press: [f32; N_CTL],
}
impl Default for Panel {
fn default() -> Panel {
Panel {
toggles: [1.0, 0.0, 1.0, 0.0, 1.0],
accent: accent_for(255.0),
selected: 0,
ring: 0.0,
volume: 82.0 / 130.0,
hover: [0.0; N_CTL],
press: [0.0; N_CTL],
}
}
}
impl Panel {
/// Height multiplier: hover lifts a little, pressing pushes it nearly flat.
fn lift(&self, id: usize) -> f32 {
(1.0 + 0.45 * self.hover[id]) * (1.0 - 0.92 * self.press[id].clamp(0.0, 1.2))
}
}
/// A clickable region in points.
#[derive(Clone, Copy, Debug)]
pub struct Hit {
pub id: usize,
pub rect: [f32; 4],
}
fn mix(a: Color, b: Color, k: f32) -> Color {
let k = k.clamp(0.0, 1.0);
Color { r: a.r + (b.r - a.r) * k, g: a.g + (b.g - a.g) * k, b: a.b + (b.b - a.b) * k, a: a.a + (b.a - a.a) * k }
}
fn settings_panel(ui: &mut Ui, card: Color, txt: Color, txt2: Color, hair: Color, st: &Panel) -> Vec<Hit> {
let accent = st.accent;
let mut hits = Vec::new();
let raise_card = |p: Prim| p.raised(4.0 * sc()).bevel(5.0 * sc(), 1.5 * sc()).gloss(0.45, 0.45);
let top = 4.0 * sc();
ui.text(160.0, 70.0, "Settings", 24.0, 600.0, txt);
ui.text(160.0, 106.0, "Appearance, sound and shortcuts", 13.0, 400.0, txt2);
let rows: [(&str, &str, u8); 9] = [
("Appearance", "Dark", 2),
("Accent colour", "", 3),
("Reduce motion", "", 1),
("Sound effects", "", 0),
("Notification volume", "", 4),
("Push to talk", "⌥ Space", 2),
("Auto-update", "", 1),
("Send crash reports", "", 0),
("Launch at login", "", 1),
];
let (mut toggle, mut button) = (0usize, 0usize);
let y = 150.0;
for (gi, group) in [&rows[0..3], &rows[3..6], &rows[6..9]].iter().enumerate() {
let x = 160.0 + gi as f32 * 330.0;
let h = group.len() as f32 * 56.0;
ui.rect(x, y, 310.0, h, 14.0, card, Some((hair, 1.0)), raise_card);
for (ri, (label, value, kind)) in group.iter().enumerate() {
let ry = y + ri as f32 * 56.0;
if ri > 0 {
ui.paint(x + 16.0, ry, 278.0, 1.0, 0.0, hair);
}
ui.text(x + 18.0, ry + 19.0, label, 13.0, 500.0, txt);
let rx = x + 310.0 - 18.0;
match kind {
0 | 1 => {
let id = TOGGLE0 + toggle;
toggle += 1;
let k = st.toggles[id - TOGGLE0];
let m = st.lift(id);
let track = mix(oklch(0.33, 0.006, 265.0), accent, k);
ui.rect(rx - 42.0, ry + 16.0, 42.0, 24.0, 12.0, track, None, |p| p.on(top).gloss(0.4, 0.4));
let kx = rx - 40.0 + 18.0 * k;
ui.rect(kx, ry + 18.0, 20.0, 20.0, 10.0, oklch(0.96, 0.0, 0.0), None, |p| {
p.on(top).raised(5.0 * sc() * m).bevel(10.0 * sc(), 4.0 * sc() * m).gloss(0.7, 0.3)
});
hits.push(Hit { id, rect: [rx - 42.0, ry + 16.0, 42.0, 24.0] });
}
2 => {
let id = BUTTON0 + button;
button += 1;
let m = st.lift(id);
let w = ui.measure(value, 12.0, 500.0) + 20.0;
ui.rect(rx - w, ry + 14.0, w, 28.0, 8.0, oklch(0.3, 0.006, 265.0), Some((hair, 1.0)), |p| {
p.on(top).raised(3.0 * sc() * m).bevel(4.0 * sc(), 1.2 * sc() * m).gloss(0.5, 0.4)
});
ui.text(rx - w + 10.0, ry + 20.0, value, 12.0, 500.0, txt);
hits.push(Hit { id, rect: [rx - w, ry + 14.0, w, 28.0] });
}
3 => {
for (k, h) in DOT_HUES.iter().enumerate() {
let id = DOT0 + k;
let m = st.lift(id);
let c = oklch(0.68, 0.15, *h);
let cx = rx - 18.0 - k as f32 * 26.0;
if k == st.selected && st.ring > 0.0 {
let o = 3.0;
let ring = oklcha(0.95, 0.0, 0.0, 0.8 * st.ring);
let r = [(cx - o) * sc(), (ry + 19.0 - o) * sc(), (18.0 + 2.0 * o) * sc(), (18.0 + 2.0 * o) * sc()];
ui.base.push(inst(r, (9.0 + o) * sc(), Color::TRANSPARENT, Some((ring, 1.5 * sc()))));
}
ui.rect(cx, ry + 19.0, 18.0, 18.0, 9.0, c, None, |p| p.on(top).raised(3.5 * sc() * m).bevel(9.0 * sc(), 3.0 * sc() * m).gloss(0.7, 0.3));
hits.push(Hit { id, rect: [cx - 4.0, ry + 15.0, 26.0, 26.0] });
}
}
_ => {
let m = st.lift(SLIDER);
let v = st.volume.clamp(0.0, 1.0);
ui.rect(rx - 130.0, ry + 26.0, 130.0, 4.0, 2.0, oklch(0.33, 0.006, 265.0), None, |p| p.on(top));
if v > 0.0 {
ui.rect(rx - 130.0, ry + 26.0, 130.0 * v, 4.0, 2.0, accent, None, |p| p.on(top));
}
ui.rect(rx - 140.0 + 130.0 * v, ry + 18.0, 20.0, 20.0, 10.0, oklch(0.96, 0.0, 0.0), None, |p| {
p.on(top).raised(6.0 * sc() * m).bevel(10.0 * sc(), 4.0 * sc() * m).gloss(0.7, 0.3)
});
// The slider's hit rect spans exactly the track in x, so value = (x - rect.x) / rect.w.
hits.push(Hit { id: SLIDER, rect: [rx - 130.0, ry + 12.0, 130.0, 32.0] });
}
}
}
}
// A wide card below with buttons.
let by = 340.0;
ui.rect(160.0, by, 970.0, 150.0, 14.0, card, Some((hair, 1.0)), raise_card);
ui.text(180.0, by + 20.0, "Keyboard shortcuts", 15.0, 600.0, txt);
ui.text(180.0, by + 46.0, "Press a key combination to record a new shortcut.", 13.0, 400.0, txt2);
for (i, k) in ["⌘", "⇧", "K"].iter().enumerate() {
let id = BUTTON0 + 2 + i;
let m = st.lift(id);
ui.rect(180.0 + i as f32 * 52.0, by + 82.0, 44.0, 44.0, 10.0, oklch(0.3, 0.006, 265.0), Some((hair, 1.0)), |p| {
p.on(top).raised(6.0 * sc() * m).bevel(7.0 * sc(), 2.5 * sc() * m).gloss(0.6, 0.35)
});
ui.text(195.0 + i as f32 * 52.0, by + 94.0, k, 15.0, 600.0, txt);
hits.push(Hit { id, rect: [180.0 + i as f32 * 52.0, by + 82.0, 44.0, 44.0] });
}
let m = st.lift(BUTTON0 + 6);
ui.rect(940.0, by + 90.0, 170.0, 36.0, 10.0, accent, None, |p| p.on(top).raised(5.0 * sc() * m).bevel(6.0 * sc(), 2.0 * sc() * m).gloss(0.7, 0.3));
ui.text(975.0, by + 99.0, "Record shortcut", 13.0, 600.0, oklch(0.18, 0.03, 255.0));
hits.push(Hit { id: BUTTON0 + 6, rect: [940.0, by + 90.0, 170.0, 36.0] });
let m = st.lift(BUTTON0 + 5);
ui.rect(780.0, by + 90.0, 140.0, 36.0, 10.0, oklch(0.3, 0.006, 265.0), Some((hair, 1.0)), |p| {
p.on(top).raised(5.0 * sc() * m).bevel(6.0 * sc(), 2.0 * sc() * m).gloss(0.6, 0.35)
});
ui.text(828.0, by + 99.0, "Reset", 13.0, 600.0, txt);
hits.push(Hit { id: BUTTON0 + 5, rect: [780.0, by + 90.0, 140.0, 36.0] });
// Lower row of tiles.
for i in 0..5 {
let x = 160.0 + i as f32 * 198.0;
ui.rect(x, 520.0, 180.0, 120.0, 14.0, card, Some((hair, 1.0)), raise_card);
let names = ["Microphone", "Speakers", "Camera", "Display", "Battery"];
ui.text(x + 18.0, 538.0, names[i], 13.0, 600.0, txt);
ui.text(x + 18.0, 560.0, ["MacBook Pro", "Studio Display", "FaceTime HD", "Built-in", "92 %"][i], 12.0, 400.0, txt2);
ui.rect(x + 18.0, 600.0, 144.0, 18.0, 9.0, oklch(0.27, 0.006, 265.0), None, |p| p.on(top));
let fill = [0.7, 0.45, 0.0, 0.85, 0.92][i];
if fill > 0.0 {
ui.rect(x + 18.0, 600.0, 144.0 * fill, 18.0, 9.0, accent, None, |p| p.on(top).raised(2.0 * sc()).bevel(9.0 * sc(), 2.0 * sc()).gloss(0.6, 0.3));
}
}
hits
}
impl Demo for Flashlight {
fn name(&self) -> &'static str {
"flashlight"
}
fn still(&self) -> f32 {
1.15
}
fn frame(&mut self, ts: &mut TextSystem, t: f32) -> Frame {
// The pointer wanders like a hand: one smooth closed path at an even pace.
let path = [[300.0, 230.0], [700.0, 180.0], [1020.0, 300.0], [860.0, 470.0], [560.0, 600.0], [260.0, 520.0]];
let p = loop_path(&path, t / 4.0 + 0.02);
flashlight_scene(ts, t, p, &Panel::default(), false).0
}
}
/// The dark settings panel lit by a torch aimed at the pointer `p` (points). `overhead` holds the torch straight
/// above the pointer so the hotspot sits exactly under it (the live window); otherwise it's held low and to the
/// right (the headless demo). Returns the panel's hit regions too.
pub fn flashlight_scene(ts: &mut TextSystem, t: f32, p: [f32; 2], panel: &Panel, overhead: bool) -> (Frame, Vec<Hit>) {
let bg = oklch(0.16, 0.005, 265.0);
let mut ui = Ui::new(ts, bg);
let hits = settings_panel(
&mut ui,
oklch(0.225, 0.006, 265.0),
oklch(0.94, 0.003, 265.0),
oklch(0.66, 0.01, 265.0),
oklcha(1.0, 0.0, 0.0, 0.06),
panel,
);
let lp = if overhead { [p[0], p[1], 260.0] } else { [p[0] + 80.0, p[1] + 130.0, 260.0] };
let axis = [p[0] - lp[0], p[1] - lp[1], -lp[2]];
let torch = Light::point(lp[0] * sc(), lp[1] * sc(), lp[2] * sc())
.color(lin(1.0, 0.95, 0.88))
.intensity(7.0)
.radius(9.0 * sc())
.range(1800.0 * sc())
.spot(axis, 0.58)
.specular(1.4);
let s = Settings {
ambient: [0.07, 0.075, 0.09],
albedo_floor: 0.04,
text: TextPolicy { floor: 0.32, ceiling: 1.3, lit: 1.0, specular: 0.1 },
rim: 1.0,
contact_ao: 0.3,
background_gloss: 0.5,
time: t,
..Default::default()
};
(finish(ui, vec![torch], s), hits)
}
// 3. Emissive UI lights its neighbours ----------------------------------------------
struct Emissive {
breath: Track,
flip: f32,
up: bool,
}
impl Demo for Emissive {
fn name(&self) -> &'static str {
"emissive"
}
fn still(&self) -> f32 {
2.4
}
fn frame(&mut self, ts: &mut TextSystem, t: f32) -> Frame {
// Breathing: a spring retargets between two levels every 1.1 s ("slow" .85/0), so the glow eases in and
// out with no phase jump; lights cool, never cut.
while t >= self.flip {
self.up = !self.up;
self.breath.retarget(self.flip as f64, if self.up { 1.0 } else { 0.55 }, Spring::new(0.85, 0.0));
self.flip += 1.1;
}
let b = self.breath.value(t as f64);
let bg = oklch(0.15, 0.006, 265.0);
let mut ui = Ui::new(ts, bg);
let card = oklch(0.23, 0.006, 265.0);
let txt = oklch(0.94, 0.003, 265.0);
let txt2 = oklch(0.64, 0.01, 265.0);
let hair = oklcha(1.0, 0.0, 0.0, 0.06);
let raise = |p: Prim| p.raised(6.0 * sc()).bevel(6.0 * sc(), 2.0 * sc()).gloss(0.5, 0.42);
ui.text(140.0, 64.0, "Voice memo", 24.0, 600.0, txt);
ui.text(140.0, 100.0, "Recording · Studio Display microphone", 13.0, 400.0, txt2);
// Left column of cards around the recorder
for (i, (title, sub)) in [("Transcript", "Live, 2 speakers"), ("Markers", "3 added"), ("Noise", "Voice isolation on")].iter().enumerate() {
let y = 150.0 + i as f32 * 128.0;
ui.rect(140.0, y, 300.0, 108.0, 16.0, card, Some((hair, 1.0)), raise);
ui.text(162.0, y + 20.0, title, 14.0, 600.0, txt);
ui.text(162.0, y + 44.0, sub, 13.0, 400.0, txt2);
}
// The recorder card in the middle
ui.rect(470.0, 150.0, 400.0, 364.0, 20.0, card, Some((hair, 1.0)), raise);
ui.text(494.0, 172.0, "00:42.18", 34.0, 600.0, txt);
ui.text(494.0, 220.0, "Recording", 13.0, 500.0, oklch(0.75, 0.12, 25.0));
// Waveform bars (flat, receive light)
for k in 0..40 {
let h = 8.0 + 46.0 * (0.5 + 0.5 * ((k as f32 * 0.7).sin() * (k as f32 * 0.23 + 1.0).cos())).abs();
ui.rect(494.0 + k as f32 * 8.8, 290.0 - h * 0.5, 4.6, h, 2.3, oklch(0.5, 0.01, 265.0), None, |p| p.on(12.0).raised(2.0 * sc()));
}
// Glowing record button with a spring breath
let red = oklch(0.66, 0.2, 25.0);
let red_lin = [red.r, red.g, red.b];
let glow = 7.0 * b;
ui.rect(620.0, 370.0, 100.0, 100.0, 50.0, oklch(0.27, 0.008, 265.0), Some((hair, 1.0)), |p| {
p.on(12.0).bevel(16.0 * sc(), 4.0 * sc()).gloss(0.6, 0.35)
});
ui.rect(640.0, 390.0, 60.0, 60.0, 30.0, red, None, |p| p.on(12.0).emissive([red_lin[0] * glow, red_lin[1] * glow, red_lin[2] * glow]));
// Progress bar under it, emitting cyan, growing
let prog = 0.25 + 0.5 * (t / 4.0).min(1.0);
let cyan = oklch(0.78, 0.13, 210.0);
ui.rect(140.0, 560.0, 730.0, 10.0, 5.0, oklch(0.24, 0.006, 265.0), None, |p| p);
let g2 = 1.9 * (0.85 + 0.15 * b);
ui.rect(140.0, 560.0, 730.0 * prog, 10.0, 5.0, cyan, None, |p| p.emissive([cyan.r * g2, cyan.g * g2, cyan.b * g2]));
ui.text(140.0, 584.0, "Uploading to OpenCode · 3 of 5 files", 12.0, 500.0, txt2);
// Right column: notifications with a small green status dot (emissive)
let green = oklch(0.78, 0.17, 150.0);
for (i, (title, sub)) in [("Agent finished", "rune-light demos rendered"), ("Build passed", "ci · 1m 12s"), ("Review", "Argon: no blockers")].iter().enumerate() {
let y = 150.0 + i as f32 * 128.0;
ui.rect(900.0, y, 300.0, 108.0, 16.0, card, Some((hair, 1.0)), raise);
ui.text(940.0, y + 20.0, title, 14.0, 600.0, txt);
ui.text(940.0, y + 44.0, sub, 13.0, 400.0, txt2);
let gd = if i == 0 { 2.2 * (0.6 + 0.4 * b) } else { 0.0 };
let c = if i == 0 { green } else { oklch(0.45, 0.01, 265.0) };
ui.rect(918.0, y + 24.0, 10.0, 10.0, 5.0, c, None, |p| p.on(12.0).emissive([c.r * gd, c.g * gd, c.b * gd]));
}
// Bottom dock of chips
for i in 0..6 {
let x = 140.0 + i as f32 * 178.0;
ui.rect(x, 640.0, 160.0, 90.0, 16.0, card, Some((hair, 1.0)), raise);
ui.text(x + 18.0, 660.0, ["Pause", "Marker", "Trim", "Share", "Export", "Delete"][i], 13.0, 600.0, txt);
}
let s = Settings {
ambient: [0.3, 0.31, 0.35],
gi: Some(Gi { strength: 1.0, air: 0.09, bounce: 0.0, absorption: 0.24, ..Default::default() }),
contact_ao: 0.4,
rim: 0.6,
time: t,
..Default::default()
};
finish(ui, vec![], s)
}
}
// 4. Raised material -------------------------------------------------------------------
struct Raised;
impl Demo for Raised {
fn name(&self) -> &'static str {
"raised"
}
fn still(&self) -> f32 {
1.4
}
fn frame(&mut self, ts: &mut TextSystem, t: f32) -> Frame {
let bg = oklch(0.2, 0.004, 265.0);
let mut ui = Ui::new(ts, bg);
let txt = oklch(0.92, 0.003, 265.0);
let txt2 = oklch(0.62, 0.008, 265.0);
let body = oklch(0.255, 0.004, 265.0);
let key = oklch(0.29, 0.004, 265.0);
// Device body
ui.rect(120.0, 90.0, 1040.0, 620.0, 36.0, body, Some((oklcha(1.0, 0.0, 0.0, 0.05), 1.0)), |p| {
p.raised(10.0 * sc()).bevel(22.0 * sc(), 7.0 * sc()).gloss(0.7, 0.32)
});
ui.text(170.0, 130.0, "OP-1 Field · Control surface", 15.0, 600.0, txt);
ui.text(170.0, 156.0, "Bevels from the SDF catch the light", 12.0, 400.0, txt2);
// Four encoder knobs
let hues = [255.0, 150.0, 60.0, 25.0];
for i in 0..4 {
let cx = 200.0 + i as f32 * 140.0;
ui.rect(cx - 48.0, 210.0, 96.0, 96.0, 48.0, key, None, |p| p.floating(10.0 * sc(), 22.0 * sc()).bevel(30.0 * sc(), 10.0 * sc()).gloss(0.9, 0.26));
let c = oklch(0.7, 0.14, hues[i]);
ui.rect(cx - 5.0, 222.0, 10.0, 10.0, 5.0, c, None, |p| p);
}
// Screen (flat, recessed look by being darker; glossy)
ui.rect(780.0, 200.0, 330.0, 200.0, 18.0, oklch(0.14, 0.01, 265.0), None, |p| p.gloss(1.0, 0.18));
ui.text(806.0, 226.0, "128 BPM", 28.0, 600.0, oklch(0.85, 0.12, 150.0));
ui.text(806.0, 270.0, "Pattern A · bar 12", 13.0, 400.0, oklch(0.6, 0.06, 150.0));
// Keys: two rows
for r in 0..2 {
for i in 0..12 {
let x = 170.0 + i as f32 * 78.0;
let y = 450.0 + r as f32 * 110.0;
let accent = (r == 0 && (i == 2 || i == 7)) || (r == 1 && i == 10);
let c = if accent { oklch(0.62, 0.17, 35.0) } else { key };
ui.rect(x, y, 68.0, 92.0, 14.0, c, None, |p| p.floating(10.0 * sc(), 18.0 * sc()).bevel(12.0 * sc(), 4.5 * sc()).gloss(0.85, 0.28));
ui.text(x + 12.0, y + 12.0, ["C", "D", "E", "F", "G", "A", "B", "C", "D", "E", "F", "G"][i], 12.0, 600.0, if accent { oklch(0.2, 0.03, 35.0) } else { txt2 });
}
}
// The light sweeps across on a slow arc (one smooth path, no reversal mid-clip).
let u = (t / self.seconds()).clamp(0.0, 1.0);
let e = u * u * (3.0 - 2.0 * u);
let x = 40.0 + e * 1200.0;
let y = 560.0 - 300.0 * (1.0 - (2.0 * e - 1.0).powi(2));
let key_l = Light::point(x * sc(), y * sc(), 150.0 * sc()).color(lin(1.0, 0.93, 0.85)).intensity(3.4).radius(26.0 * sc()).range(2200.0 * sc()).specular(2.4);
let fill = Light::point(1400.0 * sc(), 900.0 * sc(), 700.0 * sc())
.color(lin(0.5, 0.62, 1.0))
.intensity(0.4)
.radius(200.0 * sc())
.range(5000.0 * sc())
.specular(0.6);
let s = Settings { ambient: [0.3, 0.31, 0.34], rim: 1.1, contact_ao: 0.5, time: t, ..Default::default() };
finish(ui, vec![key_l, fill], s)
}
}
// 5. God rays --------------------------------------------------------------------------
struct GodRays;
impl Demo for GodRays {
fn name(&self) -> &'static str {
"godrays"
}
fn still(&self) -> f32 {
1.0
}
fn frame(&mut self, ts: &mut TextSystem, t: f32) -> Frame {
let bg = oklch(0.11, 0.014, 265.0);
let mut ui = Ui::new(ts, bg);
let card = oklch(0.21, 0.008, 265.0);
let txt = oklch(0.93, 0.003, 265.0);
let txt2 = oklch(0.6, 0.01, 265.0);
let hair = oklcha(1.0, 0.0, 0.0, 0.06);
let names = [
"Inbox", "Calendar", "Notes", "Music", "Photos", "Maps", "Files", "Terminal", "Mail", "Weather", "Clock", "Books", "Stocks", "Podcasts",
"Home", "Wallet", "Health", "Camera", "Code", "Fleet", "Chat", "Voice", "Launcher", "Rune",
];
let (cols, rows) = (8usize, 3usize);
let (cw, ch, gx, gy) = (124.0, 124.0, 28.0, 28.0);
let x0 = (1280.0 - (cols as f32 * cw + (cols - 1) as f32 * gx)) * 0.5;
let y0 = 290.0;
for r in 0..rows {
for c in 0..cols {
let x = x0 + c as f32 * (cw + gx);
let y = y0 + r as f32 * (ch + gy);
let i = r * cols + c;
ui.rect(x, y, cw, ch, 24.0, card, Some((hair, 1.0)), |p| p.raised(14.0 * sc()).bevel(8.0 * sc(), 2.5 * sc()).gloss(0.5, 0.4));
let hue = (i as f32 * 47.0) % 360.0;
ui.rect(x + 20.0, y + 20.0, 40.0, 40.0, 12.0, oklch(0.62, 0.12, hue), None, |p| p);
ui.text(x + 20.0, y + 84.0, names[i], 13.0, 600.0, txt);
}
}
ui.text(x0, 120.0, "Good evening", 30.0, 600.0, txt);
ui.text(x0, 164.0, "24 apps · light from behind the grid", 14.0, 400.0, txt2);
// The source sits behind the grid's top edge, lower than the cards, and drifts once across: every gap
// throws a shaft and the fan swings with it.
let u = (t / self.seconds()).clamp(0.0, 1.0);
let e = u * u * (3.0 - 2.0 * u);
let lx = 488.0 + e * 304.0;
let warm = lin(1.0, 0.8, 0.55);
let sun = Light::point(lx * sc(), 428.0 * sc(), 4.0 * sc())
.color(warm)
.intensity(1.6)
.radius(12.0 * sc())
.range(3000.0 * sc())
.shafts(1.5)
.softness(2.2);
let s = Settings { ambient: [0.5, 0.5, 0.58], shafts_over: 0.12, rim: 0.8, contact_ao: 0.35, time: t, ..Default::default() };
finish(ui, vec![sun], s)
}
}
pub(super) fn all_demos() -> Vec<Box<dyn Demo>> {
vec![
Box::new(Chat::new()),
Box::new(Flashlight),
Box::new(Emissive { breath: Track::at(0.8), flip: 0.0, up: false }),
Box::new(Raised),
Box::new(GodRays),
]
}
+726
View File
@@ -0,0 +1,726 @@
//! Interactive rune-light: the flashlight and chat demos in a window.
//!
//! live window: 1 flashlight, 2 chat, click the settings controls, drag the chat lamp, scroll radius,
//! L light mode (raking / overhead / backlight), M machined vs soft material, G god rays,
//! D spring follow, R reset radius, Esc quit
//! live --snap out.png [--scene chat] [--at X,Y] [--down | --click] [--after S] [--rays]
//! [--mode behind|overhead|backlight] [--soft] [--bare]
//! one frame headless at 2560×1600; --down/--click press (and release) at --at at t=0, rendered at S
#[allow(dead_code)]
#[path = "light.rs"]
mod light;
use std::sync::Arc;
use std::time::Instant;
use light::{DOT_HUES, DOT0, Frame, Hit, N_CTL, Panel, SLIDER, Spring, TOGGLE0, Track, accent_for, caption, chat_scene, flashlight_scene, lin, sc, set_scale};
use rune::color::oklcha;
use rune_light::Light;
use rune::color::Color;
use rune::render::Renderer;
use rune::text::TextSystem;
use rune_light::{LightRenderer, Scene};
use winit::application::ApplicationHandler;
use winit::dpi::LogicalSize;
use winit::event::{ElementState, MouseButton, MouseScrollDelta, WindowEvent};
use winit::event_loop::{ActiveEventLoop, ControlFlow, EventLoop};
use winit::keyboard::{Key, NamedKey};
use winit::window::{Window, WindowId};
/// The scenes are laid out on a 1280×800 pt canvas.
const PT_W: f32 = 1280.0;
const PT_H: f32 = 800.0;
const FOLLOW: Spring = Spring::new(0.12, 0.0);
const LAMP: Spring = Spring::new(0.2, 0.0);
const TOGGLE: Spring = Spring::new(0.25, 0.15);
const HOVER: Spring = Spring::new(0.2, 0.0);
const PRESS_DOWN: Spring = Spring::new(0.1, 0.0);
const PRESS_UP: Spring = Spring::new(0.3, 0.2);
const ACCENT: Spring = Spring::new(0.3, 0.0);
const VOLUME: Spring = Spring::new(0.25, 0.0);
/// The raking torch rig relative to its aim point, in points.
const RIG: [f32; 3] = [80.0, 130.0, 260.0];
const HALF_ANGLE: f32 = 0.58;
/// Where the raking torch's pool peaks relative to its aim point on bare floor, in points, measured on GPU frames
/// (`--snap --bare`, blurred-luminance argmax). The rig is shifted back by this so the hotspot sits under the cursor.
const BEHIND_COMP: [f32; 2] = [65.0, 105.5];
/// How the flashlight scene is lit (L cycles).
#[derive(Clone, Copy, PartialEq, Debug)]
enum Mode {
/// The torch held low and to the side, raking across the panel (the original demo rig).
Behind,
/// Straight above the cursor: a soft centred pool.
Overhead,
/// A source just above the floor at the cursor: no front light, only rims, silhouettes and shafts.
Backlight,
}
impl Mode {
fn next(self) -> Mode {
match self {
Mode::Behind => Mode::Overhead,
Mode::Overhead => Mode::Backlight,
Mode::Backlight => Mode::Behind,
}
}
fn label(self) -> &'static str {
match self {
Mode::Behind => "Light: raking (L)",
Mode::Overhead => "Light: overhead (L)",
Mode::Backlight => "Light: backlight (L)",
}
}
fn torch(self, p: [f32; 2]) -> Light {
let s = sc();
match self {
Mode::Behind | Mode::Overhead => {
let (lp, aim) = if self == Mode::Behind {
let c = BEHIND_COMP;
let aim = [p[0] - c[0], p[1] - c[1]];
([aim[0] + RIG[0], aim[1] + RIG[1], RIG[2]], aim)
} else {
([p[0], p[1], 260.0], p)
};
Light::point(lp[0] * s, lp[1] * s, lp[2] * s)
.color(lin(1.0, 0.95, 0.88))
.intensity(7.0)
.radius(9.0 * s)
.range(1800.0 * s)
.spot([aim[0] - lp[0], aim[1] - lp[1], -lp[2]], HALF_ANGLE)
.specular(1.4)
}
Mode::Backlight => Light::point(p[0] * s, p[1] * s, 4.0 * s)
.color(lin(1.0, 0.92, 0.82))
.intensity(4.0)
.radius(12.0 * s)
.range(3000.0 * s)
.shafts(2.5)
.softness(2.2),
}
}
}
/// Hard machined slabs: tighter bevels with a thin bright edge, tighter highlights, taller cards for clearer
/// elevation, sharper contact shadows, a darker void and less sheen on the floor.
fn machine(f: &mut Frame) {
for p in f.0.iter_mut() {
if p.z[2] > 0.0 {
p.z[2] *= 0.45;
p.mat[0] = (p.mat[0] * 1.3).min(1.0);
p.mat[1] *= 0.6;
}
p.z[0] *= 1.5;
p.z[1] *= 1.5;
}
let s = &mut f.5;
s.ambient = [0.035, 0.037, 0.045];
s.albedo_floor = 0.045;
s.contact_ao = 0.6;
s.rim = 1.8;
s.background_gloss = 0.12;
s.background_roughness = 0.25;
}
// ---------------------------------------------------------------- GPU
struct Gfx {
device: wgpu::Device,
queue: wgpu::Queue,
rune: Renderer,
ts: TextSystem,
light: LightRenderer,
base: wgpu::Texture,
text: wgpu::Texture,
size: (u32, u32),
format: wgpu::TextureFormat,
}
fn layer(device: &wgpu::Device, label: &str, (w, h): (u32, u32)) -> wgpu::Texture {
device.create_texture(&wgpu::TextureDescriptor {
label: Some(label),
size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba16Float,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
})
}
impl Gfx {
fn new(device: wgpu::Device, queue: wgpu::Queue, size: (u32, u32), format: wgpu::TextureFormat) -> Gfx {
let rune = Renderer::new(&device, wgpu::TextureFormat::Rgba16Float);
let light = LightRenderer::new(&device, &queue, size.0, size.1, format);
let base = layer(&device, "ui base", size);
let text = layer(&device, "ui text", size);
Gfx { device, queue, rune, ts: TextSystem::default(), light, base, text, size, format }
}
fn resize(&mut self, size: (u32, u32)) {
if size == self.size {
return;
}
self.size = size;
self.light = LightRenderer::new(&self.device, &self.queue, size.0, size.1, self.format);
self.base = layer(&self.device, "ui base", size);
self.text = layer(&self.device, "ui text", size);
}
/// Same path as the headless demo: rune draws the UI base and text layers, rune-light lights and composites.
fn render(&mut self, frame: Frame, target: &wgpu::TextureView) {
let (prims, base, text, clear, lights, mut s) = frame;
s.seed = 0.0;
let bv = self.base.create_view(&Default::default());
let tv = self.text.create_view(&Default::default());
self.rune.prepare(&self.device, &self.queue, &mut self.ts.atlas, &base, self.size);
let mut enc = self.device.create_command_encoder(&Default::default());
self.rune.draw(&mut enc, &bv, [clear.r, clear.g, clear.b, 1.0]);
self.queue.submit([enc.finish()]);
self.rune.prepare(&self.device, &self.queue, &mut self.ts.atlas, &text, self.size);
let mut enc = self.device.create_command_encoder(&Default::default());
self.rune.draw(&mut enc, &tv, [0.0; 4]);
self.queue.submit([enc.finish()]);
let mut enc = self.device.create_command_encoder(&Default::default());
let scene = Scene { prims: &prims, lights: &lights, settings: s, emission: None };
self.light.render(&self.device, &self.queue, &mut enc, &scene, &bv, &tv, target);
self.queue.submit([enc.finish()]);
}
}
fn request_device(instance: &wgpu::Instance, surface: Option<&wgpu::Surface<'_>>) -> (wgpu::Adapter, wgpu::Device, wgpu::Queue) {
let adapter = pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions {
power_preference: wgpu::PowerPreference::HighPerformance,
force_fallback_adapter: false,
compatible_surface: surface,
apply_limit_buckets: false,
}))
.expect("adapter");
let (device, queue) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor {
label: Some("rune-light live"),
required_features: wgpu::Features::empty(),
required_limits: wgpu::Limits::default(),
experimental_features: Default::default(),
memory_hints: wgpu::MemoryHints::Performance,
trace: Default::default(),
}))
.expect("device");
(adapter, device, queue)
}
// ---------------------------------------------------------------- interaction state
#[derive(Clone, Copy, PartialEq)]
enum Which {
Flashlight,
Chat,
}
fn busy(tr: &Track, t: f64, eps: f32) -> bool {
let (x, v) = tr.sample(t);
(x - tr.target).abs() > eps || v.abs() > eps * 10.0
}
fn tracks<const N: usize>(f: impl Fn(usize) -> f32) -> [Track; N] {
std::array::from_fn(|i| Track::at(f(i)))
}
struct State {
which: Which,
start: Instant,
/// Fixed clock for headless snapshots.
fake: Option<f64>,
/// Pointer in points.
cursor: [f32; 2],
/// The followed point: torch aim (flashlight) or lamp (chat), in points.
x: Track,
y: Track,
lamp: [f32; 2],
direct: bool,
radius: f32,
rays: bool,
mode: Mode,
mode_at: f64,
machined: bool,
bare: bool,
press: Option<[f32; 2]>,
dragging: bool,
// Settings panel.
on: [bool; 5],
toggles: [Track; 5],
selected: usize,
accent: [Track; 3],
volume: Track,
hover: [Track; N_CTL],
pressed: [Track; N_CTL],
hits: Vec<Hit>,
hovered: Option<usize>,
active: Option<usize>,
}
impl State {
fn new(which: Which) -> State {
let d = Panel::default();
let a = d.accent;
let mut s = State {
which: Which::Flashlight,
start: rune::time::now(),
fake: None,
cursor: [640.0, 400.0],
x: Track::at(640.0),
y: Track::at(400.0),
lamp: [1085.0, 250.0],
direct: true,
radius: 1.0,
rays: false,
mode: Mode::Behind,
mode_at: f64::NEG_INFINITY,
machined: true,
bare: false,
press: None,
dragging: false,
on: d.toggles.map(|k| k > 0.5),
toggles: tracks(|i| d.toggles[i]),
selected: d.selected,
accent: tracks(|i| [a.r, a.g, a.b][i]),
volume: Track::at(d.volume),
hover: tracks(|_| 0.0),
pressed: tracks(|_| 0.0),
hits: Vec::new(),
hovered: None,
active: None,
};
s.switch(which);
s
}
fn now(&self) -> f64 {
self.fake.unwrap_or_else(|| self.start.elapsed().as_secs_f64())
}
fn jump(&mut self, p: [f32; 2]) {
self.x = Track::at(p[0]);
self.y = Track::at(p[1]);
}
fn switch(&mut self, which: Which) {
if self.which == Which::Chat {
self.lamp = [self.x.target, self.y.target];
}
self.which = which;
self.dragging = false;
self.active = None;
self.set_hover(None);
match which {
Which::Flashlight => self.jump(self.cursor),
Which::Chat => self.jump(self.lamp),
}
}
fn follow(&mut self, p: [f32; 2], spring: Spring) {
if self.direct {
self.jump(p);
} else {
let t = self.now();
self.x.retarget(t, p[0], spring);
self.y.retarget(t, p[1], spring);
}
}
fn hit(&self, p: [f32; 2]) -> Option<&Hit> {
if self.which != Which::Flashlight {
return None;
}
let pad = 4.0;
self.hits.iter().rev().find(|h| {
let r = h.rect;
p[0] >= r[0] - pad && p[0] <= r[0] + r[2] + pad && p[1] >= r[1] - pad && p[1] <= r[1] + r[3] + pad
})
}
fn slider_value(&self, p: [f32; 2]) -> Option<f32> {
let h = self.hits.iter().find(|h| h.id == SLIDER)?;
Some(((p[0] - h.rect[0]) / h.rect[2]).clamp(0.0, 1.0))
}
fn set_hover(&mut self, id: Option<usize>) {
if id == self.hovered {
return;
}
let t = self.now();
if let Some(old) = self.hovered {
self.hover[old].retarget(t, 0.0, HOVER);
}
if let Some(new) = id {
self.hover[new].retarget(t, 1.0, HOVER);
}
self.hovered = id;
}
fn pointer_move(&mut self, p: [f32; 2]) {
self.cursor = p;
if let Some(down) = self.press
&& ((p[0] - down[0]).powi(2) + (p[1] - down[1]).powi(2)).sqrt() > 4.0
{
self.dragging = true;
}
if self.active == Some(SLIDER) && self.dragging
&& let Some(v) = self.slider_value(p)
{
self.volume = Track::at(v);
}
let over = if self.active.is_some() { self.active } else { self.hit(p).map(|h| h.id) };
self.set_hover(over);
match self.which {
Which::Flashlight => self.follow(p, FOLLOW),
Which::Chat if self.dragging => self.follow(p, LAMP),
Which::Chat => {}
}
}
fn button(&mut self, down: bool) {
let t = self.now();
if down {
self.press = Some(self.cursor);
self.dragging = false;
self.active = self.hit(self.cursor).map(|h| h.id);
if let Some(id) = self.active {
self.pressed[id].retarget(t, 1.0, PRESS_DOWN);
if id == SLIDER
&& let Some(v) = self.slider_value(self.cursor)
{
self.volume.retarget(t, v, VOLUME);
}
}
return;
}
if let Some(id) = self.active.take() {
self.pressed[id].retarget(t, 0.0, PRESS_UP);
if self.hit(self.cursor).map(|h| h.id) == Some(id) {
if (TOGGLE0..TOGGLE0 + 5).contains(&id) {
let i = id - TOGGLE0;
self.on[i] = !self.on[i];
self.toggles[i].retarget(t, if self.on[i] { 1.0 } else { 0.0 }, TOGGLE);
} else if (DOT0..DOT0 + 5).contains(&id) {
self.selected = id - DOT0;
let a = accent_for(DOT_HUES[self.selected]);
for (tr, v) in self.accent.iter_mut().zip([a.r, a.g, a.b]) {
tr.retarget(t, v, ACCENT);
}
}
}
let over = self.hit(self.cursor).map(|h| h.id);
self.set_hover(over);
}
self.press = None;
self.dragging = false;
}
fn animating(&self, t: f64) -> bool {
busy(&self.x, t, 0.05)
|| busy(&self.y, t, 0.05)
|| busy(&self.volume, t, 1e-3)
|| self.toggles.iter().chain(&self.accent).chain(&self.hover).chain(&self.pressed).any(|tr| busy(tr, t, 1e-3))
}
fn panel(&self, t: f64) -> Panel {
let [r, g, b] = self.accent.each_ref().map(|tr| tr.value(t));
Panel {
toggles: self.toggles.each_ref().map(|tr| tr.value(t)),
accent: Color { r, g, b, a: 1.0 },
selected: self.selected,
ring: 1.0,
volume: self.volume.value(t),
hover: self.hover.each_ref().map(|tr| tr.value(t)),
press: self.pressed.each_ref().map(|tr| tr.value(t)),
}
}
/// Builds the frame with the same scene builders as the headless demos, then applies the live knobs.
fn frame(&mut self, ts: &mut TextSystem) -> (Frame, bool) {
let t = self.now();
let p = [self.x.value(t), self.y.value(t)];
let mut f = match self.which {
Which::Flashlight => {
let (mut f, hits) = flashlight_scene(ts, t as f32, p, &self.panel(t), false);
self.hits = hits;
f.4 = vec![self.mode.torch(p)];
if self.machined {
machine(&mut f);
}
if self.mode == Mode::Backlight {
f.5.shafts_over = 0.1;
f.5.ambient = f.5.ambient.map(|a| a.max(0.06));
}
if self.bare {
f.0.clear();
f.1.clear();
f.2.clear();
}
f
}
Which::Chat => chat_scene(ts, t as f32, p),
};
if let Some(l) = f.4.first_mut() {
l.pos[3] *= self.radius;
l.extra[3] *= self.radius.sqrt();
if self.rays {
l.extra[0] = 1.5;
}
}
if self.rays && self.mode != Mode::Backlight {
f.5.shafts_over = f.5.shafts_over.max(0.12);
}
// The mode caption shows for a moment after L, then fades.
let since = t - self.mode_at;
let alpha = (1.0 - ((since - 1.2) / 0.4).clamp(0.0, 1.0)) as f32;
if self.which == Which::Flashlight && alpha > 0.0 {
caption(ts, &mut f, 24.0, 772.0, self.mode.label(), oklcha(1.0, 0.0, 0.0, alpha));
}
(f, self.animating(t) || since < 1.7)
}
}
/// Moves a frame by whole device px (centres the 1280×800 pt canvas in the window).
fn translate(f: &mut Frame, o: [f32; 2]) {
if o == [0.0, 0.0] {
return;
}
for i in f.1.iter_mut().chain(f.2.iter_mut()) {
i.rect[0] += o[0];
i.rect[1] += o[1];
}
for p in f.0.iter_mut() {
p.rect[0] += o[0];
p.rect[1] += o[1];
}
for l in f.4.iter_mut() {
l.pos[0] += o[0];
l.pos[1] += o[1];
}
}
// ---------------------------------------------------------------- window
struct Live {
window: Arc<Window>,
surface: wgpu::Surface<'static>,
config: wgpu::SurfaceConfiguration,
gfx: Gfx,
}
struct App {
state: State,
live: Option<Live>,
}
impl Live {
/// Device px per point: the window's scale at the native 1280×800 pt size, fitted when resized.
fn k(&self) -> f32 {
(self.config.width as f32 / PT_W).min(self.config.height as f32 / PT_H).max(0.1)
}
/// Device-px offset of the fitted canvas, centred in the window (whole px so text stays crisp).
fn offset(&self) -> [f32; 2] {
let k = self.k();
[((self.config.width as f32 - PT_W * k) * 0.5).round(), ((self.config.height as f32 - PT_H * k) * 0.5).round()]
}
}
impl ApplicationHandler for App {
fn resumed(&mut self, event_loop: &ActiveEventLoop) {
if self.live.is_some() {
return;
}
let attrs = Window::default_attributes()
.with_title("rune-light")
.with_inner_size(LogicalSize::new(PT_W as f64, PT_H as f64))
.with_min_inner_size(LogicalSize::new(480.0, 300.0));
let window = Arc::new(event_loop.create_window(attrs).expect("window"));
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
let surface = instance.create_surface(window.clone()).expect("surface");
let (adapter, device, queue) = request_device(&instance, Some(&surface));
let phys = window.inner_size();
let mut config = surface.get_default_config(&adapter, phys.width.max(1), phys.height.max(1)).expect("surface config");
let caps = surface.get_capabilities(&adapter);
config.format = caps.formats.iter().copied().find(|f| f.is_srgb()).unwrap_or(config.format);
config.present_mode = wgpu::PresentMode::AutoVsync;
config.desired_maximum_frame_latency = 2;
surface.configure(&device, &config);
let gfx = Gfx::new(device, queue, (config.width, config.height), config.format);
window.request_redraw();
self.live = Some(Live { window, surface, config, gfx });
}
fn window_event(&mut self, event_loop: &ActiveEventLoop, _id: WindowId, event: WindowEvent) {
let Some(l) = self.live.as_mut() else { return };
let st = &mut self.state;
match event {
WindowEvent::CloseRequested => event_loop.exit(),
WindowEvent::Resized(size) => {
l.config.width = size.width.max(1);
l.config.height = size.height.max(1);
l.surface.configure(&l.gfx.device, &l.config);
l.window.request_redraw();
}
WindowEvent::ScaleFactorChanged { .. } | WindowEvent::Occluded(false) => l.window.request_redraw(),
WindowEvent::CursorMoved { position, .. } => {
// winit reports physical px from the content view's top-left; undo the centring, then px → pt.
let (k, o) = (l.k(), l.offset());
st.pointer_move([(position.x as f32 - o[0]) / k, (position.y as f32 - o[1]) / k]);
l.window.request_redraw();
}
WindowEvent::MouseInput { state, button: MouseButton::Left, .. } => {
st.button(state == ElementState::Pressed);
l.window.request_redraw();
}
WindowEvent::MouseWheel { delta, .. } => {
let steps = match delta {
MouseScrollDelta::LineDelta(_, y) => y,
MouseScrollDelta::PixelDelta(p) => p.y as f32 / 20.0,
};
st.radius = (st.radius * 1.12f32.powf(steps)).clamp(0.1, 10.0);
l.window.request_redraw();
}
WindowEvent::KeyboardInput { event, .. } if event.state == ElementState::Pressed => {
match event.logical_key.as_ref() {
Key::Named(NamedKey::Escape) => event_loop.exit(),
Key::Character("1") => st.switch(Which::Flashlight),
Key::Character("2") => st.switch(Which::Chat),
Key::Character("d") | Key::Character("D") => st.direct = !st.direct,
Key::Character("g") | Key::Character("G") => st.rays = !st.rays,
Key::Character("r") | Key::Character("R") => st.radius = 1.0,
Key::Character("l") | Key::Character("L") => {
st.mode = st.mode.next();
st.mode_at = st.now();
}
Key::Character("m") | Key::Character("M") => st.machined = !st.machined,
_ => {}
}
l.window.request_redraw();
}
WindowEvent::RedrawRequested => {
l.gfx.resize((l.config.width, l.config.height));
set_scale(l.k());
let mut status = l.surface.get_current_texture();
if matches!(status, wgpu::CurrentSurfaceTexture::Outdated | wgpu::CurrentSurfaceTexture::Lost) {
l.surface.configure(&l.gfx.device, &l.config);
status = l.surface.get_current_texture();
}
let surface_tex = match status {
wgpu::CurrentSurfaceTexture::Success(f) | wgpu::CurrentSurfaceTexture::Suboptimal(f) => f,
// Uncovering the window redraws it (below). Redrawing now would spin a core.
wgpu::CurrentSurfaceTexture::Occluded => return,
// A timeout already waited for a drawable; anything else needs a new event.
wgpu::CurrentSurfaceTexture::Timeout => {
l.window.request_redraw();
return;
}
_ => return,
};
let view = surface_tex.texture.create_view(&Default::default());
let (mut frame, moving) = st.frame(&mut l.gfx.ts);
translate(&mut frame, l.offset());
l.gfx.render(frame, &view);
l.window.pre_present_notify();
l.gfx.queue.present(surface_tex);
if moving {
l.window.request_redraw();
}
}
_ => {}
}
}
}
// ---------------------------------------------------------------- headless snapshot
fn snap(path: &str, which: Which, at: Option<[f32; 2]>, rays: bool, click: Option<bool>, after: f64, opts: (Mode, bool, bool)) {
let (w, h) = (2560u32, 1600u32);
let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle());
let (_, device, queue) = request_device(&instance, None);
let format = wgpu::TextureFormat::Rgba8Unorm;
let mut gfx = Gfx::new(device, queue, (w, h), format);
set_scale(2.0);
let mut st = State::new(which);
st.fake = Some(0.0);
// One throwaway frame so the panel's hit regions exist before any simulated input.
let _ = st.frame(&mut gfx.ts);
if let Some(p) = at {
st.pointer_move(p);
if which == Which::Chat {
st.jump(p);
}
if let Some(release) = click {
st.button(true);
if release {
st.button(false);
}
}
}
st.rays = rays;
(st.mode, st.machined, st.bare) = opts;
st.fake = Some(after);
let out = gfx.device.create_texture(&wgpu::TextureDescriptor {
label: Some("snap"),
size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
});
let (frame, _) = st.frame(&mut gfx.ts);
gfx.render(frame, &out.create_view(&Default::default()));
let buf = gfx.device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: (w * 4 * h) as u64,
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
});
let mut enc = gfx.device.create_command_encoder(&Default::default());
enc.copy_texture_to_buffer(
wgpu::TexelCopyTextureInfo { texture: &out, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
wgpu::TexelCopyBufferInfo { buffer: &buf, layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(w * 4), rows_per_image: Some(h) } },
wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
);
gfx.queue.submit([enc.finish()]);
let slice = buf.slice(..);
slice.map_async(wgpu::MapMode::Read, |_| {});
gfx.device.poll(wgpu::PollType::wait_indefinitely()).expect("poll");
let px = slice.get_mapped_range().expect("range").to_vec();
rune::render::write_png(std::path::Path::new(path), w, h, &px).unwrap();
eprintln!("wrote {path}");
}
fn main() {
let args: Vec<String> = std::env::args().collect();
let arg = |name: &str| args.iter().position(|a| a == name).and_then(|i| args.get(i + 1)).cloned();
let which = if arg("--scene").as_deref() == Some("chat") { Which::Chat } else { Which::Flashlight };
if let Some(path) = arg("--snap") {
let at = arg("--at").and_then(|s| {
let (x, y) = s.split_once(',')?;
Some([x.parse().ok()?, y.parse().ok()?])
});
let flag = |f: &str| args.iter().any(|a| a == f);
let click = if flag("--click") { Some(true) } else if flag("--down") { Some(false) } else { None };
let after = arg("--after").and_then(|s| s.parse().ok()).unwrap_or(1.0);
let mode = match arg("--mode").as_deref() {
Some("overhead") => Mode::Overhead,
Some("backlight") => Mode::Backlight,
_ => Mode::Behind,
};
snap(&path, which, at, flag("--rays"), click, after, (mode, !flag("--soft"), flag("--bare")));
return;
}
let event_loop = EventLoop::new().expect("event loop");
event_loop.set_control_flow(ControlFlow::Wait);
let mut app = App { state: State::new(which), live: None };
event_loop.run_app(&mut app).expect("run");
}
+495
View File
@@ -0,0 +1,495 @@
//! One frame of the reel: glow and glass settings over time, subframes and the bench overlay.
use super::*;
/// Captions and labels drawn in screen space over everything.
pub(super) struct Overlay {
pub(super) items: Vec<(f32, f32, String, f32, f32, Color)>,
pub(super) rects: Vec<Instance>,
}
impl Overlay {
pub(super) fn text(&mut self, x: f32, y: f32, s: &str, size: f32, weight: f32, c: Color) {
self.items.push((x, y, s.to_string(), size, weight, c));
}
}
#[derive(Default, Clone, Copy)]
pub(super) struct Bench {
pub(super) timings: Option<Timings>,
pub(super) glass_ms: f64,
}
pub(super) struct BenchNumbers {
pub(super) gpu: String,
pub(super) gi: f64,
pub(super) field: f64,
pub(super) scene: f64,
pub(super) cascades: [f64; 5],
pub(super) fluence: f64,
pub(super) glass: f64,
pub(super) frame: f64,
}
pub(super) fn load_bench(out: &Path) -> BenchNumbers {
let mut b = BenchNumbers { gpu: "M5 Max".into(), gi: 2.3, field: 0.07, scene: 0.05, cascades: [0.4; 5], fluence: 0.01, glass: 0.5, frame: 4.0 };
if let Ok(s) = std::fs::read_to_string(out.join("bench.json")) {
let num = |k: &str| -> Option<f64> {
let i = s.find(&format!("\"{k}\""))?;
let rest = &s[i + k.len() + 3..];
let rest = rest.trim_start_matches([':', ' ']);
let end = rest.find([',', '}', ']', '\n']).unwrap_or(rest.len());
rest[..end].trim().parse().ok()
};
b.gi = num("gi").unwrap_or(b.gi);
b.field = num("field").unwrap_or(b.field);
b.scene = num("gi_scene").unwrap_or(b.scene);
b.fluence = num("fluence").unwrap_or(b.fluence);
b.glass = num("glass").unwrap_or(b.glass);
b.frame = num("frame").unwrap_or(b.frame);
for n in 0..5 {
b.cascades[n] = num(&format!("c{n}")).unwrap_or(b.cascades[n]);
}
if let Some(i) = s.find("\"gpu\": \"") {
let rest = &s[i + 8..];
if let Some(e) = rest.find('"') {
b.gpu = rest[..e].to_string();
}
}
}
b
}
pub(super) struct Reel {
pub(super) bench: BenchNumbers,
pub(super) hp: [[f32; 2]; 2],
}
pub(super) fn glow_settings(t: f32) -> Settings {
Settings {
ambient: [0.2, 0.205, 0.235],
exposure: 1.0,
gi: Some(Gi { strength: 1.15, air: 0.10, bounce: 0.0, absorption: 0.22, emission: 0.9 }),
text: TextPolicy { floor: 0.84, ceiling: 1.3, lit: 1.0, specular: 0.1 },
albedo_floor: 0.035,
contact_ao: 0.35,
rim: 0.5,
background_gloss: 0.35,
time: t,
..Default::default()
}
}
/// Glass shape and look at time t (None when off screen).
pub(super) fn glass_at(t: f32) -> Option<Glass> {
if !(T_GLASS - 0.1..T_ARC + 0.4).contains(&t) {
return None;
}
let x = keys(-520.0, &[(T_GLASS, 300.0, sp(1.3, 0.08)), (T_GLASS + 3.4, 330.0, sp(1.0, 0.0)), (T_ARC - 1.3, 1500.0, sp(1.4, 0.0))]).at(t);
let y = keys(300.0, &[(T_GLASS + 3.4, 360.0, sp(1.2, 0.0))]).at(t);
let presence = rise(t, T_GLASS, 0.9);
let (w, h, r) = (380.0, 240.0, 56.0);
let a = dpx(x, y, w, h);
// A drop of glass buds off the card toward the send button and is pulled back.
let bud = window(t, T_GLASS + 1.7, T_GLASS + 3.9, 0.9);
let bx = x + w - 40.0 + bud * 210.0;
let by = y + h - 50.0 + bud * 110.0;
let br = 46.0 + 14.0 * bud;
let b = dpx(bx, by, br * 2.0, br * 2.0);
let frost = 0.85 * window(t, T_GLASS + 4.3, T_GLASS + 6.1, 0.7);
let k = UI_SCALE * S;
Some(
Glass::rounded(a[0], a[1], a[2], a[3], r * k)
.thickness(34.0 * k)
.bevel(24.0 * k)
.gap(12.0 * k)
.dome(10.0 * k)
.ior(1.5)
.dispersion(0.045)
.frost(frost)
.presence(presence)
.rim_glow(0.45)
.union(b, br * k, 60.0 * k, 0.0),
)
}
/// Sub-frames for the shutter: enough that the fastest-moving element steps at most ~2 px between them.
fn subframes(t: f32) -> u32 {
let h = 1.0 / 480.0;
let toast = |t: f32| state(t).toast_x * UI_SCALE * S;
let gx = |t: f32| glass_at(t).map_or(0.0, |g| g.a[0] + g.a[1] + g.b[0] + g.b[1]);
let v = ((toast(t + h) - toast(t - h)).abs()).max((gx(t + h) - gx(t - h)).abs()) / (2.0 * h);
let travel = v * 0.5 / FPS as f32;
((travel / 2.0).ceil() as u32).clamp(1, 24)
}
impl Reel {
/// One frame: the lit image (shutter-integrated while things move fast), the breakdown, bloom and captions.
pub(super) fn frame(&self, ctx: &mut Ctx, t: f32, bench: bool) -> (wgpu::TextureView, Bench) {
let n = if bench { 1 } else { subframes(t) };
let (mut frame_tex, mut frame_view, b) = if n <= 1 {
self.image(ctx, t, bench)
} else {
// 180° shutter: n sub-frames across [t − 1/240, t + 1/240], weighted by a raised cosine so trails have soft
// ends (as in rune-fx's motion blur).
let shutter = 0.5 / FPS as f32;
let ws: Vec<f32> = (0..n).map(|k| 0.5 - 0.5 * (std::f32::consts::TAU * (k as f32 + 0.5) / n as f32).cos()).collect();
let wsum: f32 = ws.iter().sum();
let mut last = Bench::default();
for k in 0..n {
let tk = t + shutter * ((k as f32 + 0.5) / n as f32 - 0.5);
let (_, view, b) = self.image(ctx, tk, false);
last = b;
let mut vps = [VP::default(); 1];
vps[0].a = [ws[k as usize] / wsum, 0.0, 0.0, 0.0];
ctx.queue.write_buffer(&ctx.viz.vp, (60 * std::mem::size_of::<VP>()) as u64, bytemuck::cast_slice(&vps));
let bg = ctx.viz_bg(0, Some(&view));
let mut enc = ctx.device.create_command_encoder(&Default::default());
{
let mut pass = Ctx::pass(&mut enc, &ctx.accum.view, if k == 0 { Some([0.0; 4]) } else { None });
pass.set_pipeline(&ctx.viz.accum);
pass.set_bind_group(0, &bg, &[]);
pass.draw(0..3, 60..61);
}
ctx.queue.submit([enc.finish()]);
}
(ctx.accum.tex.clone(), ctx.accum.view.clone(), last)
};
// Breakdown: the 2.5D stack of real buffers.
let mut ov = Overlay { items: Vec::new(), rects: Vec::new() };
if (T_TILT..T_UNTILT + 1.4).contains(&t) {
frame_view = self.breakdown(ctx, t, &frame_tex, &mut ov);
frame_tex = ctx.stack.tex.clone();
}
let _ = frame_tex;
ctx.bloom(&frame_view);
self.captions(t, &mut ov);
// Overlay text.
let mut insts = ov.rects.clone();
for (x, y, s, size, weight, c) in &ov.items {
let style = TextStyle::new(*size, *weight);
let mut quads = Vec::new();
ctx.ts.glyphs(s, style, S, [(x * S).round(), (y * S).round()], &mut quads);
for q in quads {
insts.push(Instance {
rect: q.rect,
radii: [0.0; 4],
fill: c.premul(1.0),
border: [0.0; 4],
params: [0.0, KIND_GLYPH, 0.0, 1.0],
uv: [q.uv[0], q.uv[1], 0.0, 0.0],
clip: NO_CLIP,
fade: [0; 4],
});
}
}
ctx.draw_rune(&insts, &ctx.overlay.view.clone(), [0.0; 4]);
(frame_view, b)
}
/// The lit UI with effects and glass at exactly time t.
#[allow(clippy::too_many_lines)]
pub(super) fn image(&self, ctx: &mut Ctx, t: f32, bench: bool) -> (wgpu::Texture, wgpu::TextureView, Bench) {
let st = state(t);
let built = build_ui(&mut ctx.ts, &st);
let bgc = oklch(BG.0, BG.1, BG.2);
ctx.draw_rune(&built.base, &ctx.base.view.clone(), [bgc.r, bgc.g, bgc.b, 1.0]);
ctx.draw_rune(&built.text, &ctx.text.view.clone(), [0.0; 4]);
// Effects: the electric border on the danger button. Its light is rendered once into the emission texture
// (which the GI reads) and again over the lit frame.
let mut fx_layers: Vec<FxLayer> = Vec::new();
if st.arc > 0.0 {
let b = dpt(924.0 + 20.0, 424.0, 150.0, 36.0);
let e = ElectricParams {
style: ElectricStyle::Border,
color: rgb(0xff5a4a),
core: rgb(0xfff1e8),
cool: rgb(0x9b4dff),
amplitude: 3.2,
frequency: 2.6,
speed: 3.0,
glow: 5.5,
forks: 0.5,
flicker: 0.35,
intensity: 1.15 * st.arc,
gap: 3.0,
..ElectricParams::default()
};
fx_layers.push(Fx::electric(e).on(Shape::rounded(b[0], b[1], b[2], b[3], 10.0 * UI_SCALE)).seed(7).at(t).over());
}
let click = 3.3;
let shock = (click..click + 1.2).contains(&t);
let mut ts_glass = 0.0;
let mut enc = ctx.device.create_command_encoder(&Default::default());
if !fx_layers.is_empty() {
ctx.fx.prepare(&ctx.device, &ctx.queue, &FxFrame { viewport: [W, H], scale: S, layers: &fx_layers, backdrop: None, sources: &[] });
let mut pass = Ctx::pass(&mut enc, &ctx.emission.view, Some([0.0; 4]));
ctx.fx.draw_all(&mut pass, &fx_layers, None);
}
{
let scene = Scene {
prims: &built.prims,
lights: &[],
settings: glow_settings(t),
emission: (!fx_layers.is_empty()).then_some(&ctx.emission.view),
};
ctx.light.inspect = (T_TILT - 0.1..T_UNTILT + 1.5).contains(&t) || bench;
ctx.light.render(&ctx.device, &ctx.queue, &mut enc, &scene, &ctx.base.view, &ctx.text.view, &ctx.lit.view);
}
ctx.queue.submit([enc.finish()]);
let timings = if bench { ctx.light.read_timings(&ctx.device) } else { None };
let mut enc = ctx.device.create_command_encoder(&Default::default());
if !fx_layers.is_empty() {
let mut pass = Ctx::pass(&mut enc, &ctx.lit.view, None);
ctx.fx.draw_all(&mut pass, &fx_layers, None);
}
if shock {
// The click: a shockwave ripple out of the send button.
let sb = dpt(272.0 + 628.0 - 58.0, 712.0, 38.0, 38.0);
let at = [sb[0] + sb[2] * 0.5, sb[1] + sb[3] * 0.5];
let mut d = DistortParams::shockwave(at, click);
if let DistortParams::Shockwave { reach, width, amount, chroma, duration, .. } = &mut d {
*reach = 260.0;
*width = 16.0;
*amount = 9.0;
*chroma = 0.35;
*duration = 1.1;
}
let layers = [Fx::distort(d).on(Shape::rounded(at[0] - 280.0, at[1] - 280.0, 560.0, 560.0, 0.0)).at(t)];
ctx.copy(&mut enc, &ctx.lit.tex, &ctx.backdrop.tex);
ctx.queue.submit([enc.finish()]);
enc = ctx.device.create_command_encoder(&Default::default());
ctx.fx.prepare(&ctx.device, &ctx.queue, &FxFrame { viewport: [W, H], scale: S, layers: &layers, backdrop: Some(&ctx.backdrop.view), sources: &[] });
let mut pass = Ctx::pass(&mut enc, &ctx.lit.view, None);
ctx.fx.draw_all(&mut pass, &layers, None);
}
let mut frame_view = ctx.lit.view.clone();
let mut frame_tex = ctx.lit.tex.clone();
if let Some(g) = glass_at(t).or(if bench { glass_at(T_GLASS + 1.0) } else { None }) {
let lights: Vec<GlassLight> = built.prims.iter().filter_map(|p| GlassLight::from_emitter(p, 18.0 * S, 0.9)).collect();
ctx.marker(&mut enc, None, Some(0));
let settings = GlassSettings::default();
ctx.glass.render(&ctx.device, &ctx.queue, &mut enc, &[g], &lights, settings, &ctx.lit.view, ctx.light.inspect().fluence, &ctx.glassed.view);
ctx.marker(&mut enc, Some(1), None);
if let Some((qs, resolve, read)) = &ctx.query {
enc.resolve_query_set(qs, 0..2, resolve, 0);
enc.copy_buffer_to_buffer(resolve, 0, read, 0, 16);
}
frame_view = ctx.glassed.view.clone();
frame_tex = ctx.glassed.tex.clone();
ts_glass = 1.0;
}
ctx.queue.submit([enc.finish()]);
let mut glass_ms = 0.0;
if bench && ts_glass > 0.0 {
if let Some((_, _, read)) = &ctx.query {
let s = read.slice(..);
s.map_async(wgpu::MapMode::Read, |_| {});
ctx.device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
let ticks: Vec<u64> = bytemuck::cast_slice(&s.get_mapped_range().unwrap()).to_vec();
read.unmap();
glass_ms = ticks[1].saturating_sub(ticks[0]) as f64 * ctx.period as f64 / 1e6;
}
}
(frame_tex, frame_view, Bench { timings, glass_ms })
}
pub(super) fn captions(&self, t: f32, ov: &mut Overlay) {
let b = &self.bench;
let caps: Vec<(f32, f32, String, String)> = vec![
(1.0, T_TILT - 0.3, "Lit only by its own glowing elements".into(), "2D radiance cascades · every emitter lights its neighbours, with soft coloured shadow".into()),
(T_TILT + 0.2, T_INPUTS - 0.1, "How it's lit".into(), "rune-light's real GI buffers, frame by frame".into()),
(
T_INPUTS,
T_CASCADES - 0.1,
"① The scene as a distance field".into(),
format!("Rune draws analytic rounded rects, so the SDF is exact (no jump flood) · ½ res · {:.2} ms", b.field),
),
(
T_CASCADES,
T_MERGE - 0.1,
"② Five cascades of probes".into(),
"each level: probes 2× sparser, rays 4× longer, 4× the directions · same memory per level".into(),
),
(
T_MERGE,
T_FLUENCE - 0.1,
"③ Merge, top cascade down".into(),
"each ray continues into the four nearest upper probes (Sannikov's bilinear fix: no leaks between probes)".into(),
),
(T_FLUENCE, T_UNTILT - 0.1, "④ Fluence".into(), "cascade 0's directions averaged: the light arriving at every point".into()),
(
T_UNTILT,
T_GLASS - 0.2,
"⑤ Back onto the UI".into(),
format!("whole GI pass {:.1} ms on {} at 2560×1600 · cost fixed by the grid, not the number of lights", b.gi, b.gpu),
),
(
T_GLASS + 0.3,
T_ARC - 0.4,
"Thick glass, refracted per pixel".into(),
format!("Snell n = 1.50 · exact Fresnel · 8-wavelength dispersion · total internal reflection at the bevel · frost · {:.2} ms", b.glass),
),
(T_ARC + 0.2, T_END - 0.3, "Effects are light too".into(), "the electric arc is emission: it enters the cascades and lights the cards around it".into()),
];
for (a, z, title, sub) in caps {
let k = window(t, a, z, 0.35);
if k <= 0.01 {
continue;
}
let y = 754.0 + (1.0 - k) * 6.0;
let x = UI_O[0] + 4.0;
ov.text(x, y, &title, 15.0, 600.0, oklcha(0.95, 0.005, 268.0, k));
ov.text(x, y + 22.0, &sub, 12.5, 400.0, oklcha(0.68, 0.012, 268.0, k));
}
let k = rise(t, T_END + 0.3, 0.8);
if k > 0.01 {
let x = 640.0 - 150.0;
ov.text(x, 760.0 + (1.0 - k) * 6.0, "Rune · radiance cascades · 120 Hz", 16.0, 600.0, oklcha(0.95, 0.005, 268.0, k));
}
}
/// The breakdown: renders each real buffer into a layer texture and composes the 2.5D stack.
pub(super) fn breakdown(&self, ctx: &mut Ctx, t: f32, lit: &wgpu::Texture, ov: &mut Overlay) -> wgpu::TextureView {
let ins = ctx.light.inspect();
let gs = ins.gi_size;
let texel = ins.texel;
let tilt = rise(t, T_TILT, 1.3) * (1.0 - rise(t, T_UNTILT, 1.2));
let cam = Cam { pitch: 0.84 * tilt, yaw: -0.28 * tilt, scale: lerp(1.0, 0.6, tilt), ty: -20.0 * tilt, tx: -190.0 * tilt };
// Per layer: (texture slot, z, alpha, kind)
let inputs = window(t, T_INPUTS - 0.2, T_CASCADES + 0.3, 0.6);
let ui_lift = rise(t, T_INPUTS - 0.3, 0.9) * (1.0 - rise(t, T_FLUENCE + 0.6, 1.0));
let ui_alpha = 1.0 - 0.9 * rise(t, T_INPUTS - 0.3, 0.7) + 0.9 * rise(t, T_UNTILT - 0.2, 0.8);
let merge_k = |n: usize| {
// C4 merges first; each level collapses into the one below and switches to its merged radiance.
let tn = T_MERGE + 0.45 * (CASCADES as usize - 1 - n) as f32;
rise(t, tn, 0.5)
};
let gu = GU {
size: [W as f32, H as f32, gs.0 as f32, gs.1 as f32],
gi: [texel, t, 2.0, 0.0],
hp: [[self.hp[0][0], self.hp[0][1], self.hp[1][0], self.hp[1][1]], [0.0; 4]],
};
ctx.queue.write_buffer(&ctx.viz.g, 0, bytemuck::bytes_of(&gu));
let mut vps = vec![VP::default(); MAX_VP];
let mut enc = ctx.device.create_command_encoder(&Default::default());
ctx.means(&mut enc);
// Layer content passes: slot 0 field, 1 scene, 2..7 cascades 0..4, 7 fluence, 8 lit UI.
let expo = [0.9, 1.6, 2.6, 4.0, 6.0];
let mut content: Vec<(usize, &wgpu::RenderPipeline, usize)> = vec![(0, &ctx.viz.field, 0), (1, &ctx.viz.scene, 0)];
for n in 0..CASCADES as usize {
let own_to_merged = if n == CASCADES as usize - 1 { 1.0 } else { merge_k(n + 1) };
let grow = rise(t, T_CASCADES + 0.25 + 0.5 * n as f32, 0.8);
vps[2 + n] = VP {
a: [n as f32, own_to_merged, expo[n] * lerp(1.0, 0.6, own_to_merged), 0.0],
b: [1.0, 1.0, 1.0, 1.0],
c: [grow, 1.0, 0.0, 3.2],
q: [[0.0; 4]; 4],
};
content.push((2 + n, &ctx.viz.cascade, n));
}
vps[1].a = [0.0, 0.0, 0.9, 0.0];
vps[7].a = [0.0, 0.0, 1.5, 0.0];
content.push((7, &ctx.viz.fluence, 0));
drop(ins);
for (slot, pipe, level) in &content {
let bg = ctx.viz_bg(*level, None);
let mut pass = Ctx::pass(&mut enc, &ctx.layers[*slot].mips[0], Some([0.0, 0.0, 0.0, 1.0]));
pass.set_pipeline(pipe);
pass.set_bind_group(0, &bg, &[]);
pass.draw(0..3, *slot as u32..*slot as u32 + 1);
}
ctx.copy(&mut enc, lit, &ctx.layers[8].t.tex);
ctx.queue.submit([enc.finish()]);
let mut enc = ctx.device.create_command_encoder(&Default::default());
for slot in 0..9 {
ctx.build_mips(&mut enc, slot);
}
// Stack layout: (slot, z, alpha, label)
let mut stack: Vec<(usize, f32, f32, String)> = Vec::new();
let sep = 210.0;
// Inputs: field and media sit below the UI while it lifts away.
stack.push((0, -sep * 1.0 * inputs - 80.0 * (1.0 - inputs), inputs, "Distance field · ½ res, exact".into()));
stack.push((1, 0.0, inputs, format!("Emitters + cards · {}×{} texels · sub-texel coverage", gs.0, gs.1)));
// Cascades rise in from below, C0 lowest; then collapse top down.
for n in 0..CASCADES as usize {
let a_in = rise(t, T_CASCADES + 0.5 * n as f32, 0.7);
let a_out = rise(t, T_FLUENCE + 0.2, 0.6);
let base_z = (n as f32 - 2.0) * sep * 0.95;
// Collapse: once merged into level n−1, sink onto it.
let collapsed = if n == 0 { 0.0 } else { merge_k(n) };
let below = (n as f32 - 3.0) * sep * 0.95;
let z = lerp(base_z - 300.0 * (1.0 - a_in), below.min(base_z), collapsed);
// Focus: once the next level arrives, this one recedes until the merge brings it back.
let next_in = if n + 1 < CASCADES as usize { rise(t, T_CASCADES + 0.5 * (n + 1) as f32, 0.6) } else { 0.0 };
let refocus = rise(t, T_MERGE - 0.2, 0.6);
let focus = 1.0 - 0.6 * next_in * (1.0 - refocus);
let alpha = a_in * (1.0 - a_out) * focus * (1.0 - 0.85 * if n > 0 { merge_k(n) } else { 0.0 });
let p = (gs.0 >> n, gs.1 >> n);
let t0 = (4f32.powi(n as i32) - 1.0) / 3.0 * texel;
let t1 = (4f32.powi(n as i32 + 1) - 1.0) / 3.0 * texel;
let ms = self.bench.cascades[n];
stack.push((
2 + n,
z,
alpha,
format!("C{n} · {}×{} probes · {} rays · {:.0}–{:.0} px · {:.2} ms", p.0, p.1, 4 << (2 * n), t0, t1, ms),
));
}
let fl = window(t, T_FLUENCE, T_UNTILT + 0.5, 0.6);
stack.push((7, -sep * 1.9 + sep * 1.9 * rise(t, T_FLUENCE, 0.8), fl, format!("Fluence · {:.2} ms", self.bench.fluence)));
stack.push((8, sep * 3.2 * ui_lift, ui_alpha.clamp(0.0, 1.0), String::new()));
// Back to front: sort by projected depth of the layer's centre.
let mut order: Vec<usize> = (0..stack.len()).filter(|&i| stack[i].2 > 0.003).collect();
order.sort_by(|&a, &b| {
let za = project(&cam, W as f32 * 0.5, H as f32 * 0.5, stack[a].1)[3];
let zb = project(&cam, W as f32 * 0.5, H as f32 * 0.5, stack[b].1)[3];
zb.total_cmp(&za)
});
let first_vp = 16;
for (k, &i) in order.iter().enumerate() {
let (_, z, alpha, _) = &stack[i];
let q = [project(&cam, 0.0, 0.0, *z), project(&cam, W as f32, 0.0, *z), project(&cam, 0.0, H as f32, *z), project(&cam, W as f32, H as f32, *z)];
vps[first_vp + k] = VP { a: [0.0; 4], b: [0.0; 4], c: [0.0, *alpha, 0.55 * tilt, 0.0], q };
}
ctx.queue.write_buffer(&ctx.viz.vp, 0, bytemuck::cast_slice(&vps));
let bgc = oklch(BG.0, BG.1, BG.2);
{
let bgs: Vec<wgpu::BindGroup> = order.iter().map(|&i| ctx.viz_bg(0, Some(&ctx.layers[stack[i].0].t.view))).collect();
let mut pass = Ctx::pass(&mut enc, &ctx.stack.view, Some([bgc.r, bgc.g, bgc.b, 1.0]));
pass.set_pipeline(&ctx.viz.layer);
for (k, bg) in bgs.iter().enumerate() {
pass.set_bind_group(0, bg, &[]);
pass.draw(0..4, (first_vp + k) as u32..(first_vp + k) as u32 + 1);
}
}
ctx.queue.submit([enc.finish()]);
// Labels beside each layer's right edge, pushed apart so they never overlap.
let mut labels: Vec<(f32, f32, f32, &str)> = Vec::new();
for &i in &order {
let (_, z, alpha, label) = &stack[i];
if label.is_empty() || *alpha < 0.05 || tilt < 0.3 {
continue;
}
let p = to_screen(project(&cam, W as f32, H as f32 * 0.5, *z));
let a = alpha.min(1.0) * ((tilt - 0.3) / 0.4).clamp(0.0, 1.0);
labels.push((p[0] / S + 44.0, p[1] / S - 8.0, a, label.as_str()));
}
labels.sort_by(|a, b| a.1.total_cmp(&b.1));
for k in 1..labels.len() {
let min = labels[k - 1].1 + 22.0;
if labels[k].1 < min {
labels[k].1 = min;
}
}
for (x, y, a, l) in labels {
ov.text(x, y, l, 12.0, 500.0, oklcha(0.9, 0.01, 268.0, a));
}
ctx.stack.view.clone()
}
}
+696
View File
@@ -0,0 +1,696 @@
//! The GPU context: textures, pipelines, bloom and the Y'CbCr encode.
use super::*;
pub(super) struct Tex {
pub(super) tex: wgpu::Texture,
pub(super) view: wgpu::TextureView,
}
fn tex(device: &wgpu::Device, label: &str, w: u32, h: u32, mips: u32, format: wgpu::TextureFormat, usage: wgpu::TextureUsages) -> Tex {
let tex = device.create_texture(&wgpu::TextureDescriptor {
label: Some(label),
size: wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
mip_level_count: mips,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage,
view_formats: &[],
});
let view = tex.create_view(&Default::default());
Tex { tex, view }
}
pub(super) struct Layer {
pub(super) t: Tex,
pub(super) mips: Vec<wgpu::TextureView>,
}
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
pub(super) struct GU {
pub(super) size: [f32; 4],
pub(super) gi: [f32; 4],
pub(super) hp: [[f32; 4]; 2],
}
#[repr(C)]
#[derive(Clone, Copy, Default, bytemuck::Pod, bytemuck::Zeroable)]
pub(super) struct VP {
pub(super) a: [f32; 4],
pub(super) b: [f32; 4],
pub(super) c: [f32; 4],
pub(super) q: [[f32; 4]; 4],
}
pub(super) const MAX_VP: usize = 64;
pub(super) struct Viz {
pub(super) g: wgpu::Buffer,
pub(super) vp: wgpu::Buffer,
pub(super) bgl: wgpu::BindGroupLayout,
pub(super) field: wgpu::RenderPipeline,
pub(super) scene: wgpu::RenderPipeline,
pub(super) cascade: wgpu::RenderPipeline,
pub(super) fluence: wgpu::RenderPipeline,
pub(super) mip: wgpu::RenderPipeline,
pub(super) layer: wgpu::RenderPipeline,
pub(super) accum: wgpu::RenderPipeline,
pub(super) mean_bgl: wgpu::BindGroupLayout,
pub(super) mean: wgpu::ComputePipeline,
pub(super) mean_u: Vec<wgpu::Buffer>,
pub(super) means_own: Vec<Tex>,
pub(super) means_mrg: Vec<Tex>,
pub(super) lin: wgpu::Sampler,
pub(super) aniso: wgpu::Sampler,
pub(super) dummy: Tex,
}
pub(super) struct Enc {
pub(super) u: wgpu::Buffer,
pub(super) bgl: wgpu::BindGroupLayout,
pub(super) yuv: wgpu::ComputePipeline,
pub(super) rgba: wgpu::ComputePipeline,
pub(super) noise: Tex,
pub(super) y8: wgpu::Buffer,
pub(super) y10: wgpu::Buffer,
pub(super) rgba_buf: wgpu::Buffer,
pub(super) read8: wgpu::Buffer,
pub(super) read10: wgpu::Buffer,
pub(super) read_rgba: wgpu::Buffer,
}
pub(super) struct Ctx {
pub(super) device: wgpu::Device,
pub(super) queue: wgpu::Queue,
pub(super) rune: Renderer,
pub(super) ts: TextSystem,
pub(super) light: LightRenderer,
pub(super) glass: GlassRenderer,
pub(super) fx: FxRenderer,
pub(super) viz: Viz,
pub(super) enc: Enc,
pub(super) base: Tex,
pub(super) text: Tex,
pub(super) emission: Tex,
pub(super) lit: Tex,
pub(super) backdrop: Tex,
pub(super) glassed: Tex,
pub(super) stack: Tex,
pub(super) overlay: Tex,
pub(super) accum: Tex,
pub(super) bloom: Bloom,
pub(super) layers: Vec<Layer>,
pub(super) timestamps: bool,
pub(super) query: Option<(wgpu::QuerySet, wgpu::Buffer, wgpu::Buffer)>,
pub(super) period: f32,
pub(super) noop: wgpu::ComputePipeline,
pub(super) gpu: String,
}
fn bgl_entry(binding: u32, vis: wgpu::ShaderStages, ty: wgpu::BindingType) -> wgpu::BindGroupLayoutEntry {
wgpu::BindGroupLayoutEntry { binding, visibility: vis, ty, count: None }
}
fn ftex() -> wgpu::BindingType {
wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Float { filterable: true }, view_dimension: wgpu::TextureViewDimension::D2, multisampled: false }
}
fn ubuf() -> wgpu::BindingType {
wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None }
}
fn sbuf(read_only: bool) -> wgpu::BindingType {
wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Storage { read_only }, has_dynamic_offset: false, min_binding_size: None }
}
fn bind(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, entries: &[wgpu::BindingResource<'_>]) -> wgpu::BindGroup {
let e: Vec<wgpu::BindGroupEntry> = entries.iter().enumerate().map(|(i, r)| wgpu::BindGroupEntry { binding: i as u32, resource: r.clone() }).collect();
device.create_bind_group(&wgpu::BindGroupDescriptor { label: None, layout, entries: &e })
}
fn tv(v: &wgpu::TextureView) -> wgpu::BindingResource<'_> {
wgpu::BindingResource::TextureView(v)
}
fn wgsl_part(name: &str) -> String {
let src = include_str!("reel.wgsl");
let (viz, rest) = src.split_once("// ---- bloom ----").unwrap();
let (bloom, rest) = rest.split_once("// ---- per-probe mean of a cascade level ----").unwrap();
let (mean, enc) = rest.split_once("// ---- final encode ----").unwrap();
match name {
"viz" => viz.to_string(),
"bloom" => bloom.to_string(),
"mean" => mean.to_string(),
_ => enc.to_string(),
}
}
/// 64×64 blue noise, three independent channels (void and cluster, Ulichney 1993).
fn blue_noise() -> Vec<u8> {
const N: usize = 64;
let sigma = 1.9f32;
let mut kernel = vec![0f32; N * N];
for y in 0..N {
for x in 0..N {
let dx = (x.min(N - x)) as f32;
let dy = (y.min(N - y)) as f32;
kernel[y * N + x] = (-(dx * dx + dy * dy) / (2.0 * sigma * sigma)).exp();
}
}
let mut out = vec![255u8; N * N * 4];
let mut seed = 0x9e3779b9u32;
let mut rnd = || {
seed ^= seed << 13;
seed ^= seed >> 17;
seed ^= seed << 5;
seed
};
for ch in 0..3 {
let mut on = vec![false; N * N];
let mut energy = vec![0f32; N * N];
let toggle = |on: &mut Vec<bool>, energy: &mut Vec<f32>, i: usize, add: bool| {
on[i] = add;
let (ix, iy) = (i % N, i / N);
let s = if add { 1.0 } else { -1.0 };
for y in 0..N {
for x in 0..N {
let kx = (x + N - ix) % N;
let ky = (y + N - iy) % N;
energy[y * N + x] += s * kernel[ky * N + kx];
}
}
};
let ones = N * N / 10;
let mut placed = 0;
while placed < ones {
let i = (rnd() as usize) % (N * N);
if !on[i] {
toggle(&mut on, &mut energy, i, true);
placed += 1;
}
}
let tightest = |on: &Vec<bool>, energy: &Vec<f32>| (0..N * N).filter(|&i| on[i]).max_by(|&a, &b| energy[a].total_cmp(&energy[b])).unwrap();
let voidest = |on: &Vec<bool>, energy: &Vec<f32>| (0..N * N).filter(|&i| !on[i]).min_by(|&a, &b| energy[a].total_cmp(&energy[b])).unwrap();
loop {
let c = tightest(&on, &energy);
toggle(&mut on, &mut energy, c, false);
let v = voidest(&on, &energy);
toggle(&mut on, &mut energy, v, true);
if v == c {
break;
}
}
let mut rank = vec![0usize; N * N];
let (proto_on, proto_e) = (on.clone(), energy.clone());
for r in (0..ones).rev() {
let c = tightest(&on, &energy);
toggle(&mut on, &mut energy, c, false);
rank[c] = r;
}
on = proto_on;
energy = proto_e;
for r in ones..N * N {
let v = voidest(&on, &energy);
toggle(&mut on, &mut energy, v, true);
rank[v] = r;
}
for i in 0..N * N {
out[i * 4 + ch] = ((rank[i] as f32 + 0.5) / (N * N) as f32 * 255.0).round() as u8;
}
}
out
}
impl Ctx {
pub(super) fn new() -> Ctx {
let rune::render::Gpu { adapter, device, queue, .. } = rune::render::Gpu::headless();
let ts_feat = device.features() & wgpu::Features::TIMESTAMP_QUERY;
eprintln!("adapter: {:?}, timestamps: {}", adapter.get_info().name, !ts_feat.is_empty());
use wgpu::TextureUsages as U;
let rt = U::RENDER_ATTACHMENT | U::TEXTURE_BINDING;
let full = |label: &str| tex(&device, label, W, H, 1, F16, rt | U::COPY_SRC | U::COPY_DST);
let base = full("ui base");
let text = full("ui text");
let emission = full("emission");
let lit = full("lit");
let backdrop = full("backdrop");
let glassed = full("glassed");
let stack = full("stack");
let overlay = full("overlay");
let accum = full("accum");
let bloom = Bloom::new(&device);
let layers = (0..10)
.map(|i| {
let t = tex(&device, &format!("layer {i}"), W, H, MIPS, F16, rt | U::COPY_DST);
let mips = (0..MIPS)
.map(|m| t.tex.create_view(&wgpu::TextureViewDescriptor { base_mip_level: m, mip_level_count: Some(1), ..Default::default() }))
.collect();
Layer { t, mips }
})
.collect();
let rune = Renderer::new(&device, F16);
let light = LightRenderer::new(&device, &queue, W, H, F16);
let glass = GlassRenderer::new(&device, W, H, F16);
let fx = FxRenderer::new(&device, F16, FxOptions { dither: false });
let viz = Self::viz(&device, light.inspect().gi_size);
let enc = Self::enc(&device, &queue);
let query = (!ts_feat.is_empty()).then(|| {
let qs = device.create_query_set(&wgpu::QuerySetDescriptor { label: Some("reel ts"), ty: wgpu::QueryType::Timestamp, count: 4 });
let resolve = device.create_buffer(&wgpu::BufferDescriptor { label: None, size: 32, usage: wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false });
let read = device.create_buffer(&wgpu::BufferDescriptor { label: None, size: 32, usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, mapped_at_creation: false });
(qs, resolve, read)
});
let period = queue.get_timestamp_period();
let nm = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: None, source: wgpu::ShaderSource::Wgsl("@compute @workgroup_size(1) fn noop() {}".into()) });
let noop = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("noop"),
layout: None,
module: &nm,
entry_point: Some("noop"),
compilation_options: Default::default(),
cache: None,
});
Ctx {
device,
queue,
rune,
ts: TextSystem::default(),
light,
glass,
fx,
viz,
enc,
base,
text,
emission,
lit,
backdrop,
glassed,
stack,
overlay,
accum,
bloom,
layers,
timestamps: !ts_feat.is_empty(),
query,
period,
noop,
gpu: adapter.get_info().name.trim_start_matches("Apple ").to_string(),
}
}
/// An empty compute pass that writes a timestamp at its start or end (render-pass timestamps aren't ordered on
/// tile GPUs, so render work is timed between two of these).
pub(super) fn marker(&self, enc: &mut wgpu::CommandEncoder, begin: Option<u32>, end: Option<u32>) {
if let Some((qs, _, _)) = &self.query {
let mut p = enc.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("ts marker"),
timestamp_writes: Some(wgpu::ComputePassTimestampWrites { query_set: qs, beginning_of_pass_write_index: begin, end_of_pass_write_index: end }),
});
p.set_pipeline(&self.noop);
p.dispatch_workgroups(1, 1, 1);
}
}
pub(super) fn viz(device: &wgpu::Device, gs: (u32, u32)) -> Viz {
use wgpu::ShaderStages as Ss;
let vf = Ss::VERTEX_FRAGMENT;
let f = Ss::FRAGMENT;
let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("viz"),
entries: &[
bgl_entry(0, vf, ubuf()),
bgl_entry(1, vf, sbuf(true)),
bgl_entry(2, f, ftex()),
bgl_entry(3, f, ftex()),
bgl_entry(4, f, ftex()),
bgl_entry(5, f, ftex()),
bgl_entry(6, f, ftex()),
bgl_entry(7, f, ftex()),
bgl_entry(8, f, ftex()),
bgl_entry(9, f, ftex()),
bgl_entry(10, f, wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering)),
bgl_entry(11, f, ftex()),
bgl_entry(12, f, wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering)),
],
});
let m = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("reel viz"), source: wgpu::ShaderSource::Wgsl(wgsl_part("viz").into()) });
let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[Some(&bgl)], immediate_size: 0 });
let pipe = |vs: &str, fs: &str, blend: Option<wgpu::BlendState>, strip: bool| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(fs),
layout: Some(&pl),
vertex: wgpu::VertexState { module: &m, entry_point: Some(vs), compilation_options: Default::default(), buffers: &[] },
primitive: wgpu::PrimitiveState {
topology: if strip { wgpu::PrimitiveTopology::TriangleStrip } else { wgpu::PrimitiveTopology::TriangleList },
..Default::default()
},
depth_stencil: None,
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &m,
entry_point: Some(fs),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState { format: F16, blend, write_mask: wgpu::ColorWrites::ALL })],
}),
multiview_mask: None,
cache: None,
})
};
let field = pipe("vs_full", "fs_field", None, false);
let scene = pipe("vs_full", "fs_scene", None, false);
let cascade = pipe("vs_full", "fs_cascade", None, false);
let fluence = pipe("vs_full", "fs_fluence", None, false);
let mip = pipe("vs_full", "fs_mip", None, false);
let layer = pipe("vs_layer", "fs_layer", Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING), true);
let add = wgpu::BlendComponent { src_factor: wgpu::BlendFactor::One, dst_factor: wgpu::BlendFactor::One, operation: wgpu::BlendOperation::Add };
let accum = pipe("vs_full", "fs_accum", Some(wgpu::BlendState { color: add, alpha: add }), false);
let mean_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("mean"),
entries: &[
bgl_entry(0, Ss::COMPUTE, ubuf()),
bgl_entry(1, Ss::COMPUTE, ftex()),
bgl_entry(
2,
Ss::COMPUTE,
wgpu::BindingType::StorageTexture { access: wgpu::StorageTextureAccess::WriteOnly, format: F16, view_dimension: wgpu::TextureViewDimension::D2 },
),
],
});
let mm = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("reel mean"), source: wgpu::ShaderSource::Wgsl(wgsl_part("mean").into()) });
let mpl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[Some(&mean_bgl)], immediate_size: 0 });
let mean = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some("mean"),
layout: Some(&mpl),
module: &mm,
entry_point: Some("cs_mean"),
compilation_options: Default::default(),
cache: None,
});
let mean_u = (0..CASCADES)
.map(|n| {
use wgpu::util::DeviceExt;
device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: None, contents: bytemuck::cast_slice(&[n, 0, 0, 0]), usage: wgpu::BufferUsages::UNIFORM })
})
.collect();
use wgpu::TextureUsages as U;
let mk = |n: u32| tex(device, "mean", gs.0 >> n, gs.1 >> n, 1, F16, U::STORAGE_BINDING | U::TEXTURE_BINDING);
let means_own = (0..CASCADES).map(mk).collect();
let means_mrg = (0..CASCADES).map(mk).collect();
let lin = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("viz lin"),
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
..Default::default()
});
let aniso = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("viz aniso"),
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
mipmap_filter: wgpu::MipmapFilterMode::Linear,
anisotropy_clamp: 16,
..Default::default()
});
let g = device.create_buffer(&wgpu::BufferDescriptor { label: Some("viz g"), size: std::mem::size_of::<GU>() as u64, usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST, mapped_at_creation: false });
let vp = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("viz vp"),
size: (MAX_VP * std::mem::size_of::<VP>()) as u64,
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let dummy = tex(device, "dummy", 1, 1, 1, F16, U::TEXTURE_BINDING);
Viz { g, vp, bgl, field, scene, cascade, fluence, mip, layer, accum, mean_bgl, mean, mean_u, means_own, means_mrg, lin, aniso, dummy }
}
pub(super) fn enc(device: &wgpu::Device, queue: &wgpu::Queue) -> Enc {
use wgpu::ShaderStages as Ss;
let c = Ss::COMPUTE;
let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("enc"),
entries: &[
bgl_entry(0, c, ubuf()),
bgl_entry(1, c, ftex()),
bgl_entry(2, c, ftex()),
bgl_entry(3, c, ftex()),
bgl_entry(4, c, sbuf(false)),
bgl_entry(5, c, sbuf(false)),
bgl_entry(6, c, sbuf(false)),
bgl_entry(7, c, ftex()),
bgl_entry(8, c, wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering)),
],
});
let m = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("reel enc"), source: wgpu::ShaderSource::Wgsl(wgsl_part("enc").into()) });
let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[Some(&bgl)], immediate_size: 0 });
let cp = |e: &str| {
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some(e), layout: Some(&pl), module: &m, entry_point: Some(e), compilation_options: Default::default(), cache: None })
};
let yuv = cp("cs_yuv");
let rgba = cp("cs_rgba");
let noise = tex(device, "blue noise", 64, 64, 1, wgpu::TextureFormat::Rgba8Unorm, wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST);
queue.write_texture(
wgpu::TexelCopyTextureInfo { texture: &noise.tex, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
&blue_noise(),
wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(256), rows_per_image: Some(64) },
wgpu::Extent3d { width: 64, height: 64, depth_or_array_layers: 1 },
);
let n = (W * H) as u64;
let buf = |label: &str, size: u64, usage: wgpu::BufferUsages| device.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size, usage, mapped_at_creation: false });
use wgpu::BufferUsages as B;
let y8 = buf("y8", n * 3 / 2, B::STORAGE | B::COPY_SRC);
let y10 = buf("y10", n * 3, B::STORAGE | B::COPY_SRC);
let rgba_buf = buf("rgba", n * 4, B::STORAGE | B::COPY_SRC);
let read8 = buf("read8", n * 3 / 2, B::COPY_DST | B::MAP_READ);
let read10 = buf("read10", n * 3, B::COPY_DST | B::MAP_READ);
let read_rgba = buf("read rgba", n * 4, B::COPY_DST | B::MAP_READ);
let u = buf("enc u", 32, B::UNIFORM | B::COPY_DST);
Enc { u, bgl, yuv, rgba, noise, y8, y10, rgba_buf, read8, read10, read_rgba }
}
pub(super) fn draw_rune(&mut self, insts: &[Instance], target: &wgpu::TextureView, clear: [f32; 4]) {
self.rune.prepare(&self.device, &self.queue, &mut self.ts.atlas, insts, (W, H));
let mut enc = self.device.create_command_encoder(&Default::default());
self.rune.draw(&mut enc, target, clear);
self.queue.submit([enc.finish()]);
}
pub(super) fn pass<'a>(enc: &'a mut wgpu::CommandEncoder, view: &'a wgpu::TextureView, load: Option<[f32; 4]>) -> wgpu::RenderPass<'a> {
let ops = match load {
Some(c) => wgpu::LoadOp::Clear(wgpu::Color { r: c[0] as f64, g: c[1] as f64, b: c[2] as f64, a: c[3] as f64 }),
None => wgpu::LoadOp::Load,
};
enc.begin_render_pass(&wgpu::RenderPassDescriptor {
label: None,
color_attachments: &[Some(wgpu::RenderPassColorAttachment { view, depth_slice: None, resolve_target: None, ops: wgpu::Operations { load: ops, store: wgpu::StoreOp::Store } })],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
})
}
pub(super) fn copy(&self, enc: &mut wgpu::CommandEncoder, src: &wgpu::Texture, dst: &wgpu::Texture) {
enc.copy_texture_to_texture(
wgpu::TexelCopyTextureInfo { texture: src, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
wgpu::TexelCopyTextureInfo { texture: dst, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
wgpu::Extent3d { width: W, height: H, depth_or_array_layers: 1 },
);
}
/// Viz bind group with the GI buffers of `level` (or level 0) and `layer` as the sampled layer texture.
pub(super) fn viz_bg(&self, level: usize, layer: Option<&wgpu::TextureView>) -> wgpu::BindGroup {
let ins = self.light.inspect();
let v = &self.viz;
bind(
&self.device,
&v.bgl,
&[
v.g.as_entire_binding(),
v.vp.as_entire_binding(),
tv(ins.field),
tv(ins.emission),
tv(ins.occluders),
tv(&ins.own[level]),
tv(&ins.merged[level]),
tv(&v.means_own[level].view),
tv(&v.means_mrg[level].view),
tv(ins.fluence),
wgpu::BindingResource::Sampler(&v.lin),
tv(layer.unwrap_or(&v.dummy.view)),
wgpu::BindingResource::Sampler(&v.aniso),
],
)
}
pub(super) fn means(&self, enc: &mut wgpu::CommandEncoder) {
let ins = self.light.inspect();
let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("means"), timestamp_writes: None });
pass.set_pipeline(&self.viz.mean);
for n in 0..CASCADES as usize {
for (src, dst) in [(&ins.own[n], &self.viz.means_own[n]), (&ins.merged[n], &self.viz.means_mrg[n])] {
let bg = bind(&self.device, &self.viz.mean_bgl, &[self.viz.mean_u[n].as_entire_binding(), tv(src), tv(&dst.view)]);
pass.set_bind_group(0, &bg, &[]);
pass.dispatch_workgroups((ins.gi_size.0 >> n).div_ceil(8), (ins.gi_size.1 >> n).div_ceil(8), 1);
}
}
}
pub(super) fn build_mips(&self, enc: &mut wgpu::CommandEncoder, layer: usize) {
for m in 1..MIPS as usize {
let bg = self.viz_bg(0, Some(&self.layers[layer].mips[m - 1]));
let mut pass = Self::pass(enc, &self.layers[layer].mips[m], Some([0.0; 4]));
pass.set_pipeline(&self.viz.mip);
pass.set_bind_group(0, &bg, &[]);
pass.draw(0..3, 0..1);
}
}
/// Encode the final image (+ overlay) to yuv420p (8-bit) and yuv420p10le, and optionally RGBA8.
pub(super) fn encode(&mut self, frame: &wgpu::TextureView, rgba: bool, yuv: bool) -> (Option<Vec<u8>>, Option<Vec<u8>>, Option<Vec<u8>>) {
let e = &self.enc;
let bloom_mix = 0.045;
self.queue.write_buffer(&e.u, 0, bytemuck::cast_slice(&[W as f32, H as f32, 1.0, 1.0, bloom_mix, 1.0 / BLOOM_LEVELS as f32, 0.0, 0.0]));
let bg = bind(
&self.device,
&e.bgl,
&[
e.u.as_entire_binding(),
tv(frame),
tv(&self.overlay.view),
tv(&e.noise.view),
e.y8.as_entire_binding(),
e.y10.as_entire_binding(),
e.rgba_buf.as_entire_binding(),
tv(&self.bloom.levels[0]),
wgpu::BindingResource::Sampler(&self.bloom.sampler),
],
);
let mut enc = self.device.create_command_encoder(&Default::default());
{
let mut pass = enc.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("encode"), timestamp_writes: None });
pass.set_bind_group(0, &bg, &[]);
if yuv {
pass.set_pipeline(&e.yuv);
pass.dispatch_workgroups((W / 8).div_ceil(8), (H / 2).div_ceil(8), 1);
}
if rgba {
pass.set_pipeline(&e.rgba);
pass.dispatch_workgroups(W.div_ceil(8), H.div_ceil(8), 1);
}
}
let n = (W * H) as u64;
if yuv {
enc.copy_buffer_to_buffer(&e.y8, 0, &e.read8, 0, n * 3 / 2);
enc.copy_buffer_to_buffer(&e.y10, 0, &e.read10, 0, n * 3);
}
if rgba {
enc.copy_buffer_to_buffer(&e.rgba_buf, 0, &e.read_rgba, 0, n * 4);
}
self.queue.submit([enc.finish()]);
let read = |b: &wgpu::Buffer| {
let s = b.slice(..);
s.map_async(wgpu::MapMode::Read, |_| {});
self.device.poll(wgpu::PollType::wait_indefinitely()).expect("poll");
let v = s.get_mapped_range().expect("range").to_vec();
b.unmap();
v
};
let (a, b) = if yuv { (Some(read(&e.read8)), Some(read(&e.read10))) } else { (None, None) };
let c = if rgba { Some(read(&e.read_rgba)) } else { None };
(a, b, c)
}
}
const BLOOM_LEVELS: u32 = 7;
pub(super) struct Bloom {
pub(super) levels: Vec<wgpu::TextureView>,
pub(super) bgl: wgpu::BindGroupLayout,
pub(super) down: wgpu::RenderPipeline,
pub(super) up: wgpu::RenderPipeline,
pub(super) karis: wgpu::Buffer,
pub(super) plain: wgpu::Buffer,
pub(super) sampler: wgpu::Sampler,
}
impl Bloom {
pub(super) fn new(device: &wgpu::Device) -> Bloom {
use wgpu::util::DeviceExt;
let f = wgpu::ShaderStages::FRAGMENT;
let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("bloom"),
entries: &[bgl_entry(0, f, ubuf()), bgl_entry(1, f, ftex()), bgl_entry(2, f, wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering))],
});
let m = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("bloom"), source: wgpu::ShaderSource::Wgsl(wgsl_part("bloom").into()) });
let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[Some(&bgl)], immediate_size: 0 });
let pipe = |fs: &str, blend: Option<wgpu::BlendState>| {
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(fs),
layout: Some(&pl),
vertex: wgpu::VertexState { module: &m, entry_point: Some("vs_b"), compilation_options: Default::default(), buffers: &[] },
primitive: wgpu::PrimitiveState::default(),
depth_stencil: None,
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &m,
entry_point: Some(fs),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState { format: F16, blend, write_mask: wgpu::ColorWrites::ALL })],
}),
multiview_mask: None,
cache: None,
})
};
let add = wgpu::BlendComponent { src_factor: wgpu::BlendFactor::One, dst_factor: wgpu::BlendFactor::One, operation: wgpu::BlendOperation::Add };
let down = pipe("fs_bdown", None);
let up = pipe("fs_bup", Some(wgpu::BlendState { color: add, alpha: add }));
let t = device.create_texture(&wgpu::TextureDescriptor {
label: Some("bloom"),
size: wgpu::Extent3d { width: W / 2, height: H / 2, depth_or_array_layers: 1 },
mip_level_count: BLOOM_LEVELS,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: F16,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
});
let levels = (0..BLOOM_LEVELS)
.map(|k| t.create_view(&wgpu::TextureViewDescriptor { base_mip_level: k, mip_level_count: Some(1), ..Default::default() }))
.collect();
let karis = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: None, contents: bytemuck::cast_slice(&[1.0f32, 1.0, 0.0, 0.0]), usage: wgpu::BufferUsages::UNIFORM });
let plain = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: None, contents: bytemuck::cast_slice(&[0.0f32, 1.0, 0.0, 0.0]), usage: wgpu::BufferUsages::UNIFORM });
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("bloom"),
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
..Default::default()
});
Bloom { levels, bgl, down, up, karis, plain, sampler }
}
}
impl Ctx {
pub(super) fn bloom(&self, src: &wgpu::TextureView) {
let b = &self.bloom;
let mut enc = self.device.create_command_encoder(&Default::default());
let bg = |u: &wgpu::Buffer, v: &wgpu::TextureView| bind(&self.device, &b.bgl, &[u.as_entire_binding(), tv(v), wgpu::BindingResource::Sampler(&b.sampler)]);
for k in 0..BLOOM_LEVELS as usize {
let g = if k == 0 { bg(&b.karis, src) } else { bg(&b.plain, &b.levels[k - 1]) };
let mut pass = Self::pass(&mut enc, &b.levels[k], Some([0.0; 4]));
pass.set_pipeline(&b.down);
pass.set_bind_group(0, &g, &[]);
pass.draw(0..3, 0..1);
}
for k in (1..BLOOM_LEVELS as usize).rev() {
let g = bg(&b.plain, &b.levels[k]);
let mut pass = Self::pass(&mut enc, &b.levels[k - 1], None);
pass.set_pipeline(&b.up);
pass.set_bind_group(0, &g, &[]);
pass.draw(0..3, 0..1);
}
self.queue.submit([enc.finish()]);
}
}
+211
View File
@@ -0,0 +1,211 @@
//! The radiance-cascades reel: Rune's UI lit only by its own glowing elements, a breakdown that steps through
//! rune-light's real GI buffers, thick refracting glass, and an effect whose light enters the cascades. Headless.
//!
//! reel render [--out demo/reel] [--from S] [--to S] H.264 (8-bit) + HEVC (10-bit) MP4s, poster, contact sheet
//! reel stills T1,T2,… [--out DIR] PNGs at those times, for review
//! reel bench [--out demo/reel] GPU timestamps per pass → bench.json
//!
//! Frames render in Rgba16Float linear light and are converted on the GPU to BT.709 Y'CbCr 4:2:0 with blue-noise TPDF
//! dither at the exact 8- and 10-bit quantisation steps, then piped raw to ffmpeg (no swscale conversion).
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use rune::color::{Color, oklch, oklcha};
use rune::render::{Instance, KIND_GLYPH, KIND_RECT, KIND_SHADOW, NO_CLIP, Renderer};
use rune::text::TextSystem;
use rune::tok::TextStyle;
use rune_fx::{DistortParams, ElectricParams, ElectricStyle, Fx, FxFrame, FxLayer, FxOptions, FxRenderer, Shape, rgb};
use rune_light::{CASCADES, Gi, Glass, GlassLight, GlassRenderer, GlassSettings, LightRenderer, Prim, Scene, Settings, TextPolicy, Timings};
mod frame;
mod gpu;
mod output;
mod ui;
use frame::{Reel, glass_at, glow_settings, load_bench};
use gpu::{Ctx, GU, MAX_VP, VP};
use output::{bench, render, write_png};
use ui::{BG, UI_O, UI_SCALE, build_ui, dpt, dpx, state};
const S: f32 = 2.0;
const W: u32 = 2560;
const H: u32 = 1600;
const FPS: u32 = 60;
const DURATION: f32 = 31.0;
const F16: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float;
const MIPS: u32 = 12;
// ---------------------------------------------------------------- springs (SwiftUI parameterisation: duration, bounce)
#[derive(Clone, Copy)]
struct Spring {
duration: f32,
bounce: f32,
}
const fn sp(duration: f32, bounce: f32) -> Spring {
Spring { duration, bounce }
}
impl Spring {
fn eval(&self, d0: f32, v0: f32, t: f32) -> (f32, f32) {
let w = std::f32::consts::TAU / self.duration.max(1e-3);
let z = (1.0 - self.bounce).clamp(0.05, 1.0);
if z > 0.9999 {
let c = v0 + w * d0;
let e = (-w * t).exp();
return ((d0 + c * t) * e, (c - w * (d0 + c * t)) * e);
}
let wd = w * (1.0 - z * z).sqrt();
let a = d0;
let b = (v0 + z * w * d0) / wd;
let e = (-z * w * t).exp();
let (s, c) = (wd * t).sin_cos();
(e * (a * c + b * s), e * ((b * wd - z * w * a) * c - (a * wd + z * w * b) * s))
}
}
/// A value driven by springs retargeted at key times; a pure function of absolute time (velocity carries over).
struct Keys {
init: f32,
keys: Vec<(f32, f32, Spring)>,
}
fn keys(init: f32, k: &[(f32, f32, Spring)]) -> Keys {
Keys { init, keys: k.to_vec() }
}
impl Keys {
fn at(&self, t: f32) -> f32 {
let (mut x, mut v, mut t0, mut target, mut spring) = (self.init, 0.0, 0.0, self.init, sp(0.3, 0.0));
for &(tk, tg, s) in &self.keys {
if tk > t {
break;
}
let (d, vv) = spring.eval(x - target, v, tk - t0);
x = target + d;
v = vv;
t0 = tk;
target = tg;
spring = s;
}
target + spring.eval(x - target, v, t - t0).0
}
}
/// 0 → 1 released at `t0` with a critically damped spring of `dur`.
fn rise(t: f32, t0: f32, dur: f32) -> f32 {
if t <= t0 {
return 0.0;
}
1.0 - sp(dur, 0.0).eval(1.0, 0.0, t - t0).0
}
fn window(t: f32, a: f32, b: f32, fade: f32) -> f32 {
rise(t, a, fade) * (1.0 - rise(t, b, fade))
}
fn lerp(a: f32, b: f32, t: f32) -> f32 {
a + (b - a) * t
}
// ---------------------------------------------------------------- timeline
const T_TILT: f32 = 7.0;
const T_INPUTS: f32 = 8.3;
const T_CASCADES: f32 = 10.0;
const T_MERGE: f32 = 12.9;
const T_FLUENCE: f32 = 15.2;
const T_UNTILT: f32 = 16.4;
const T_GLASS: f32 = 17.8;
const T_ARC: f32 = 25.2;
const T_END: f32 = 28.4;
// ---------------------------------------------------------------- the camera for the 2.5D stack
#[derive(Clone, Copy)]
struct Cam {
pitch: f32,
yaw: f32,
scale: f32,
ty: f32,
tx: f32,
}
const FOV_D: f32 = 3200.0; // camera distance in px: pixel-exact at rest
fn project(c: &Cam, x: f32, y: f32, z: f32) -> [f32; 4] {
// Layer plane centred on the frame, z up toward the viewer; yaw spins it in its plane, pitch tips its top away.
let (x, y) = ((x - W as f32 * 0.5) * c.scale, (y - H as f32 * 0.5) * c.scale);
let z = z * c.scale;
let (sy, cy) = c.yaw.sin_cos();
let (x, y) = (x * cy - y * sy, x * sy + y * cy);
let (sp_, cp) = c.pitch.sin_cos();
let cz = -z;
let y2 = y * cp + cz * sp_;
let z2 = -y * sp_ + cz * cp;
let x2 = x + c.tx;
let y2 = y2 + c.ty;
let w = z2 + FOV_D;
[x2 * FOV_D / (W as f32 * 0.5), -y2 * FOV_D / (H as f32 * 0.5), 0.5 * w, w]
}
fn to_screen(c: [f32; 4]) -> [f32; 2] {
[(c[0] / c[3] + 1.0) * 0.5 * W as f32, (1.0 - c[1] / c[3]) * 0.5 * H as f32]
}
fn main() {
let args: Vec<String> = std::env::args().collect();
let cmd = args.get(1).map(String::as_str).unwrap_or("render");
let mut out = PathBuf::from("demo/reel");
let (mut from, mut to) = (0.0, DURATION);
let mut times: Vec<f32> = Vec::new();
let mut i = 2;
while i < args.len() {
match args[i].as_str() {
"--out" => {
out = PathBuf::from(&args[i + 1]);
i += 1;
}
"--from" => {
from = args[i + 1].parse().unwrap();
i += 1;
}
"--to" => {
to = args[i + 1].parse().unwrap();
i += 1;
}
s if cmd == "stills" && times.is_empty() => times = s.split(',').filter_map(|x| x.parse().ok()).collect(),
_ => {}
}
i += 1;
}
std::fs::create_dir_all(&out).unwrap();
let mut ctx = Ctx::new();
let bench_out = PathBuf::from(rune::env::var("REEL_BENCH").unwrap_or_else(|| "demo/reel".into()));
let reel = Reel {
bench: load_bench(&bench_out),
// Highlighted probes: in the gap under the progress bar, and between the chat and the right panel.
hp: [
[dpx(620.0, 421.0, 0.0, 0.0)[0], dpx(620.0, 421.0, 0.0, 0.0)[1]],
[dpx(912.0, 300.0, 0.0, 0.0)[0], dpx(912.0, 300.0, 0.0, 0.0)[1]],
],
};
match cmd {
"bench" => {
let gpu = rune::env::var("REEL_GPU").unwrap_or_else(|| ctx.gpu.clone());
bench(&reel, &mut ctx, &out, &gpu);
}
"stills" => {
for t in times {
let (view, _) = reel.frame(&mut ctx, t, false);
let (_, _, rgba) = ctx.encode(&view, true, false);
write_png(&out.join(format!("still-{t:05.2}.png")), W, H, &rgba.unwrap());
eprintln!("still {t}");
}
}
_ => render(&reel, &mut ctx, &out, from, to),
}
}
@@ -0,0 +1,163 @@
//! Output: PNGs, the ffmpeg pipes, the render loop and the bench.
use super::*;
pub(super) fn write_png(path: &Path, w: u32, h: u32, rgba: &[u8]) {
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
rune::render::write_png(path, w, h, rgba).unwrap();
}
fn downscale(src: &[u8], w: u32, h: u32, k: u32) -> Vec<u8> {
let (ow, oh) = (w / k, h / k);
let mut out = vec![0u8; (ow * oh * 4) as usize];
let lin = |v: u8| rune::color::srgb_decode(v as f32 / 255.0);
for y in 0..oh {
for x in 0..ow {
let mut acc = [0f32; 3];
for dy in 0..k {
for dx in 0..k {
let i = (((y * k + dy) * w + x * k + dx) * 4) as usize;
for c in 0..3 {
acc[c] += lin(src[i + c]);
}
}
}
let o = ((y * ow + x) * 4) as usize;
for c in 0..3 {
out[o + c] = (rune::color::srgb_encode(acc[c] / (k * k) as f32) * 255.0).round() as u8;
}
out[o + 3] = 255;
}
}
out
}
fn ffmpeg(args: &[&str], out: &Path) -> Child {
Command::new("ffmpeg")
.args(["-y", "-loglevel", "error", "-f", "rawvideo", "-s", &format!("{W}x{H}"), "-framerate", &FPS.to_string()])
.args(args)
.arg(out)
.stdin(Stdio::piped())
.spawn()
.expect("ffmpeg")
}
pub(super) fn render(reel: &Reel, ctx: &mut Ctx, out: &Path, from: f32, to: f32) {
let tag = ["-colorspace", "bt709", "-color_primaries", "bt709", "-color_trc", "bt709", "-color_range", "tv", "-movflags", "+faststart"];
let mut h264_args = vec!["-pix_fmt", "yuv420p", "-i", "-", "-c:v", "libx264", "-preset", "slow", "-crf", "12", "-tune", "film", "-pix_fmt", "yuv420p"];
h264_args.extend(tag);
let mut hevc_args = vec!["-pix_fmt", "yuv420p10le", "-i", "-", "-c:v", "libx265", "-preset", "medium", "-crf", "10", "-pix_fmt", "yuv420p10le", "-tag:v", "hvc1", "-x265-params", "log-level=error:aq-mode=3"];
hevc_args.extend(tag);
let mut h264 = ffmpeg(&h264_args, &out.join("rc-reel.mp4"));
let mut hevc = ffmpeg(&hevc_args, &out.join("rc-reel-master-10bit.mp4"));
let n0 = (from * FPS as f32).round() as u32;
let n1 = (to * FPS as f32).round() as u32;
let poster_t = T_END + 1.8;
let sheet_t = [T_TILT + 2.2, T_INPUTS + 1.0, T_CASCADES + 2.2, T_MERGE + 1.4, T_FLUENCE + 0.7, T_UNTILT + 0.9];
let mut sheet: Vec<Vec<u8>> = Vec::new();
let t0 = rune::time::now();
for f in n0..n1 {
let t = f as f32 / FPS as f32;
let (view, _) = reel.frame(ctx, t, false);
let want_png = (t - poster_t).abs() < 0.5 / FPS as f32 || sheet_t.iter().any(|s| (t - s).abs() < 0.5 / FPS as f32);
let (y8, y10, rgba) = ctx.encode(&view, want_png, true);
h264.stdin.as_mut().unwrap().write_all(&y8.unwrap()).expect("h264 write");
hevc.stdin.as_mut().unwrap().write_all(&y10.unwrap()).expect("hevc write");
if let Some(px) = rgba {
if (t - poster_t).abs() < 0.5 / FPS as f32 {
write_png(&out.join("poster.png"), W, H, &px);
} else {
sheet.push(downscale(&px, W, H, 4));
}
}
if f % 60 == 0 {
let line = format!("frame {f}/{n1} ({:.1}s)\n", t0.elapsed().as_secs_f32());
std::fs::OpenOptions::new().create(true).append(true).open(out.join("progress.log")).and_then(|mut fh| fh.write_all(line.as_bytes())).ok();
}
}
drop(h264.stdin.take());
drop(hevc.stdin.take());
h264.wait().expect("h264");
hevc.wait().expect("hevc");
if !sheet.is_empty() {
let (sw, sh) = (W / 4, H / 4);
let cols = 3u32;
let rows = (sheet.len() as u32).div_ceil(cols);
let gap = 8;
let (tw, th) = (sw * cols + gap * (cols - 1), sh * rows + gap * (rows - 1));
let mut img = vec![10u8; (tw * th * 4) as usize];
for (k, fr) in sheet.iter().enumerate() {
let (cx, cy) = (k as u32 % cols, k as u32 / cols);
for y in 0..sh {
let src = &fr[(y * sw * 4) as usize..((y + 1) * sw * 4) as usize];
let d = (((cy * (sh + gap) + y) * tw + cx * (sw + gap)) * 4) as usize;
img[d..d + src.len()].copy_from_slice(src);
}
}
for i in (3..img.len()).step_by(4) {
img[i] = 255;
}
write_png(&out.join("breakdown-sheet.png"), tw, th, &img);
}
eprintln!("rendered {} frames in {:.1}s", n1 - n0, t0.elapsed().as_secs_f32());
}
fn median(v: &mut [f64]) -> f64 {
v.sort_by(|a, b| a.partial_cmp(b).unwrap());
v[v.len() / 2]
}
pub(super) fn bench(reel: &Reel, ctx: &mut Ctx, out: &Path, gpu: &str) {
if !ctx.timestamps {
eprintln!("no TIMESTAMP_QUERY on this adapter");
return;
}
let mut runs: Vec<(Timings, f64)> = Vec::new();
for f in 0..150 {
// The hero at its fullest: every emitter on, progress flooding.
let t = 5.0 + (f % 60) as f32 / 60.0;
let (_, b) = reel.frame(ctx, t, true);
if f >= 30 {
if let Some(tm) = b.timings {
runs.push((tm, b.glass_ms));
}
}
}
// Whole frame, wall clock of back-to-back light + glass passes (GPU-bound), no readback.
let wall = {
let st = state(5.5);
let built = build_ui(&mut ctx.ts, &st);
let g = glass_at(T_GLASS + 1.5).unwrap();
let lights: Vec<GlassLight> = built.prims.iter().filter_map(|p| GlassLight::from_emitter(p, 18.0 * S, 0.9)).collect();
ctx.light.inspect = false;
let one = |ctx: &mut Ctx| {
let mut enc = ctx.device.create_command_encoder(&Default::default());
let scene = Scene { prims: &built.prims, lights: &[], settings: glow_settings(5.5), emission: None };
ctx.light.render(&ctx.device, &ctx.queue, &mut enc, &scene, &ctx.base.view, &ctx.text.view, &ctx.lit.view);
ctx.glass.render(&ctx.device, &ctx.queue, &mut enc, &[g], &lights, GlassSettings::default(), &ctx.lit.view, ctx.light.inspect().fluence, &ctx.glassed.view);
ctx.queue.submit([enc.finish()]);
};
one(ctx);
ctx.device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
let t0 = rune::time::now();
for _ in 0..120 {
one(ctx);
}
ctx.device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
t0.elapsed().as_secs_f64() * 1000.0 / 120.0
};
let col = |f: &dyn Fn(&(Timings, f64)) -> f64| median(&mut runs.iter().map(f).collect::<Vec<_>>());
let field = col(&|r| r.0.field);
let gi = col(&|r| r.0.gi);
let scene = col(&|r| r.0.gi_scene);
let fluence = col(&|r| r.0.fluence);
let glass = col(&|r| r.1);
let cs: Vec<f64> = (0..CASCADES as usize).map(|n| col(&|r| r.0.cascades[n])).collect();
let mut s = format!("{{\n \"gpu\": \"{gpu}\",\n \"resolution\": \"{W}x{H}\",\n \"field\": {field:.4},\n \"gi\": {gi:.4},\n \"gi_scene\": {scene:.4},\n");
for (n, c) in cs.iter().enumerate() {
s += &format!(" \"c{n}\": {c:.4},\n");
}
s += &format!(" \"fluence\": {fluence:.4},\n \"glass\": {glass:.4},\n \"frame\": {wall:.4}\n}}\n");
print!("{s}");
std::fs::write(out.join("bench.json"), s).unwrap();
}
@@ -0,0 +1,490 @@
// The reel's own passes: visualisations of rune-light's real GI buffers, the 2.5D layer stack, mips, and the final
// encode (sRGB → BT.709 Y'CbCr 4:2:0 with blue-noise TPDF dither at the exact quantisation step).
struct G {
size: vec4<f32>, // W, H, gi w, gi h
gi: vec4<f32>, // px per gi texel, time, highlighted probe count, unused
hp: array<vec4<f32>, 2>,
};
struct VP {
a: vec4<f32>, // level, merged mix (0 own … 1 merged), exposure, unused
b: vec4<f32>, // cells, probe dots, rays, rings
c: vec4<f32>, // ray growth 0…1, alpha, border, unused
q0: vec4<f32>, // layer quad clip corners: TL, TR, BL, BR
q1: vec4<f32>,
q2: vec4<f32>,
q3: vec4<f32>,
};
@group(0) @binding(0) var<uniform> g: G;
@group(0) @binding(1) var<storage, read> vp: array<VP>;
@group(0) @binding(2) var field: texture_2d<f32>;
@group(0) @binding(3) var emit: texture_2d<f32>;
@group(0) @binding(4) var occ: texture_2d<f32>;
@group(0) @binding(5) var c_own: texture_2d<f32>;
@group(0) @binding(6) var c_mrg: texture_2d<f32>;
@group(0) @binding(7) var m_own: texture_2d<f32>;
@group(0) @binding(8) var m_mrg: texture_2d<f32>;
@group(0) @binding(9) var flu: texture_2d<f32>;
@group(0) @binding(10) var lsamp: sampler;
@group(0) @binding(11) var layer: texture_2d<f32>;
@group(0) @binding(12) var asamp: sampler;
const TAU: f32 = 6.28318531;
struct FOut {
@builtin(position) pos: vec4<f32>,
@location(0) @interpolate(flat) k: u32,
};
@vertex
fn vs_full(@builtin(vertex_index) vi: u32, @builtin(instance_index) ii: u32) -> FOut {
let uv = vec2<f32>(f32((vi << 1u) & 2u), f32(vi & 2u));
var o: FOut;
o.pos = vec4<f32>(uv * 2.0 - 1.0, 0.0, 1.0);
o.k = ii;
return o;
}
fn tone(x: vec3<f32>) -> vec3<f32> {
return vec3<f32>(1.0) - exp(-max(x, vec3<f32>(0.0)));
}
// Panel colour behind every visualisation.
fn panel(p: vec2<f32>) -> vec3<f32> {
let uv = p / g.size.xy;
let v = 1.0 - 0.25 * dot(uv - 0.5, uv - 0.5);
return vec3<f32>(0.0075, 0.0085, 0.013) * v;
}
fn aa_line(d: f32, w: f32) -> f32 {
let fw = max(fwidth(d), 1e-4);
return 1.0 - smoothstep(w * 0.5 - fw * 0.5, w * 0.5 + fw * 0.5, abs(d));
}
// ---- field: the GI distance (px, clamped at 128) as bands and contours ----
@fragment
fn fs_field(i: FOut) -> @location(0) vec4<f32> {
let p = i.pos.xy;
let f = textureSampleLevel(field, lsamp, p / g.size.xy, 0.0);
let d = f.w;
var col = panel(p);
let fw = max(fwidth(d), 1e-3);
if (d < 0.0) {
let x = clamp(-d / 60.0, 0.0, 1.0);
col = mix(vec3<f32>(0.20, 0.085, 0.03), vec3<f32>(0.06, 0.02, 0.008), x);
let band = abs(fract(-d / 12.0 + 0.5) - 0.5) * 12.0;
col = col + vec3<f32>(0.35, 0.16, 0.05) * (1.0 - smoothstep(0.0, fw * 1.2, band)) * 0.5;
} else {
let x = clamp(d / 128.0, 0.0, 1.0);
col = col + mix(vec3<f32>(0.03, 0.10, 0.16), vec3<f32>(0.004, 0.012, 0.025), sqrt(x)) * (1.0 - smoothstep(120.0, 128.0, d));
let band = abs(fract(d / 16.0 + 0.5) - 0.5) * 16.0;
let line = (1.0 - smoothstep(0.0, fw * 1.2, band)) * (1.0 - smoothstep(96.0, 127.0, d));
col = col + vec3<f32>(0.10, 0.32, 0.48) * line * (0.55 - 0.4 * x);
}
let zero = 1.0 - smoothstep(0.0, fw * 1.6, abs(d));
col = col + vec3<f32>(0.95, 0.85, 0.7) * zero;
return vec4<f32>(col, 1.0);
}
// ---- scene: the media the cascades march through, at gi resolution (nearest, so texels show) ----
@fragment
fn fs_scene(i: FOut) -> @location(0) vec4<f32> {
let p = i.pos.xy;
let v = vp[i.k];
let t = vec2<i32>(p / g.gi.x);
let em = textureLoad(emit, t, 0);
let oc = textureLoad(occ, t, 0);
var col = panel(p);
// Card coverage as slate, emitters as their radiance (σ·L / σ) times coverage.
col = col + vec3<f32>(0.045, 0.05, 0.065) * oc.a;
let cov = clamp(em.a / 1.5, 0.0, 1.0);
let rad = em.rgb / max(em.a, 1e-4);
col = col + tone(rad * v.a.z) * cov;
return vec4<f32>(col, 1.0);
}
fn ray_tex(n: u32, probe: vec2<i32>, j: u32) -> vec2<i32> {
let b = 2u << n;
return probe * i32(b) + vec2<i32>(i32(j % b), i32(j / b));
}
// ---- one cascade: per-probe mean radiance as cells, probe dots, and the real rays of a few probes ----
@fragment
fn fs_cascade(i: FOut) -> @location(0) vec4<f32> {
let p = i.pos.xy;
let v = vp[i.k];
let n = u32(v.a.x + 0.5);
let mixk = v.a.y;
let expo = v.a.z;
let s = f32(1u << n);
let sp = s * g.gi.x;
let nprobe = vec2<i32>(g.size.zw / s);
var col = vec3<f32>(0.0);
var alpha = 0.0;
let idx = clamp(vec2<i32>(floor(p / sp)), vec2<i32>(0), nprobe - vec2<i32>(1));
let c = (vec2<f32>(idx) + 0.5) * sp;
let local = p - c;
let gap = max(0.75, sp * 0.07);
let half = sp * 0.5 - gap;
let r = sp * 0.16;
let q = abs(local) - vec2<f32>(half - r);
let dcell = length(max(q, vec2<f32>(0.0))) + min(max(q.x, q.y), 0.0) - r;
let cell = 1.0 - smoothstep(-0.6, 0.6, dcell);
let val = mix(textureLoad(m_own, idx, 0).rgb, textureLoad(m_mrg, idx, 0).rgb, mixk);
col = col + (tone(val * expo) * 0.95 + vec3<f32>(0.02, 0.024, 0.034)) * cell * v.b.x;
alpha = max(alpha, cell * v.b.x * 0.8);
let dr = max(0.9, sp * 0.06);
let dot_k = (1.0 - smoothstep(dr - 0.6, dr + 0.6, length(local))) * v.b.y * 0.6 * smoothstep(9.0, 16.0, sp);
col = mix(col, vec3<f32>(0.85, 0.9, 1.0), dot_k);
// Highlighted probes: interval ring, and every ray as a segment coloured by the radiance it carries.
let t0 = (pow(4.0, f32(n)) - 1.0) / 3.0 * g.gi.x;
let t1 = (pow(4.0, f32(n) + 1.0) - 1.0) / 3.0 * g.gi.x;
let nd = 4u << (2u * n);
let grow = v.c.x;
let t1g = mix(t0 + 0.001, t1, grow);
let nh = i32(g.gi.z);
var ray = vec3<f32>(0.0);
var ring = 0.0;
for (var h = 0; h < nh; h = h + 1) {
let hp4 = g.hp[h / 2];
var hp = hp4.xy;
if ((h & 1) == 1) {
hp = hp4.zw;
}
let pidx = clamp(vec2<i32>(floor(hp / sp)), vec2<i32>(0), nprobe - vec2<i32>(1));
let pc = (vec2<f32>(pidx) + 0.5) * sp;
let rel = p - pc;
let rr = length(rel);
// Interval band and its edges.
let band = smoothstep(t0 - 1.0, t0 + 1.0, rr) * (1.0 - smoothstep(t1g - 1.0, t1g + 1.0, rr));
ring = ring + band * 0.025 + (aa_line(rr - t0, v.c.w) + aa_line(rr - t1g, v.c.w) * step(0.01, grow)) * 0.55;
// Every ray of C0–C2; for C3 and C4 an evenly spaced subset, so neighbouring rays stay ≥ ~14 px apart where
// they start (all 1024 of C4's would merge into a disc).
let gap_px = max(t0, 1.0) * TAU / f32(nd);
let stride = u32(max(1.0, exp2(ceil(log2(max(14.0 / gap_px, 1.0))))));
let shown = nd / stride;
if (rr > t0 - 3.0 && rr < t1g + 3.0) {
var ang = atan2(rel.y, rel.x);
if (ang < 0.0) {
ang = ang + TAU;
}
let fj = ang / TAU * f32(shown) - 0.5;
let j0 = i32(floor(fj));
for (var o = 0; o < 2; o = o + 1) {
let js = u32((j0 + o + i32(shown)) % i32(shown));
let j = js * stride + stride / 2u;
let a = (f32(j) + 0.5) / f32(nd) * TAU;
let dir = vec2<f32>(cos(a), sin(a));
let along = clamp(dot(rel, dir), t0, t1g);
let dist = length(rel - dir * along);
let rw = v.c.w;
let fade = 1.0 - 0.6 * clamp((along - t0) / max(t1 - t0, 1.0), 0.0, 1.0);
let w = (1.0 - smoothstep(rw * 0.5 - 0.6, rw * 0.5 + 0.6, dist)) * fade;
if (w > 0.0) {
let tx = ray_tex(n, pidx, j);
let rv = mix(textureLoad(c_own, tx, 0).rgb, textureLoad(c_mrg, tx, 0).rgb, mixk);
ray = max(ray, (tone(rv * expo * 2.5) * 1.3 + vec3<f32>(0.06, 0.065, 0.085)) * w);
}
}
}
// The probe itself.
let pd = length(rel);
ring = ring + (1.0 - smoothstep(6.0, 8.0, pd)) * 1.2 + aa_line(pd - 14.0, v.c.w) * 0.8;
}
let rk = ray * v.b.z;
let gk = clamp(ring * v.b.w, 0.0, 1.0);
col = col + rk + vec3<f32>(0.75, 0.82, 1.0) * gk;
alpha = clamp(max(alpha, max(max(rk.r, rk.g), rk.b) * 1.5 + gk), 0.0, 1.0);
return vec4<f32>(col, alpha);
}
// ---- fluence (cascade 0's directions averaged) ----
@fragment
fn fs_fluence(i: FOut) -> @location(0) vec4<f32> {
let p = i.pos.xy;
let v = vp[i.k];
let f = textureSampleLevel(flu, lsamp, p / g.size.xy, 0.0).rgb;
return vec4<f32>(panel(p) + tone(f * v.a.z), 1.0);
}
// ---- accumulate a sub-frame (shutter): additive, weighted ----
@fragment
fn fs_accum(i: FOut) -> @location(0) vec4<f32> {
let c = textureLoad(layer, vec2<i32>(i.pos.xy), 0);
return vec4<f32>(c.rgb * vp[i.k].a.x, vp[i.k].a.x);
}
// ---- mips: 2×2 box from the level above ----
@fragment
fn fs_mip(i: FOut) -> @location(0) vec4<f32> {
let sz = vec2<f32>(textureDimensions(layer, 0));
let uv = i.pos.xy * 2.0 / sz;
return textureSampleLevel(layer, lsamp, uv, 0.0);
}
// ---- 2.5D layer stack ----
struct LOut {
@builtin(position) pos: vec4<f32>,
@location(0) uv: vec2<f32>,
@location(1) @interpolate(flat) k: u32,
};
@vertex
fn vs_layer(@builtin(vertex_index) vi: u32, @builtin(instance_index) ii: u32) -> LOut {
let v = vp[ii];
var q = v.q0;
if (vi == 1u) {
q = v.q1;
} else if (vi == 2u) {
q = v.q2;
} else if (vi == 3u) {
q = v.q3;
}
var o: LOut;
o.pos = q;
o.uv = vec2<f32>(f32(vi & 1u), f32(vi >> 1u));
o.k = ii;
return o;
}
@fragment
fn fs_layer(i: LOut) -> @location(0) vec4<f32> {
let v = vp[i.k];
let c = textureSample(layer, asamp, i.uv).rgb;
// Edge distance in screen px: antialiased quad edges and a hairline frame.
let fw = max(fwidth(i.uv), vec2<f32>(1e-6));
let e2 = min(i.uv, vec2<f32>(1.0) - i.uv) / fw;
let e = min(e2.x, e2.y);
let alpha = v.c.y * clamp(e, 0.0, 1.0);
let frame = (1.0 - smoothstep(0.8, 1.8, e)) * v.c.z;
let rgb = c + vec3<f32>(0.55, 0.62, 0.78) * frame;
return vec4<f32>(rgb * alpha, alpha);
}
// ---- bloom ----
// Physically based bloom (Jimenez, "Next generation post processing in Call of Duty: AW"): a 13-tap downsample
// chain (Karis luma-weighted average on the first step, so a lone bright pixel never flickers), a 3×3 tent upsample
// added back up the chain, and a small energy-conserving mix at the end.
struct BU {
p: vec4<f32>, // karis 0/1, tent radius (texels), unused, unused
};
@group(0) @binding(0) var<uniform> bu: BU;
@group(0) @binding(1) var bsrc: texture_2d<f32>;
@group(0) @binding(2) var bsamp: sampler;
@vertex
fn vs_b(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4<f32> {
let uv = vec2<f32>(f32((vi << 1u) & 2u), f32(vi & 2u));
return vec4<f32>(uv * 2.0 - 1.0, 0.0, 1.0);
}
fn karis(c: vec3<f32>) -> f32 {
return 1.0 / (1.0 + dot(c, vec3<f32>(0.2126, 0.7152, 0.0722)));
}
@fragment
fn fs_bdown(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
let sz = vec2<f32>(textureDimensions(bsrc, 0));
let uv = pos.xy * 2.0 / sz;
let t = 1.0 / sz;
let s = array<vec2<f32>, 13>(
vec2<f32>(-2.0, -2.0), vec2<f32>(0.0, -2.0), vec2<f32>(2.0, -2.0),
vec2<f32>(-2.0, 0.0), vec2<f32>(0.0, 0.0), vec2<f32>(2.0, 0.0),
vec2<f32>(-2.0, 2.0), vec2<f32>(0.0, 2.0), vec2<f32>(2.0, 2.0),
vec2<f32>(-1.0, -1.0), vec2<f32>(1.0, -1.0), vec2<f32>(-1.0, 1.0), vec2<f32>(1.0, 1.0),
);
var c: array<vec3<f32>, 13>;
for (var k = 0; k < 13; k = k + 1) {
c[k] = max(textureSampleLevel(bsrc, bsamp, uv + t * s[k], 0.0).rgb, vec3<f32>(0.0));
}
// Five overlapping 2×2 boxes: the centre one (j k l m) weighs 0.5, the four corners 0.125 each.
let b0 = (c[9] + c[10] + c[11] + c[12]) * 0.25;
let b1 = (c[0] + c[1] + c[3] + c[4]) * 0.25;
let b2 = (c[1] + c[2] + c[4] + c[5]) * 0.25;
let b3 = (c[3] + c[4] + c[6] + c[7]) * 0.25;
let b4 = (c[4] + c[5] + c[7] + c[8]) * 0.25;
var w = vec4<f32>(0.5, 0.125, 0.125, 0.125);
var w4 = 0.125;
if (bu.p.x > 0.5) {
w = w * vec4<f32>(karis(b0), karis(b1), karis(b2), karis(b3));
w4 = w4 * karis(b4);
}
let o = (b0 * w.x + b1 * w.y + b2 * w.z + b3 * w.w + b4 * w4) / (w.x + w.y + w.z + w.w + w4);
return vec4<f32>(o, 1.0);
}
@fragment
fn fs_bup(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
let sz = vec2<f32>(textureDimensions(bsrc, 0));
// The target is twice the source's size.
let uv = pos.xy * 0.5 / sz;
let t = bu.p.y / sz;
var o = textureSampleLevel(bsrc, bsamp, uv, 0.0).rgb * 4.0;
o = o + (textureSampleLevel(bsrc, bsamp, uv + vec2<f32>(-t.x, 0.0), 0.0).rgb + textureSampleLevel(bsrc, bsamp, uv + vec2<f32>(t.x, 0.0), 0.0).rgb
+ textureSampleLevel(bsrc, bsamp, uv + vec2<f32>(0.0, -t.y), 0.0).rgb + textureSampleLevel(bsrc, bsamp, uv + vec2<f32>(0.0, t.y), 0.0).rgb) * 2.0;
o = o + textureSampleLevel(bsrc, bsamp, uv - t, 0.0).rgb + textureSampleLevel(bsrc, bsamp, uv + t, 0.0).rgb
+ textureSampleLevel(bsrc, bsamp, uv + vec2<f32>(t.x, -t.y), 0.0).rgb + textureSampleLevel(bsrc, bsamp, uv + vec2<f32>(-t.x, t.y), 0.0).rgb;
return vec4<f32>(o / 16.0, 1.0);
}
// ---- per-probe mean of a cascade level ----
struct MeanU {
n: u32,
pad0: u32,
pad1: u32,
pad2: u32,
};
@group(0) @binding(0) var<uniform> mu: MeanU;
@group(0) @binding(1) var csrc: texture_2d<f32>;
@group(0) @binding(2) var mout: texture_storage_2d<rgba16float, write>;
@compute @workgroup_size(8, 8)
fn cs_mean(@builtin(global_invocation_id) gid: vec3<u32>) {
let dims = textureDimensions(mout);
let b = 2u << mu.n;
let np = textureDimensions(csrc) / b;
if (gid.x >= np.x || gid.y >= np.y || gid.x >= dims.x || gid.y >= dims.y) {
return;
}
var acc = vec3<f32>(0.0);
for (var y = 0u; y < b; y = y + 1u) {
for (var x = 0u; x < b; x = x + 1u) {
acc = acc + textureLoad(csrc, vec2<i32>(gid.xy * b + vec2<u32>(x, y)), 0).rgb;
}
}
textureStore(mout, gid.xy, vec4<f32>(acc / f32(b * b), 1.0));
}
// ---- final encode ----
struct EncU {
size: vec4<f32>, // W, H, dither 8-bit (LSB), dither 10-bit (LSB)
misc: vec4<f32>, // bloom mix, bloom scale (1 / levels), unused
};
@group(0) @binding(0) var<uniform> eu: EncU;
@group(0) @binding(1) var img: texture_2d<f32>;
@group(0) @binding(2) var overlay: texture_2d<f32>;
@group(0) @binding(3) var noise: texture_2d<f32>;
@group(0) @binding(4) var<storage, read_write> y8: array<u32>;
@group(0) @binding(5) var<storage, read_write> y10: array<u32>;
@group(0) @binding(6) var<storage, read_write> rgba: array<u32>;
@group(0) @binding(7) var bloom: texture_2d<f32>;
@group(0) @binding(8) var esamp: sampler;
fn srgb(c: vec3<f32>) -> vec3<f32> {
let x = clamp(c, vec3<f32>(0.0), vec3<f32>(1.0));
let lo = x * 12.92;
let hi = 1.055 * pow(x, vec3<f32>(1.0 / 2.4)) - 0.055;
return select(hi, lo, x <= vec3<f32>(0.0031308));
}
fn final_px(p: vec2<i32>) -> vec3<f32> {
let b = textureSampleLevel(bloom, esamp, (vec2<f32>(p) + 0.5) / eu.size.xy, 0.0).rgb;
let c = mix(textureLoad(img, p, 0).rgb, b * eu.misc.y, eu.misc.x);
let o = textureLoad(overlay, p, 0);
return srgb(c * (1.0 - o.a) + o.rgb);
}
// Triangular (TPDF) dither in (−1, 1) from two channels of a 64×64 blue-noise tile; `ch` picks the pair.
fn tpdf(p: vec2<i32>, ch: i32) -> f32 {
let n = textureLoad(noise, vec2<i32>(p.x & 63, p.y & 63), 0);
let o = textureLoad(noise, vec2<i32>((p.x + 32) & 63, (p.y + 17) & 63), 0);
var a = n.x;
var b = o.y;
if (ch == 1) {
a = n.y;
b = o.z;
} else if (ch == 2) {
a = n.z;
b = o.x;
}
return a + b - 1.0;
}
@compute @workgroup_size(8, 8)
fn cs_yuv(@builtin(global_invocation_id) gid: vec3<u32>) {
let w = u32(eu.size.x);
let h = u32(eu.size.y);
let x0 = gid.x * 8u;
let yy = gid.y * 2u;
if (x0 >= w || yy >= h) {
return;
}
var cb = array<f32, 4>(0.0, 0.0, 0.0, 0.0);
var cr = array<f32, 4>(0.0, 0.0, 0.0, 0.0);
for (var r = 0u; r < 2u; r = r + 1u) {
let y = yy + r;
var w8 = array<u32, 2>(0u, 0u);
var w10 = array<u32, 4>(0u, 0u, 0u, 0u);
for (var i = 0u; i < 8u; i = i + 1u) {
let p = vec2<i32>(i32(x0 + i), i32(y));
let c = final_px(p);
let yl = dot(c, vec3<f32>(0.2126, 0.7152, 0.0722));
cb[i / 2u] = cb[i / 2u] + (c.b - yl) / 1.8556 * 0.25;
cr[i / 2u] = cr[i / 2u] + (c.r - yl) / 1.5748 * 0.25;
let d = tpdf(p, 0);
let v8 = u32(clamp(round(16.0 + 219.0 * yl + d * eu.size.z), 0.0, 255.0));
let v10 = u32(clamp(round(64.0 + 876.0 * yl + d * eu.size.w), 0.0, 1023.0));
w8[i / 4u] = w8[i / 4u] | (v8 << (8u * (i % 4u)));
w10[i / 2u] = w10[i / 2u] | (v10 << (16u * (i % 2u)));
}
let o8 = (y * w + x0) / 4u;
y8[o8] = w8[0];
y8[o8 + 1u] = w8[1];
let o10 = (y * w + x0) / 2u;
for (var k = 0u; k < 4u; k = k + 1u) {
y10[o10 + k] = w10[k];
}
}
// Chroma, sited at the centre of each 2×2 block.
let cw = w / 2u;
let crow = yy / 2u;
let cx0 = x0 / 2u;
var u8w = 0u;
var v8w = 0u;
var u10 = array<u32, 2>(0u, 0u);
var v10 = array<u32, 2>(0u, 0u);
for (var k = 0u; k < 4u; k = k + 1u) {
let p = vec2<i32>(i32(cx0 + k), i32(crow)) * 2;
let du = tpdf(p, 1);
let dv = tpdf(p, 2);
let a8 = u32(clamp(round(128.0 + 224.0 * cb[k] + du * eu.size.z), 0.0, 255.0));
let b8 = u32(clamp(round(128.0 + 224.0 * cr[k] + dv * eu.size.z), 0.0, 255.0));
u8w = u8w | (a8 << (8u * k));
v8w = v8w | (b8 << (8u * k));
let a10 = u32(clamp(round(512.0 + 896.0 * cb[k] + du * eu.size.w), 0.0, 1023.0));
let b10 = u32(clamp(round(512.0 + 896.0 * cr[k] + dv * eu.size.w), 0.0, 1023.0));
u10[k / 2u] = u10[k / 2u] | (a10 << (16u * (k % 2u)));
v10[k / 2u] = v10[k / 2u] | (b10 << (16u * (k % 2u)));
}
let ysz = w * h;
let csz = cw * (h / 2u);
y8[(ysz + crow * cw + cx0) / 4u] = u8w;
y8[(ysz + csz + crow * cw + cx0) / 4u] = v8w;
let b10u = (ysz + crow * cw + cx0) / 2u;
let b10v = (ysz + csz + crow * cw + cx0) / 2u;
y10[b10u] = u10[0];
y10[b10u + 1u] = u10[1];
y10[b10v] = v10[0];
y10[b10v + 1u] = v10[1];
}
@compute @workgroup_size(8, 8)
fn cs_rgba(@builtin(global_invocation_id) gid: vec3<u32>) {
let w = u32(eu.size.x);
let h = u32(eu.size.y);
if (gid.x >= w || gid.y >= h) {
return;
}
let p = vec2<i32>(gid.xy);
let c = final_px(p);
var o = 0u;
for (var k = 0; k < 3; k = k + 1) {
let v = u32(clamp(round(c[k] * 255.0 + tpdf(p, k) * eu.size.z), 0.0, 255.0));
o = o | (v << (8u * u32(k)));
}
rgba[gid.y * w + gid.x] = o | (255u << 24u);
}
+343
View File
@@ -0,0 +1,343 @@
//! Building the reel's UI: instances, glyphs and the state at each moment.
use super::*;
pub(super) struct Ui<'a> {
pub(super) ts: &'a mut TextSystem,
pub(super) base: Vec<Instance>,
pub(super) text: Vec<Instance>,
pub(super) prims: Vec<Prim>,
/// pt → device px: px = (o + x·k)·S
pub(super) k: f32,
pub(super) o: [f32; 2],
}
fn inst(rect: [f32; 4], r: f32, fill: Color, border: Option<(Color, f32)>) -> Instance {
let (bc, bw) = border.unwrap_or((Color::TRANSPARENT, 0.0));
Instance {
rect,
radii: [r; 4],
fill: fill.premul(1.0),
border: if bw > 0.0 { bc.premul(1.0) } else { [0.0; 4] },
params: [bw, KIND_RECT, 0.0, 1.0],
uv: [0.0; 4],
clip: NO_CLIP,
fade: [0; 4],
}
}
impl<'a> Ui<'a> {
pub(super) fn new(ts: &'a mut TextSystem, k: f32, o: [f32; 2]) -> Self {
Ui { ts, base: Vec::new(), text: Vec::new(), prims: Vec::new(), k, o }
}
pub(super) fn px(&self, x: f32, y: f32, w: f32, h: f32) -> [f32; 4] {
[(self.o[0] + x * self.k) * S, (self.o[1] + y * self.k) * S, w * self.k * S, h * self.k * S]
}
pub(super) fn d(&self, v: f32) -> f32 {
v * self.k * S
}
#[allow(clippy::too_many_arguments)]
pub(super) fn rect(&mut self, x: f32, y: f32, w: f32, h: f32, r: f32, fill: Color, border: Option<(Color, f32)>, light: impl FnOnce(Prim, f32) -> Prim) {
let rect = self.px(x, y, w, h);
let rr = self.d(r);
self.base.push(inst(rect, rr, fill, border.map(|(c, bw)| (c, bw * S))));
let p = Prim::rect(rect[0], rect[1], rect[2], rect[3]).radius(rr).albedo([fill.r, fill.g, fill.b]);
self.prims.push(light(p, self.k * S));
}
pub(super) fn paint(&mut self, x: f32, y: f32, w: f32, h: f32, r: f32, fill: Color) {
let rect = self.px(x, y, w, h);
let rr = self.d(r);
self.base.push(inst(rect, rr, fill, None));
}
pub(super) fn shadow(&mut self, x: f32, y: f32, w: f32, h: f32, r: f32, sigma: f32, color: Color) {
let mut i = inst(self.px(x, y, w, h), self.d(r), color, None);
i.params = [0.0, KIND_SHADOW, self.d(sigma), 1.0];
self.base.push(i);
}
pub(super) fn text(&mut self, x: f32, y: f32, s: &str, size: f32, weight: f32, color: Color) -> f32 {
let style = TextStyle::new(size, weight);
let scale = S * self.k;
let mut quads = Vec::new();
self.ts.glyphs(s, style, scale, [((self.o[0] + x * self.k) * S).round(), ((self.o[1] + y * self.k) * S).round()], &mut quads);
for q in quads {
self.text.push(Instance {
rect: q.rect,
radii: [0.0; 4],
fill: color.premul(1.0),
border: [0.0; 4],
params: [0.0, KIND_GLYPH, 0.0, 1.0],
uv: [q.uv[0], q.uv[1], 0.0, 0.0],
clip: NO_CLIP,
fade: [0; 4],
});
}
self.ts.measure(s, style, scale).0 / self.k
}
pub(super) fn measure(&mut self, s: &str, size: f32, weight: f32) -> f32 {
self.ts.measure(s, TextStyle::new(size, weight), S * self.k).0 / self.k
}
}
fn scaled(c: Color, k: f32) -> [f32; 3] {
[c.r * k, c.g * k, c.b * k]
}
/// Everything animated, at one instant.
pub(super) struct St {
pub(super) t: f32,
pub(super) send: f32,
pub(super) rec: f32,
pub(super) prog: f32,
pub(super) prog_glow: f32,
pub(super) toast_x: f32,
pub(super) toast_glow: f32,
pub(super) status: f32,
pub(super) arc: f32,
pub(super) danger_glow: f32,
}
pub(super) fn state(t: f32) -> St {
// Emitters warm up one after another (lights cool, never cut).
let warm = |t0: f32| rise(t, t0, 0.9);
// Breathing: a spring retargeted every 1.1 s between two levels.
let mut bk = Vec::new();
let mut k = 0.25;
let mut up = true;
while k < DURATION + 2.0 {
bk.push((k, if up { 1.0 } else { 0.5 }, sp(0.9, 0.0)));
up = !up;
k += 1.1;
}
let breath = keys(0.5, &bk).at(t);
let click = 3.3;
// The send button flares on the click and cools exponentially back to rest.
let flare = if t > click { (-(t - click) / 0.35).exp() * rise(t, click, 0.08) } else { 0.0 };
let send = warm(0.1) * (1.0 + 1.6 * flare);
let prog = keys(0.08, &[(click + 0.15, 1.0, sp(2.8, 0.0))]).at(t).min(1.0);
let done = 6.1;
let pflash = if t > done { (-(t - done) / 0.5).exp() * rise(t, done, 0.1) } else { 0.0 };
// Fills, floods on completion, then cools to a low resting glow.
let prog_glow = warm(0.5) * (0.7 + 0.3 * rise(t, click, 0.6)) * (1.0 - 0.7 * rise(t, done + 0.4, 1.6)) + 1.4 * pflash;
let toast_x = keys(420.0, &[(1.2, 0.0, sp(0.75, 0.12))]).at(t);
let toast_glow = warm(1.0);
let arc_in = rise(t, T_ARC, 0.35);
let arc_out = rise(t, T_END - 0.4, 0.6);
St {
t,
send,
rec: warm(0.7) * breath,
prog,
prog_glow,
toast_x,
toast_glow,
status: warm(0.3),
arc: arc_in * (1.0 - arc_out),
danger_glow: arc_in * (1.0 - arc_out),
}
}
pub(super) const BG: (f32, f32, f32) = (0.115, 0.012, 268.0);
fn build(ui: &mut Ui, st: &St) {
let bg = oklch(0.155, 0.01, 268.0);
let side = oklch(0.175, 0.01, 268.0);
let card = oklch(0.215, 0.011, 268.0);
let card2 = oklch(0.245, 0.012, 268.0);
let user = oklch(0.27, 0.04, 268.0);
let txt = oklch(0.94, 0.005, 268.0);
let txt2 = oklch(0.70, 0.012, 268.0);
let txt3 = oklch(0.54, 0.012, 268.0);
let hair = oklcha(1.0, 0.0, 0.0, 0.07);
let raise = |p: Prim, k: f32| p.raised(6.0 * k).bevel(6.0 * k, 2.0 * k).gloss(0.5, 0.42);
let chip = |p: Prim, k: f32| p.on(6.0 * k).raised(2.5 * k).bevel(4.0 * k, 1.0 * k).gloss(0.45, 0.4);
// Window: soft drop shadow on the desktop, then the window itself (flat: it receives light).
ui.shadow(0.0, 18.0, 1280.0, 800.0, 18.0, 40.0, oklcha(0.0, 0.0, 0.0, 0.6));
ui.rect(0.0, 0.0, 1280.0, 800.0, 18.0, bg, Some((oklcha(1.0, 0.0, 0.0, 0.08), 1.0)), |p, _| p);
// Sidebar
ui.rect(0.0, 0.0, 244.0, 800.0, 18.0, side, None, |p, _| p);
let r = ui.d(18.0);
ui.base.last_mut().unwrap().radii = [r, 0.0, 0.0, r];
*ui.prims.last_mut().unwrap() = ui.prims.last().unwrap().radii([r, 0.0, 0.0, r]);
ui.paint(244.0, 0.0, 1.0, 800.0, 0.0, hair);
for (i, c) in [oklch(0.62, 0.17, 25.0), oklch(0.78, 0.15, 85.0), oklch(0.72, 0.17, 145.0)].iter().enumerate() {
ui.paint(20.0 + i as f32 * 18.0, 20.0, 11.0, 11.0, 5.5, oklcha(c.to_oklab()[0], 0.02, 268.0, 0.9));
}
ui.text(22.0, 52.0, "OpenCode", 16.0, 600.0, txt);
ui.rect(16.0, 86.0, 212.0, 36.0, 10.0, card, Some((hair, 1.0)), |p, k| p.raised(3.0 * k).bevel(3.0 * k, 1.2 * k).gloss(0.5, 0.45));
ui.text(32.0, 95.0, "+ New session", 13.0, 500.0, txt);
ui.text(22.0, 146.0, "TODAY", 11.0, 600.0, txt3);
let sessions = ["Radiance cascades for UI", "Thick glass optics", "Electric arcs into GI", "Theme tokens codegen", "Scroll momentum", "Slug text spike"];
for (i, s) in sessions.iter().enumerate() {
let y = 170.0 + i as f32 * 38.0;
if i == 0 {
ui.rect(10.0, y - 8.0, 224.0, 34.0, 9.0, oklcha(1.0, 0.0, 0.0, 0.055), None, |p, _| p);
}
ui.text(24.0, y, s, 13.0, if i == 0 { 500.0 } else { 400.0 }, if i == 0 { txt } else { txt2 });
}
// Status pill with a green light.
ui.rect(16.0, 740.0, 212.0, 40.0, 20.0, card, Some((hair, 1.0)), |p, k| p.raised(3.0 * k).bevel(5.0 * k, 1.5 * k).gloss(0.5, 0.4));
let green = oklch(0.80, 0.19, 150.0);
let g = 3.2 * st.status;
ui.rect(34.0, 755.0, 10.0, 10.0, 5.0, green, None, |p, k| p.on(3.0 * k).emissive(scaled(green, g)));
ui.text(54.0, 751.0, "Connected · studio", 12.0, 500.0, txt2);
// Header
ui.text(272.0, 22.0, "Radiance cascades for UI", 15.0, 600.0, txt);
let model = "claude-opus-5.5";
let mw = ui.measure(model, 12.0, 500.0);
ui.rect(900.0 - mw - 26.0, 16.0, mw + 26.0, 28.0, 14.0, card, Some((hair, 1.0)), |p, k| p.raised(2.0 * k).bevel(4.0 * k, 1.0 * k).gloss(0.5, 0.4));
ui.text(900.0 - mw - 13.0, 22.0, model, 12.0, 500.0, txt2);
ui.paint(245.0, 60.0, 1035.0, 1.0, 0.0, hair);
// Chat column
let cx = 272.0;
let cw = 628.0;
let ub = "come on, do radiance cascades UI";
let uw = ui.measure(ub, 14.0, 400.0) + 36.0;
ui.rect(cx + cw - uw, 82.0, uw, 46.0, 16.0, user, Some((oklcha(1.0, 0.0, 0.0, 0.08), 1.0)), raise);
ui.text(cx + cw - uw + 18.0, 95.0, ub, 14.0, 400.0, txt);
ui.rect(cx, 150.0, cw, 140.0, 16.0, card, Some((hair, 1.0)), raise);
let lines = [
"Every Rune element is an analytic rounded rect, so the frame is already",
"an exact distance field. Glowing elements are the only lights here: five",
"cascades of probes trace that field, merge top down, and light the cards",
"around them with soft coloured bounce and shadow.",
];
for (i, l) in lines.iter().enumerate() {
ui.text(cx + 22.0, 168.0 + i as f32 * 22.0, l, 14.0, 400.0, txt);
}
for (i, c) in ["Read gi.wgsl", "Edit cascades", "Run bench"].iter().enumerate() {
let x = cx + 22.0 + [0.0, 116.0, 236.0][i];
let w = ui.measure(c, 12.0, 500.0) + 22.0;
ui.rect(x, 256.0 - 4.0 + 8.0, w, 24.0, 12.0, card2, Some((hair, 1.0)), chip);
ui.text(x + 11.0, 264.0, c, 12.0, 500.0, txt2);
}
// Tool card with the progress bar.
ui.rect(cx, 310.0, cw, 102.0, 16.0, card, Some((hair, 1.0)), raise);
ui.text(cx + 22.0, 326.0, "Rendering reel", 14.0, 600.0, txt);
let frame = (st.prog * 1860.0).round() as u32;
let sub = format!("frame {frame} / 1860 · 2560×1600 · 60 fps");
ui.text(cx + 22.0, 348.0, &sub, 12.0, 400.0, txt2);
let pct = format!("{}%", (st.prog * 100.0).round() as u32);
let pw = ui.measure(&pct, 12.0, 600.0);
ui.text(cx + cw - 22.0 - pw, 326.0, &pct, 12.0, 600.0, txt2);
ui.rect(cx + 22.0, 380.0, cw - 44.0, 10.0, 5.0, oklch(0.19, 0.01, 268.0), None, |p, k| p.on(6.0 * k));
let cyan = oklch(0.82, 0.14, 205.0);
let pg = 1.7 * st.prog_glow;
ui.rect(cx + 22.0, 380.0, (cw - 44.0) * st.prog, 10.0, 5.0, cyan, None, |p, k| p.on(6.0 * k).emissive(scaled(cyan, pg)));
// Code card
ui.rect(cx, 432.0, cw, 156.0, 16.0, card, Some((hair, 1.0)), raise);
ui.text(cx + 22.0, 448.0, "Glowing elements are lights:", 14.0, 400.0, txt);
ui.rect(cx + 18.0, 478.0, cw - 36.0, 92.0, 10.0, oklch(0.18, 0.01, 268.0), Some((hair, 1.0)), |p, k| p.on(6.0 * k).gloss(0.2, 0.5));
let code = [
("let send = Prim::from_rune(rect, radii)", oklch(0.84, 0.07, 230.0)),
(" .emissive(ACCENT * glow);", oklch(0.80, 0.09, 300.0)),
("lights.render(&Scene { prims, gi: Some(Gi::default()), .. });", oklch(0.84, 0.07, 160.0)),
];
for (i, (l, c)) in code.iter().enumerate() {
ui.text(cx + 36.0, 492.0 + i as f32 * 22.0, l, 13.0, 400.0, *c);
}
// Composer with the recording dot and the send button.
ui.rect(cx, 652.0, cw, 112.0, 20.0, card, Some((oklcha(1.0, 0.0, 0.0, 0.1), 1.0)), |p, k| p.raised(9.0 * k).bevel(7.0 * k, 2.5 * k).gloss(0.6, 0.38));
ui.text(cx + 22.0, 672.0, "Ask anything…", 14.0, 400.0, txt3);
let red = oklch(0.66, 0.22, 25.0);
let rg = 6.0 * st.rec;
ui.rect(cx + 22.0, 724.0, 14.0, 14.0, 7.0, red, None, |p, k| p.on(9.0 * k).emissive(scaled(red, rg)));
let secs = 7 + st.t as u32;
ui.text(cx + 44.0, 722.0, &format!("Recording 0:{secs:02}"), 12.0, 500.0, oklch(0.78, 0.09, 25.0));
let accent = oklch(0.70, 0.19, 275.0);
let sg = 3.4 * st.send;
ui.rect(cx + cw - 58.0, 712.0, 38.0, 38.0, 19.0, accent, None, |p, k| p.on(9.0 * k).raised(3.0 * k).emissive(scaled(accent, sg)));
let aw = ui.measure("↑", 17.0, 700.0);
ui.text(cx + cw - 39.0 - aw * 0.5, 719.0, "↑", 17.0, 700.0, oklch(0.99, 0.01, 275.0));
// Right panel
let rx = 924.0;
let rw = 332.0;
ui.rect(rx, 150.0, rw, 170.0, 16.0, card, Some((hair, 1.0)), raise);
ui.text(rx + 20.0, 166.0, "Agents", 14.0, 600.0, txt);
let agents = [("cascades", "tracing · 5 levels"), ("glass", "refraction pass"), ("review", "Argon · no blockers")];
for (i, (a, b)) in agents.iter().enumerate() {
let y = 198.0 + i as f32 * 38.0;
ui.rect(rx + 20.0, y + 4.0, 8.0, 8.0, 4.0, oklch(0.5, 0.02, 268.0), None, |p, k| p.on(6.0 * k));
ui.text(rx + 38.0, y, a, 13.0, 500.0, txt);
let bw = ui.measure(b, 12.0, 400.0);
ui.text(rx + rw - 20.0 - bw, y + 1.0, b, 12.0, 400.0, txt2);
}
ui.rect(rx, 340.0, rw, 140.0, 16.0, card, Some((hair, 1.0)), raise);
ui.text(rx + 20.0, 356.0, "Branch rc-reel", 14.0, 600.0, txt);
ui.text(rx + 20.0, 380.0, "12 commits ahead · 3 files changed", 12.0, 400.0, txt2);
let danger = oklch(0.42, 0.13, 25.0);
let dg = 1.4 * st.danger_glow;
ui.rect(rx + 20.0, 424.0, 150.0, 36.0, 10.0, danger, Some((oklcha(0.75, 0.14, 25.0, 0.5), 1.0)), |p, k| {
let p = p.on(6.0 * k).raised(3.0 * k).bevel(5.0 * k, 1.5 * k).gloss(0.6, 0.35);
if dg > 0.0 { p.emissive(scaled(oklch(0.66, 0.2, 25.0), dg)) } else { p }
});
ui.text(rx + 43.0, 433.0, "Delete branch", 13.0, 600.0, oklch(0.95, 0.03, 25.0));
ui.rect(rx + 182.0, 424.0, 130.0, 36.0, 10.0, card2, Some((hair, 1.0)), chip);
ui.text(rx + 225.0, 433.0, "Cancel", 13.0, 600.0, txt);
ui.rect(rx, 500.0, rw, 264.0, 16.0, card, Some((hair, 1.0)), raise);
ui.text(rx + 20.0, 516.0, "GPU per frame", 14.0, 600.0, txt);
for i in 0..10 {
let h = 30.0 + 90.0 * (0.5 + 0.5 * ((i as f32 * 0.9).sin() * 0.7 + (i as f32 * 0.37).cos() * 0.3));
ui.rect(rx + 24.0 + i as f32 * 29.0, 720.0 - h, 16.0, h, 4.0, oklch(0.34, 0.03, 268.0), None, |p, k| p.on(6.0 * k).raised(2.0 * k));
}
ui.text(rx + 20.0, 734.0, "GI · composite · glass", 11.0, 500.0, txt3);
// Toast: slides in from the right edge; its icon glows amber.
let tx = rx + st.toast_x;
ui.rect(tx, 76.0, rw, 56.0, 14.0, card2, Some((oklcha(1.0, 0.0, 0.0, 0.1), 1.0)), |p, k| p.floating(10.0 * k, 16.0 * k).bevel(6.0 * k, 2.0 * k).gloss(0.6, 0.38));
let amber = oklch(0.80, 0.16, 70.0);
let ag = 2.8 * st.toast_glow;
ui.rect(tx + 16.0, 92.0, 24.0, 24.0, 12.0, amber, None, |p, k| p.on(16.0 * k).emissive(scaled(amber, ag)));
let cw2 = ui.measure("✓", 14.0, 700.0);
if cw2 > 0.0 {
ui.text(tx + 28.0 - cw2 * 0.5, 94.0, "✓", 14.0, 700.0, oklch(0.25, 0.05, 70.0));
}
ui.text(tx + 54.0, 88.0, "Build passed", 13.0, 600.0, txt);
ui.text(tx + 54.0, 107.0, "ci · 1m 12s", 12.0, 400.0, txt2);
}
// Window placement on the 1280×800 pt canvas: a caption band sits below it.
pub(super) const UI_SCALE: f32 = 0.9;
pub(super) const UI_O: [f32; 2] = [64.0, 18.0];
pub(super) struct Built {
pub(super) base: Vec<Instance>,
pub(super) text: Vec<Instance>,
pub(super) prims: Vec<Prim>,
}
pub(super) fn build_ui(ts: &mut TextSystem, st: &St) -> Built {
let mut ui = Ui::new(ts, UI_SCALE, UI_O);
build(&mut ui, st);
// The electric border around the danger button may glow anywhere within this rect: tell the GI tracer.
if st.arc > 0.0 {
let r = ui.px(924.0 + 20.0 - 24.0, 424.0 - 24.0, 150.0 + 48.0, 36.0 + 48.0);
ui.prims.push(Prim::rect(r[0], r[1], r[2], r[3]).radius(ui.d(30.0)).gi_hint());
}
Built { base: ui.base, text: ui.text, prims: ui.prims }
}
/// Device-px rect of a design-space rect.
pub(super) fn dpx(x: f32, y: f32, w: f32, h: f32) -> [f32; 4] {
[(UI_O[0] + x * UI_SCALE) * S, (UI_O[1] + y * UI_SCALE) * S, w * UI_SCALE * S, h * UI_SCALE * S]
}
/// The same rect in points on the canvas (rune-fx shapes are in points).
pub(super) fn dpt(x: f32, y: f32, w: f32, h: f32) -> [f32; 4] {
[UI_O[0] + x * UI_SCALE, UI_O[1] + y * UI_SCALE, w * UI_SCALE, h * UI_SCALE]
}
@@ -0,0 +1,16 @@
//! What each pipeline set Rune, rune-fx and rune-light build costs the first time a process
//! makes it, in milliseconds, as one JSON line. Run it in fresh processes, `--profile perf`,
//! with `RUNE_GPU_BACKEND=metal` (and Rune's `metal-backend` feature) or `wgpu`, after clearing
//! the Metal shader cache (`$(getconf DARWIN_USER_CACHE_DIR)/com.apple.metal`) for a cold run.
#[path = "../tests/support/builtin.rs"]
mod builtin;
fn main() {
let start = rune::time::now();
let gpu = rune::render::Gpu::headless();
let mut out = vec![("device", start.elapsed().as_secs_f64() * 1e3)];
out.extend(builtin::build_every_pipeline(&gpu));
let fields: Vec<String> = out.iter().map(|(k, v)| format!("\"{k}\":{v:.3}")).collect();
println!("{{{}}}", fields.join(","));
}
+155
View File
@@ -0,0 +1,155 @@
use crate::glass::{Glass, GlassLight, GlassU};
use crate::{Cascade, FLAG_EMISSIVE, FLAG_GI_HINT, FLAG_OCCLUDER, FLAG_RAISED, FrameU, Light, Prim};
#[test]
fn wgsl_uniform_storage_and_flags_match_rust() {
use wgpu::naga::{Expression, Literal, Module, TypeInner, front::wgsl, proc::Layouter, valid::{Capabilities, ValidationFlags, Validator}};
let parse = |label: &str, source: &str| -> (Module, Layouter) {
let module = wgsl::parse_str(source).unwrap_or_else(|e| panic!("{label}: {}", e.emit_to_string(source)));
Validator::new(ValidationFlags::all(), Capabilities::default())
.validate(&module)
.unwrap_or_else(|e| panic!("{label}: {e}"));
let mut layouter = Layouter::default();
layouter.update(module.to_ctx()).unwrap_or_else(|e| panic!("{label}: {e}"));
(module, layouter)
};
let check_struct = |label: &str, module: &Module, layouter: &Layouter, name: &str, size: usize, expected: &[(&str, usize)]| {
let (handle, ty) = module
.types
.iter()
.find(|(_, t)| t.name.as_deref() == Some(name))
.unwrap_or_else(|| panic!("{label}: WGSL struct {name} not found"));
assert_eq!(layouter[handle].size as usize, size, "{label} {name} size");
let TypeInner::Struct { members, span } = &ty.inner else { panic!("{label}: {name} is not a struct") };
assert_eq!(*span as usize, size, "{label} {name} span");
assert_eq!(members.len(), expected.len(), "{label} {name} member count");
for (member, &(field, offset)) in members.iter().zip(expected) {
assert_eq!(member.name.as_deref(), Some(field), "{label} {name}.{field} name");
assert_eq!(member.offset as usize, offset, "{label} {name}.{field} offset");
}
};
let check_u32_const = |label: &str, module: &Module, name: &str, expected: u32| {
let (_, c) = module
.constants
.iter()
.find(|(_, c)| c.name.as_deref() == Some(name))
.unwrap_or_else(|| panic!("{label}: WGSL const {name} not found"));
match module.global_expressions[c.init] {
Expression::Literal(Literal::U32(val)) => assert_eq!(val, expected, "{label} const {name}"),
ref other => panic!("{label}: const {name} is {other:?}, expected u32 literal"),
}
};
let gbuf_src = format!("{}\n{}", crate::gpu::COMMON, include_str!("shaders/gbuffer.wgsl"));
let (gbuf_mod, gbuf_layout) = parse("common+gbuffer.wgsl", &gbuf_src);
check_struct(
"common.wgsl",
&gbuf_mod,
&gbuf_layout,
"Frame",
std::mem::size_of::<FrameU>(),
&[
("sf", std::mem::offset_of!(FrameU, sf)),
("gs", std::mem::offset_of!(FrameU, gs)),
("ambient", std::mem::offset_of!(FrameU, ambient)),
("counts", std::mem::offset_of!(FrameU, counts)),
("misc", std::mem::offset_of!(FrameU, misc)),
("text", std::mem::offset_of!(FrameU, text)),
("gi", std::mem::offset_of!(FrameU, gi)),
("bg", std::mem::offset_of!(FrameU, bg)),
("ext", std::mem::offset_of!(FrameU, ext)),
],
);
check_struct(
"common.wgsl",
&gbuf_mod,
&gbuf_layout,
"Prim",
std::mem::size_of::<Prim>(),
&[
("rect", std::mem::offset_of!(Prim, rect)),
("radii", std::mem::offset_of!(Prim, radii)),
("z", std::mem::offset_of!(Prim, z)),
("mat", std::mem::offset_of!(Prim, mat)),
("emit", std::mem::offset_of!(Prim, emit)),
("albedo", std::mem::offset_of!(Prim, albedo)),
],
);
check_struct(
"common.wgsl",
&gbuf_mod,
&gbuf_layout,
"Light",
std::mem::size_of::<Light>(),
&[
("pos", std::mem::offset_of!(Light, pos)),
("color", std::mem::offset_of!(Light, color)),
("axis", std::mem::offset_of!(Light, axis)),
("extra", std::mem::offset_of!(Light, extra)),
],
);
check_u32_const("common.wgsl", &gbuf_mod, "F_OCC", FLAG_OCCLUDER);
check_u32_const("common.wgsl", &gbuf_mod, "F_EMIT", FLAG_EMISSIVE);
check_u32_const("common.wgsl", &gbuf_mod, "F_RAISED", FLAG_RAISED);
check_u32_const("common.wgsl", &gbuf_mod, "F_HINT", FLAG_GI_HINT);
let gi_src = format!("{}\n{}", crate::gpu::COMMON, crate::gpu::gi_section("cascades"));
let (gi_mod, gi_layout) = parse("common+gi(cascades).wgsl", &gi_src);
check_struct(
"gi.wgsl",
&gi_mod,
&gi_layout,
"Cascade",
std::mem::size_of::<Cascade>(),
&[
("n", std::mem::offset_of!(Cascade, n)),
("count", std::mem::offset_of!(Cascade, count)),
("merge", std::mem::offset_of!(Cascade, merge)),
("pad1", std::mem::offset_of!(Cascade, pad1)),
],
);
let glass_src = crate::glass::section("glass");
let (glass_mod, glass_layout) = parse("glass.wgsl", &glass_src);
check_struct(
"glass.wgsl",
&glass_mod,
&glass_layout,
"U",
std::mem::size_of::<GlassU>(),
&[
("size", std::mem::offset_of!(GlassU, size)),
("misc", std::mem::offset_of!(GlassU, misc)),
("shadow", std::mem::offset_of!(GlassU, shadow)),
],
);
check_struct(
"glass.wgsl",
&glass_mod,
&glass_layout,
"Glass",
std::mem::size_of::<Glass>(),
&[
("a", std::mem::offset_of!(Glass, a)),
("b", std::mem::offset_of!(Glass, b)),
("r", std::mem::offset_of!(Glass, r)),
("p0", std::mem::offset_of!(Glass, p0)),
("p1", std::mem::offset_of!(Glass, p1)),
("tint", std::mem::offset_of!(Glass, tint)),
],
);
check_struct(
"glass.wgsl",
&glass_mod,
&glass_layout,
"GLight",
std::mem::size_of::<GlassLight>(),
&[
("pos", std::mem::offset_of!(GlassLight, pos)),
("color", std::mem::offset_of!(GlassLight, color)),
],
);
}
+161
View File
@@ -0,0 +1,161 @@
//! CPU references for the soft-shadow pass.
//!
//! - [`estimate`]: the shader's penumbra estimator over the *exact* analytic field (no half-res texture), so a GPU
//! texel can be checked against the same maths without quantisation.
//! - [`ground_truth`]: brute force. Many rays from the receiver to points spread over the spherical source's disc,
//! each sphere traced against the exact 3D distance to every slab; visibility is the unblocked share.
use crate::{FLAG_OCCLUDER, Light, Prim};
const CONTINUOUS_K: f32 = 1.528_664_8;
fn sd_continuous(p: [f32; 2], half: [f32; 2], r: f32) -> f32 {
let e = CONTINUOUS_K * r;
let q = [half[0] - p[0].abs(), half[1] - p[1].abs()];
let v = [e - q[0], e - q[1]];
if v[0] <= 0.0 || v[1] <= 0.0 {
return (-q[0]).max(-q[1]);
}
let u = v[1].atan2(v[0]) * (4.0 / std::f32::consts::PI) - 1.0;
let u2 = u * u;
(v[0] * v[0] + v[1] * v[1]).sqrt() - e * (1.146_022_95 + u2 * (-0.375_731_61 + u2 * (0.307_966_09 - 0.077_243_54 * u2)))
}
fn sd_rrect(p: [f32; 2], half: [f32; 2], radii: [f32; 4]) -> f32 {
let r = if p[0] > 0.0 {
if p[1] > 0.0 { radii[2] } else { radii[1] }
} else if p[1] > 0.0 {
radii[3]
} else {
radii[0]
};
let m = half[0].min(half[1]);
if r < 0.0 {
return sd_continuous(p, half, (-r).min(m));
}
let r = r.min(m);
let q = [p[0].abs() - half[0] + r, p[1].abs() - half[1] + r];
q[0].max(q[1]).min(0.0) + (q[0].max(0.0).hypot(q[1].max(0.0))) - r
}
fn prim_sd(pr: &Prim, p: [f32; 2]) -> f32 {
let half = [pr.rect[2] * 0.5, pr.rect[3] * 0.5];
sd_rrect([p[0] - pr.rect[0] - half[0], p[1] - pr.rect[1] - half[1]], half, pr.radii)
}
/// The field texel the shader builds: union 2D distance and the nearest occluder's z range.
pub fn field(prims: &[Prim], p: [f32; 2]) -> [f32; 3] {
let mut best = [1e4, 0.0, 0.0];
for pr in prims.iter().filter(|p| p.flags() & FLAG_OCCLUDER != 0) {
let d = prim_sd(pr, p);
if d < best[0] {
best = [d, pr.z[0], pr.z[1]];
}
}
best
}
fn slab(f: [f32; 3], z: f32) -> f32 {
let dz = (z - f[2]).max(f[1] - z);
let a = [f[0], dz];
a[0].max(0.0).hypot(a[1].max(0.0)) + a[0].max(a[1]).min(0.0)
}
/// Exact 3D distance to the union of slabs.
pub fn scene_sd(prims: &[Prim], q: [f32; 3]) -> f32 {
prims
.iter()
.filter(|p| p.flags() & FLAG_OCCLUDER != 0)
.map(|pr| slab([prim_sd(pr, [q[0], q[1]]), pr.z[0], pr.z[1]], q[2]))
.fold(1e4, f32::min)
}
fn smooth(res: f32) -> f32 {
let k = (0.5 + 0.5 * res).clamp(0.0, 1.0);
k * k * (3.0 - 2.0 * k)
}
/// The shader's estimator (shadow.wgsl `trace`) with the field evaluated exactly.
pub fn estimate(prims: &[Prim], light: &Light, p: [f32; 3]) -> f32 {
let l = [light.pos[0], light.pos[1], light.pos[2]];
let radius = light.pos[3] * light.extra[3];
let d = [l[0] - p[0], l[1] - p[1], l[2] - p[2]];
let dist = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
let rd = [d[0] / dist, d[1] / dist, d[2] / dist];
let theta = (radius / dist).max(1e-3);
let zmax = prims.iter().filter(|p| p.flags() & FLAG_OCCLUDER != 0).fold(0.0f32, |m, p| m.max(p.z[1])) + 0.5;
let (mut t, mut res, mut ph) = (0.75f32, 1.0f32, 1e10f32);
for _ in 0..64 {
if t >= dist - radius {
break;
}
let q = [p[0] + rd[0] * t, p[1] + rd[1] * t, p[2] + rd[2] * t];
if rd[2] >= 0.0 && q[2] > zmax {
break;
}
let h = slab(field(prims, [q[0], q[1]]), q[2]);
if h <= 0.0 {
res = res.min(h / (t * theta));
} else {
let y = h * h / (2.0 * ph);
let dd = (h * h - y * y).max(0.0).sqrt();
res = res.min(dd / ((t - y).max(1e-3) * theta));
}
ph = h.max(1e-3);
if res <= -1.0 {
break;
}
t += h.abs().clamp(0.6 + t * 0.012, 96.0);
}
smooth(res)
}
fn blocked(prims: &[Prim], p: [f32; 3], target: [f32; 3]) -> bool {
let d = [target[0] - p[0], target[1] - p[1], target[2] - p[2]];
let dist = (d[0] * d[0] + d[1] * d[1] + d[2] * d[2]).sqrt();
let rd = [d[0] / dist, d[1] / dist, d[2] / dist];
let mut t = 0.05;
while t < dist {
let q = [p[0] + rd[0] * t, p[1] + rd[1] * t, p[2] + rd[2] * t];
let h = scene_sd(prims, q);
if h < 0.01 {
return true;
}
t += h.max(0.02);
}
false
}
/// Unblocked share of the source's disc (as seen from p), `n`×`n` stratified samples.
pub fn ground_truth(prims: &[Prim], light: &Light, p: [f32; 3], n: u32) -> f32 {
let c = [light.pos[0], light.pos[1], light.pos[2]];
let r = light.pos[3] * light.extra[3];
let w = [c[0] - p[0], c[1] - p[1], c[2] - p[2]];
let wl = (w[0] * w[0] + w[1] * w[1] + w[2] * w[2]).sqrt();
let w = [w[0] / wl, w[1] / wl, w[2] / wl];
let up = if w[2].abs() < 0.9 { [0.0, 0.0, 1.0] } else { [1.0, 0.0, 0.0] };
let cross = |a: [f32; 3], b: [f32; 3]| [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
let u = cross(w, up);
let ul = (u[0] * u[0] + u[1] * u[1] + u[2] * u[2]).sqrt();
let u = [u[0] / ul, u[1] / ul, u[2] / ul];
let v = cross(w, u);
let (mut lit, mut total) = (0u32, 0u32);
for i in 0..n {
for j in 0..n {
let a = [(i as f32 + 0.5) / n as f32 * 2.0 - 1.0, (j as f32 + 0.5) / n as f32 * 2.0 - 1.0];
if a[0] * a[0] + a[1] * a[1] > 1.0 {
continue;
}
total += 1;
let tgt = [
c[0] + (u[0] * a[0] + v[0] * a[1]) * r,
c[1] + (u[1] * a[0] + v[1] * a[1]) * r,
c[2] + (u[2] * a[0] + v[2] * a[1]) * r,
];
if !blocked(prims, p, tgt) {
lit += 1;
}
}
}
lit as f32 / total.max(1) as f32
}
+366
View File
@@ -0,0 +1,366 @@
//! Thick refracting glass over a lit frame (see `shaders/glass.wgsl` for the optics).
//!
//! ```ignore
//! let card = Glass::rounded(x, y, w, h, 40.0 * s).thickness(36.0 * s).bevel(28.0 * s).gap(10.0 * s);
//! glass.render(&device, &queue, &mut encoder, &[card], &lights, GlassSettings::default(), &lit, lights.inspect().fluence, &target);
//! ```
use bytemuck::{Pod, Zeroable};
use crate::{FLAG_EMISSIVE, Prim};
/// One glass slab, in device px.
#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable, PartialEq)]
pub struct Glass {
pub a: [f32; 4],
pub b: [f32; 4],
/// radius a, radius b, smooth-union k, morph a → b
pub r: [f32; 4],
/// thickness, bevel, gap above the UI, dome
pub p0: [f32; 4],
/// ior at 550 nm, dispersion n(400) − n(700), frost 0…1, presence 0…1
pub p1: [f32; 4],
/// absorption per px rgb (Beer–Lambert), rim glow from GI
pub tint: [f32; 4],
}
const _: () = {
assert!(std::mem::size_of::<Glass>() == 96);
assert!(std::mem::offset_of!(Glass, a) == 0);
assert!(std::mem::offset_of!(Glass, b) == 16);
assert!(std::mem::offset_of!(Glass, r) == 32);
assert!(std::mem::offset_of!(Glass, p0) == 48);
assert!(std::mem::offset_of!(Glass, p1) == 64);
assert!(std::mem::offset_of!(Glass, tint) == 80);
};
impl Glass {
/// Crown glass (n = 1.5 at 550 nm, a little stronger dispersion than real for visibility), faintly green in depth.
pub fn rounded(x: f32, y: f32, w: f32, h: f32, radius: f32) -> Glass {
Glass {
a: [x, y, w, h],
b: [0.0; 4],
r: [radius, 0.0, 0.0, 0.0],
p0: [40.0, 30.0, 12.0, 0.0],
p1: [1.5, 0.03, 0.0, 1.0],
tint: [0.0016, 0.00045, 0.0011, 0.35],
}
}
pub fn thickness(mut self, t: f32) -> Glass {
self.p0[0] = t;
self
}
/// Width of the rounded shoulder from the rim to the flat top.
pub fn bevel(mut self, b: f32) -> Glass {
self.p0[1] = b;
self
}
/// Height of the bottom face above the UI.
pub fn gap(mut self, g: f32) -> Glass {
self.p0[2] = g;
self
}
/// Extra height in the middle: a convex top that magnifies.
pub fn dome(mut self, d: f32) -> Glass {
self.p0[3] = d;
self
}
pub fn ior(mut self, n: f32) -> Glass {
self.p1[0] = n;
self
}
pub fn dispersion(mut self, d: f32) -> Glass {
self.p1[1] = d;
self
}
pub fn frost(mut self, f: f32) -> Glass {
self.p1[2] = f;
self
}
/// Scales thickness, dome and shadow together: glass appears by lensing, not by fading.
pub fn presence(mut self, p: f32) -> Glass {
self.p1[3] = p;
self
}
pub fn tint(mut self, absorb: [f32; 3]) -> Glass {
self.tint[..3].copy_from_slice(&absorb);
self
}
pub fn rim_glow(mut self, g: f32) -> Glass {
self.tint[3] = g;
self
}
/// Smooth-union a second rounded rect with blend radius `k`; `morph` moves the whole shape toward it.
pub fn union(mut self, rect: [f32; 4], radius: f32, k: f32, morph: f32) -> Glass {
self.b = rect;
self.r[1] = radius;
self.r[2] = k;
self.r[3] = morph;
self
}
}
/// A glowing UI element as a sphere light for the glass's highlights.
#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable, PartialEq)]
pub struct GlassLight {
/// x, y, z, radius
pub pos: [f32; 4],
pub color: [f32; 4],
}
const _: () = {
assert!(std::mem::size_of::<GlassLight>() == 32);
assert!(std::mem::offset_of!(GlassLight, pos) == 0);
assert!(std::mem::offset_of!(GlassLight, color) == 16);
};
impl GlassLight {
/// From an emissive primitive: a sphere of the element's size, `z` px above the UI, radiance × `gain`.
pub fn from_emitter(p: &Prim, z: f32, gain: f32) -> Option<GlassLight> {
if p.flags() & FLAG_EMISSIVE == 0 {
return None;
}
let r = 0.5 * (p.rect[2] * p.rect[3]).sqrt();
Some(GlassLight {
pos: [p.rect[0] + p.rect[2] * 0.5, p.rect[1] + p.rect[3] * 0.5, z, r],
color: [p.emit[0] * gain, p.emit[1] * gain, p.emit[2] * gain, 0.0],
})
}
}
#[derive(Clone, Copy, Debug)]
pub struct GlassSettings {
/// Environment (studio) reflection strength.
pub env: f32,
/// Drop shadow strength, offset and blur (px).
pub shadow: f32,
pub shadow_offset: [f32; 2],
pub shadow_blur: f32,
/// Caustic ring strength.
pub caustic: f32,
}
impl Default for GlassSettings {
fn default() -> Self {
GlassSettings { env: 1.0, shadow: 0.35, shadow_offset: [8.0, 22.0], shadow_blur: 30.0, caustic: 0.6 }
}
}
#[repr(C)]
#[derive(Clone, Copy, Pod, Zeroable)]
pub(crate) struct GlassU {
pub(crate) size: [f32; 4],
pub(crate) misc: [f32; 4],
pub(crate) shadow: [f32; 4],
}
const _: () = {
assert!(std::mem::size_of::<GlassU>() == 48);
assert!(std::mem::offset_of!(GlassU, size) == 0);
assert!(std::mem::offset_of!(GlassU, misc) == 16);
assert!(std::mem::offset_of!(GlassU, shadow) == 32);
};
const MAX_GLASS: usize = 8;
const MAX_GLIGHTS: usize = 32;
const LEVELS: u32 = 7;
pub struct GlassRenderer {
/// The size it was made for; make a new one when the target changes size.
pub width: u32,
pub height: u32,
/// Mips in the frost pyramid (fewer than `LEVELS` for small targets).
mips: u32,
uniform: wgpu::Buffer,
glass: wgpu::Buffer,
lights: wgpu::Buffer,
sampler: wgpu::Sampler,
pipe: wgpu::RenderPipeline,
bgl: wgpu::BindGroupLayout,
down: wgpu::RenderPipeline,
down_bgl: wgpu::BindGroupLayout,
pyramid: wgpu::TextureView,
levels: Vec<wgpu::TextureView>,
down_bgs: Vec<wgpu::BindGroup>,
/// The pyramid's first level, keyed on the backdrop.
first_bg: crate::BindCache<wgpu::TextureView>,
/// Keyed on the backdrop and fluence.
bg: crate::BindCache<[wgpu::TextureView; 2]>,
staging: Option<rune_staging::Staging>,
}
pub(crate) fn section(name: &str) -> String {
let src = include_str!("shaders/glass.wgsl");
let (main, pyr) = src.split_once("// ---- pyramid ----").unwrap_or((src, ""));
if name == "pyramid" {
format!(
"@vertex\nfn vs(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4<f32> {{\n let uv = vec2<f32>(f32((vi << 1u) & 2u), f32(vi & 2u));\n return vec4<f32>(uv * 2.0 - 1.0, 0.0, 1.0);\n}}\n{pyr}"
)
} else {
main.to_string()
}
}
impl GlassRenderer {
pub fn new(device: &wgpu::Device, width: u32, height: u32, format: wgpu::TextureFormat) -> GlassRenderer {
let f = wgpu::ShaderStages::FRAGMENT;
let buf = |label, size, usage| device.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size, usage, mapped_at_creation: false });
use wgpu::BufferUsages as B;
let uniform = buf("glass u", std::mem::size_of::<GlassU>() as u64, B::UNIFORM | B::COPY_DST);
let glass = buf("glass", (MAX_GLASS * std::mem::size_of::<Glass>()) as u64, B::STORAGE | B::COPY_DST);
let lights = buf("glass lights", (MAX_GLIGHTS * std::mem::size_of::<GlassLight>()) as u64, B::STORAGE | B::COPY_DST);
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("glass linear"),
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
mipmap_filter: wgpu::MipmapFilterMode::Linear,
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
..Default::default()
});
let bgl = crate::layout(
device,
"glass",
&[
crate::bgl::uniform(0, f),
crate::bgl::storage(1, f),
crate::bgl::storage(2, f),
crate::bgl::f2(3, f),
crate::bgl::f2(4, f),
crate::bgl::f2(5, f),
crate::bgl::sampler(6, f),
],
);
let pipeline = |label: &str, src: String, entry: &str, layout: &wgpu::BindGroupLayout, fmt: wgpu::TextureFormat| {
let m = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some(label), source: wgpu::ShaderSource::Wgsl(src.into()) });
let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[Some(layout)], immediate_size: 0 });
device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(label),
layout: Some(&pl),
vertex: wgpu::VertexState { module: &m, entry_point: Some("vs"), compilation_options: Default::default(), buffers: &[] },
primitive: wgpu::PrimitiveState::default(),
depth_stencil: None,
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &m,
entry_point: Some(entry),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState { format: fmt, blend: None, write_mask: wgpu::ColorWrites::ALL })],
}),
multiview_mask: None,
cache: None,
})
};
let pipe = pipeline("glass", section("glass"), "fs", &bgl, format);
let down_bgl = crate::layout(device, "glass down", &[crate::bgl::f2(0, f), crate::bgl::sampler(1, f)]);
let down = pipeline("glass down", section("pyramid"), "fs_down", &down_bgl, wgpu::TextureFormat::Rgba16Float);
let half = (width.div_ceil(2).max(1), height.div_ceil(2).max(1));
let mips = LEVELS.min(32 - half.0.max(half.1).leading_zeros());
let tex = device.create_texture(&wgpu::TextureDescriptor {
label: Some("glass pyramid"),
size: wgpu::Extent3d { width: half.0, height: half.1, depth_or_array_layers: 1 },
mip_level_count: mips,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba16Float,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
});
let pyramid = tex.create_view(&Default::default());
let levels: Vec<wgpu::TextureView> = (0..mips)
.map(|k| tex.create_view(&wgpu::TextureViewDescriptor { base_mip_level: k, mip_level_count: Some(1), ..Default::default() }))
.collect();
let down_bgs = (1..mips as usize)
.map(|k| crate::bind(device, &down_bgl, [crate::tv(&levels[k - 1]), wgpu::BindingResource::Sampler(&sampler)]))
.collect();
GlassRenderer { width, height, mips, uniform, glass, lights, sampler, pipe, bgl, down, down_bgl, pyramid, levels, down_bgs, first_bg: crate::BindCache::new(), bg: crate::BindCache::new(), staging: None }
}
fn pass<'a>(encoder: &'a mut wgpu::CommandEncoder, target: &'a wgpu::TextureView, label: &'a str) -> wgpu::RenderPass<'a> {
encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some(label),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: target,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), store: wgpu::StoreOp::Store },
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
})
}
/// Draw `backdrop` (the lit frame, linear, filterable) with `glass` over it into `target` (a different texture).
/// `fluence` is the GI's fluence ([`crate::Inspect::fluence`]), or any black texture.
#[allow(clippy::too_many_arguments)]
pub fn render(
&mut self,
device: &wgpu::Device,
queue: &wgpu::Queue,
encoder: &mut wgpu::CommandEncoder,
glass: &[Glass],
lights: &[GlassLight],
settings: GlassSettings,
backdrop: &wgpu::TextureView,
fluence: &wgpu::TextureView,
target: &wgpu::TextureView,
) {
let ng = glass.len().min(MAX_GLASS);
let nl = lights.len().min(MAX_GLIGHTS);
let staging = self.staging.get_or_insert_with(|| rune_staging::Staging::new(device, queue));
staging.write_buffer(&self.glass, 0, bytemuck::cast_slice(&glass[..ng]));
staging.write_buffer(&self.lights, 0, bytemuck::cast_slice(&lights[..nl]));
let u = GlassU {
size: [self.width as f32, self.height as f32, ng as f32, nl as f32],
misc: [self.mips as f32, settings.env, settings.shadow, settings.caustic],
shadow: [settings.shadow_offset[0], settings.shadow_offset[1], settings.shadow_blur, 0.0],
};
staging.write_buffer(&self.uniform, 0, bytemuck::bytes_of(&u));
staging.flush(encoder);
if ng > 0 {
let first = self.first_bg.get(backdrop.clone(), || {
crate::bind(device, &self.down_bgl, [crate::tv(backdrop), wgpu::BindingResource::Sampler(&self.sampler)])
});
for k in 0..self.mips as usize {
let mut pass = Self::pass(encoder, &self.levels[k], "glass pyramid");
pass.set_pipeline(&self.down);
pass.set_bind_group(0, if k == 0 { first } else { &self.down_bgs[k - 1] }, &[]);
pass.draw(0..3, 0..1);
}
}
let bg = self.bg.get([backdrop.clone(), fluence.clone()], || {
crate::bind(
device,
&self.bgl,
[
self.uniform.as_entire_binding(),
self.glass.as_entire_binding(),
self.lights.as_entire_binding(),
crate::tv(backdrop),
crate::tv(&self.pyramid),
crate::tv(fluence),
wgpu::BindingResource::Sampler(&self.sampler),
],
)
});
let mut pass = Self::pass(encoder, target, "glass");
pass.set_pipeline(&self.pipe);
pass.set_bind_group(0, bg, &[]);
pass.draw(0..3, 0..1);
}
}
+137
View File
@@ -0,0 +1,137 @@
//! Small wgpu helpers shared by the light and glass renderers.
pub(crate) const COMMON: &str = include_str!("shaders/common.wgsl");
pub(crate) fn module(device: &wgpu::Device, label: &str, src: &str) -> wgpu::ShaderModule {
device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some(label),
source: wgpu::ShaderSource::Wgsl(format!("{COMMON}\n{src}").into()),
})
}
pub(crate) fn gi_section(name: &str) -> String {
let src = include_str!("shaders/gi.wgsl");
let mut parts = src.split("// ---- ");
let header = parts.next().unwrap_or_default();
let body = parts.find(|p| p.starts_with(name)).unwrap_or_default();
format!("{header}\n// ---- {body}")
}
pub(crate) mod bgl {
pub fn uniform(binding: u32, vis: wgpu::ShaderStages) -> wgpu::BindGroupLayoutEntry {
wgpu::BindGroupLayoutEntry {
binding,
visibility: vis,
ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None },
count: None,
}
}
pub fn storage(binding: u32, vis: wgpu::ShaderStages) -> wgpu::BindGroupLayoutEntry {
wgpu::BindGroupLayoutEntry {
binding,
visibility: vis,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: true },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
}
}
pub fn tex(binding: u32, vis: wgpu::ShaderStages, kind: wgpu::TextureSampleType, dim: wgpu::TextureViewDimension) -> wgpu::BindGroupLayoutEntry {
wgpu::BindGroupLayoutEntry {
binding,
visibility: vis,
ty: wgpu::BindingType::Texture { sample_type: kind, view_dimension: dim, multisampled: false },
count: None,
}
}
pub fn f2(binding: u32, vis: wgpu::ShaderStages) -> wgpu::BindGroupLayoutEntry {
tex(binding, vis, wgpu::TextureSampleType::Float { filterable: true }, wgpu::TextureViewDimension::D2)
}
pub fn f2a(binding: u32, vis: wgpu::ShaderStages) -> wgpu::BindGroupLayoutEntry {
tex(binding, vis, wgpu::TextureSampleType::Float { filterable: true }, wgpu::TextureViewDimension::D2Array)
}
pub fn u2(binding: u32, vis: wgpu::ShaderStages) -> wgpu::BindGroupLayoutEntry {
tex(binding, vis, wgpu::TextureSampleType::Uint, wgpu::TextureViewDimension::D2)
}
pub fn store(binding: u32, dim: wgpu::TextureViewDimension) -> wgpu::BindGroupLayoutEntry {
wgpu::BindGroupLayoutEntry {
binding,
visibility: wgpu::ShaderStages::COMPUTE,
ty: wgpu::BindingType::StorageTexture {
access: wgpu::StorageTextureAccess::WriteOnly,
format: wgpu::TextureFormat::Rgba16Float,
view_dimension: dim,
},
count: None,
}
}
pub fn sampler(binding: u32, vis: wgpu::ShaderStages) -> wgpu::BindGroupLayoutEntry {
wgpu::BindGroupLayoutEntry {
binding,
visibility: vis,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
}
}
}
pub(crate) fn layout(device: &wgpu::Device, label: &str, entries: &[wgpu::BindGroupLayoutEntry]) -> wgpu::BindGroupLayout {
device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some(label), entries })
}
pub(crate) fn compute(device: &wgpu::Device, label: &str, m: &wgpu::ShaderModule, entry: &str, bgls: &[&wgpu::BindGroupLayout]) -> wgpu::ComputePipeline {
let bgls: Vec<Option<&wgpu::BindGroupLayout>> = bgls.iter().map(|b| Some(*b)).collect();
let pl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some(label), bind_group_layouts: &bgls, immediate_size: 0 });
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some(label),
layout: Some(&pl),
module: m,
entry_point: Some(entry),
compilation_options: Default::default(),
cache: None,
})
}
pub(crate) fn texture(device: &wgpu::Device, label: &str, w: u32, h: u32, layers: u32, format: wgpu::TextureFormat, usage: wgpu::TextureUsages) -> wgpu::Texture {
device.create_texture(&wgpu::TextureDescriptor {
label: Some(label),
size: wgpu::Extent3d { width: w.max(1), height: h.max(1), depth_or_array_layers: layers },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage,
view_formats: &[],
})
}
pub(crate) fn bind<const N: usize>(device: &wgpu::Device, layout: &wgpu::BindGroupLayout, entries: [wgpu::BindingResource<'_>; N]) -> wgpu::BindGroup {
let mut binding = 0;
let entries = entries.map(|resource| {
binding += 1;
wgpu::BindGroupEntry { binding: binding - 1, resource }
});
device.create_bind_group(&wgpu::BindGroupDescriptor { label: None, layout, entries: &entries })
}
/// The last bind group made, reused while the resources it's keyed on stay the same.
pub(crate) struct BindCache<K>(Option<(K, wgpu::BindGroup)>);
impl<K: PartialEq> BindCache<K> {
pub(crate) const fn new() -> Self {
BindCache(None)
}
pub(crate) fn get(&mut self, key: K, make: impl FnOnce() -> wgpu::BindGroup) -> &wgpu::BindGroup {
if self.0.as_ref().is_none_or(|(k, _)| *k != key) {
self.0 = Some((key, make()));
}
&self.0.as_ref().expect("just set").1
}
}
pub(crate) fn tv(v: &wgpu::TextureView) -> wgpu::BindingResource<'_> {
wgpu::BindingResource::TextureView(v)
}
+789
View File
@@ -0,0 +1,789 @@
//! rune-light: real-time lighting for Rune UIs.
//!
//! Every Rune element is an analytic rounded rect, so a frame is an exact 2D distance field for free. rune-light
//! extrudes the elements marked as occluders into short slabs standing on the UI plane and lights them:
//!
//! 1. **Surface buffer** (full res, instanced quads): topmost primitive's own SDF, outward gradient, top z, id.
//! 2. **Field** (half res, compute): exact union SDF of occluders + the nearest slab's z range, and a GI distance.
//! 3. **Soft shadows** (half res, compute): per light, sphere tracing the field from each receiver toward a
//! spherical source with Quílez/Aaltonen's penumbra estimate; contact-hardening comes out of the geometry.
//! Optional "air" trace at the light's height for god rays.
//! 4. **GI** (optional, quarter res): 2D radiance cascades; emitters light their neighbours, cards bounce.
//! 5. **Composite** (full res): UI colour as albedo, bevel normals from the SDF, GGX highlights, rim hairlines,
//! contact AO, text with a contrast floor, soft shoulder, sRGB + dither.
//!
//! Zero lights and no emitters: [`LightRenderer::render`] records nothing and returns `false`; draw the UI as usual.
#![forbid(unsafe_code)]
#[cfg(all(test, not(target_arch = "wasm32")))]
mod abi_tests;
pub mod cpu;
pub mod glass;
mod gpu;
mod render;
mod targets;
pub use glass::Glass;
pub use glass::GlassLight;
pub use glass::GlassRenderer;
pub use glass::GlassSettings;
use gpu::{BindCache, bgl, bind, compute, gi_section, layout, module, texture, tv};
use targets::Targets;
use bytemuck::{Pod, Zeroable};
pub const MAX_LIGHTS: usize = 8;
pub const FLAG_OCCLUDER: u32 = 1;
pub const FLAG_EMISSIVE: u32 = 2;
pub const FLAG_RAISED: u32 = 4;
/// Seen only by the GI tracer's distance field: marks where [`Scene::emission`] may glow. Never a surface.
pub const FLAG_GI_HINT: u32 = 8;
/// One lit primitive, in device pixels. Mirrors Rune's `Instance` rect/radii plus lighting fields.
#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable, PartialEq)]
pub struct Prim {
/// x, y, w, h
pub rect: [f32; 4],
/// top-left, top-right, bottom-right, bottom-left
pub radii: [f32; 4],
/// bottom z, top z, bevel width, bevel height
pub z: [f32; 4],
/// gloss, roughness, flags, unused
pub mat: [f32; 4],
/// linear emitted radiance rgb (GI), unused
pub emit: [f32; 4],
/// albedo rgb for bounce, unused
pub albedo: [f32; 4],
}
const _: () = {
assert!(std::mem::size_of::<Prim>() == 96);
assert!(std::mem::offset_of!(Prim, rect) == 0);
assert!(std::mem::offset_of!(Prim, radii) == 16);
assert!(std::mem::offset_of!(Prim, z) == 32);
assert!(std::mem::offset_of!(Prim, mat) == 48);
assert!(std::mem::offset_of!(Prim, emit) == 64);
assert!(std::mem::offset_of!(Prim, albedo) == 80);
};
impl Prim {
/// A flat surface (receives light, casts nothing).
pub fn rect(x: f32, y: f32, w: f32, h: f32) -> Prim {
Prim {
rect: [x, y, w, h],
radii: [0.0; 4],
z: [0.0, 0.0, 0.0, 0.0],
mat: [0.0, 0.6, 0.0, 0.0],
emit: [0.0; 4],
albedo: [0.5, 0.5, 0.5, 0.0],
}
}
pub fn radius(mut self, r: f32) -> Prim {
self.radii = [r; 4];
self
}
pub fn radii(mut self, r: [f32; 4]) -> Prim {
self.radii = r;
self
}
/// Sit on a surface at height `z` (a chip on a card): the base for `raised`, and the receiver height.
pub fn on(mut self, z: f32) -> Prim {
self.z[0] = z;
self.z[1] = z;
self
}
/// Stand `height` px proud of its base and cast shadows.
pub fn raised(mut self, height: f32) -> Prim {
self.z[1] = self.z[0] + height;
self.set(FLAG_OCCLUDER, height > 0.0)
}
/// Float between `bottom` and `top` (a popover): its shadow detaches from it.
pub fn floating(mut self, bottom: f32, top: f32) -> Prim {
self.z[0] = bottom;
self.z[1] = top;
self.set(FLAG_OCCLUDER, true)
}
/// Bevel the edge: `width` px of rounded shoulder rising `height` px, for normals and highlights.
pub fn bevel(mut self, width: f32, height: f32) -> Prim {
self.z[2] = width;
self.z[3] = height;
self.set(FLAG_RAISED, width > 0.0)
}
pub fn gloss(mut self, gloss: f32, roughness: f32) -> Prim {
self.mat[0] = gloss;
self.mat[1] = roughness;
self
}
/// Glow with linear radiance `rgb` (feeds the GI pass; the pixel itself is never darkened).
pub fn emissive(mut self, rgb: [f32; 3]) -> Prim {
self.emit = [rgb[0], rgb[1], rgb[2], 0.0];
let on = rgb.iter().any(|c| *c > 0.0);
self.set(FLAG_EMISSIVE, on)
}
/// Turn this rect into a GI hint: the region where the extra emission texture may glow (around an electric
/// border, say), so the cascades' sphere tracing slows down there instead of stepping over it.
pub fn gi_hint(mut self) -> Prim {
self.mat[2] = FLAG_GI_HINT as f32;
self
}
pub fn albedo(mut self, rgb: [f32; 3]) -> Prim {
self.albedo = [rgb[0], rgb[1], rgb[2], 0.0];
self
}
pub fn flags(&self) -> u32 {
self.mat[2] as u32
}
fn set(mut self, flag: u32, on: bool) -> Prim {
let f = if on { self.flags() | flag } else { self.flags() & !flag };
self.mat[2] = f as f32;
self
}
/// From a Rune uber-quad instance's rect and radii (device px); lighting fields start flat.
pub fn from_rune(rect: [f32; 4], radii: [f32; 4]) -> Prim {
Prim::rect(rect[0], rect[1], rect[2], rect[3]).radii(radii)
}
}
/// A light, in device pixels. `z` is height above the UI plane.
#[repr(C)]
#[derive(Clone, Copy, Debug, Pod, Zeroable, PartialEq)]
pub struct Light {
/// x, y, z, source radius
pub pos: [f32; 4],
/// linear rgb × intensity, range
pub color: [f32; 4],
/// spot axis (unit), half-angle (0 = point)
pub axis: [f32; 4],
/// shafts, bulb glow, specular, softness
pub extra: [f32; 4],
}
const _: () = {
assert!(std::mem::size_of::<Light>() == 64);
assert!(std::mem::offset_of!(Light, pos) == 0);
assert!(std::mem::offset_of!(Light, color) == 16);
assert!(std::mem::offset_of!(Light, axis) == 32);
assert!(std::mem::offset_of!(Light, extra) == 48);
};
impl Light {
pub fn point(x: f32, y: f32, z: f32) -> Light {
Light {
pos: [x, y, z, 12.0],
color: [1.0, 1.0, 1.0, 2400.0],
axis: [0.0, 0.0, -1.0, 0.0],
extra: [0.0, 0.0, 1.0, 1.0],
}
}
/// Linear colour; intensity is separate.
pub fn color(mut self, rgb: [f32; 3]) -> Light {
let i = self.intensity_of();
self.color[..3].copy_from_slice(&rgb);
self.intensity(i)
}
/// Irradiance 1.0 at 200 device px from the source (before n·l).
pub fn intensity(mut self, i: f32) -> Light {
let cur = self.intensity_of();
let s = if cur > 0.0 { i / cur } else { 0.0 };
if cur > 0.0 {
for c in &mut self.color[..3] {
*c *= s;
}
} else {
self.color[..3].copy_from_slice(&[i, i, i]);
}
self
}
fn intensity_of(&self) -> f32 {
self.color[0].max(self.color[1]).max(self.color[2])
}
/// Source radius: bigger sources throw softer, wider penumbrae and broader highlights.
pub fn radius(mut self, r: f32) -> Light {
self.pos[3] = r;
self
}
/// Where the light fades to nothing (windowed inverse square).
pub fn range(mut self, r: f32) -> Light {
self.color[3] = r;
self
}
/// Aim a torch-profile cone (Arcade's Outbreak beam) along `axis` with `half_angle` radians.
pub fn spot(mut self, axis: [f32; 3], half_angle: f32) -> Light {
let l = (axis[0] * axis[0] + axis[1] * axis[1] + axis[2] * axis[2]).sqrt().max(1e-6);
self.axis = [axis[0] / l, axis[1] / l, axis[2] / l, half_angle];
self
}
/// God rays: in-scatter strength of the air term (flatland wedges at the light's height).
pub fn shafts(mut self, s: f32) -> Light {
self.extra[0] = s;
self
}
/// Show the source itself as a soft bloom.
pub fn bulb(mut self, g: f32) -> Light {
self.extra[1] = g;
self
}
pub fn specular(mut self, s: f32) -> Light {
self.extra[2] = s;
self
}
/// Multiplies the radius for shadows only.
pub fn softness(mut self, s: f32) -> Light {
self.extra[3] = s;
self
}
/// Scales the whole light (fade in/out: lights cool, never cut).
pub fn scaled(mut self, k: f32) -> Light {
for c in &mut self.color[..3] {
*c *= k;
}
self.extra[0] *= k;
self.extra[1] *= k;
self
}
}
#[derive(Clone, Copy, Debug)]
pub struct TextPolicy {
/// Text never gets darker than this share of its design colour.
pub floor: f32,
/// Nor brighter than this.
pub ceiling: f32,
/// 0 = text ignores lighting, 1 = text takes the surface's light (clamped).
pub lit: f32,
/// Share of the surface highlight that shows over glyphs.
pub specular: f32,
}
impl Default for TextPolicy {
fn default() -> Self {
TextPolicy { floor: 0.82, ceiling: 1.25, lit: 1.0, specular: 0.15 }
}
}
#[derive(Clone, Copy, Debug)]
pub struct Gi {
/// Fluence → irradiance on surfaces.
pub strength: f32,
/// Fluence added as glow in the air (visible on dark backgrounds).
pub air: f32,
/// Share of the direct light a card re-emits (one bounce).
pub bounce: f32,
/// Absorption per gi texel inside cards (how far light bleeds into them).
pub absorption: f32,
/// Gain on [`Scene::emission`] (linear radiance per gi texel).
pub emission: f32,
}
impl Default for Gi {
fn default() -> Self {
Gi { strength: 1.0, air: 0.12, bounce: 0.25, absorption: 0.35, emission: 1.0 }
}
}
#[derive(Clone, Copy, Debug)]
pub struct Settings {
/// Linear ambient irradiance; the UI looks exactly as designed at 1.0.
pub ambient: [f32; 3],
pub exposure: f32,
pub text: TextPolicy,
pub gi: Option<Gi>,
pub background_gloss: f32,
pub background_roughness: f32,
/// Contact darkening on the floor around raised cards.
pub contact_ao: f32,
/// Hairline rim catch on occluder edges facing a light.
pub rim: f32,
/// God-ray strength over occluders relative to the gaps.
pub shafts_over: f32,
/// Added to the UI colour as albedo for direct light and GI only (linear). Dark UI colours are nearly black as
/// materials; this lets light pools and shadows read on them while ambient keeps the designed look.
pub albedo_floor: f32,
/// Seed for the dither pattern; output is a pure function of inputs, time and seed.
pub seed: f32,
pub time: f32,
}
impl Default for Settings {
fn default() -> Self {
Settings {
ambient: [0.55, 0.55, 0.58],
exposure: 1.0,
text: TextPolicy::default(),
gi: None,
background_gloss: 0.4,
background_roughness: 0.55,
contact_ao: 0.35,
rim: 0.6,
shafts_over: 0.35,
albedo_floor: 0.025,
seed: 0.0,
time: 0.0,
}
}
}
/// What to light this frame.
pub struct Scene<'a> {
pub prims: &'a [Prim],
pub lights: &'a [Light],
pub settings: Settings,
/// Extra linear emission at output resolution (effect layers such as electric arcs) that enters the GI as
/// glowing medium. Mark where it can be with [`Prim::gi_hint`] rects.
pub emission: Option<&'a wgpu::TextureView>,
}
/// GPU time per pass in milliseconds (needs `Features::TIMESTAMP_QUERY`).
#[derive(Clone, Copy, Debug, Default)]
pub struct Timings {
pub field: f64,
pub shadows: f64,
pub gi: f64,
/// GI breakdown: media from the primitives, each cascade (index = level), fluence.
pub gi_scene: f64,
pub cascades: [f64; CASCADES as usize],
pub fluence: f64,
/// Surface buffer + composite render passes (frame total minus the compute passes).
pub raster: f64,
/// First pass start to last pass end.
pub total: f64,
}
#[repr(C)]
#[derive(Clone, Copy, Pod, Zeroable)]
struct FrameU {
sf: [f32; 4],
gs: [f32; 4],
ambient: [f32; 4],
counts: [u32; 4],
misc: [f32; 4],
text: [f32; 4],
gi: [f32; 4],
bg: [f32; 4],
ext: [f32; 4],
}
#[repr(C)]
#[derive(Clone, Copy, Pod, Zeroable)]
struct Cascade {
n: u32,
count: u32,
merge: u32,
pad1: u32,
}
const _: () = {
assert!(std::mem::size_of::<FrameU>() == 144);
assert!(std::mem::offset_of!(FrameU, sf) == 0);
assert!(std::mem::offset_of!(FrameU, gs) == 16);
assert!(std::mem::offset_of!(FrameU, ambient) == 32);
assert!(std::mem::offset_of!(FrameU, counts) == 48);
assert!(std::mem::offset_of!(FrameU, misc) == 64);
assert!(std::mem::offset_of!(FrameU, text) == 80);
assert!(std::mem::offset_of!(FrameU, gi) == 96);
assert!(std::mem::offset_of!(FrameU, bg) == 112);
assert!(std::mem::offset_of!(FrameU, ext) == 128);
assert!(std::mem::size_of::<Cascade>() == 16);
assert!(std::mem::offset_of!(Cascade, n) == 0);
assert!(std::mem::offset_of!(Cascade, count) == 4);
assert!(std::mem::offset_of!(Cascade, merge) == 8);
assert!(std::mem::offset_of!(Cascade, pad1) == 12);
};
pub const CASCADES: u32 = 5;
const QUERIES: u32 = 12 + 2 * CASCADES;
const GI_SCALE: f32 = 0.125;
pub struct LightRenderer {
pub width: u32,
pub height: u32,
field_size: (u32, u32),
gi_size: (u32, u32),
frame: wgpu::Buffer,
prims: rune_staging::GrowBuffer,
lights: wgpu::Buffer,
cascade_u: Vec<wgpu::Buffer>,
own_u: Vec<wgpu::Buffer>,
sampler: wgpu::Sampler,
gbuf_pipe: wgpu::RenderPipeline,
gbuf_bgl: wgpu::BindGroupLayout,
gbuf_bg: wgpu::BindGroup,
field_pipe: wgpu::ComputePipeline,
field_bgl: wgpu::BindGroupLayout,
shadow_pipe: wgpu::ComputePipeline,
gi_bg0: wgpu::BindGroup,
scene_pipe: wgpu::ComputePipeline,
scene_bgl: wgpu::BindGroupLayout,
cascade_pipe: wgpu::ComputePipeline,
cascade_bgl: wgpu::BindGroupLayout,
fluence_pipe: wgpu::ComputePipeline,
fluence_bgl: wgpu::BindGroupLayout,
comp_pipe: wgpu::RenderPipeline,
noop_pipe: wgpu::ComputePipeline,
comp_bgl: wgpu::BindGroupLayout,
black: wgpu::TextureView,
/// One black view per cascade, for `inspect` before GI runs.
blacks: Vec<wgpu::TextureView>,
t: Targets,
/// Keyed on the prim buffer and the extra emission.
scene_bg: BindCache<(wgpu::Buffer, Option<wgpu::TextureView>)>,
/// Keyed on the prim buffer, base, text and fluence.
comp_bg: BindCache<(wgpu::Buffer, [wgpu::TextureView; 3])>,
query: Option<(wgpu::QuerySet, wgpu::Buffer, wgpu::Buffer)>,
/// Whether the last timed frame ran GI; without it the GI queries aren't written.
timed_gi: bool,
/// Compute passes the last `render` recorded.
compute_passes: u32,
period: f32,
staging: rune_staging::Staging,
/// Formats the composite can write; float formats get linear light, other non-sRGB formats get a manual sRGB
/// encode + dither.
pub output_format: wgpu::TextureFormat,
/// Also trace every cascade's own interval without the merge, for inspection ([`LightRenderer::inspect`]).
pub inspect: bool,
}
/// The GI pass's intermediate buffers, for inspection and visualisation. All are `Rgba16Float`.
pub struct Inspect<'a> {
/// Half resolution: x occluder distance, y/z nearest occluder's z range, w distance to anything the GI sees.
pub field: &'a wgpu::TextureView,
/// gi resolution: rgb σ·L of emitters, a σ.
pub emission: &'a wgpu::TextureView,
/// gi resolution: rgb coverage × bounce radiance, a card coverage.
pub occluders: &'a wgpu::TextureView,
/// Per level, merged with every level above: probe (px, py) direction d at texel (px·b + d mod b, py·b + d / b),
/// b = 2^(n+1); rgb radiance, a transmittance.
pub merged: &'a [wgpu::TextureView],
/// Per level, its own interval only (valid when `inspect` was on for the frame).
pub own: &'a [wgpu::TextureView],
/// gi resolution fluence (cascade 0's directions averaged).
pub fluence: &'a wgpu::TextureView,
/// Probe grid of cascade 0 in gi texels.
pub gi_size: (u32, u32),
/// Output px per gi texel.
pub texel: f32,
pub field_size: (u32, u32),
}
impl LightRenderer {
/// `width`×`height` device px output in `output_format`. Timestamps are recorded when the device has
/// `Features::TIMESTAMP_QUERY`.
pub fn new(device: &wgpu::Device, queue: &wgpu::Queue, width: u32, height: u32, output_format: wgpu::TextureFormat) -> LightRenderer {
use wgpu::ShaderStages as S;
let c = S::COMPUTE;
let f = S::FRAGMENT;
let vf = S::VERTEX_FRAGMENT;
let frame = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("light frame"),
size: std::mem::size_of::<FrameU>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let prims = rune_staging::GrowBuffer::new(
device,
"light prims",
wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
std::mem::size_of::<Prim>(),
256,
0,
);
let lights = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("lights"),
size: (MAX_LIGHTS * std::mem::size_of::<Light>()) as u64,
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let cascade_buf = |n: u32, merge: u32| {
let b = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("cascade"),
size: std::mem::size_of::<Cascade>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let c = Cascade { n, count: CASCADES, merge, pad1: 0 };
queue.write_buffer(&b, 0, bytemuck::bytes_of(&c));
b
};
let cascade_u: Vec<wgpu::Buffer> = (0..CASCADES).map(|n| cascade_buf(n, 1)).collect();
let own_u: Vec<wgpu::Buffer> = (0..CASCADES).map(|n| cascade_buf(n, 0)).collect();
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("light linear"),
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
..Default::default()
});
let gbuf_bgl = layout(device, "gbuf", &[bgl::uniform(0, vf), bgl::storage(1, vf)]);
let gm = module(device, "light gbuffer", include_str!("shaders/gbuffer.wgsl"));
let gpl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[Some(&gbuf_bgl)], immediate_size: 0 });
let gbuf_pipe = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("light gbuffer"),
layout: Some(&gpl),
vertex: wgpu::VertexState { module: &gm, entry_point: Some("vs"), compilation_options: Default::default(), buffers: &[] },
primitive: wgpu::PrimitiveState { topology: wgpu::PrimitiveTopology::TriangleStrip, ..Default::default() },
depth_stencil: None,
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &gm,
entry_point: Some("fs"),
compilation_options: Default::default(),
targets: &[
Some(wgpu::ColorTargetState { format: wgpu::TextureFormat::Rgba16Float, blend: None, write_mask: wgpu::ColorWrites::ALL }),
Some(wgpu::ColorTargetState { format: wgpu::TextureFormat::R32Uint, blend: None, write_mask: wgpu::ColorWrites::ALL }),
],
}),
multiview_mask: None,
cache: None,
});
let field_bgl = layout(device, "field", &[bgl::uniform(0, c), bgl::storage(1, c), bgl::store(2, wgpu::TextureViewDimension::D2)]);
let fm = module(device, "light field", include_str!("shaders/field.wgsl"));
let field_pipe = compute(device, "light field", &fm, "main", &[&field_bgl]);
let shadow_bgl = layout(
device,
"shadow",
&[
bgl::uniform(0, c),
bgl::storage(1, c),
bgl::f2(2, c),
bgl::sampler(3, c),
bgl::f2(4, c),
bgl::store(5, wgpu::TextureViewDimension::D2Array),
bgl::store(6, wgpu::TextureViewDimension::D2Array),
],
);
let sm = module(device, "light shadow", include_str!("shaders/shadow.wgsl"));
let shadow_pipe = compute(device, "light shadow", &sm, "main", &[&shadow_bgl]);
let gi_bgl0 = layout(device, "gi0", &[bgl::uniform(0, c)]);
let scene_bgl = layout(
device,
"gi scene",
&[
bgl::storage(0, c),
bgl::storage(1, c),
bgl::f2a(2, c),
bgl::f2(3, c),
bgl::sampler(4, c),
bgl::store(5, wgpu::TextureViewDimension::D2),
bgl::store(6, wgpu::TextureViewDimension::D2),
],
);
let scene_pipe = compute(device, "gi scene", &module(device, "gi scene", &gi_section("scene")), "scene", &[&gi_bgl0, &scene_bgl]);
let cascade_bgl = layout(
device,
"gi cascade",
&[
bgl::uniform(0, c),
bgl::f2(1, c),
bgl::f2(2, c),
bgl::f2(3, c),
bgl::sampler(4, c),
bgl::f2(5, c),
bgl::store(6, wgpu::TextureViewDimension::D2),
bgl::f2(7, c),
],
);
let cascade_pipe =
compute(device, "gi cascade", &module(device, "gi cascade", &gi_section("cascades")), "cascade", &[&gi_bgl0, &cascade_bgl]);
let fluence_bgl = layout(device, "gi fluence", &[bgl::f2(0, c), bgl::store(1, wgpu::TextureViewDimension::D2)]);
let fluence_pipe =
compute(device, "gi fluence", &module(device, "gi fluence", &gi_section("fluence")), "fluence", &[&gi_bgl0, &fluence_bgl]);
let comp_bgl = layout(
device,
"composite",
&[
bgl::uniform(0, f),
bgl::storage(1, f),
bgl::storage(2, f),
bgl::f2(3, f),
bgl::f2(4, f),
bgl::f2(5, f),
bgl::u2(6, f),
bgl::f2a(7, f),
bgl::f2a(8, f),
bgl::f2(9, f),
bgl::f2(10, f),
bgl::sampler(11, f),
],
);
let cm = module(device, "light composite", include_str!("shaders/composite.wgsl"));
let cpl = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: None, bind_group_layouts: &[Some(&comp_bgl)], immediate_size: 0 });
let comp_pipe = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("light composite"),
layout: Some(&cpl),
vertex: wgpu::VertexState { module: &cm, entry_point: Some("vs"), compilation_options: Default::default(), buffers: &[] },
primitive: wgpu::PrimitiveState::default(),
depth_stencil: None,
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &cm,
entry_point: Some("fs"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState { format: output_format, blend: None, write_mask: wgpu::ColorWrites::ALL })],
}),
multiview_mask: None,
cache: None,
});
let noop_pipe = compute(device, "light ts marker", &module(device, "noop", "@compute @workgroup_size(1) fn noop() {}"), "noop", &[]);
let gbuf_bg = bind(device, &gbuf_bgl, [frame.as_entire_binding(), prims.as_entire_binding()]);
let gi_bg0 = bind(device, &gi_bgl0, [frame.as_entire_binding()]);
let black = texture(device, "light black", 1, 1, 1, wgpu::TextureFormat::Rgba16Float, wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST);
queue.write_texture(
wgpu::TexelCopyTextureInfo { texture: &black, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
&[0u8; 8],
wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(8), rows_per_image: Some(1) },
wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 },
);
let black = black.create_view(&Default::default());
let query = device.features().contains(wgpu::Features::TIMESTAMP_QUERY).then(|| {
let qs = device.create_query_set(&wgpu::QuerySetDescriptor { label: Some("light ts"), ty: wgpu::QueryType::Timestamp, count: QUERIES });
let resolve = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("light ts resolve"),
size: QUERIES as u64 * 8,
usage: wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC,
mapped_at_creation: false,
});
let read = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("light ts read"),
size: QUERIES as u64 * 8,
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
});
(qs, resolve, read)
});
let field_size = (width.div_ceil(2), height.div_ceil(2));
let gi_size = ((width.div_ceil(8)).div_ceil(16) * 16, (height.div_ceil(8)).div_ceil(16) * 16);
let t = Self::targets(device, width, height, field_size, &frame, prims.buffer(), &lights, &sampler, [&field_bgl, &shadow_bgl]);
LightRenderer {
width,
height,
field_size,
gi_size,
frame,
prims,
lights,
cascade_u,
own_u,
sampler,
gbuf_pipe,
gbuf_bgl,
gbuf_bg,
field_pipe,
field_bgl,
shadow_pipe,
gi_bg0,
scene_pipe,
scene_bgl,
cascade_pipe,
cascade_bgl,
fluence_pipe,
fluence_bgl,
comp_pipe,
noop_pipe,
comp_bgl,
blacks: vec![black.clone(); CASCADES as usize],
black,
t,
scene_bg: BindCache::new(),
comp_bg: BindCache::new(),
query,
timed_gi: false,
compute_passes: 0,
period: queue.get_timestamp_period(),
staging: rune_staging::Staging::new(device, queue),
output_format,
inspect: false,
}
}
/// Blocking read of the last submitted frame's pass times. Call after the encoder from `render` was submitted.
pub fn read_timings(&self, device: &wgpu::Device) -> Option<Timings> {
let (_, _, read) = self.query.as_ref()?;
let slice = read.slice(..);
// A map that failed (a lost device) shows as `get_mapped_range`'s error below; a lost or
// removed device reads as no timings.
slice.map_async(wgpu::MapMode::Read, |_| {});
rune_staging::health::poll(device, wgpu::PollType::wait_indefinitely()).ok()?;
let ticks: Vec<u64> = {
let data = slice.get_mapped_range().ok()?;
bytemuck::cast_slice(&data).to_vec()
};
read.unmap();
let ms = |a: u32, b: u32| ticks[b as usize].saturating_sub(ticks[a as usize]) as f64 * self.period as f64 / 1e6;
let gi_ms = |a: u32, b: u32| if self.timed_gi { ms(a, b) } else { 0.0 };
let (field, shadows, total) = (ms(1, 2), ms(3, 4), ms(0, self.last_query()));
let gi_scene = gi_ms(5, 6);
let mut cascades = [0.0; CASCADES as usize];
for (n, c) in cascades.iter_mut().enumerate() {
*c = gi_ms(7 + 2 * n as u32, 8 + 2 * n as u32);
}
let fluence = gi_ms(7 + 2 * CASCADES, 8 + 2 * CASCADES);
let gi = gi_scene + cascades.iter().sum::<f64>() + fluence;
// The surface and composite render passes overlap the compute work on tile GPUs, so they are reported
// together as the rest of the frame.
Some(Timings { field, shadows, gi, gi_scene, cascades, fluence, raster: (total - field - shadows - gi).max(0.0), total })
}
/// The frame's closing timestamp: after the GI passes, or in the first GI slot when GI didn't run.
fn last_query(&self) -> u32 {
if self.timed_gi { QUERIES - 1 } else { 5 }
}
/// The half-resolution visibility texture (2 layers × 4 lights), for debugging and the CPU reference check.
pub fn visibility_texture(&self) -> &wgpu::Texture {
&self.t.vis_tex
}
pub fn field_size(&self) -> (u32, u32) {
self.field_size
}
/// The GI pass's intermediate buffers from the last recorded frame.
/// Before GI first runs, its buffers are black.
pub fn inspect(&self) -> Inspect<'_> {
let g = self.t.gi.as_ref();
Inspect {
field: &self.t.field,
emission: g.map_or(&self.black, |g| &g.scene_emit),
occluders: g.map_or(&self.black, |g| &g.scene_occ),
merged: g.map_or(&self.blacks, |g| &g.levels),
own: g.map_or(&self.blacks, |g| &g.own),
fluence: g.map_or(&self.black, |g| &g.fluence),
gi_size: self.gi_size,
texel: 1.0 / GI_SCALE,
field_size: self.field_size,
}
}
}
+249
View File
@@ -0,0 +1,249 @@
//! `LightRenderer::render`: upload a scene and record its lighting passes.
use super::*;
impl LightRenderer {
/// Light `base` (the UI without text, linear, filterable) and composite `text` (premultiplied linear) over it into
/// `target`. Returns false and records nothing when there's nothing to light.
pub fn render(
&mut self,
device: &wgpu::Device,
_queue: &wgpu::Queue,
encoder: &mut wgpu::CommandEncoder,
scene: &Scene<'_>,
base: &wgpu::TextureView,
text: &wgpu::TextureView,
target: &wgpu::TextureView,
) -> bool {
let any_emit = scene.prims.iter().any(|p| p.flags() & FLAG_EMISSIVE != 0) || scene.emission.is_some();
if scene.lights.is_empty() && !(any_emit && scene.settings.gi.is_some()) {
return false;
}
let s = &scene.settings;
if self.prims.ensure(device, scene.prims.len()) {
self.rebind_prims(device);
}
if !scene.prims.is_empty() {
self.staging.write_buffer(self.prims.buffer(), 0, bytemuck::cast_slice(scene.prims));
}
let nl = scene.lights.len().min(MAX_LIGHTS);
if nl > 0 {
self.staging.write_buffer(&self.lights, 0, bytemuck::cast_slice(&scene.lights[..nl]));
}
let zmax = scene.prims.iter().filter(|p| p.flags() & FLAG_OCCLUDER != 0).fold(0.0f32, |m, p| m.max(p.z[1]));
let shafts = scene.lights.iter().any(|l| l.extra[0] > 0.0);
let gi = s.gi.filter(|_| any_emit || s.gi.is_some_and(|g| g.bounce > 0.0 && nl > 0));
let float_target = matches!(self.output_format, wgpu::TextureFormat::Rgba16Float | wgpu::TextureFormat::Rgba32Float);
let encode = !self.output_format.is_srgb() && !float_target;
let extra = gi.is_some() && scene.emission.is_some();
let flags = gi.is_some() as u32
| (shafts as u32) << 1
| (encode as u32) << 2
| ((s.contact_ao > 0.0) as u32) << 3
| (extra as u32) << 4;
if gi.is_some() {
self.gi_targets(device);
if self.inspect {
self.own_targets(device);
}
}
self.timed_gi = gi.is_some();
let g = gi.unwrap_or_default();
let fu = FrameU {
sf: [self.width as f32, self.height as f32, self.field_size.0 as f32, self.field_size.1 as f32],
gs: [self.gi_size.0 as f32, self.gi_size.1 as f32, 0.5, GI_SCALE],
ambient: [s.ambient[0], s.ambient[1], s.ambient[2], s.exposure],
counts: [scene.prims.len() as u32, nl as u32, CASCADES, flags],
misc: [zmax, s.time, s.seed, s.shafts_over],
text: [s.text.floor, s.text.ceiling, s.text.lit, s.text.specular],
gi: [g.strength, g.air, g.bounce, g.absorption],
bg: [s.background_gloss, s.background_roughness, s.contact_ao, s.rim],
ext: [s.albedo_floor, g.emission, 0.0, 0.0],
};
self.staging.write_buffer(&self.frame, 0, bytemuck::bytes_of(&fu));
self.staging.flush(encoder);
let ts = |i: u32| {
self.query.as_ref().map(|(qs, _, _)| wgpu::ComputePassTimestampWrites {
query_set: qs,
beginning_of_pass_write_index: Some(i),
end_of_pass_write_index: Some(i + 1),
})
};
// Render-pass timestamps are unreliable on tile GPUs, so the two render passes are timed between the end of
// an empty marker pass before them and the start of the compute pass (or marker) after them.
let marker = |encoder: &mut wgpu::CommandEncoder, passes: &mut u32, begin: Option<u32>, end: Option<u32>| {
if let Some((qs, _, _)) = &self.query {
*passes += 1;
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
label: Some("light ts marker"),
timestamp_writes: Some(wgpu::ComputePassTimestampWrites {
query_set: qs,
beginning_of_pass_write_index: begin,
end_of_pass_write_index: end,
}),
});
pass.set_pipeline(&self.noop_pipe);
pass.dispatch_workgroups(1, 1, 1);
}
};
let mut passes = 0;
marker(encoder, &mut passes, None, Some(0));
{
fn clear(v: &wgpu::TextureView, c: wgpu::Color) -> wgpu::RenderPassColorAttachment<'_> {
wgpu::RenderPassColorAttachment {
view: v,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations { load: wgpu::LoadOp::Clear(c), store: wgpu::StoreOp::Store },
}
}
let gb0 = clear(&self.t.gb0, wgpu::Color { r: 1e4, g: 0.0, b: 0.0, a: 0.0 });
let gb1 = clear(&self.t.gb1, wgpu::Color::TRANSPARENT);
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("light surface"),
color_attachments: &[Some(gb0), Some(gb1)],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
if !scene.prims.is_empty() {
pass.set_pipeline(&self.gbuf_pipe);
pass.set_bind_group(0, &self.gbuf_bg, &[]);
pass.draw(0..4, 0..scene.prims.len() as u32);
}
}
let wg = |w: u32, h: u32| (w.div_ceil(8), h.div_ceil(8));
passes += 2;
{
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("light field"), timestamp_writes: ts(1) });
pass.set_pipeline(&self.field_pipe);
pass.set_bind_group(0, &self.t.field_bg, &[]);
let (x, y) = (self.field_size.0.div_ceil(16), self.field_size.1.div_ceil(16));
pass.dispatch_workgroups(x, y, 1);
}
{
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("light shadows"), timestamp_writes: ts(3) });
pass.set_pipeline(&self.shadow_pipe);
pass.set_bind_group(0, &self.t.shadow_bg, &[]);
let (x, y) = wg(self.field_size.0, self.field_size.1);
pass.dispatch_workgroups(x, y, 1);
}
// GI: media, then each cascade top down, then fluence, each in its own timed pass.
let smp = wgpu::BindingResource::Sampler(&self.sampler);
if let (Some(_), Some(gt)) = (gi, self.t.gi.as_ref()) {
let gi_pass = |encoder: &mut wgpu::CommandEncoder, label: &str, q: u32, f: &dyn Fn(&mut wgpu::ComputePass<'_>)| {
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some(label), timestamp_writes: ts(q) });
pass.set_bind_group(0, &self.gi_bg0, &[]);
f(&mut pass);
};
let scene_bg = self.scene_bg.get((self.prims.buffer().clone(), scene.emission.cloned()), || {
bind(
device,
&self.scene_bgl,
[
self.prims.as_entire_binding(),
self.lights.as_entire_binding(),
tv(&self.t.vis),
tv(scene.emission.unwrap_or(&self.black)),
smp.clone(),
tv(&gt.scene_emit),
tv(&gt.scene_occ),
],
)
});
gi_pass(encoder, "gi scene", 5, &|pass| {
pass.set_pipeline(&self.scene_pipe);
pass.set_bind_group(1, scene_bg, &[]);
let (x, y) = wg(self.gi_size.0, self.gi_size.1);
pass.dispatch_workgroups(x, y, 1);
});
for (k, bg) in gt.cascade_bgs.iter().enumerate() {
let n = CASCADES - 1 - k as u32;
gi_pass(encoder, "gi cascade", 7 + 2 * n, &|pass| {
pass.set_pipeline(&self.cascade_pipe);
pass.set_bind_group(1, bg, &[]);
let (x, y) = wg(self.gi_size.0 * 2, self.gi_size.1 * 2);
pass.dispatch_workgroups(x, y, 1);
});
}
let fq = 7 + 2 * CASCADES;
gi_pass(encoder, "gi fluence", fq, &|pass| {
pass.set_pipeline(&self.fluence_pipe);
pass.set_bind_group(1, &gt.fluence_bg, &[]);
let (x, y) = wg(self.gi_size.0, self.gi_size.1);
pass.dispatch_workgroups(x, y, 1);
});
passes += 2 + CASCADES;
if self.inspect && !gt.own_bgs.is_empty() {
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("gi inspect"), timestamp_writes: None });
pass.set_bind_group(0, &self.gi_bg0, &[]);
pass.set_pipeline(&self.cascade_pipe);
for bg in &gt.own_bgs {
pass.set_bind_group(1, bg, &[]);
let (x, y) = wg(self.gi_size.0 * 2, self.gi_size.1 * 2);
pass.dispatch_workgroups(x, y, 1);
}
passes += 1;
}
}
let fluence = match (gi, self.t.gi.as_ref()) {
(Some(_), Some(gt)) => &gt.fluence,
_ => &self.black,
};
let comp_bg = self.comp_bg.get((self.prims.buffer().clone(), [base.clone(), text.clone(), fluence.clone()]), || {
bind(
device,
&self.comp_bgl,
[
self.frame.as_entire_binding(),
self.prims.as_entire_binding(),
self.lights.as_entire_binding(),
tv(base),
tv(text),
tv(&self.t.gb0),
tv(&self.t.gb1),
tv(&self.t.vis),
tv(&self.t.air),
tv(fluence),
tv(&self.t.field),
smp,
],
)
});
{
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("light composite"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: target,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), store: wgpu::StoreOp::Store },
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
pass.set_pipeline(&self.comp_pipe);
pass.set_bind_group(0, comp_bg, &[]);
pass.draw(0..3, 0..1);
}
let last = self.last_query();
marker(encoder, &mut passes, Some(last), None);
if let Some((qs, resolve, read)) = &self.query {
encoder.resolve_query_set(qs, 0..last + 1, resolve, 0);
encoder.copy_buffer_to_buffer(resolve, 0, read, 0, (last as u64 + 1) * 8);
}
self.compute_passes = passes;
true
}
/// Compute passes the last `render` recorded, timestamp markers included. For tests.
#[doc(hidden)]
pub fn compute_passes(&self) -> u32 {
self.compute_passes
}
}
@@ -0,0 +1,114 @@
// Shared by every rune-light pass. All positions are output device pixels unless a name says otherwise.
struct Frame {
sf: vec4<f32>, // output size xy, field size zw
gs: vec4<f32>, // gi probe grid xy, field scale (field px per output px), gi scale
ambient: vec4<f32>, // rgb ambient irradiance, exposure
counts: vec4<u32>, // prims, lights, cascades, flags (1 gi, 2 shafts, 4 encode sRGB, 8 ao, 16 extra emission)
misc: vec4<f32>, // max occluder top z, time, seed, shafts over occluders
text: vec4<f32>, // floor, ceiling, how much light text takes, specular on text
gi: vec4<f32>, // strength, air glow, bounce, absorption per gi texel
bg: vec4<f32>, // background gloss, background roughness, contact AO strength, rim strength
ext: vec4<f32>, // albedo floor, extra emission gain, unused
};
struct Prim {
rect: vec4<f32>, // x, y, w, h
radii: vec4<f32>, // tl, tr, br, bl
z: vec4<f32>, // bottom, top, bevel width, bevel height
mat: vec4<f32>, // gloss, roughness, flags, ao reach
emit: vec4<f32>, // linear radiance rgb, unused
albedo: vec4<f32>, // rgb albedo for bounce, unused
};
struct Light {
pos: vec4<f32>, // x, y, z, source radius
color: vec4<f32>, // linear rgb × intensity, range
axis: vec4<f32>, // spot axis xyz (unit), half-angle in radians (0 = point light)
extra: vec4<f32>, // shafts, bulb glow, specular, softness multiplier
};
const PI: f32 = 3.14159265;
const TAU: f32 = 6.28318531;
// Intensity 1 gives irradiance 1 at this distance (device px) from a small source.
const REF: f32 = 200.0;
const F_OCC: u32 = 1u;
const F_EMIT: u32 = 2u;
const F_RAISED: u32 = 4u;
// Seen only by the GI tracer's distance (marks where extra emission may be); never a surface.
const F_HINT: u32 = 8u;
fn flags_of(p: Prim) -> u32 {
return u32(p.mat.z + 0.5);
}
// Rune's rounded rect (crates/rune/src/shaders/clip.wgsl `sd_continuous` / `sd_rounded`):
// radii tl, tr, br, bl, y down; negative selects Apple's continuous corner.
const CONTINUOUS_K: f32 = 1.52866483;
fn sd_continuous(p: vec2<f32>, half: vec2<f32>, r: f32) -> f32 {
let e = CONTINUOUS_K * r;
let q = half - abs(p);
let v = vec2<f32>(e) - q;
if (v.x <= 0.0 || v.y <= 0.0) { return max(-q.x, -q.y); }
let u = atan2(v.y, v.x) * (4.0 / PI) - 1.0;
let u2 = u * u;
return length(v) - e * (1.14602295 + u2 * (-0.37573161 + u2 * (0.30796609 - 0.07724354 * u2)));
}
fn sd_rrect(p: vec2<f32>, half: vec2<f32>, radii: vec4<f32>) -> f32 {
var r = radii.x;
if (p.x > 0.0) {
r = select(radii.y, radii.z, p.y > 0.0);
} else {
r = select(radii.x, radii.w, p.y > 0.0);
}
if (r < 0.0) { return sd_continuous(p, half, min(-r, min(half.x, half.y))); }
r = min(r, min(half.x, half.y));
let q = abs(p) - half + vec2<f32>(r);
return min(max(q.x, q.y), 0.0) + length(max(q, vec2<f32>(0.0))) - r;
}
fn prim_sd(pr: Prim, p: vec2<f32>) -> f32 {
let half = pr.rect.zw * 0.5;
return sd_rrect(p - (pr.rect.xy + half), half, pr.radii);
}
// Torch profile from Arcade (packages/kit/gpu/lights/beam.ts:71-83, Outbreak's flashlight), between its
// Darkwood and hot-core presets: soft cone, a hot core, faint reflector rings and a little spill.
fn beam_angle(c: f32) -> f32 {
let omc = max(0.0, 1.0 - clamp(c, -1.0, 1.0));
return sqrt(2.0 * omc) * (1.0 + 0.083333 * omc);
}
fn beam_bell(x: f32) -> f32 { return 1.0 / (1.0 + x * x * (1.0 + 0.35 * x * x)); }
fn beam_lorentz(x: f32) -> f32 { return 1.0 / (1.0 + x * x * (1.0 + 0.48 * x * x)); }
fn beam_profile(t: f32) -> f32 {
let inner = 0.5;
let core = 0.45;
let core_w = 0.34;
let spill = 0.035;
let spill_w = 1.6;
let rings = 0.18;
if (t >= spill_w * 1.7) { return 0.0; }
let ring = 1.0 + rings * (0.2 * beam_bell((t - 0.84) * 12.5) - 0.18 * beam_bell((t - core_w * 1.35) * 9.0));
return (1.0 - smoothstep(inner, 1.0, t)) * ring + core * beam_lorentz(t / core_w) + spill * beam_lorentz(t / spill_w);
}
// Direction to the light and its unshadowed irradiance scale at P (before n·l): Karis' windowed inverse
// square with the source radius as the near clamp (Arcade packages/kit/gpu/lights/physical.ts:159-163).
fn light_term(L: Light, P: vec3<f32>) -> vec4<f32> {
let D = L.pos.xyz - P;
let d2 = dot(D, D);
let d = sqrt(d2);
let l = D / max(d, 1e-4);
let x = d / max(L.color.w, 1.0);
let w = clamp(1.0 - x * x * x * x, 0.0, 1.0);
var a = REF * REF / (d2 + L.pos.w * L.pos.w) * w * w;
if (L.axis.w > 0.0) {
a = a * beam_profile(beam_angle(dot(-l, L.axis.xyz)) / L.axis.w);
}
return vec4<f32>(l, a);
}
fn luma(c: vec3<f32>) -> f32 {
return dot(c, vec3<f32>(0.2126, 0.7152, 0.0722));
}
@@ -0,0 +1,211 @@
// Full-resolution resolve: the UI's colour as albedo under ambient + every light (visibility from the shadow
// pass, bevel normals from the surface buffer, GGX highlights widened by the source size), contact AO,
// one-bounce / emitter GI, god-ray air, visible bulbs, then text with a contrast floor, a soft shoulder, sRGB
// encode and dither.
@group(0) @binding(0) var<uniform> F: Frame;
@group(0) @binding(1) var<storage, read> prims: array<Prim>;
@group(0) @binding(2) var<storage, read> lights: array<Light>;
@group(0) @binding(3) var ui_base: texture_2d<f32>;
@group(0) @binding(4) var ui_text: texture_2d<f32>;
@group(0) @binding(5) var gb0: texture_2d<f32>;
@group(0) @binding(6) var gb1: texture_2d<u32>;
@group(0) @binding(7) var vis: texture_2d_array<f32>;
@group(0) @binding(8) var air: texture_2d_array<f32>;
@group(0) @binding(9) var flu: texture_2d<f32>;
@group(0) @binding(10) var field: texture_2d<f32>;
@group(0) @binding(11) var samp: sampler;
@vertex
fn vs(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4<f32> {
let uv = vec2<f32>(f32((vi << 1u) & 2u), f32(vi & 2u));
return vec4<f32>(uv * 2.0 - 1.0, 0.0, 1.0);
}
// Joint-bilateral upsample of the half-resolution visibility: taps on a different surface height
// (card top vs. the floor beside it) are rejected so shadows never bleed across an edge.
fn vis_at(tex: texture_2d_array<f32>, px: vec2<f32>, zr: f32, layer: i32) -> vec4<f32> {
let fsz = vec2<i32>(F.sf.zw);
let f = px * F.gs.z - 0.5;
let b = vec2<i32>(floor(f));
let w = fract(f);
var acc = vec4<f32>(0.0);
var wsum = 0.0;
var nearest = vec4<f32>(1.0);
var best = 1e9;
for (var k = 0; k < 4; k = k + 1) {
let o = vec2<i32>(k & 1, k >> 1u);
let q = clamp(b + o, vec2<i32>(0), fsz - vec2<i32>(1));
let v = textureLoad(tex, q, layer, 0);
let qp = clamp(vec2<i32>((vec2<f32>(q) + 0.5) / F.gs.z), vec2<i32>(0), vec2<i32>(F.sf.xy) - vec2<i32>(1));
let dz = abs(textureLoad(gb0, qp, 0).w - zr);
let bw = select(1.0 - w.x, w.x, o.x == 1) * select(1.0 - w.y, w.y, o.y == 1);
let ww = bw / (1.0 + dz * dz * 4.0);
acc = acc + v * ww;
wsum = wsum + ww;
if (dz < best) {
best = dz;
nearest = v;
}
}
return select(nearest, acc / wsum, wsum > 1e-3);
}
fn ggx(nh: f32, a: f32) -> f32 {
let a2 = a * a;
let d = nh * nh * (a2 - 1.0) + 1.0;
return a2 / (PI * d * d);
}
fn shoulder(x: vec3<f32>) -> vec3<f32> {
let k = 0.8;
let over = max(x - vec3<f32>(k), vec3<f32>(0.0));
return min(x, vec3<f32>(k)) + (1.0 - k) * (vec3<f32>(1.0) - exp(-over / (1.0 - k)));
}
fn to_srgb(c: vec3<f32>) -> vec3<f32> {
let lo = c * 12.92;
let hi = 1.055 * pow(max(c, vec3<f32>(0.0)), vec3<f32>(1.0 / 2.4)) - 0.055;
return select(hi, lo, c <= vec3<f32>(0.0031308));
}
// Interleaved gradient noise (Jimenez), a stable per-pixel pattern: dither without crawling grain.
fn ign(p: vec2<f32>) -> f32 {
return fract(52.9829189 * fract(dot(p, vec2<f32>(0.06711056, 0.00583715))));
}
@fragment
fn fs(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
let px = pos.xy;
let ip = vec2<i32>(px);
let base = textureLoad(ui_base, ip, 0);
let text = textureLoad(ui_text, ip, 0);
let g = textureLoad(gb0, ip, 0);
let id = textureLoad(gb1, ip, 0).r;
let sd = g.x;
let grad = g.yz;
let zr = g.w;
var n = vec3<f32>(0.0, 0.0, 1.0);
var gloss = F.bg.x;
var rough = F.bg.y;
var fl = 0u;
var rim = 0.0;
var emissive = false;
if (id > 0u) {
let pr = prims[id - 1u];
fl = flags_of(pr);
gloss = pr.mat.x;
rough = pr.mat.y;
emissive = (fl & F_EMIT) != 0u;
if ((fl & F_RAISED) != 0u) {
let bw = max(pr.z.z, 0.5);
let x = clamp(-sd / bw, 0.0, 1.0);
let slope = pr.z.w / bw * 3.0 * (1.0 - x) * (1.0 - x);
n = normalize(vec3<f32>(grad * slope, 1.0));
}
// Hairline catch on the rim, about a device pixel and a half wide.
rim = F.bg.w * (1.0 - smoothstep(0.0, 2.0, -sd)) * select(0.0, 1.0, (fl & F_OCC) != 0u);
}
let P = vec3<f32>(px, zr + 0.35);
var irr = F.ambient.rgb;
// Contact AO on surfaces below the occluders around them (the floor next to a raised card).
if ((F.counts.w & 8u) != 0u) {
let f = textureSampleLevel(field, samp, px * F.gs.z / F.sf.zw, 0.0);
let below = max(f.z - zr, 0.0);
if (below > 0.0 && f.x > 0.0) {
let reach = below * 3.0 + 6.0;
let occ = 1.0 - smoothstep(0.0, reach, f.x);
irr = irr * (1.0 - F.bg.z * occ * occ);
}
}
var diffuse = vec3<f32>(0.0);
var spec = vec3<f32>(0.0);
var airc = vec3<f32>(0.0);
let nl = min(F.counts.y, 8u);
let v0 = vis_at(vis, px, zr, 0);
var v1 = vec4<f32>(1.0);
if (nl > 4u) {
v1 = vis_at(vis, px, zr, 1);
}
let shafts = (F.counts.w & 2u) != 0u;
var a0 = vec4<f32>(1.0);
var a1 = vec4<f32>(1.0);
if (shafts) {
a0 = vis_at(air, px, zr, 0);
if (nl > 4u) {
a1 = vis_at(air, px, zr, 1);
}
}
for (var li = 0u; li < nl; li = li + 1u) {
let L = lights[li];
let lt = light_term(L, P);
let l = lt.xyz;
var v = v0[li % 4u];
if (li >= 4u) {
v = v1[li % 4u];
}
let ndl = max(dot(n, l), 0.0);
let e = L.color.rgb * lt.w * v;
// A shaft light stands behind the UI: it lights nothing from the front, only rims and the air.
let front = select(1.0, 0.0, L.extra.x > 0.0);
diffuse = diffuse + e * ndl * front;
// GGX toward a viewer straight above; the source radius widens the lobe (Karis), energy-kept.
let h = normalize(l + vec3<f32>(0.0, 0.0, 1.0));
let dist = length(L.pos.xyz - P);
let a = clamp(rough * rough + L.pos.w / (2.0 * dist), 0.02, 1.0);
let energy = (rough * rough) / a;
let fres = 0.04 + 0.96 * pow(1.0 - max(dot(l, h), 0.0), 5.0);
spec = spec + e * ndl * ggx(max(dot(n, h), 0.0), a) * energy * fres * gloss * L.extra.z * front;
// Rim: edges whose outward normal faces the light catch a bright hairline.
let lxy = L.pos.xy - px;
let face = max(dot(grad, lxy / max(length(lxy), 1e-3)), 0.0);
spec = spec + e * rim * face * face * max(l.z, 0.15);
let d2 = length(lxy);
if (shafts && L.extra.x > 0.0) {
var av = a0[li % 4u];
if (li >= 4u) {
av = a1[li % 4u];
}
// Over occluders the cards in front dim the shafts.
let over = select(1.0, F.misc.w, zr > 0.5);
let fall = 1.5 * REF / (d2 + 1.5 * REF);
airc = airc + L.color.rgb * L.extra.x * av * over * fall * fall;
}
if (L.extra.y > 0.0) {
let r = max(L.pos.w, 1.0);
let q = r * r / (d2 * d2 + r * r);
airc = airc + L.color.rgb * L.extra.y * (q * sqrt(q) + 0.05 * q);
}
}
var gi_irr = vec3<f32>(0.0);
if ((F.counts.w & 1u) != 0u) {
let flv = textureSampleLevel(flu, samp, px * F.gs.w / F.gs.xy, 0.0).rgb;
gi_irr = flv * F.gi.x;
airc = airc + flv * F.gi.y;
}
let lightf = irr + diffuse + gi_irr;
// A dark UI colour is nearly black as a material; a small albedo floor lets light pools and shadows read
// on it while ambient keeps the designed look.
var col = base.rgb * irr + (base.rgb + vec3<f32>(F.ext.x)) * (diffuse + gi_irr) + spec;
if (emissive) {
col = base.rgb * max(lightf, vec3<f32>(1.0)) + spec * 0.25;
}
// Text: lit like the surface under it, but clamped so shadows never crush it and highlights never wash it.
let tf = mix(vec3<f32>(1.0), clamp(lightf, vec3<f32>(F.text.x), vec3<f32>(F.text.y)), F.text.z);
col = col * (1.0 - text.a) + text.rgb * tf + spec * text.a * F.text.w;
col = col + airc * (1.0 - 0.6 * text.a);
var o = shoulder(col * F.ambient.w);
if ((F.counts.w & 4u) != 0u) {
o = to_srgb(o);
let dn = ign(px + vec2<f32>(F.misc.z * 5.588238, 0.0)) + ign(px.yx + vec2<f32>(17.0, F.misc.z)) - 1.0;
o = o + vec3<f32>(dn / 255.0);
}
return vec4<f32>(o, 1.0);
}
@@ -0,0 +1,80 @@
// Scene distance field at field resolution, straight from the analytic primitives (exact, no jump flood):
// x: union signed distance to occluders (device px), y/z: bottom/top z of the nearest occluder,
// w: distance to emitters (and GI hints), for radiance-cascade sphere tracing alongside x.
// Distances are clamped to CLAMP (no tracer steps further), so each 16×16 tile first culls the primitives whose
// bounds lie further than CLAMP from it into workgroup memory and only those are evaluated per texel.
const CLAMP: f32 = 256.0;
const MAX_LOCAL: u32 = 256u;
@group(0) @binding(0) var<uniform> F: Frame;
@group(0) @binding(1) var<storage, read> prims: array<Prim>;
@group(0) @binding(2) var out_field: texture_storage_2d<rgba16float, write>;
var<workgroup> local_ids: array<u32, MAX_LOCAL>;
var<workgroup> local_n: atomic<u32>;
@compute @workgroup_size(16, 16)
fn main(@builtin(global_invocation_id) gid: vec3<u32>, @builtin(local_invocation_index) li: u32, @builtin(workgroup_id) wid: vec3<u32>) {
if (li == 0u) {
atomicStore(&local_n, 0u);
}
workgroupBarrier();
// Tile bounds in device px.
let lo = vec2<f32>(wid.xy * 16u) / F.gs.z;
let hi = vec2<f32>(wid.xy * 16u + 16u) / F.gs.z;
let tc = (lo + hi) * 0.5;
let th = (hi - lo) * 0.5;
let n = F.counts.x;
for (var i = li; i < n; i = i + 256u) {
let pr = prims[i];
if ((flags_of(pr) & (F_OCC | F_EMIT | F_HINT)) == 0u) {
continue;
}
let half = pr.rect.zw * 0.5;
let c = pr.rect.xy + half;
let gap = max(abs(c - tc) - half - th, vec2<f32>(0.0));
if (length(gap) < CLAMP) {
let k = atomicAdd(&local_n, 1u);
if (k < MAX_LOCAL) {
local_ids[k] = i;
}
}
}
workgroupBarrier();
let count = min(atomicLoad(&local_n), MAX_LOCAL);
// Keep painter's order deterministic regardless of which thread appended first: the min is order-free,
// and ties pick the lowest index.
let fs = vec2<u32>(F.sf.zw);
if (gid.x >= fs.x || gid.y >= fs.y) {
return;
}
let p = (vec2<f32>(gid.xy) + 0.5) / F.gs.z;
var best = CLAMP;
var best_i = 0xffffffffu;
var bot = 0.0;
var top = 0.0;
var gi = CLAMP;
for (var k = 0u; k < count; k = k + 1u) {
let i = local_ids[k];
let pr = prims[i];
let half = pr.rect.zw * 0.5;
let c = pr.rect.xy + half;
let q0 = abs(p - c) - half;
let bd = min(max(q0.x, q0.y), 0.0) + length(max(q0, vec2<f32>(0.0)));
if (bd > best && bd > gi) {
continue;
}
let d = sd_rrect(p - c, half, pr.radii);
if ((flags_of(pr) & (F_EMIT | F_HINT)) != 0u) {
gi = min(gi, d);
}
if ((flags_of(pr) & F_OCC) != 0u && (d < best || (d == best && i < best_i))) {
best = d;
best_i = i;
bot = pr.z.x;
top = pr.z.y;
}
}
textureStore(out_field, gid.xy, vec4<f32>(best, bot, top, gi));
}
@@ -0,0 +1,49 @@
// Surface buffer: for every pixel, the topmost primitive's own signed distance, outward gradient, top z and id.
// Painter's order, no blending: the last primitive drawn over a pixel owns it.
@group(0) @binding(0) var<uniform> F: Frame;
@group(0) @binding(1) var<storage, read> prims: array<Prim>;
struct VOut {
@builtin(position) pos: vec4<f32>,
@location(0) @interpolate(flat) idx: u32,
};
@vertex
fn vs(@builtin(vertex_index) vi: u32, @builtin(instance_index) ii: u32) -> VOut {
let pr = prims[ii];
let corner = vec2<f32>(f32(vi & 1u), f32(vi >> 1u));
let p = pr.rect.xy - vec2<f32>(1.0) + corner * (pr.rect.zw + vec2<f32>(2.0));
var o: VOut;
o.pos = vec4<f32>(p.x / F.sf.x * 2.0 - 1.0, 1.0 - p.y / F.sf.y * 2.0, 0.0, 1.0);
o.idx = ii;
return o;
}
struct GOut {
@location(0) g: vec4<f32>,
@location(1) id: u32,
};
@fragment
fn fs(i: VOut) -> GOut {
let pr = prims[i.idx];
let half = pr.rect.zw * 0.5;
// Fragment position is the rasterizer's exact pixel centre; interpolated `p` drifts by
// subpixel ULPs on D3D12, discarding outer-edge pixels that sit on the exact `d == 0.5` cut.
let q = i.pos.xy - (pr.rect.xy + half);
let d = sd_rrect(q, half, pr.radii);
if (d > 0.5 || (flags_of(pr) & F_HINT) != 0u) {
discard;
}
let e = 0.5;
let gx = sd_rrect(q + vec2<f32>(e, 0.0), half, pr.radii) - sd_rrect(q - vec2<f32>(e, 0.0), half, pr.radii);
let gy = sd_rrect(q + vec2<f32>(0.0, e), half, pr.radii) - sd_rrect(q - vec2<f32>(0.0, e), half, pr.radii);
var g = vec2<f32>(gx, gy);
let gl = length(g);
g = select(vec2<f32>(0.0), g / gl, gl > 1e-5);
var o: GOut;
o.g = vec4<f32>(d, g, pr.z.y);
o.id = i.idx + 1u;
return o;
}
+230
View File
@@ -0,0 +1,230 @@
// 2D radiance cascades (Sannikov; GM Shaders and Jason McGhee's write-ups), over the same analytic field.
//
// Scene: two gi-resolution media textures built from the analytic primitives with sub-texel coverage, so an
// emitter moving by a fraction of a texel changes the light by that fraction instead of popping a whole texel:
// emit: rgb = σ·L of emitters (emission density), a = σ (emitters are nearly opaque glowing media),
// occ: rgb = coverage × the light a card re-emits (one bounce in its albedo), a = card coverage.
// A card absorbs only rays from probes standing lower than its top (light reaches a card from things standing on
// it); its top comes from the field. An optional full-resolution emission texture (effects such as electric arcs)
// adds emission-only medium. The march samples the media bilinearly.
//
// Cascade n: probes every 2^n texels, 4·4^n directions stored as a 2^(n+1) square block per probe, each ray
// covering [a(4^n − 1)/3, a(4^(n+1) − 1)/3]. Rays sphere trace through empty space with the field's gi distance.
// Merging runs top down: a ray that isn't fully absorbed adds the bilinearly interpolated, four-direction mean
// of cascade n+1. Fluence is cascade 0's four directions averaged. Cost is fixed by the grid, not the emitters.
@group(0) @binding(0) var<uniform> F: Frame;
const SIGMA_EMIT: f32 = 1.5;
// ---- scene ----
@group(1) @binding(0) var<storage, read> prims: array<Prim>;
@group(1) @binding(1) var<storage, read> lights: array<Light>;
@group(1) @binding(2) var vis: texture_2d_array<f32>;
@group(1) @binding(3) var extra: texture_2d<f32>;
@group(1) @binding(4) var lin: sampler;
@group(1) @binding(5) var out_emit: texture_storage_2d<rgba16float, write>;
@group(1) @binding(6) var out_occ: texture_storage_2d<rgba16float, write>;
@compute @workgroup_size(8, 8)
fn scene(@builtin(global_invocation_id) gid: vec3<u32>) {
let gs = vec2<u32>(F.gs.xy);
if (gid.x >= gs.x || gid.y >= gs.y) {
return;
}
let texel = 1.0 / F.gs.w;
let p = (vec2<f32>(gid.xy) + 0.5) * texel;
var em = vec4<f32>(0.0);
var oc = vec4<f32>(0.0);
let n = F.counts.x;
for (var i = 0u; i < n; i = i + 1u) {
let pr = prims[i];
let fl = flags_of(pr);
if ((fl & (F_EMIT | F_OCC)) == 0u) {
continue;
}
let half = pr.rect.zw * 0.5;
let c = pr.rect.xy + half;
if (any(abs(p - c) > half + vec2<f32>(texel))) {
continue;
}
// Box-filtered coverage of the texel by the rounded rect (exact for straight edges).
let cov = clamp(0.5 - sd_rrect(p - c, half, pr.radii) / texel, 0.0, 1.0);
if (cov <= 0.0) {
continue;
}
// Painter's order: each primitive lies over what came before it.
if ((fl & F_EMIT) != 0u) {
em = mix(em, vec4<f32>(pr.emit.rgb * SIGMA_EMIT, SIGMA_EMIT), cov);
oc = oc * (1.0 - cov);
} else {
var e = vec3<f32>(0.0);
if (F.gi.z > 0.0) {
// One bounce: the direct light on this card, re-emitted in its albedo.
let P = vec3<f32>(p, pr.z.y);
let fp = clamp(vec2<i32>(p * F.gs.z), vec2<i32>(0), vec2<i32>(F.sf.zw) - vec2<i32>(1));
let nl = min(F.counts.y, 8u);
for (var li = 0u; li < nl; li = li + 1u) {
let L = lights[li];
let lt = light_term(L, P);
let v = textureLoad(vis, fp, i32(li / 4u), 0)[li % 4u];
e = e + L.color.rgb * lt.w * max(lt.z, 0.0) * v;
}
}
em = em * (1.0 - cov);
oc = mix(oc, vec4<f32>(pr.albedo.rgb * e * F.gi.z, 1.0), cov);
}
}
// Extra emission (full resolution): the box mean over this texel from 4×4 bilinear taps, emission-only.
if ((F.counts.w & 16u) != 0u) {
let sz = F.sf.xy;
var acc = vec3<f32>(0.0);
for (var k = 0; k < 16; k = k + 1) {
let o = (vec2<f32>(f32(k & 3), f32(k >> 2u)) - 1.5) * 0.25 * texel;
acc = acc + textureSampleLevel(extra, lin, (p + o) / sz, 0.0).rgb;
}
em = vec4<f32>(em.rgb + acc / 16.0 * F.ext.y, em.a);
}
textureStore(out_emit, gid.xy, em);
textureStore(out_occ, gid.xy, oc);
}
// ---- cascades ----
struct Cascade {
n: u32,
count: u32,
merge: u32,
pad1: u32,
};
@group(1) @binding(0) var<uniform> C: Cascade;
@group(1) @binding(1) var scene_emit: texture_2d<f32>;
@group(1) @binding(2) var scene_occ: texture_2d<f32>;
@group(1) @binding(3) var field: texture_2d<f32>;
@group(1) @binding(4) var samp: sampler;
@group(1) @binding(5) var upper: texture_2d<f32>;
@group(1) @binding(6) var out_c: texture_storage_2d<rgba16float, write>;
@group(1) @binding(7) var gb0: texture_2d<f32>;
// Radiance and transmittance along a → b (gi texels) for a probe standing at height zp.
fn march(a: vec2<f32>, b: vec2<f32>, zp: f32, inner: f32) -> vec4<f32> {
let gsz = F.gs.xy;
let D = b - a;
let len = length(D);
if (len < 1e-4) {
return vec4<f32>(0.0, 0.0, 0.0, 1.0);
}
let dir = D / len;
var rad = vec3<f32>(0.0);
var T = 1.0;
var t = 0.0;
for (var i = 0; i < 48; i = i + 1) {
if (t >= len || T < 0.01) {
break;
}
let q = a + dir * t;
if (any(q < vec2<f32>(0.0)) || any(q > gsz)) {
break;
}
let f = textureSampleLevel(field, samp, (q / F.gs.w) * F.gs.z / F.sf.zw, 0.0);
// Distances in gi texels: to the nearest emitter, and to the occluder boundary. Space is empty unless an
// emitter is near or the ray is near or inside a card that stands taller than the probe: outside cards
// that's the nearer boundary; inside a card the probe sees over, it's the card's own boundary.
let de = f.w * F.gs.w;
let dx = f.x * F.gs.w;
let tall = f.z > zp + 0.5;
var free = min(de, abs(dx));
if (dx < 0.0 && tall) {
free = 0.0;
}
if (free > 1.0) {
t = t + max(free - 0.5, 1.0);
continue;
}
let step = min(inner, len - t);
let uv = (q + dir * step * 0.5) / gsz;
let em = textureSampleLevel(scene_emit, samp, uv, 0.0);
let oc = textureSampleLevel(scene_occ, samp, uv, 0.0);
// Cards only absorb rays from probes lower than their top.
let blocks = F.gi.w * smoothstep(zp, zp + 1.0, f.z);
let sigma = em.a + oc.a * blocks;
let e = em.rgb + oc.rgb * blocks;
let tr = exp(-sigma * step);
let k = select(step, (1.0 - tr) / sigma, sigma > 1e-4);
rad = rad + T * e * k;
T = T * tr;
t = t + step;
}
return vec4<f32>(rad, T);
}
@compute @workgroup_size(8, 8)
fn cascade(@builtin(global_invocation_id) gid: vec3<u32>) {
let n = C.n;
let s = 1u << n;
let b = 2u << n;
let probes = vec2<u32>(F.gs.xy) / s;
let probe = gid.xy / b;
if (probe.x >= probes.x || probe.y >= probes.y) {
return;
}
let sub = gid.xy % b;
let di = sub.y * b + sub.x;
let nd = b * b;
let ang = (f32(di) + 0.5) / f32(nd) * TAU;
let dir = vec2<f32>(cos(ang), sin(ang));
let origin = (vec2<f32>(probe) + 0.5) * f32(s);
let pix = clamp(vec2<i32>(origin / F.gs.w), vec2<i32>(0), vec2<i32>(F.sf.xy) - vec2<i32>(1));
let zp = textureLoad(gb0, pix, 0).w;
let p4 = f32(1u << (2u * n));
let t0 = (p4 - 1.0) / 3.0;
let t1 = (p4 * 4.0 - 1.0) / 3.0;
let inner = max(1.0, f32(s) * 0.5);
let a = origin + dir * t0;
var r = vec4<f32>(0.0);
if (n + 1u < C.count) {
// Bilinear fix (Sannikov): one ray to each of the four upper probes' interval starts, each merged with
// that probe's radiance, so light never leaks across an occluder between probes. Without the merge
// (inspection), the same four rays stop at the upper probes' interval starts: this cascade's own interval.
let us = s * 2u;
let ub = b * 2u;
let uprobes = vec2<i32>(vec2<u32>(F.gs.xy) / us);
let f = origin / f32(us) - 0.5;
let base = vec2<i32>(floor(f));
let w = fract(f);
for (var k = 0; k < 4; k = k + 1) {
let o = vec2<i32>(k & 1, k >> 1u);
let q = clamp(base + o, vec2<i32>(0), uprobes - vec2<i32>(1));
let wk = select(1.0 - w.x, w.x, o.x == 1) * select(1.0 - w.y, w.y, o.y == 1);
let uo = (vec2<f32>(q) + 0.5) * f32(us);
let seg = march(a, uo + dir * t1, zp, inner);
var far = vec3<f32>(0.0);
if (C.merge != 0u) {
for (var j = 0u; j < 4u; j = j + 1u) {
let idx = di * 4u + j;
let tex = q * i32(ub) + vec2<i32>(i32(idx % ub), i32(idx / ub));
far = far + textureLoad(upper, tex, 0).rgb;
}
}
r = r + wk * vec4<f32>(seg.rgb + seg.a * far * 0.25, seg.a);
}
} else {
r = march(a, origin + dir * t1, zp, inner);
}
textureStore(out_c, gid.xy, r);
}
// ---- fluence ----
@group(1) @binding(0) var c0: texture_2d<f32>;
@group(1) @binding(1) var out_f: texture_storage_2d<rgba16float, write>;
@compute @workgroup_size(8, 8)
fn fluence(@builtin(global_invocation_id) gid: vec3<u32>) {
let gs = vec2<u32>(F.gs.xy);
if (gid.x >= gs.x || gid.y >= gs.y) {
return;
}
let b = vec2<i32>(gid.xy) * 2;
let v = textureLoad(c0, b, 0) + textureLoad(c0, b + vec2<i32>(1, 0), 0) + textureLoad(c0, b + vec2<i32>(0, 1), 0)
+ textureLoad(c0, b + vec2<i32>(1, 1), 0);
textureStore(out_f, gid.xy, vec4<f32>(v.rgb * 0.25, 1.0));
}
+444
View File
@@ -0,0 +1,444 @@
// Thick glass over the lit frame. Every glass is a slab: a flat bottom floating `gap` px above the UI and a top
// whose height rises over the bevel with a quarter-circle profile (vertical at the rim), plus an optional gentle
// dome. A viewer straight above sends one ray per pixel:
//
// enter the top (Snell, n ≈ 1.5) → cross the glass to the bottom (Beer–Lambert tint over the path) → leave into
// the air gap (Snell) and land on the UI, or, past the critical angle, reflect off the bottom (total internal
// reflection) and climb back to the top, where it leaves toward the environment or stays trapped.
//
// The entry splits reflection and transmission with the exact dielectric Fresnel equations (unpolarised), the exit
// takes its own Fresnel loss. Dispersion: rays are traced at the two ends of the visible range (Cauchy IOR) and
// eight wavelengths interpolate between them, each weighted into RGB, so rims fringe as a smooth spectrum. Frost
// widens every refracted ray into a cone: the UI is read from a prefiltered pyramid at the cone's footprint.
// Highlights are GGX reflections of the glowing UI elements (sphere lights, Karis widening, normal-variance
// specular AA), and light the GI carries under the glass scatters into its bevel.
struct U {
size: vec4<f32>, // w, h, glass count, light count
misc: vec4<f32>, // pyramid levels, env strength, shadow, caustic
shadow: vec4<f32>, // shadow offset xy, blur, unused
};
struct Glass {
a: vec4<f32>, // rect x, y, w, h
b: vec4<f32>, // second shape rect (w = 0: none)
r: vec4<f32>, // radius a, radius b, smooth-union k, morph a→b
p0: vec4<f32>, // thickness, bevel, gap, dome
p1: vec4<f32>, // ior, dispersion (n400 − n700), frost, presence
tint: vec4<f32>, // absorption per px rgb, glow from GI
};
struct GLight {
pos: vec4<f32>, // x, y, z, radius
color: vec4<f32>, // rgb intensity, unused
};
@group(0) @binding(0) var<uniform> u: U;
@group(0) @binding(1) var<storage, read> glass: array<Glass>;
@group(0) @binding(2) var<storage, read> glights: array<GLight>;
@group(0) @binding(3) var backdrop: texture_2d<f32>;
@group(0) @binding(4) var pyramid: texture_2d<f32>;
@group(0) @binding(5) var fluence: texture_2d<f32>;
@group(0) @binding(6) var samp: sampler;
const PI: f32 = 3.14159265;
@vertex
fn vs(@builtin(vertex_index) vi: u32) -> @builtin(position) vec4<f32> {
let uv = vec2<f32>(f32((vi << 1u) & 2u), f32(vi & 2u));
return vec4<f32>(uv * 2.0 - 1.0, 0.0, 1.0);
}
// Apple's continuous corner (crates/rune/src/shaders/clip.wgsl `sd_continuous` / `sd_rounded`).
const CONTINUOUS_K: f32 = 1.52866483;
fn sd_continuous(p: vec2<f32>, half: vec2<f32>, r: f32) -> f32 {
let e = CONTINUOUS_K * r;
let q = half - abs(p);
let v = vec2<f32>(e) - q;
if (v.x <= 0.0 || v.y <= 0.0) { return max(-q.x, -q.y); }
let u = atan2(v.y, v.x) * (4.0 / PI) - 1.0;
let u2 = u * u;
return length(v) - e * (1.14602295 + u2 * (-0.37573161 + u2 * (0.30796609 - 0.07724354 * u2)));
}
fn sd_rrect(p: vec2<f32>, half: vec2<f32>, r0: f32) -> f32 {
if (r0 < 0.0) { return sd_continuous(p, half, min(-r0, min(half.x, half.y))); }
let r = min(r0, min(half.x, half.y));
let q = abs(p) - half + vec2<f32>(r);
return min(max(q.x, q.y), 0.0) + length(max(q, vec2<f32>(0.0))) - r;
}
fn smin(a: f32, b: f32, k: f32) -> f32 {
if (k <= 0.0) {
return min(a, b);
}
let h = max(k - abs(a - b), 0.0) / k;
return min(a, b) - h * h * k * 0.25;
}
fn sdf(g: Glass, p: vec2<f32>) -> f32 {
let da = sd_rrect(p - (g.a.xy + g.a.zw * 0.5), g.a.zw * 0.5, g.r.x);
if (g.b.z <= 0.0) {
return da;
}
let db = sd_rrect(p - (g.b.xy + g.b.zw * 0.5), g.b.zw * 0.5, g.r.y);
return mix(smin(da, db, g.r.z), db, g.r.w);
}
// The dome rides on shape A's inscribed capsule: its medial axis is a single segment at the inscribed radius, and
// the smoothstep profile has zero slope there and at the rim, so the top has no crease anywhere.
fn dome(g: Glass, p: vec2<f32>) -> f32 {
let half = g.a.zw * 0.5;
let ri = min(half.x, half.y);
let dc = sd_rrect(p - (g.a.xy + half), half, ri);
let x = clamp(-dc / ri, 0.0, 1.0);
return g.p0.w * g.p1.w * x * x * (3.0 - 2.0 * x) * (1.0 - g.r.w);
}
// Top surface height above the UI plane at p (device px), given the shape's distance d there: a quarter-circle
// shoulder (vertical at the rim) up to the flat top, plus the dome.
fn height_d(g: Glass, p: vec2<f32>, d: f32) -> f32 {
let thick = g.p0.x * g.p1.w;
let bevel = max(g.p0.y, 1.0);
let x = clamp(-d / bevel, 0.0, 1.0);
let prof = sqrt(max(1.0 - (1.0 - x) * (1.0 - x), 0.0));
return g.p0.z + thick * (0.04 + 0.96 * prof) + dome(g, p);
}
fn height(g: Glass, p: vec2<f32>) -> f32 {
return height_d(g, p, sdf(g, p));
}
fn normal_at(g: Glass, p: vec2<f32>) -> vec3<f32> {
let e = 0.5;
let hx = height(g, p + vec2<f32>(e, 0.0)) - height(g, p - vec2<f32>(e, 0.0));
let hy = height(g, p + vec2<f32>(0.0, e)) - height(g, p - vec2<f32>(0.0, e));
return normalize(vec3<f32>(-hx / (2.0 * e), -hy / (2.0 * e), 1.0));
}
// Unpolarised dielectric Fresnel reflectance for a ray from medium n1 into n2.
fn fresnel(cos_i: f32, n1: f32, n2: f32) -> f32 {
let ci = clamp(cos_i, 0.0, 1.0);
let s2 = (n1 / n2) * (n1 / n2) * (1.0 - ci * ci);
if (s2 >= 1.0) {
return 1.0;
}
let ct = sqrt(1.0 - s2);
let rs = (n1 * ci - n2 * ct) / (n1 * ci + n2 * ct);
let rp = (n1 * ct - n2 * ci) / (n1 * ct + n2 * ci);
return 0.5 * (rs * rs + rp * rp);
}
fn env(d: vec3<f32>) -> vec3<f32> {
// A dim studio: deep blue-grey dome, a large soft box up and to the left, a thin strip to the right.
let up = clamp(d.z, 0.0, 1.0);
var c = mix(vec3<f32>(0.006, 0.007, 0.011), vec3<f32>(0.030, 0.034, 0.046), up);
let box = normalize(vec3<f32>(-0.42, -0.58, 0.70));
c = c + vec3<f32>(0.85, 0.88, 0.95) * smoothstep(0.80, 0.97, dot(d, box)) * 4.0;
let strip = normalize(vec3<f32>(0.80, 0.10, 0.59));
c = c + vec3<f32>(0.55, 0.62, 0.80) * smoothstep(0.93, 0.99, dot(d, strip)) * 2.0;
return c * u.misc.y;
}
// Cubic B-spline sample of one pyramid level (4 bilinear taps), so heavy blur never shows texel diamonds.
fn bspline(uv: vec2<f32>, lod: f32) -> vec3<f32> {
let dim = vec2<f32>(textureDimensions(pyramid, i32(lod)));
let st = uv * dim - 0.5;
let i = floor(st);
let f = st - i;
let w0 = (1.0 - f) * (1.0 - f) * (1.0 - f) / 6.0;
let w1 = (4.0 - 6.0 * f * f + 3.0 * f * f * f) / 6.0;
let w2 = (1.0 + 3.0 * f + 3.0 * f * f - 3.0 * f * f * f) / 6.0;
let w3 = f * f * f / 6.0;
let g0 = w0 + w1;
let g1 = w2 + w3;
let h0 = (i + vec2<f32>(-1.0) + w1 / g0 + 0.5) / dim;
let h1 = (i + vec2<f32>(1.0) + w3 / g1 + 0.5) / dim;
let a = textureSampleLevel(pyramid, samp, vec2<f32>(h0.x, h0.y), lod).rgb;
let b = textureSampleLevel(pyramid, samp, vec2<f32>(h1.x, h0.y), lod).rgb;
let c = textureSampleLevel(pyramid, samp, vec2<f32>(h0.x, h1.y), lod).rgb;
let d = textureSampleLevel(pyramid, samp, vec2<f32>(h1.x, h1.y), lod).rgb;
return g0.y * (g0.x * a + g1.x * b) + g1.y * (g0.x * c + g1.x * d);
}
// The UI at p read through a blur of `radius` px (0 = sharp).
fn ui_at(p: vec2<f32>, radius: f32) -> vec3<f32> {
let uv = p / u.size.xy;
let sharp = textureSampleLevel(backdrop, samp, uv, 0.0).rgb;
if (radius <= 1.0) {
return sharp;
}
// Pyramid level k has a footprint of about 2^(k+1) px.
let lod = clamp(log2(radius) - 1.0, 0.0, u.misc.x - 1.0);
let l0 = floor(lod);
let blur = mix(bspline(uv, l0), bspline(uv, min(l0 + 1.0, u.misc.x - 1.0)), lod - l0);
return mix(sharp, blur, smoothstep(1.0, 3.0, radius));
}
fn glass_shadow(g: Glass, p: vec2<f32>) -> f32 {
let blur = u.shadow.z;
let d = sdf(g, p - u.shadow.xy * g.p1.w);
let s = 1.0 - smoothstep(-blur, blur * 1.6, d);
let contact = 1.0 - smoothstep(0.0, 10.0, sdf(g, p));
return clamp((s * 0.7 + contact * 0.3) * u.misc.z * g.p1.w, 0.0, 0.9);
}
// The floor as glass sees it: the UI with the glass's own shadow and a bright caustic ring where the bevel focuses
// the light the GI carries around it.
fn floor_at(g: Glass, q: vec2<f32>, radius: f32) -> vec3<f32> {
var c = ui_at(q, radius);
let dq = sdf(g, q);
let sh = glass_shadow(g, q);
let flu = textureSampleLevel(fluence, samp, q / u.size.xy, 0.0).rgb;
let bevel = max(g.p0.y, 1.0);
let ring = exp(-pow((-dq - bevel * 0.45) / (bevel * 0.22), 2.0)) * select(0.0, 1.0, dq < 0.0);
c = c * (1.0 - sh) + (flu * 0.55 + vec3<f32>(0.01)) * ring * u.misc.w * g.p1.w;
return c;
}
struct Path {
q: vec2<f32>, // where it lands on the UI (floor = true)
dir: vec3<f32>, // or the direction it leaves the glass toward the environment
len: f32, // path length inside the glass
t_out: f32, // exit transmission (Fresnel)
floor: bool,
};
fn trace(g: Glass, p: vec2<f32>, n: vec3<f32>, zt: f32, ior: f32) -> Path {
var o: Path;
let v = vec3<f32>(0.0, 0.0, -1.0);
let r1 = refract(v, n, 1.0 / ior);
let s = (zt - g.p0.z) / max(-r1.z, 1e-3);
let pb = p + r1.xy * s;
let up = vec3<f32>(0.0, 0.0, 1.0);
let ci = -r1.z;
let r2 = refract(r1, up, ior);
if (dot(r2, r2) > 0.0) {
o.floor = true;
o.q = pb + r2.xy * (g.p0.z / max(-r2.z, 0.05));
o.len = s;
o.t_out = 1.0 - fresnel(ci, ior, 1.0);
return o;
}
// Total internal reflection off the bottom: climb back to the top surface.
let r1b = reflect(r1, up);
var t = (zt - g.p0.z) / max(r1b.z, 1e-3);
for (var k = 0; k < 4; k = k + 1) {
t = (height(g, pb + r1b.xy * t) - g.p0.z) / max(r1b.z, 1e-3);
}
let pe = pb + r1b.xy * t;
let ne = normal_at(g, pe);
let r3 = refract(r1b, -ne, ior);
o.floor = false;
o.len = s + t;
if (dot(r3, r3) > 0.0) {
o.dir = r3;
o.t_out = 1.0 - fresnel(dot(r1b, ne), ior, 1.0);
} else {
// Trapped: it rattles on until absorbed; a little leaks out as a dim mean of the environment.
o.dir = reflect(r1b, ne);
o.t_out = 0.25;
}
return o;
}
// Approximate CIE response of eight wavelengths 400…700 nm in linear sRGB, normalised so they sum to white.
fn spectrum(i: i32) -> vec3<f32> {
var w = array<vec3<f32>, 8>(
vec3<f32>(0.20, 0.00, 0.62),
vec3<f32>(0.12, 0.02, 1.00),
vec3<f32>(0.00, 0.22, 0.86),
vec3<f32>(0.00, 0.62, 0.30),
vec3<f32>(0.18, 0.92, 0.00),
vec3<f32>(0.70, 0.62, 0.00),
vec3<f32>(1.00, 0.20, 0.00),
vec3<f32>(0.62, 0.00, 0.00),
);
return w[i];
}
fn ggx(nh: f32, a: f32) -> f32 {
let a2 = a * a;
let d = nh * nh * (a2 - 1.0) + 1.0;
return a2 / (PI * d * d);
}
// One glass sample at p: returns the shaded colour and coverage.
fn shade(g: Glass, p: vec2<f32>, spec_var: f32, fp: f32) -> vec4<f32> {
let d = sdf(g, p);
let cov = clamp(0.5 - d, 0.0, 1.0);
if (cov <= 0.0) {
return vec4<f32>(0.0);
}
let zt = height_d(g, p, d);
let n = normal_at(g, p);
let ior = g.p1.x;
let disp = g.p1.y;
let frost = g.p1.z;
// Cauchy: n(λ) = A + B/λ², with n(550) = ior and n(400) − n(700) = disp.
let B = disp / (1.0 / (0.4 * 0.4) - 1.0 / (0.7 * 0.7));
let A = ior - B / (0.55 * 0.55);
let n_lo = A + B / (0.7 * 0.7);
let n_hi = A + B / (0.4 * 0.4);
let a = trace(g, p, n, zt, n_lo);
let b = trace(g, p, n, zt, n_hi);
let thick = max(g.p0.x, 1.0);
var trans = vec3<f32>(0.0);
var wsum = vec3<f32>(0.0);
for (var i = 0; i < 8; i = i + 1) {
let k = f32(i) / 7.0; // 0 = 400 nm (n_hi), 1 = 700 nm (n_lo)
let w = spectrum(i);
var c: vec3<f32>;
var len: f32;
var tout: f32;
if (a.floor && b.floor) {
let q = mix(b.q, a.q, k);
len = mix(b.len, a.len, k);
tout = mix(b.t_out, a.t_out, k);
c = floor_at(g, q, max(frost * (6.0 + len * 0.35), fp));
} else if (!a.floor && !b.floor) {
let dir = normalize(mix(b.dir, a.dir, k));
len = mix(b.len, a.len, k);
tout = mix(b.t_out, a.t_out, k);
c = env(dir);
} else {
var pa = b;
if (k > 0.5) {
pa = a;
}
len = pa.len;
tout = pa.t_out;
if (pa.floor) {
c = floor_at(g, pa.q, max(frost * (6.0 + len * 0.35), fp));
} else {
c = env(pa.dir);
}
}
let beer = exp(-g.tint.rgb * len);
trans = trans + w * c * beer * tout;
wsum = wsum + w;
}
trans = trans / wsum;
let v_up = vec3<f32>(0.0, 0.0, 1.0);
let F = fresnel(n.z, 1.0, ior);
// Reflection: upward rays see the studio, downward ones (off steep walls) the lit UI beside the glass, glowing
// elements included: those are the coloured highlights on the bevel.
let rr = reflect(vec3<f32>(0.0, 0.0, -1.0), n);
let reach = min(zt * length(rr.xy) / max(-rr.z, 1e-3), zt * 4.0);
let below = ui_at(p + normalize(rr.xy + vec2<f32>(1e-5)) * reach, 4.0 + reach * 0.08);
let refl = mix(env(rr), below, smoothstep(0.05, -0.15, rr.z));
// Frost scatters the light passing through into a milky veil.
let flu = textureSampleLevel(fluence, samp, p / u.size.xy, 0.0).rgb;
var col = trans * (1.0 - F) + refl * F;
col = col + flu * frost * 0.10;
// Highlights: the glowing UI elements as sphere lights.
let P = vec3<f32>(p, zt);
let rough = mix(0.035, 0.32, frost);
var spec = vec3<f32>(0.0);
let nl = i32(u.size.w);
for (var i = 0; i < nl; i = i + 1) {
let L = glights[i];
let D = L.pos.xyz - P;
let dist = length(D);
let l = D / max(dist, 1e-3);
let ndl = max(dot(n, l), 0.0);
if (ndl <= 0.0) {
continue;
}
let h = normalize(l + v_up);
let a0 = sqrt(rough * rough + spec_var);
let al = clamp(a0 + L.pos.w / (2.0 * dist), 0.02, 1.0);
let energy = (a0 * a0) / (al * al);
let fh = fresnel(max(dot(l, h), 0.0), 1.0, ior);
let fall = 1.0 / (1.0 + dist * dist / (L.pos.w * L.pos.w + 1.0));
spec = spec + L.color.rgb * ggx(max(dot(n, h), 0.0), al) * energy * fh * ndl * fall;
}
col = col + spec;
// GI light that enters the bevel scatters along it: rims pick up the colour of the lights around them.
let bevel = max(g.p0.y, 1.0);
let rim = pow(1.0 - clamp(-d / bevel, 0.0, 1.0), 2.0);
col = col + flu * rim * g.tint.w;
return vec4<f32>(col, cov);
}
@fragment
fn fs(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
let p = pos.xy;
let base = textureLoad(backdrop, vec2<i32>(p), 0).rgb;
let ng = i32(u.size.z);
let reach = u.shadow.z * 2.5 + length(u.shadow.xy) + 12.0;
var col = base;
// No `continue` in this loop: every iteration stays in uniform control flow for the derivatives.
for (var gk = 0; gk < ng; gk = gk + 1) {
let g = glass[gk];
let d = sdf(g, p);
// Normal variance for specular AA (Tokuyoshi & Kaplanyan), and the footprint of the refracted lookup: where
// the bevel squeezes the UI into a thin band, one pixel covers many, so the lookup is prefiltered to match
// instead of aliasing into streaks. Both come from this slab's values, computed only near it (a shaded pixel's
// quad neighbours are all within a few px of the edge).
var nv = vec3<f32>(0.0, 0.0, 1.0);
var q0 = p;
if (g.p1.w > 0.0 && d < 8.0) {
nv = normal_at(g, p);
let tr = trace(g, p, nv, height(g, p), g.p1.x);
q0 = select(p + tr.dir.xy * 400.0, tr.q, tr.floor);
}
let dn = dpdx(nv);
let dm = dpdy(nv);
let spec_var = min(2.0 * 0.25 * (dot(dn, dn) + dot(dm, dm)), 0.18);
let fpx = max(length(dpdx(q0)), length(dpdy(q0)));
let fp = clamp(fpx * 0.5 - 0.5, 0.0, 24.0);
if (g.p1.w > 0.0 && d <= reach) {
// Shadow on the UI outside the glass.
let outside = col * (1.0 - glass_shadow(g, p));
let bevel = max(g.p0.y, 1.0);
if (d > 1.0) {
col = outside;
} else if (-d < bevel + 1.0) {
// Supersample the bevel (rotated grid), where refraction changes fastest.
let o = array<vec2<f32>, 4>(vec2<f32>(-0.125, -0.375), vec2<f32>(0.375, -0.125), vec2<f32>(0.125, 0.375), vec2<f32>(-0.375, 0.125));
var acc = vec4<f32>(0.0);
for (var k = 0; k < 4; k = k + 1) {
let s = shade(g, p + o[k], spec_var, fp);
acc = acc + vec4<f32>(s.rgb * s.a, s.a);
}
acc = acc * 0.25;
col = outside * (1.0 - acc.a) + acc.rgb;
} else {
let s = shade(g, p, spec_var, fp);
col = mix(outside, s.rgb, s.a);
}
}
}
return vec4<f32>(col, 1.0);
}
// ---- pyramid ----
// 13-tap downsample (Jimenez, "Next generation post processing in Call of Duty: AW"): no box aliasing, no flicker.
@group(0) @binding(0) var src: texture_2d<f32>;
@group(0) @binding(1) var ssamp: sampler;
@fragment
fn fs_down(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
let sz = vec2<f32>(textureDimensions(src, 0));
let uv = pos.xy * 2.0 / sz;
let t = 1.0 / sz;
let a = textureSampleLevel(src, ssamp, uv + t * vec2<f32>(-2.0, -2.0), 0.0).rgb;
let b = textureSampleLevel(src, ssamp, uv + t * vec2<f32>(0.0, -2.0), 0.0).rgb;
let c = textureSampleLevel(src, ssamp, uv + t * vec2<f32>(2.0, -2.0), 0.0).rgb;
let d = textureSampleLevel(src, ssamp, uv + t * vec2<f32>(-2.0, 0.0), 0.0).rgb;
let e = textureSampleLevel(src, ssamp, uv, 0.0).rgb;
let f = textureSampleLevel(src, ssamp, uv + t * vec2<f32>(2.0, 0.0), 0.0).rgb;
let g = textureSampleLevel(src, ssamp, uv + t * vec2<f32>(-2.0, 2.0), 0.0).rgb;
let h = textureSampleLevel(src, ssamp, uv + t * vec2<f32>(0.0, 2.0), 0.0).rgb;
let i = textureSampleLevel(src, ssamp, uv + t * vec2<f32>(2.0, 2.0), 0.0).rgb;
let j = textureSampleLevel(src, ssamp, uv + t * vec2<f32>(-1.0, -1.0), 0.0).rgb;
let k = textureSampleLevel(src, ssamp, uv + t * vec2<f32>(1.0, -1.0), 0.0).rgb;
let l = textureSampleLevel(src, ssamp, uv + t * vec2<f32>(-1.0, 1.0), 0.0).rgb;
let m = textureSampleLevel(src, ssamp, uv + t * vec2<f32>(1.0, 1.0), 0.0).rgb;
let o = e * 0.125 + (a + c + g + i) * 0.03125 + (b + d + f + h) * 0.0625 + (j + k + l + m) * 0.125;
return vec4<f32>(o, 1.0);
}
@@ -0,0 +1,129 @@
// Soft visibility of every light, sphere traced through the scene distance field.
//
// Occluders are extruded rounded rects (slabs from z bottom to z top) standing on the UI plane. A receiver P
// (the surface's own top) traces toward the light's centre; at each step the 3D clearance h to the nearest slab
// against the cone to a spherical source of radius R (half-angle R / D) gives the penumbra, as in Arcade's
// capsule shadows (packages/kit/gpu/shadows/capsule-shadows.ts:508-527: k = 0.5 + 0.5 h / (t θ), smoothstep).
// Aaltonen's closest-approach refinement of Quílez's estimate stops sphere-tracing steps from banding the
// penumbra. Penumbrae harden toward contact for free: t → 0 makes the cone vanish.
//
// Shafts ("air") trace the same field along a horizontal ray at the light's own height, so a light standing
// lower than the cards throws flatland wedges: god rays through every gap.
@group(0) @binding(0) var<uniform> F: Frame;
@group(0) @binding(1) var<storage, read> lights: array<Light>;
@group(0) @binding(2) var field: texture_2d<f32>;
@group(0) @binding(3) var samp: sampler;
@group(0) @binding(4) var gb0: texture_2d<f32>;
@group(0) @binding(5) var out_vis: texture_storage_2d_array<rgba16float, write>;
@group(0) @binding(6) var out_air: texture_storage_2d_array<rgba16float, write>;
fn field_at(q: vec2<f32>) -> vec4<f32> {
return textureSampleLevel(field, samp, q * F.gs.z / F.sf.zw, 0.0);
}
fn slab(f: vec4<f32>, z: f32) -> f32 {
let dz = max(z - f.z, f.y - z);
let a = vec2<f32>(f.x, dz);
return length(max(a, vec2<f32>(0.0))) + min(max(a.x, a.y), 0.0);
}
fn trace(P: vec3<f32>, L: vec3<f32>, radius: f32, t_start: f32, zcut: bool) -> f32 {
let D = L - P;
let dist = length(D);
if (dist < 1e-3) {
return 1.0;
}
let rd = D / dist;
let theta = max(radius / dist, 1e-3);
let zmax = F.misc.x + 0.5;
var t = t_start;
var res = 1.0;
var ph = 1e10;
let t_end = dist - radius;
for (var i = 0; i < 64; i = i + 1) {
if (t >= t_end) {
break;
}
let q = P + rd * t;
if (zcut && rd.z >= 0.0 && q.z > zmax) {
break;
}
let h = slab(field_at(q.xy), q.z);
if (h <= 0.0) {
res = min(res, h / (t * theta));
} else {
let y = h * h / (2.0 * ph);
let dd = sqrt(max(h * h - y * y, 0.0));
res = min(res, dd / (max(t - y, 1e-3) * theta));
}
ph = max(h, 1e-3);
if (res <= -1.0) {
break;
}
// Inside a slab, walk through in small steps; outside, the clearance is a safe step. A floor that
// grows with t keeps the step count bounded on long rays.
t = t + clamp(abs(h), 0.6 + t * 0.012, 96.0);
}
let k = clamp(0.5 + 0.5 * res, 0.0, 1.0);
return k * k * (3.0 - 2.0 * k);
}
// God rays from a light behind the UI (Mitchell, GPU Gems 3 ch. 13, done in the field instead of a blurred
// buffer): the light's glow shows only through gaps between occluders, and each pixel integrates that masked glow
// along its path to the light. The mask is prefiltered to the sample spacing, so edges never band into steps.
fn shaft(p: vec2<f32>, L: Light) -> f32 {
let D = L.pos.xy - p;
let len = length(D);
let R = max(L.pos.w * L.extra.w, 1.0);
let n = 48;
let step = len / f32(n);
let w = max(step * 0.6, 2.0);
var acc = 0.0;
for (var i = 0; i < n; i = i + 1) {
let q = p + D * ((f32(i) + 0.5) / f32(n));
let open = smoothstep(-w, w, field_at(q).x);
let r = length(L.pos.xy - q);
acc = acc + open * R * R / (r * r + R * R);
}
return acc / f32(n);
}
@compute @workgroup_size(8, 8)
fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
let fs = vec2<u32>(F.sf.zw);
if (gid.x >= fs.x || gid.y >= fs.y) {
return;
}
let p = (vec2<f32>(gid.xy) + 0.5) / F.gs.z;
let pix = clamp(vec2<i32>(p), vec2<i32>(0), vec2<i32>(F.sf.xy) - vec2<i32>(1));
let zr = textureLoad(gb0, pix, 0).w + 0.35;
let P = vec3<f32>(p, zr);
let shafts = (F.counts.w & 2u) != 0u;
var vis: array<vec4<f32>, 2>;
var air: array<vec4<f32>, 2>;
vis[0] = vec4<f32>(1.0);
vis[1] = vec4<f32>(1.0);
air[0] = vec4<f32>(1.0);
air[1] = vec4<f32>(1.0);
let n = min(F.counts.y, 8u);
for (var li = 0u; li < n; li = li + 1u) {
let L = lights[li];
let lt = light_term(L, P);
var v = 1.0;
// Skip rays that can't matter: no light reaches P (range, cone) or it comes from below the surface.
if (lt.w > 1e-5 && L.pos.z > zr) {
v = trace(P, L.pos.xyz, L.pos.w * L.extra.w, 0.75, true);
}
vis[li / 4u][li % 4u] = v;
if (shafts && L.extra.x > 0.0) {
air[li / 4u][li % 4u] = shaft(p, L);
}
}
textureStore(out_vis, gid.xy, 0, vis[0]);
textureStore(out_air, gid.xy, 0, air[0]);
if (n > 4u) {
textureStore(out_vis, gid.xy, 1, vis[1]);
textureStore(out_air, gid.xy, 1, air[1]);
}
}
+126
View File
@@ -0,0 +1,126 @@
//! The renderer's size-dependent textures and the bind groups that read them.
use super::*;
pub(crate) struct Targets {
pub(crate) vis_tex: wgpu::Texture,
pub(crate) gb0: wgpu::TextureView,
pub(crate) gb1: wgpu::TextureView,
pub(crate) field: wgpu::TextureView,
pub(crate) vis: wgpu::TextureView,
pub(crate) air: wgpu::TextureView,
pub(crate) field_bg: wgpu::BindGroup,
pub(crate) shadow_bg: wgpu::BindGroup,
/// GI's textures, made the first frame GI runs.
pub(crate) gi: Option<GiTargets>,
}
pub(crate) struct GiTargets {
pub(crate) scene_emit: wgpu::TextureView,
pub(crate) scene_occ: wgpu::TextureView,
/// Merged radiance per cascade level (index = level).
pub(crate) levels: Vec<wgpu::TextureView>,
/// Each level's own interval without the merge: black until `inspect` is first on, then written while it's on.
pub(crate) own: Vec<wgpu::TextureView>,
pub(crate) fluence: wgpu::TextureView,
pub(crate) cascade_bgs: Vec<wgpu::BindGroup>,
pub(crate) own_bgs: Vec<wgpu::BindGroup>,
pub(crate) fluence_bg: wgpu::BindGroup,
}
impl LightRenderer {
#[allow(clippy::too_many_arguments)]
pub(crate) fn targets(
device: &wgpu::Device,
w: u32,
h: u32,
fsz: (u32, u32),
frame: &wgpu::Buffer,
prims: &wgpu::Buffer,
lights: &wgpu::Buffer,
sampler: &wgpu::Sampler,
[field_bgl, shadow_bgl]: [&wgpu::BindGroupLayout; 2],
) -> Targets {
use wgpu::TextureFormat as Tf;
use wgpu::TextureUsages as U;
let rt = U::RENDER_ATTACHMENT | U::TEXTURE_BINDING;
let st = U::STORAGE_BINDING | U::TEXTURE_BINDING | U::COPY_SRC;
let gb0 = texture(device, "gb0", w, h, 1, Tf::Rgba16Float, rt).create_view(&Default::default());
let gb1 = texture(device, "gb1", w, h, 1, Tf::R32Uint, rt).create_view(&Default::default());
let field = texture(device, "field", fsz.0, fsz.1, 1, Tf::Rgba16Float, st).create_view(&Default::default());
let arr = |label| {
let t = texture(device, label, fsz.0, fsz.1, 2, Tf::Rgba16Float, st);
let v = t.create_view(&wgpu::TextureViewDescriptor { dimension: Some(wgpu::TextureViewDimension::D2Array), ..Default::default() });
(t, v)
};
let (vis_tex, vis) = arr("vis");
let (_, air) = arr("air");
let smp = wgpu::BindingResource::Sampler(sampler);
let field_bg = bind(device, field_bgl, [frame.as_entire_binding(), prims.as_entire_binding(), tv(&field)]);
let shadow_bg = bind(device, shadow_bgl, [frame.as_entire_binding(), lights.as_entire_binding(), tv(&field), smp, tv(&gb0), tv(&vis), tv(&air)]);
Targets { vis_tex, gb0, gb1, field, vis, air, field_bg, shadow_bg, gi: None }
}
/// GI's textures and bind groups, made the first frame GI runs.
pub(crate) fn gi_targets(&mut self, device: &wgpu::Device) {
if self.t.gi.is_some() {
return;
}
use wgpu::TextureFormat as Tf;
let st = wgpu::TextureUsages::STORAGE_BINDING | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC;
let gsz = self.gi_size;
let scene_emit = texture(device, "gi emit", gsz.0, gsz.1, 1, Tf::Rgba16Float, st).create_view(&Default::default());
let scene_occ = texture(device, "gi occ", gsz.0, gsz.1, 1, Tf::Rgba16Float, st).create_view(&Default::default());
let level = |label| texture(device, label, gsz.0 * 2, gsz.1 * 2, 1, Tf::Rgba16Float, st).create_view(&Default::default());
let levels: Vec<wgpu::TextureView> = (0..CASCADES).map(|_| level("cascade")).collect();
let fluence = texture(device, "fluence", gsz.0, gsz.1, 1, Tf::Rgba16Float, st).create_view(&Default::default());
let (t, black) = (&self.t, &self.black);
let smp = wgpu::BindingResource::Sampler(&self.sampler);
// Dispatched top cascade first; each level reads the merged level above it.
let cascade_bgs = (0..CASCADES as usize)
.rev()
.map(|n| {
let upper = if n + 1 < CASCADES as usize { &levels[n + 1] } else { black };
bind(
device,
&self.cascade_bgl,
[self.cascade_u[n].as_entire_binding(), tv(&scene_emit), tv(&scene_occ), tv(&t.field), smp.clone(), tv(upper), tv(&levels[n]), tv(&t.gb0)],
)
})
.collect();
let fluence_bg = bind(device, &self.fluence_bgl, [tv(&levels[0]), tv(&fluence)]);
let own = vec![black.clone(); CASCADES as usize];
self.t.gi = Some(GiTargets { scene_emit, scene_occ, levels, own, fluence, cascade_bgs, own_bgs: Vec::new(), fluence_bg });
}
/// The per-level textures for `inspect`, made the first time it's on with GI.
pub(crate) fn own_targets(&mut self, device: &wgpu::Device) {
let Some(g) = self.t.gi.as_ref().filter(|g| g.own_bgs.is_empty()) else { return };
let st = wgpu::TextureUsages::STORAGE_BINDING | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC;
let (gw, gh) = (self.gi_size.0 * 2, self.gi_size.1 * 2);
let own: Vec<wgpu::TextureView> =
(0..CASCADES).map(|_| texture(device, "cascade own", gw, gh, 1, wgpu::TextureFormat::Rgba16Float, st).create_view(&Default::default())).collect();
let t = &self.t;
let smp = wgpu::BindingResource::Sampler(&self.sampler);
let own_bgs = (0..CASCADES as usize)
.rev()
.map(|n| {
bind(
device,
&self.cascade_bgl,
[self.own_u[n].as_entire_binding(), tv(&g.scene_emit), tv(&g.scene_occ), tv(&t.field), smp.clone(), tv(&self.black), tv(&own[n]), tv(&t.gb0)],
)
})
.collect();
if let Some(g) = self.t.gi.as_mut() {
g.own = own;
g.own_bgs = own_bgs;
}
}
/// After `prims` was reallocated: rebuild only the bind groups that bind it.
pub(crate) fn rebind_prims(&mut self, device: &wgpu::Device) {
self.gbuf_bg = bind(device, &self.gbuf_bgl, [self.frame.as_entire_binding(), self.prims.as_entire_binding()]);
self.t.field_bg = bind(device, &self.field_bgl, [self.frame.as_entire_binding(), self.prims.as_entire_binding(), tv(&self.t.field)]);
}
}
@@ -0,0 +1,16 @@
//! Every pipeline Rune, rune-fx and rune-light ship finds its function in Rune's precompiled
//! Metal library under `RUNE_GPU_BACKEND=metal`. A miss means a shader or its layout changed:
//! run `scripts/precompile-metal-shaders.sh`, which runs this test with `RUNE_METAL_CAPTURE`
//! set to capture them.
#[path = "support/builtin.rs"]
mod builtin;
#[test]
fn every_builtin_pipeline_is_precompiled() {
let gpu = rune::render::Gpu::headless();
builtin::build_every_pipeline(&gpu);
if std::env::var_os("RUNE_METAL_CAPTURE").is_some() { return }
let Some(misses) = rune::render::precompiled_misses(&gpu.device) else { return };
assert_eq!(misses, 0, "{misses} built-in pipelines compiled at runtime; run scripts/precompile-metal-shaders.sh");
}
@@ -0,0 +1,306 @@
//! Continuous corners (negative radii) in `rune-light`'s shaders (`common.wgsl`, `glass.wgsl`) and
//! CPU reference (`cpu.rs`) must match Rune's uber shader (`clip.wgsl` `sd_rounded`).
use rune::render::{Gpu, Instance, KIND_RECT, NO_CLIP, OFFSCREEN_FORMAT, Offscreen, Renderer};
use rune_light::{Glass, GlassRenderer, GlassSettings, Light, LightRenderer, Prim, Scene, Settings, cpu};
const W: u32 = 96;
const H: u32 = 80;
fn read_rgba8(device: &wgpu::Device, queue: &wgpu::Queue, tex: &wgpu::Texture, w: u32, h: u32) -> Vec<u8> {
let padded = (w * 4).div_ceil(256) * 256;
let buf = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("readback"),
size: u64::from(padded * h),
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
});
let mut enc = device.create_command_encoder(&Default::default());
enc.copy_texture_to_buffer(
wgpu::TexelCopyTextureInfo { texture: tex, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
wgpu::TexelCopyBufferInfo {
buffer: &buf,
layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(padded), rows_per_image: Some(h) },
},
wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
);
queue.submit([enc.finish()]);
let slice = buf.slice(..);
slice.map_async(wgpu::MapMode::Read, |_| {});
device.poll(wgpu::PollType::wait_indefinitely()).expect("poll");
let data = slice.get_mapped_range().expect("mapped");
let mut out = Vec::with_capacity((w * h * 4) as usize);
for y in 0..h as usize {
out.extend_from_slice(&data[y * padded as usize..y * padded as usize + (w * 4) as usize]);
}
drop(data);
buf.unmap();
out
}
fn read_rgba16f(device: &wgpu::Device, queue: &wgpu::Queue, tex: &wgpu::Texture, w: u32, h: u32) -> Vec<[f32; 4]> {
let row_bytes = w * 8;
let padded = row_bytes.div_ceil(256) * 256;
let buf = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("readback f16"),
size: u64::from(padded * h),
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
});
let mut enc = device.create_command_encoder(&Default::default());
enc.copy_texture_to_buffer(
wgpu::TexelCopyTextureInfo { texture: tex, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
wgpu::TexelCopyBufferInfo {
buffer: &buf,
layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(padded), rows_per_image: Some(h) },
},
wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
);
queue.submit([enc.finish()]);
let slice = buf.slice(..);
slice.map_async(wgpu::MapMode::Read, |_| {});
device.poll(wgpu::PollType::wait_indefinitely()).expect("poll");
let data = slice.get_mapped_range().expect("mapped");
let mut out = Vec::with_capacity((w * h) as usize);
for y in 0..h as usize {
let row = &data[y * padded as usize..y * padded as usize + row_bytes as usize];
for px in row.chunks_exact(8) {
let f = |i: usize| f16_to_f32(u16::from_le_bytes([px[i], px[i + 1]]));
out.push([f(0), f(2), f(4), f(6)]);
}
}
drop(data);
buf.unmap();
out
}
fn f16_to_f32(bits: u16) -> f32 {
let sign = u32::from(bits >> 15) << 31;
let exp = u32::from((bits >> 10) & 0x1f);
let mant = u32::from(bits & 0x3ff);
if exp == 0 {
if mant == 0 {
return f32::from_bits(sign);
}
let v = (mant as f32) * 2.0f32.powi(-24);
return if sign != 0 { -v } else { v };
}
if exp == 31 {
return f32::from_bits(sign | 0x7f80_0000 | (mant << 13));
}
f32::from_bits(sign | ((exp + 112) << 23) | (mant << 13))
}
fn render_uber_rect(gpu: &Gpu, rect: [f32; 4], radii: [f32; 4]) -> Vec<u8> {
let inst = Instance {
rect,
radii,
fill: [1.0; 4],
border: [0.0; 4],
params: [0.0, KIND_RECT, 0.0, 1.0],
uv: [0.0; 4],
clip: NO_CLIP,
fade: [0; 4],
};
let mut atlas = rune::text::Atlas::new();
let mut renderer = Renderer::new(&gpu.device, OFFSCREEN_FORMAT);
renderer.prepare(&gpu.device, &gpu.queue, &mut atlas, &[inst], (W, H));
let target = Offscreen::new(&gpu.device, W, H);
let mut enc = gpu.device.create_command_encoder(&Default::default());
renderer.draw(&mut enc, &target.view, [0.0; 4]);
target.copy(&mut enc);
renderer.submit(&gpu.queue, enc);
target.read(&gpu.device)
}
fn solid_texture(device: &wgpu::Device, queue: &wgpu::Queue, format: wgpu::TextureFormat, color: wgpu::Color) -> wgpu::Texture {
let tex = device.create_texture(&wgpu::TextureDescriptor {
label: None,
size: wgpu::Extent3d { width: W, height: H, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
});
let view = tex.create_view(&Default::default());
let mut enc = device.create_command_encoder(&Default::default());
let _pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
label: None,
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations { load: wgpu::LoadOp::Clear(color), store: wgpu::StoreOp::Store },
})],
..Default::default()
});
drop(_pass);
queue.submit([enc.finish()]);
tex
}
#[test]
fn light_gbuffer_field_and_cpu_match_rune_continuous_corners() {
let Ok(gpu) = Gpu::try_new(Gpu::instance(), None) else { return eprintln!("no adapter; skipped") };
let rect = [8.0, 8.0, 80.0, 64.0];
let cases = [
("uniform-continuous", [-20.0; 4]),
("mixed-continuous", [-20.0, 12.0, -10.0, 0.0]),
];
let base_tex = solid_texture(&gpu.device, &gpu.queue, wgpu::TextureFormat::Rgba16Float, wgpu::Color { r: 0.5, g: 0.5, b: 0.5, a: 1.0 });
let text_tex = solid_texture(&gpu.device, &gpu.queue, wgpu::TextureFormat::Rgba16Float, wgpu::Color::TRANSPARENT);
let out_tex = solid_texture(&gpu.device, &gpu.queue, wgpu::TextureFormat::Rgba8Unorm, wgpu::Color::BLACK);
let (base_view, text_view, out_view) = (
base_tex.create_view(&Default::default()),
text_tex.create_view(&Default::default()),
out_tex.create_view(&Default::default()),
);
let mut light = LightRenderer::new(&gpu.device, &gpu.queue, W, H, wgpu::TextureFormat::Rgba8Unorm);
for (name, radii) in cases {
let uber = render_uber_rect(&gpu, rect, radii);
let prim = Prim::from_rune(rect, radii).raised(16.0).emissive([1.0, 1.0, 1.0]);
// Zero ambient + zero-intensity light isolates gbuffer surface ownership (`emissive` lights
// `base` wherever `gbuffer.wgsl` keeps the pixel with `d <= 0.5`).
let lights = [Light::point(48.0, 40.0, 100.0).intensity(0.0)];
let settings = Settings {
ambient: [0.0; 3],
contact_ao: 0.0,
rim: 0.0,
albedo_floor: 0.0,
background_gloss: 0.0,
..Settings::default()
};
let scene = Scene { prims: &[prim], lights: &lights, settings, emission: None };
let mut enc = gpu.device.create_command_encoder(&Default::default());
assert!(light.render(&gpu.device, &gpu.queue, &mut enc, &scene, &base_view, &text_view, &out_view));
gpu.queue.submit([enc.finish()]);
let lit = read_rgba8(&gpu.device, &gpu.queue, &out_tex, W, H);
// 1. Compare gbuffer surface silhouette inside the primitive's rect against Rune's uber
// shader continuous-corner mask. gbuffer keeps `d <= 0.5` (including the exact 0.5 px
// straight-edge outer border where uber alpha is 0), so check inside `[8..88, 8..72]`
// where every corner's continuous curve lies.
let mut mismatches = 0usize;
let mut first = None;
for y in 8..72u32 {
for x in 8..88u32 {
let i = ((y * W + x) * 4) as usize;
let uber_a = uber[i + 3];
let lit_r = lit[i];
let uber_inside = uber_a > 5;
let uber_outside = uber_a == 0;
let lit_inside = lit_r > 100;
if (uber_inside && !lit_inside) || (uber_outside && lit_inside) {
mismatches += 1;
if first.is_none() {
first = Some((x, y, uber_a, lit_r));
}
}
}
}
assert_eq!(
mismatches, 0,
"{name}: rune-light gbuffer silhouette drifted from uber shader: {mismatches} pixels, first={first:?}"
);
// 2. Compare GPU `field` SDF against `cpu::field` AND check that the continuous corner
// actually cuts the corner (at `(10, 10)` inside the bounding box, distance must be positive!).
let (fw, fh) = light.field_size();
let field_tex = light.inspect().field.texture().clone();
let gpu_field = read_rgba16f(&gpu.device, &gpu.queue, &field_tex, fw, fh);
let mut max_sd_err = 0.0f32;
let mut worst_sd = None;
for fy in 0..fh {
for fx in 0..fw {
let p = [(fx as f32 + 0.5) * 2.0, (fy as f32 + 0.5) * 2.0];
let cpu_d = cpu::field(&[prim], p)[0];
let gpu_d = gpu_field[(fy * fw + fx) as usize][0];
let err = (cpu_d - gpu_d).abs();
if err > max_sd_err {
max_sd_err = err;
worst_sd = Some((fx, fy, cpu_d, gpu_d));
}
}
}
assert!(
max_sd_err < 0.05,
"{name}: GPU field SDF drifted from cpu::field: max_err={max_sd_err} worst={worst_sd:?}"
);
// Pixel (11, 11) is 3 px inside the sharp corner (8, 8): outside a continuous r=20 corner.
let corner_cpu = cpu::field(&[prim], [11.0, 11.0])[0];
let corner_gpu = gpu_field[(5 * fw + 5) as usize][0];
assert!(
corner_cpu > 3.0 && corner_gpu > 3.0,
"{name}: continuous corner at (11,11) must have positive SDF (outside shape), got cpu={corner_cpu} gpu={corner_gpu}"
);
}
}
#[test]
fn glass_continuous_corners_match_rune_uber_shader() {
let Ok(gpu) = Gpu::try_new(Gpu::instance(), None) else { return eprintln!("no adapter; skipped") };
let rect = [8.0, 8.0, 80.0, 64.0];
let uber = render_uber_rect(&gpu, rect, [-20.0; 4]);
// Pure red backdrop, opaque-absorbing glass with zero env/shadow/caustic: outside glass stays
// red (255), inside glass goes black (0), edge coverage blends linearly with `clamp(0.5 - d)`.
let backdrop = solid_texture(&gpu.device, &gpu.queue, wgpu::TextureFormat::Rgba16Float, wgpu::Color { r: 1.0, g: 0.0, b: 0.0, a: 1.0 });
let black = solid_texture(&gpu.device, &gpu.queue, wgpu::TextureFormat::Rgba16Float, wgpu::Color::BLACK);
let out = solid_texture(&gpu.device, &gpu.queue, wgpu::TextureFormat::Rgba8Unorm, wgpu::Color::BLACK);
let (bd_view, bl_view, out_view) = (
backdrop.create_view(&Default::default()),
black.create_view(&Default::default()),
out.create_view(&Default::default()),
);
let mut glass = GlassRenderer::new(&gpu.device, W, H, wgpu::TextureFormat::Rgba8Unorm);
let slab = Glass::rounded(rect[0], rect[1], rect[2], rect[3], -20.0)
.thickness(24.0)
.bevel(1.0)
.gap(4.0)
.tint([10.0, 10.0, 10.0])
.rim_glow(0.0);
let settings = GlassSettings { env: 0.0, shadow: 0.0, caustic: 0.0, ..GlassSettings::default() };
let mut enc = gpu.device.create_command_encoder(&Default::default());
glass.render(&gpu.device, &gpu.queue, &mut enc, &[slab], &[], settings, &bd_view, &bl_view, &out_view);
gpu.queue.submit([enc.finish()]);
let px = read_rgba8(&gpu.device, &gpu.queue, &out, W, H);
let mut mismatches = 0usize;
let mut first = None;
for y in 0..H {
for x in 0..W {
let i = ((y * W + x) * 4) as usize;
let uber_a = uber[i + 3];
// Outside the continuous corner (`uber_a == 0`), glass with shadow=0 leaves the red
// backdrop untouched (r=255). Deep inside (past the 1px bevel, so 3x3 neighbourhood is
// all uber_a == 255), absorbing glass reduces red near zero (only ~4% Fresnel).
let glass_cov = 255u8.saturating_sub(px[i]);
let deep_inside = x >= 10 && x < 86 && y >= 10 && y < 70 && uber_a == 255 && {
let mut all = true;
for dy in -1i32..=1 {
for dx in -1i32..=1 {
let ni = (((y as i32 + dy) as u32 * W + (x as i32 + dx) as u32) * 4) as usize;
if uber[ni + 3] != 255 {
all = false;
}
}
}
all
};
if (uber_a == 0 && glass_cov > 10) || (deep_inside && glass_cov < 200) {
mismatches += 1;
if first.is_none() {
first = Some((x, y, uber_a, px[i]));
}
}
}
}
assert_eq!(
mismatches, 0,
"glass.wgsl continuous corner drifted from uber shader: {mismatches} pixels, first={first:?}"
);
}
@@ -0,0 +1,24 @@
//! Builds every pipeline Rune, rune-fx and rune-light ship, once, timing each step in
//! milliseconds.
fn ms<T>(f: impl FnOnce() -> T) -> (T, f64) {
let start = rune::time::now();
let out = f();
(out, start.elapsed().as_secs_f64() * 1e3)
}
pub fn build_every_pipeline(gpu: &rune::render::Gpu) -> Vec<(&'static str, f64)> {
let format = wgpu::TextureFormat::Bgra8UnormSrgb;
let mut out = Vec::new();
let (renderer, t) = ms(|| rune::render::Renderer::new(&gpu.device, format));
out.push(("renderer", t));
out.extend(renderer.first_use_ms(&gpu.device));
let (mut fx, t) = ms(|| rune_fx::FxRenderer::new(&gpu.device, format, Default::default()));
out.push(("fx", t));
out.push(("fx_layer_format", ms(|| fx.add_format(&gpu.device, wgpu::TextureFormat::Rgba16Float)).1));
out.push(("fx_every_pipeline", ms(|| fx.build_every_pipeline()).1));
out.push(("fx_fire_sim", ms(|| fx.set_fire_sim(&gpu.device, true)).1));
out.push(("light", ms(|| drop(rune_light::LightRenderer::new(&gpu.device, &gpu.queue, 256, 256, format))).1));
out.push(("glass", ms(|| drop(rune_light::GlassRenderer::new(&gpu.device, 256, 256, format))).1));
out
}
+124
View File
@@ -0,0 +1,124 @@
//! What `LightRenderer::render` and `GlassRenderer::render` allocate and record, on a real device. Skips when no
//! adapter is found.
use rune_light::{Gi, Light, LightRenderer, Prim, Scene, Settings};
const W: u32 = 256;
const H: u32 = 160;
struct Rig {
device: wgpu::Device,
queue: wgpu::Queue,
light: LightRenderer,
base: wgpu::TextureView,
text: wgpu::TextureView,
target: wgpu::TextureView,
timed: bool,
}
fn rig() -> Option<Rig> {
// Rune's GPU, so `RUNE_GPU_BACKEND` picks the backend these run on.
let rune::render::Gpu { device, queue, .. } = rune::render::Gpu::try_new(rune::render::Gpu::instance(), None).ok()?;
let features = device.features() & wgpu::Features::TIMESTAMP_QUERY;
let view = |format| {
device
.create_texture(&wgpu::TextureDescriptor {
label: None,
size: wgpu::Extent3d { width: W, height: H, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
})
.create_view(&Default::default())
};
let (base, text, target) = (view(wgpu::TextureFormat::Rgba16Float), view(wgpu::TextureFormat::Rgba16Float), view(wgpu::TextureFormat::Rgba8Unorm));
let light = LightRenderer::new(&device, &queue, W, H, wgpu::TextureFormat::Rgba8Unorm);
Some(Rig { device, queue, light, base, text, target, timed: !features.is_empty() })
}
impl Rig {
fn frame(&mut self, prims: &[Prim], gi: Option<Gi>) {
let encoder = self.record(prims, gi);
self.submit(encoder);
}
fn record(&mut self, prims: &[Prim], gi: Option<Gi>) -> wgpu::CommandEncoder {
let lights = [Light::point(60.0, 40.0, 120.0)];
let scene = Scene { prims, lights: &lights, settings: Settings { gi, ..Settings::default() }, emission: None };
let mut encoder = self.device.create_command_encoder(&Default::default());
assert!(self.light.render(&self.device, &self.queue, &mut encoder, &scene, &self.base, &self.text, &self.target));
encoder
}
fn submit(&self, encoder: wgpu::CommandEncoder) {
self.queue.submit([encoder.finish()]);
self.device.poll(wgpu::PollType::wait_indefinitely()).expect("poll");
}
#[cfg(feature = "test-gpu-counters")]
fn live_bind_groups(&self) -> isize {
self.device.get_internal_counters().hal.bind_groups.read()
}
}
fn prims(n: usize) -> Vec<Prim> {
(0..n).map(|i| Prim::rect((i % 16) as f32 * 14.0, (i / 16) as f32 * 8.0, 10.0, 6.0).raised(4.0)).collect()
}
#[test]
fn growing_the_prim_buffer_keeps_the_render_targets() {
let Some(mut r) = rig() else { return eprintln!("no adapter; skipped") };
r.frame(&prims(8), None);
let vis = r.light.visibility_texture().clone();
r.frame(&prims(300), None);
assert!(*r.light.visibility_texture() == vis, "a bigger scene reallocated the render targets");
}
#[test]
fn without_gi_nothing_gi_is_allocated_or_recorded() {
let Some(mut r) = rig() else { return eprintln!("no adapter; skipped") };
r.frame(&prims(8), None);
{
let ins = r.light.inspect();
assert!(ins.emission == ins.fluence && ins.merged[0] == *ins.fluence, "GI textures exist with GI off");
}
// Field and shadows, plus the two timestamp markers when timing.
assert_eq!(r.light.compute_passes(), if r.timed { 4 } else { 2 });
r.frame(&prims(8), Some(Gi::default()));
let ins = r.light.inspect();
assert!(ins.emission != ins.fluence, "turning GI on made its textures");
if r.timed {
assert!(r.light.read_timings(&r.device).is_some_and(|t| t.gi >= 0.0));
}
}
/// A bind group made for one frame lives only as long as that frame's commands, so recording a steady frame
/// raises the live count until it's submitted. A cached one is already live.
#[cfg(feature = "test-gpu-counters")]
#[test]
fn a_steady_frame_makes_no_bind_groups() {
use rune_light::{Glass, GlassRenderer, GlassSettings};
let Some(mut r) = rig() else { return eprintln!("no adapter; skipped") };
let mut glass = GlassRenderer::new(&r.device, W, H, wgpu::TextureFormat::Rgba8Unorm);
let panes = [Glass::rounded(40.0, 30.0, 80.0, 60.0, 16.0)];
let mut glass_frame = |r: &mut Rig, gi: Option<Gi>| {
let mut encoder = r.record(&prims(8), gi);
let fluence = r.light.inspect().fluence.clone();
glass.render(&r.device, &r.queue, &mut encoder, &panes, &[], GlassSettings::default(), &r.base, &fluence, &r.target);
encoder
};
for gi in [None, Some(Gi::default())] {
for _ in 0..2 {
let encoder = glass_frame(&mut r, gi);
r.submit(encoder);
}
let idle = r.live_bind_groups();
let encoder = glass_frame(&mut r, gi);
assert_eq!(r.live_bind_groups(), idle, "recording a steady frame made bind groups (gi: {})", gi.is_some());
r.submit(encoder);
}
}