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

+36
View File
@@ -0,0 +1,36 @@
[package]
name = "rune-fx"
version = "0.0.1"
edition.workspace = true
license.workspace = true
description = "Rune's special-effects layers: glow, pulses, electricity, fire, motion blur, distortion."
autotests = false
[dependencies]
rune-motion = { workspace = true }
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 }
ab_glyph = "0.2.32"
png = { workspace = true }
[[test]]
name = "integration"
[lints]
workspace = true
+344
View File
@@ -0,0 +1,344 @@
# rune-fx
Effect layers for Rune: glow, pulses, electricity, fire, motion blur, distortion, some extras
(shimmer, sparkles, aurora, grain), and a family of fills (liquid metal, mesh gradient, dither, grain
gradient, fluted glass, metaballs, swirl, voronoi, waves, halftone, plastic). Each effect is a WGSL fragment shader on an instanced quad with
typed params. Given (time, seed), every frame is deterministic. A layer whose intensity is 0, whose
one-shot has finished, or that is off screen is never drawn.
Build and run from the workspace root:
```sh
cargo run --release -p rune-fx --example gallery # stills, strips, timings
cargo test -p rune-fx --lib # contract tests
```
`examples/lab` composites these layers live inside Rune's renderer, with knobs.
Output lands in `demo/fx/` (repo root): `<effect>.png`, `<effect>-strip.png` (8 frames),
`<effect>-reduced.png` (reduced motion), `<effect>.mp4`, `motion-quarter-speed.mp4`, `timings.md`.
`gallery --frames DIR --fps 60 --seconds 2 --effect fire [--start 0] [--reduced]` dumps a PNG sequence.
| | |
|---|---|
| ![glow](../../demo/fx/glow.png) | ![pulse](../../demo/fx/pulse.png) |
| ![electric](../../demo/fx/electric.png) | ![fire](../../demo/fx/fire.png) |
| ![motion](../../demo/fx/motion.png) | ![distort](../../demo/fx/distort.png) |
| ![extras](../../demo/fx/extras.png) | ![liquid metal](../../demo/fx/liquid-metal.png) |
| ![mesh gradient](../../demo/fx/mesh-gradient.png) | ![dither](../../demo/fx/dither.png) |
| ![grain gradient](../../demo/fx/grain-gradient.png) | ![fluted glass](../../demo/fx/fluted-glass.png) |
| ![more fills](../../demo/fx/fills.png) | ![every fill preset](../../demo/fx/fill-presets.png) |
| ![plastic keys, glossy and matte, and liquid metal keys anchored to the window or to each key](../../demo/fx/plastic.png) | ![blend modes over cream paper](../../demo/fx/blend.png) |
Liquid metal over eight frames (four seconds): ![liquid metal strip](../../demo/fx/liquid-metal-strip.png)
## API
```rust
use rune_fx::*;
let card = Shape::rounded(262.0, 70.0, 156.0, 96.0, 14.0); // points
let layers = [
Fx::glow(GlowParams { style: GlowStyle::Neon, color: rgb(0x22d3ee), heat: heat.at(t), ..Default::default() })
.on(card).over().at(t),
Fx::electric(ElectricParams::charged()).on(Shape::capsule(380.0, 222.0, 196.0, 50.0)).seed(3).at(t),
Fx::lens(LensParams { second: Some(Shape::circle(lx, 116.0, 30.0)), ..Default::default() })
.on(Shape::capsule(140.0, 84.0, 200.0, 64.0)).at(t),
];
let mut fx = FxRenderer::new(&device, target_format, FxOptions { dither: target_is_8_bit });
let stats = fx.prepare(&device, &queue, &FxFrame {
viewport: [w, h], scale: 2.0, layers: &layers,
backdrop: Some(&backdrop_view), // only distortion reads it
sources: &[&mask_pyramid.view, &node_layer_view],
});
// in the node's render pass, around the node itself:
fx.draw_layer(&mut pass, 0); // or fx.draw_all(&mut pass, &layers, Some(Place::Under))
```
`FxLayer` builders: `.at(time)`, `.seed(n)`, `.over()` / `.under()`, `.reduced(bool)`,
`.source(slot, rect)`, `.opacity(k)` (also the pub field `opacity`, so struct
literals need it).
`layer.is_animating()` tells the frame loop whether to keep ticking; it is false for a layer that
draws nothing (zero opacity or amplitude).
For Rune effect slots, use `prepare_with_slots(device, queue, frame, slots)` with one
`FxSlot::default().scale(site.scale).clip(i.clip, i.fade)` per layer. Missing entries default
to the frame scale and no clip. Keeping this metadata separate preserves existing `FxLayer`
and `FxFrame` struct literals.
One-shots overlap: `OneShots<T>::new(cap)` keeps a bounded pool. `trigger(t, data)` starts a new
instance beside the live ones, and `live(t, life)` yields each `(shot, opacity)`. Draw one layer per
instance with `.seed(shot.seed).opacity(k)`. When the pool is full the oldest instance fades out
over `OneShots::FADE` (0.16 s) instead of being cut. Ripples, pings, shockwaves, lightning zaps
(`ElectricParams::zap: Some(t0)`, lives `ZAP_LIFE`) and sparkle bursts
(`SparkleParams::burst: Some(t0)`, lives `burst_life()`) all work this way.
Simulated fire and smoke: `fx.set_fire_sim(&device, true)` makes `Top` and `Heat` fires a small
GPU fluid simulation per layer (stable fluids at 1–3 pt cells: buoyancy, vorticity confinement,
expansion at the fuel line, cooling into smoke, monotone cubic advection) instead of noise. Call
`fx.simulate(&queue, &mut encoder, None)` after `prepare` and before drawing. Steps are fixed
1/60 s (at most 4 per frame); a new or time-jumped grid warms up 1.2 s in one frame; reduced motion
settles one pose and then steps nothing. Flames are blackbody light (1000–2700 K) with a
per-channel shoulder; `FireParams::smoke` sets how much smoke the cooling flame leaves, and smoke
covers what is behind it, lit warm from below. The lab's fire scene costs 0.8–0.9 ms GPU per frame at 2×.
Frosted glass (`LensParams::frost > 0` or `FlutedGlassParams::frost > 0`) reads a blurred backdrop.
After copying the backdrop (or in `EffectPhase::Backdrop(encoder)` at a Rune
`El::effect_backdrop(true)` slot), call
`fx.blur_backdrop(&device, &queue, &mut encoder, &backdrop_view, layer)` for that layer (or
`fx.set_layer_backdrop(&device, &backdrop_view, layer)` for an unblurred backdrop reader when
`FxFrame::backdrop` is `None`). `blur_backdrop` runs a half-resolution dual-filter pyramid scissored
to the layer and binds both `backdrop_view` and the blurred output on that layer; if the layer has
`frost == 0`, it binds `backdrop_view` without running the pyramid. Without `blur_backdrop` a lens
falls back to an 8-tap spiral blur.
`Fx::cost()` returns the static cost declaration. `FxStats` reports draws, idle and off-screen
culls, covered pixels, and whether any drawn layer needs a backdrop.
Time helpers:
- `Phase` keeps an effect's phase continuous when you animate its speed: `set_speed(t, s)`
adjusts an offset so `at(t)` never jumps.
- `Heat` gives a light with attack and exponential cooling. Feed it to `GlowParams::heat` and the
glow shrinks, deepens and dims instead of cutting off (see the neon card in `glow-strip.png`).
- `MotionSamples::from_track(params, rest_rect, t, scale, |t| Pose)` samples the analytic track
inside the shutter interval.
### Fills
A fill paints the node's shape (or, with `.border(w)`, a band `w` pt wide inside its edge) and
goes under the node as its background. Every style is `Fx::fill(params)` with typed params,
`Default` and named presets:
```rust
Fx::fill(LiquidMetalParams::gold()).on(Shape::capsule(x, y, 180.0, 52.0)).at(t) // a gold pill
Fx::fill(LiquidMetalParams::chrome().border(6.0)).on(card).at(t) // a chrome tube border
Fx::fill(LiquidMetalParams::chrome().anchor(FillAnchor::Element)).on(key).at(t) // every key ripples alike
Fx::fill(PlasticParams { color: rgb(0xd7263d), roughness: 0.7, dome: -0.4, ..PlasticParams::glossy() }).on(key) // a matte dished keycap
Fx::fill(MeshGradientParams { colors: Stops::hex(&[0x1b1f3b, 0xff6f91, 0xffc75f]), ..MeshGradientParams::dusk() }).on(card).at(t)
Fx::fill(DitherParams { pattern: DitherPattern::Bayer8, pixel: 3.0, ..DitherParams::backdrop() }).on(card).at(t) // over the backdrop
Fx::fill(GrainGradientParams { kind: GradientKind::Conic, ..GrainGradientParams::sweep() }).on(card).at(t)
Fx::fill(FlutedGlassParams { rib: 10.0, frost: 0.4, ..FlutedGlassParams::reeded() }).on(card).at(t)
```
- Shared parts: a shape mask with an optional border band, `intensity`, a colour list (`Stops`, up
to six, blended in OKLab) and, for dither and halftone, a tone input (`FillInput`: linear or
radial ramp, drifting noise, the backdrop, or an image in a source slot via `.source(1, rect)`).
- Fills that read the backdrop (fluted glass, dither or halftone of `Backdrop`) go over instead
and need a backdrop copy, like distortion. Frosted fluted glass reads the same blur pyramid as a
frosted lens: call `fx.blur_backdrop` for the layer.
- Reduced motion: each fill settles on one fixed pose (drift, flow and grain stop) and
`is_animating()` is false.
- The catalog describes every style for tools: `fill_styles()` lists `StyleInfo { id, name,
summary, params, presets, reads_backdrop }`; each `Param` has an id (the Rust field), a display
name and a `ParamKind` (number with range, step and unit; count; toggle; choice; colour; colours;
point; points). `FillParams::COMMON` holds `border` and `intensity`. `FillParams::get`/`set`
read and write any param by id as a `Value`, and `to_rust()` writes the `Fx::fill(...)` call,
as a struct literal over the closest preset.
## Integration contract (for the Rune renderer)
**Inputs per layer**
- Node shape in points: a rounded rect, capsule or circle (`Shape`), or a mask texture plus the
rect it covers (`Source`).
- Time from Rune's clock, so slow-mo, pause and stepping work and goldens stay deterministic. One-shots
(ping, ripple, shockwave) take a `t0` on the same clock.
- Seed.
- Params.
- `reduced_motion`.
- Optional:
- an analytic track (motion blur);
- the backdrop texture (distortion: a copy of the target taken right before the layer, which
must not be the render target);
- a source texture (mask glow and mask shimmer use a `MaskPyramid`; motion blur uses the node
rendered at rest with at least 2 px of transparent margin).
**Output**
- A premultiplied, linear-light colour layer, drawn with `PREMULTIPLIED_ALPHA_BLENDING` over or
under the node (`Place`).
- Light effects (glow, pulses, electricity, fire) write `rgb > a`, so they add light like a screen
blend on dark UI. `occlusion` controls how much they also cover what's behind.
- Distortion and motion blur write replacement pixels with `a = 1` inside their mask.
**Targets and blend modes**
- One `FxRenderer` draws into any number of target formats: `add_format` adds another one, and `draw_layer_in(pass, format, origin, layer)` draws into a pass of that format
whose top-left pixel is at `origin` in window pixels (a Rune effect slot's `EffectSite`: the
frame target, or an isolated layer's `Rgba16Float` target, where the layer's opacity, blur and
clip then apply). Effects are still shaded in window coordinates; pass `FxSlot::scale(site.scale)`
so a zoomed slot (`scale` / `live_scale`) converts its device-pixel rect and lengths with its own
device-px-per-pt factor, and `FxSlot::clip(i.clip, i.fade)` in `prepare_with_slots` so a slot outside an isolated layer
is cut by rounded container corners and soft scroll-edge feathers (`CLIP_WGSL`).
- Each effect family's pipeline for a format and blend is built the first time a frame draws
it (those one `prepare` needs build in parallel), so a renderer pays only for what it shows.
On a cold Metal shader cache that's 20 to 150 ms per pipeline.
- `FxSlot::blend(FxBlend)` selects how a slot composites onto the target beneath it:
`FxBlend::Normal` (default premultiplied source-over with additive light), `FxBlend::Multiply`,
`FxBlend::Screen`, `FxBlend::Overlay`, or `FxBlend::SoftLight`. `Screen` uses
fixed-function `wgpu::BlendState` (zero backdrop reads); `Multiply`, `Overlay` and `SoftLight` sample the
backdrop (`FxFrame::backdrop` or `EffectSite::backdrop` via `set_layer_backdrop` /
`blur_backdrop`, setting `FxStats::needs_backdrop`) and fall back to `Normal` when no backdrop
is bound. Separable formulas run in the frame's working colour space (linear light by default, or
sRGB when `set_srgb_blend(true)` is active). Overlay and SoftLight have little contrast near
white by definition; use Multiply for a strong coloured halo on light surfaces.
- `set_srgb_blend(frame.srgb_blend())` matches a gamma-blended Rune frame: the premultiplied output
is sRGB-encoded for the non-sRGB target. When prepared without `FxFrame::backdrop`, per-slot
`backdrop` / `blurred` samples default to that same encoding and are decoded before shading.
Pass a backdrop view of the pass's own format
(`EffectSite::backdrop`: non-sRGB on the frame target, `Rgba16Float` inside an isolated layer);
glass, lenses, distortion and backdrop dither/halftone then shade in linear light without
double-encoding on either target. Explicit `FxFrame::backdrop` inputs retain the linear-samples
default. `FxSlot::backdrop_srgb(bool)` overrides either convention: use `false` for an `*Srgb`
view (hardware already decodes it) or a linear `Rgba16Float` view, and `true` for encoded
premultiplied samples, independently of the frame's output blend mode.
**Cost and culling**
- `prepare` does all culling: idle layers (intensity 0, a fully cooled glow, a one-shot outside its
window) and layers whose bounds miss the viewport get no instance, no CPU tables and no draw.
- Motion blur at rest has `count == 1`. The renderer should then skip the layer
(`!samples.is_moving()`) and draw the node normally.
- Each layer is one quad clipped to its bounds, in one pass.
- Distortion adds the backdrop copy: scissor it to the union of the distortion bounds.
- Mask glow adds a mip build once per mask change (6 small passes).
**Per-frame CPU tables**
- Anything that is a 1D function of (time, seed), or a particle list, is evaluated once per frame
into the `data` storage buffer instead of once per pixel: bolt paths and their blurred halo paths,
energy crawl, forks, embers, sparkles, aurora curtains, and motion poses.
- They use the same integer hash as the shaders, so there is no `sin`-hash and results don't vary
by GPU.
- This cut electricity from 9.6 ms to about 0.5–1 ms for a full 1200×800 px quad.
**Reduced motion**
- Every effect has a calm fallback with no travel:
- Looping noise effects (electricity, fire, haze, aurora) freeze on a fixed, pleasant pose.
Forks, embers and flicker stop.
- Radar becomes a static halo, breathing holds still, and heartbeat holds a steady glow.
- Ping fades its destination in and out without travelling. Ripple and shockwave become a short,
soft brightening.
- Shimmer becomes a gentle opacity breath. Motion blur turns off.
- Glow cooling stays, because it's a fade, not travel.
- See `<effect>-reduced.png`.
**Quality**
- Dither:
- The gallery renders into Rgba16Float and dithers once at the resolve (TPDF, ±1 LSB, static per
pixel, so there's no temporal shimmer).
- For 8-bit targets, set `FxOptions::dither` and each effect dithers its own output in sRGB
space, gated to where there is signal.
- Edges:
- Every light falls off analytically and is windowed inside its bounds, so no quad edge ever
shows.
- Overlays (aurora, grain, shimmer) feather inside the node shape.
- Glass and the CRT anti-alias their edges at 1 px.
## Effects and params
Lengths are in points, times in seconds.
| Effect | Variants | Key params (default) | Notes |
|---|---|---|---|
| **Glow** `GlowParams` | `Soft`, `Neon` (white-hot hairline rim, bloom both sides), `Aura` (3-colour spectrum flowing round the perimeter, inner rim light), `Mask` (text/icon bloom from a `MaskPyramid`) | radius 14, intensity 1, inner 0, occlusion .15, breathe 0, breathe_period 2.6, heat 1, hot .6, aura_speed .12, rim_width .6, reach 4.5 | Bloom = tight Gaussian (0.35 r) + wide Gaussian (1.2 r), so the light is gone by about 2.5 r, through a soft knee (`1 − e^−x`) that keeps the hue instead of clipping to white. `heat` cools the light. Mask glow samples fractional mip levels with tent taps, so an animated radius never steps |
| **Pulse** `PulseParams` | `Radar`, `Breathe`, `Heartbeat`, `Ping{from,dir,travel}`, `Ripple{at}` | count 3, period 2.4, reach 36, width 1.6, t0, duration .75, repeat 0, lag .16, head_radius 2.6 | Rings follow the shape's SDF. The ping winds up against its travel (Bézier P1 = −0.12), shoots, decelerates to zero velocity, then blooms and cools. Ripple `reach: 0` = auto (farthest corner) |
| **Electric** `ElectricParams` | `Arc{a,b}`, `Border`, `Charged` (`ElectricParams::charged()`) | amplitude 5, frequency 2.4 cells/100pt, speed 3.2, core_width .6, glow 5, forks .55, flicker .45, strands 2, gap 2, fork_len 20, zap None | Lightning: a midpoint-displacement bolt (CPU tables) that strikes with a flash, holds, sometimes return-strokes, and re-strikes every ~0.55/speed s, mostly down the same channel. Extra strands are the last two strikes' afterimages (≈70 ms decay). Forks branch off at each strike, shoot out in 35 ms, then cool white → tint → violet and die within 70–200 ms. Narrow halo along a blurred copy of the path. Arc bounds cover the bolt's full reach. `Charged` keeps a calm crawling hairline |
| **Fire** `FireParams` | `Top`, `Border`, `Heat` (`FireParams::heat()`), `Embers`; `FireParams::plasma()` | height 54, scale 20, speed 1.5, embers 16, ember_rise 58, ember_size .8, ember_life 1.5, warp 1, sides .32, base_glow .5, swirl 0 | Flames: domain-warped fbm (warp grows with height) in height-normalised density, so tongues rise and narrow. Per-column flicker (slow + ~8 Hz). Temperature ramp from a white-yellow base through orange and deep red to a faint smoke veil. Plasma is a thin band hugging the outside of the edge, with ridged filaments that breathe (3 noise evaluations). Embers are flung up, slow under drag (`EMBER_DRAG` 2.4/s) to a buoyant drift, sway, and cool exponentially. Heat haze only distorts above the flame |
| **Motion blur** `MotionBlurParams` + `MotionSamples` | `Shutter` (exact sub-frame poses), `Directional` (taps along the velocity) | shutter_angle 180, frame_dt 1/60, max_samples 48, px_per_sample 1.25, smooth_shutter true | Sample count = travel px / 1.25, so it's 1 at rest. Raised-cosine shutter weights give soft trail ends. Poses include rotation, scale and opacity |
| **Distort** `DistortParams` | `HeatHaze`, `Shockwave`, `Lens(LensParams)`, `Crt`, `ChromaSplit` | lens: bevel 14, depth 16, dispersion .14, magnification 1.04, presence 1, frost 0, shadow .35, rim 1.6, union_k 22, morph 0, `second: Option<Shape>` | Lens uses psychopomp's thin-surface optics: a superellipse bevel (power 3) bends light by `tan(θ − asin(sin θ / 1.5))`. Per-channel spread splits colour at the rim, a soft blur covers the squeezed rim, and it adds sky fresnel, a specular line on the lit arc, a counter-line and a drop shadow. `presence` ramps lensing, rim and shadow together, so the glass appears by lensing, not by fading. A second shape smooth-unions into a gooey merge; `morph` lerps toward it. `frost` is Liquid Glass "regular": a wide pyramid blur (σ up to 18 pt), saturation ×(1 + 0.9 k), a compressive sRGB lift that brightens dark backdrops more than light ones, and grain against banding |
| **Shimmer** `ShimmerParams` | shape or mask (`use_mask`) | period 1.8, band 28, angle .35 rad, intensity .16, pause .3 | Skeleton loaders and "Thinking…" text sheen. The band starts and ends off the shape, so it never cuts |
| **Sparkles** `SparkleParams` | continuous or `burst: Some(t0)` | count 6, life 1.5, size 7, margin 10 | Crisp four-point stars (concave superellipse, 1 px AA) with a white-hot centre. Sizes skew small with a few large. Each pops in with overshoot, twinkles at its own 5–9 Hz, spins slowly and shrinks away; continuous stars rest between appearances so only a few are lit. A burst flings every star out once |
| **Aurora** `AuroraParams` | – | scale 120, speed .25, intensity .5, feather 40 | 3 curtains from CPU tables, plus noise rays |
| **Grain** `GrainParams` | static or animated (`fps`) | amount .03, fps 0 | Static by default (no temporal shimmer) |
Fills (`Fx::fill`; every style also takes `border` and `intensity`):
| Fill | Presets | Key params (default) | Notes |
|---|---|---|---|
| **Liquid metal** `LiquidMetalParams` | `chrome`, `gold`, `rose`, `gunmetal` | flow .6, scale 100, speed .35, bevel 14, dome .55, angle −.12, iridescence .08, contrast 1 | A studio reflected in polished metal: bright sky falling to a hard horizon over a dark floor, an overhead soft box and two strip lights. The face is domed so the horizon crosses it, the rim rolls off over `bevel`, and a domain-warped height field ripples the normal (calmer toward the rim). Conductor Fresnel (Schlick) goes from the tint to white at grazing angles; lights roll off through a per-channel shoulder. As a border it is a round tube. `anchor` pins the ripples to the window (`World`, the default: neighbouring shapes show neighbouring parts of one surface) or to each shape's centre (`Element`: shapes of the same size, seed and time are pixel-identical, so a row of keys matches) |
| **Mesh gradient** `MeshGradientParams` | `dusk`, `lagoon`, `orchid`, `graphite` | 3–6 colours, points, drift .12, speed .25, sharpness 1.6, warp .35 | Each colour owns a point that drifts on a slow CPU-side path; inverse-distance weights blend them in OKLab, then the output is dithered against banding |
| **Dither** `DitherParams` | `bayer`, `handheld`, `grain`, `backdrop` | Bayer 2×2 / 4×4 / 8×8, blue noise (32×32 void-and-cluster tile), white noise; pixel 2, 2–6 colours, bias, contrast | Quantises a tone (ramp, noise, backdrop or image) into the palette in square pixels anchored to the shape |
| **Grain gradient** `GrainGradientParams` | `ember`, `halo`, `sweep` | linear / radial / conic, amount .4, size .5, mono, fps 12 | Triangular noise scatters the ramp position, so colours stipple into each other, plus brightness grain (mono or per channel). Conic gradients loop |
| **Fluted glass** `FlutedGlassParams` | `reeded`, `fine`, `frosted`, `wide` | rib 14, angle 0, refraction 9, frost 0, dispersion .15, highlight .5 | Each rib is a cylindrical lens: the strip under it comes back squeezed and flipped, with a per-channel split toward its edges, a sheen and a shaded groove |
| **Metaballs** `MetaballParams` | `lava`, `mint` | count 6, size .2, speed .4, gloss .5 | Blobs on CPU paths summed as a field; the iso-edge is anti-aliased from the field's slope, with a glossy rim |
| **Swirl** `SwirlParams` | `ink`, `marble` | scale 140, speed .2, twist .6, warp 1 | A centre twist over twice domain-warped noise, through the colour ramp |
| **Voronoi** `VoronoiParams` | `cells`, `stained` | scale 36, speed .25, edge 1.5, edge_color, depth .4 | Orbiting cell points, exact seam distance to the bisectors, shaded cells |
| **Waves** `WaveParams` | `sea`, `dunes` | amplitude .05, frequency 1.6, speed .4, angle 0, softness .006 | Layered bands with two-sine crests; each front band shades the one behind |
| **Halftone** `HalftoneParams` | `print`, `backdrop` | cell 6, angle 45°, ink, base; input as dither | Round dots on a rotated screen sized by tone; the four nearest dots merge |
| **Plastic** `PlasticParams` | `glossy`, `matte`, `dished` | colour, roughness .15, dome .35, bevel 6, angle −.5 | Moulded plastic under one soft light from `angle` (50° up), with liquid metal's dome and rolled rim. Diffuse shading (ambient plus Lambert) keeps `color` on a flat face, darkens slopes facing away and lightens toward white facing the light; a GGX highlight is small and bright when glossy, broad and faint when matte; Schlick Fresnel (f0 .04) adds a faint sky at grazing angles. Highlight and Fresnel fill the room left above the base, so rgb never exceeds alpha and it blends the same with `srgb_blend` on or off. Negative `dome` dishes the face like a keycap. Never animates |
## Costs
From `demo/fx/timings.md`: Apple M5 Max (shared with other jobs). One layer covers a
600×400 pt region at 2× (1200×800 = 960k px, smaller where noted). GPU time per draw is the median
over 10 draws per timestamped pass. "reads" = texture taps plus CPU-table reads per pixel; "noise" =
gradient-noise evaluations per pixel. "was" is the previous effects on the same machine (median of
three runs each).
| effect | px | reads | noise | backdrop | ms | was |
|---|---:|---:|---:|:-:|---:|---:|
| glow soft / neon | 960k | 0 | 0 | | 0.10 / 0.11 | 0.10 / 0.12 |
| glow aura | 960k | 0 | 1 | | 0.21 | 0.21 |
| glow mask (text) | 960k | 13 | 0 | | 0.23 | 0.22 |
| pulse radar / breathe / heartbeat | 960k | 0 | 0 | | 0.16 / 0.07 / 0.17 | 0.21 / 0.09 / 0.09 |
| pulse ripple | 544k | 0 | 0 | | 0.05 | 0.06 |
| electric arc (3 strands) / border / charged | 960k | 37 / 43 / 37 | 0 | | 0.39 / 0.38 / 0.24 | 0.43 / 0.28 / 0.23 |
| fire top + 16 embers / plasma border / heat | 644k / 960k / 635k | 32 / 0 / 8 | 8 / 3 / 8 | | 1.32 / 0.51 / 0.74 | 1.19 / 1.00 / 0.78 |
| distort heat haze | 960k | 1 | 6 | yes | 0.68 | 0.70 |
| distort shockwave / CRT / chroma split | 960k | 3 / 7 / 3 | 0 | yes | 0.09 / 0.11 / 0.06 | 0.10 / 0.13 / 0.06 |
| distort lens / lens + frost | 960k | 12 | 0 | yes | 0.21 / 0.40 | 0.21 / 0.44 |
| shimmer / grain | 960k | 0 | 0 | | 0.09 / 0.08 | 0.08 / 0.08 |
| sparkles ×9 / aurora | 960k | 18 / 12 | 0 / 3 | | 0.18 / 0.48 | 0.36 / 0.49 |
| motion shutter (48 poses) / directional (32 taps) | 467k | 48 / 32 | 0 | | 0.66 / 0.50 | 0.64 / 0.60 |
Deltas: the heartbeat doubles (four overlapping beat instances instead of one) and the electric
border costs about 0.1 ms more (sharper fractal paths keep more of the near-field slope
correction). Flames cost about 10% more for the height-normalised warp. Plasma halves (3 noise
evaluations instead of 8) and sparkles halve (stars outside their own radius are skipped). The frost
pyramid adds a half-resolution blur scissored to the lens (in the lab, lens-frost measures
0.7 ms per whole frame against 0.5–0.6 ms for the clear lens). Every row stays within the old budgets.
Fills were measured on an Apple M4 Pro (headless Metal), where the rows above run about twice as
long as on the M5 Max (glow soft 0.21 ms, lens 0.37 ms, fire top 1.8 ms; `demo/fx/timings.md` now
holds that run). Each fill covers a 480×280 pt rounded rect at 2× (544k px):
| fill | reads | noise | backdrop | ms |
|---|---:|---:|:-:|---:|
| liquid metal / still (flow 0) / 8 pt border | 0 | 8 / 0 / 8 | | 0.93 / 0.22 / 0.17 |
| liquid metal, element anchor | 0 | 8 | | 0.94 (world in the same run: 0.95) |
| plastic glossy / matte / 8 pt border | 0 | 0 | | 0.15 / 0.15 / 0.06 |
| mesh gradient (5 colours) | 10 | 2 | | 0.37 |
| dither Bayer ramp / blue noise / palette over noise / backdrop | 1 / 2 / 1 / 2 | 0 / 0 / 3 / 0 | backdrop only | 0.15 / 0.15 / 0.45 / 0.16 |
| grain gradient linear mono / conic colour | 2 | 0 | | 0.18 / 0.26 |
| fluted glass / + frost | 3 / 6 | 0 | yes | 0.12 / 0.25 |
| metaballs ×6 / waves (5 bands) | 12 / 5 | 0 | | 0.28 / 0.29 |
| swirl / voronoi | 2 / 1 | 9 / 0 | | 1.05 / 1.17 |
| halftone radial / backdrop | 0 / 4 | 0 | backdrop only | 0.31 / 0.34 |
Liquid metal's cost is the flowing surface (eight noise evaluations for the height field and its
slope); a still slab costs a quarter, and a border pays only for its band. The element anchor
costs nothing extra. Plastic is a still slab with a highlight: about a sixth of flowing liquid metal. Swirl and voronoi are
the heaviest per pixel; keep them to cards rather than full screens.
These are worst-case full-region numbers. Real layers hug their node: the gallery's 224 pt card
with flames and embers covers about 195k px (about 0.4 ms), and a charged 196×50 button border
about 115k px (about 0.05 ms).
Timings on a shared machine vary by about 1.5× between runs, so read them as relative costs. A
reserved machine is needed for gating.
## Gaps and next steps
- **Glow from mask** needs the caller to render the mask into `MaskPyramid::levels[0]` and call
`build_mips`. Rune should cache the pyramid per text run.
- **Backdrop** slots (`El::effect_backdrop(true)`) split the pass in `Renderer::draw_with_backdrop`
and copy the target up to each slot into a pooled viewport-sized backdrop texture (`EffectSite::backdrop`),
which `blur_backdrop` / `set_layer_backdrop` binds for that layer. A future optimisation could copy
only the scissored reach of the slot rather than the full target.
- **Motion blur** composites a cached node layer. Rune needs to render the moving subtree into that
layer, and should skip the effect at rest.
- **Fire** is the heaviest per pixel (8 noise evaluations). Half-resolution evaluation with a
bilateral upsample would cut it about 3×. Not done.
- Electricity forks grow and cool but don't sub-branch.
- The frost pyramid needs one `blur_backdrop` call per frosted layer (about 10 per frame fit the
uniform slots). The clear lens's rim blur is still an 8-tap spiral.
- Bind groups are rebuilt every `prepare`. They should be cached per (backdrop, source) pair.
- Fills have no inspector UI of their own: the catalog (`fill_styles()`) is the data a tool needs
to build one. Image input for dither and halftone needs the caller to bind the image as a source.
- No CPU reference renderer or golden tests for the shaders yet; the CPU-table and contract tests
live in `src/lib.rs`.
+47
View File
@@ -0,0 +1,47 @@
//! What one glow costs the first time a process draws it, in milliseconds, as one JSON line:
//! `FxRenderer::new`, `add_format` for an isolated layer's `Rgba16Float`, and the first frame
//! (prepare, draw, submit, read back), each timed on its own, with `total` the three together.
//! Run it in fresh processes, `--profile perf`, after clearing the Metal shader cache
//! (`$(getconf DARWIN_USER_CACHE_DIR)/com.apple.metal`) for a cold run.
use rune::render::{Gpu, Offscreen};
use rune_fx::*;
fn main() {
let gpu = Gpu::headless();
let format = wgpu::TextureFormat::Bgra8UnormSrgb;
let target = Offscreen::with_format(&gpu.device, 96, 96, format);
let layers = [Fx::glow(GlowParams::default()).on(Shape::rounded(24.0, 24.0, 48.0, 48.0, 8.0))];
let start = rune::time::now();
let mut fx = FxRenderer::new(&gpu.device, format, FxOptions::default());
let new = start.elapsed();
fx.add_format(&gpu.device, wgpu::TextureFormat::Rgba16Float);
let add_format = start.elapsed() - new;
fx.prepare(&gpu.device, &gpu.queue, &FxFrame { viewport: [96, 96], scale: 1.0, layers: &layers, backdrop: None, sources: &[] });
let mut encoder = gpu.device.create_command_encoder(&Default::default());
{
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &target.view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), store: wgpu::StoreOp::Store },
})],
..Default::default()
});
fx.draw_layer(&mut pass, 0);
}
target.copy(&mut encoder);
gpu.queue.submit([encoder.finish()]);
let pixels = target.read(&gpu.device);
let total = start.elapsed();
assert!(pixels.chunks(4).any(|p| p[3] != 0), "the glow drew");
let ms = |d: std::time::Duration| d.as_secs_f64() * 1e3;
println!(
"{{\"new\":{:.3},\"add_format\":{:.3},\"first_frame\":{:.3},\"total\":{:.3}}}",
ms(new),
ms(add_format),
ms(total - new - add_format),
ms(total)
);
}
+588
View File
@@ -0,0 +1,588 @@
//! Headless gallery for rune-fx: stills, frame strips, PNG sequences and GPU timings.
//!
//! gallery all effects -> demo/fx/<effect>.png, -strip.png, -reduced.png, timings.md
//! gallery --effect fire one effect
//! gallery --frames DIR --fps 60 --seconds 2 --effect fire PNG sequence
//! gallery --timings GPU timings only
mod scenes;
mod ui;
use scenes::{fling, scene};
use rune::render::{Gpu, Offscreen, write_png};
use rune_fx::*;
use std::ops::Range;
use std::path::{Path, PathBuf};
use ui::{col, TextAtlas, UiInst, UiRenderer};
const W: f32 = 640.0;
const H: f32 = 360.0;
const S: f32 = 2.0;
const FMT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float;
const EFFECTS: [&str; 15] = ["glow", "pulse", "electric", "fire", "motion", "distort", "extras", "liquid-metal", "plastic", "mesh-gradient", "dither", "grain-gradient", "fluted-glass", "fills", "fill-presets"];
// ------------------------------------------------------------------ scene builder
#[derive(Clone, Copy, PartialEq)]
enum Target {
Main,
Mask,
Src,
}
enum Op {
Ui(Range<usize>),
Fx(usize),
Backdrop,
}
struct B<'a> {
atlas: &'a mut TextAtlas,
ui: Vec<UiInst>,
mask: Vec<UiInst>,
src: Vec<UiInst>,
src_rect: Option<Rect>,
layers: Vec<FxLayer>,
slots: Vec<FxSlot>,
ops: Vec<Op>,
target: Target,
t: f32,
reduced: bool,
}
const SRC_PAD: f32 = 4.0;
impl<'a> B<'a> {
fn new(atlas: &'a mut TextAtlas, t: f32, reduced: bool) -> B<'a> {
B { atlas, ui: vec![], mask: vec![], src: vec![], src_rect: None, layers: vec![], slots: vec![], ops: vec![], target: Target::Main, t, reduced }
}
fn push(&mut self, mut u: UiInst) {
match self.target {
Target::Main => {
u.vp = [W * S, H * S, 0.0, 0.0];
let i = self.ui.len();
self.ui.push(u);
if let Some(Op::Ui(r)) = self.ops.last_mut() {
if r.end == i {
r.end = i + 1;
return;
}
}
self.ops.push(Op::Ui(i..i + 1));
}
Target::Mask => {
u.vp = [W * S, H * S, 0.0, 0.0];
self.mask.push(u);
}
Target::Src => {
let r = self.src_rect.unwrap();
u.rect[0] -= (r.x - SRC_PAD) * S;
u.rect[1] -= (r.y - SRC_PAD) * S;
u.vp = [(r.w + 2.0 * SRC_PAD) * S, (r.h + 2.0 * SRC_PAD) * S, 0.0, 0.0];
self.src.push(u);
}
}
}
fn rect(&mut self, r: Rect, radius: f32, fill: [f32; 4], fill2: [f32; 4], border: [f32; 4], bw: f32) {
self.push(UiInst {
rect: [r.x * S, r.y * S, r.w * S, r.h * S],
p: [radius * S, bw * S, 0.0, 0.0],
fill,
fill2,
border,
uv: [0.0; 4],
vp: [0.0; 4],
});
}
fn shadow(&mut self, r: Rect, radius: f32, sigma: f32, c: [f32; 4]) {
self.push(UiInst {
rect: [r.x * S, r.y * S, r.w * S, r.h * S],
p: [radius * S, 0.0, 2.0, sigma * S],
fill: c,
fill2: c,
border: [0.0; 4],
uv: [0.0; 4],
vp: [0.0; 4],
});
}
/// Text with its baseline at y. Returns width in pt.
fn text(&mut self, x: f32, y: f32, s: &str, size: f32, weight: u8, c: [f32; 4]) -> f32 {
let r = self.atlas.get(s, size * S, weight);
self.push(UiInst {
rect: [x * S - 2.0, y * S - r.ascent, r.w, r.h],
p: [0.0, 0.0, 1.0, 0.0],
fill: c,
fill2: c,
border: [0.0; 4],
uv: r.uv,
vp: [0.0; 4],
});
r.w / S
}
fn text_w(&mut self, s: &str, size: f32, weight: u8) -> f32 {
self.atlas.get(s, size * S, weight).w / S - 4.0 / S
}
fn text_c(&mut self, cx: f32, cy: f32, s: &str, size: f32, weight: u8, c: [f32; 4]) {
let w = self.text_w(s, size, weight);
self.text(cx - w * 0.5, cy + size * 0.36, s, size, weight, c);
}
fn fx(&mut self, l: FxLayer) {
self.fx_with(l, FxSlot::default());
}
fn fx_with(&mut self, l: FxLayer, slot: FxSlot) {
let l = l.at(if l.time == 0.0 { self.t } else { l.time }).reduced(self.reduced);
self.ops.push(Op::Fx(self.layers.len()));
self.layers.push(l);
self.slots.push(slot);
}
fn backdrop(&mut self) {
self.ops.push(Op::Backdrop);
}
// --- design kit
fn background(&mut self, title: &str, sub: &str) {
self.rect(Rect::new(0.0, 0.0, W, H), 0.0, col(0x0c0d11, 1.0), col(0x0a0b0e, 1.0), [0.0; 4], 0.0);
let w = self.text(24.0, 34.0, title, 15.0, 2, col(0xeceef2, 1.0));
self.text(24.0 + w + 8.0, 34.0, sub, 12.0, 0, col(0x6b7280, 1.0));
}
fn card(&mut self, r: Rect, radius: f32) {
self.shadow(Rect::new(r.x, r.y + 8.0, r.w, r.h), radius, 16.0, [0.0, 0.0, 0.0, 0.45]);
self.rect(r, radius, col(0x17191f, 1.0), col(0x121419, 1.0), col(0xffffff, 0.075), 1.0 / S);
}
fn lines(&mut self, x: f32, y: f32, w: f32, n: usize) {
for i in 0..n {
let ww = w * [1.0, 0.82, 0.6, 0.9][i % 4];
self.rect(Rect::new(x, y + i as f32 * 14.0, ww, 6.0), 3.0, col(0x262a33, 1.0), col(0x262a33, 1.0), [0.0; 4], 0.0);
}
}
fn button(&mut self, r: Rect, label: &str, top: u32, bottom: u32, text: u32) {
self.shadow(Rect::new(r.x, r.y + 4.0, r.w, r.h), r.h * 0.5, 8.0, [0.0, 0.0, 0.0, 0.4]);
self.rect(r, r.h * 0.5, col(top, 1.0), col(bottom, 1.0), col(0xffffff, 0.16), 1.0 / S);
let c = r.center();
self.text_c(c.x, c.y, label, 14.0, 2, col(text, 1.0));
}
fn caption(&mut self, x: f32, y: f32, s: &str) {
self.text(x, y, s, 11.0, 1, col(0x6b7280, 1.0));
}
}
// ------------------------------------------------------------------ GPU
struct Ctx {
device: wgpu::Device,
queue: wgpu::Queue,
ui: UiRenderer,
fx: FxRenderer,
atlas: TextAtlas,
scene: wgpu::Texture,
scene_view: wgpu::TextureView,
backdrop: wgpu::Texture,
backdrop_view: wgpu::TextureView,
out: Offscreen,
pyramid: MaskPyramid,
src: Option<(wgpu::Texture, wgpu::TextureView, [u32; 2])>,
resolve: wgpu::RenderPipeline,
resolve_bg: wgpu::BindGroup,
timestamps: bool,
w: u32,
h: u32,
}
fn tex(device: &wgpu::Device, w: u32, h: u32, format: wgpu::TextureFormat, usage: wgpu::TextureUsages) -> (wgpu::Texture, wgpu::TextureView) {
let t = 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,
view_formats: &[],
});
let v = t.create_view(&Default::default());
(t, v)
}
fn pass<'e>(enc: &'e mut wgpu::CommandEncoder, view: &'e wgpu::TextureView, clear: Option<wgpu::Color>, ts: Option<wgpu::RenderPassTimestampWrites<'e>>) -> wgpu::RenderPass<'e> {
enc.begin_render_pass(&wgpu::RenderPassDescriptor {
label: None,
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations { load: clear.map_or(wgpu::LoadOp::Load, wgpu::LoadOp::Clear), store: wgpu::StoreOp::Store },
})],
depth_stencil_attachment: None,
timestamp_writes: ts,
occlusion_query_set: None,
multiview_mask: None,
})
}
impl Ctx {
fn new(w: u32, h: u32) -> 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 ui = UiRenderer::new(&device, FMT);
let fx = FxRenderer::new(&device, FMT, FxOptions { dither: false });
let u = wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC;
let (scene, scene_view) = tex(&device, w, h, FMT, u);
let (backdrop, backdrop_view) = tex(&device, w, h, FMT, wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST);
let out = Offscreen::with_format(&device, w, h, wgpu::TextureFormat::Rgba8Unorm);
let pyramid = MaskPyramid::new(&device, w, h);
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("resolve"),
source: wgpu::ShaderSource::Wgsl(include_str!("resolve.wgsl").into()),
});
let resolve = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("resolve"),
layout: None,
vertex: wgpu::VertexState { module: &module, entry_point: Some("vs_full"), compilation_options: Default::default(), buffers: &[] },
primitive: Default::default(),
depth_stencil: None,
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &module,
entry_point: Some("fs_resolve"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState { format: wgpu::TextureFormat::Rgba8Unorm, blend: None, write_mask: wgpu::ColorWrites::ALL })],
}),
multiview_mask: None,
cache: None,
});
let resolve_bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: None,
layout: &resolve.get_bind_group_layout(0),
entries: &[wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&scene_view) }],
});
Ctx {
device,
queue,
ui,
fx,
atlas: TextAtlas::new(),
scene,
scene_view,
backdrop,
backdrop_view,
out,
pyramid,
src: None,
resolve,
resolve_bg,
timestamps,
w,
h,
}
}
fn render(&mut self, name: &str, t: f32, reduced: bool) -> Vec<u8> {
let mut b = B::new(&mut self.atlas, t, reduced);
scene(name, &mut b);
let B { ui, mask, src, src_rect, layers, slots, ops, .. } = b;
let mut all = ui;
let mask_r = all.len()..all.len() + mask.len();
all.extend_from_slice(&mask);
let src_r = all.len()..all.len() + src.len();
all.extend_from_slice(&src);
self.ui.prepare(&self.device, &self.queue, &mut self.atlas, &all);
if let Some(r) = src_rect {
let sz = [((r.w + 2.0 * SRC_PAD) * S) as u32, ((r.h + 2.0 * SRC_PAD) * S) as u32];
if self.src.as_ref().is_none_or(|s| s.2 != sz) {
let (t, v) = tex(&self.device, sz[0], sz[1], FMT, wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING);
self.src = Some((t, v, sz));
}
}
let src_view = self.src.as_ref().map(|s| &s.1);
let mut sources: Vec<&wgpu::TextureView> = vec![&self.pyramid.view];
if let Some(v) = src_view {
sources.push(v);
}
let frame = FxFrame { viewport: [self.w, self.h], scale: S, layers: &layers, backdrop: Some(&self.backdrop_view), sources: &sources };
self.fx.prepare_with_slots(&self.device, &self.queue, &frame, &slots);
let mut enc = self.device.create_command_encoder(&Default::default());
if !mask.is_empty() {
{
let mut p = pass(&mut enc, &self.pyramid.levels[0], Some(wgpu::Color::TRANSPARENT), None);
self.ui.draw(&mut p, mask_r.clone());
}
self.fx.build_mips(&self.device, &mut enc, &self.pyramid);
}
if let Some(s) = &self.src {
if !src.is_empty() {
let mut p = pass(&mut enc, &s.1, Some(wgpu::Color::TRANSPARENT), None);
self.ui.draw(&mut p, src_r.clone());
}
}
{
let _ = pass(&mut enc, &self.scene_view, Some(wgpu::Color::BLACK), None);
}
for op in &ops {
match op {
Op::Ui(r) => {
let mut p = pass(&mut enc, &self.scene_view, None, None);
self.ui.draw(&mut p, r.clone());
}
Op::Fx(i) => {
self.fx.blur_backdrop(&self.device, &self.queue, &mut enc, &self.backdrop_view, *i);
let mut p = pass(&mut enc, &self.scene_view, None, None);
self.fx.draw_layer(&mut p, *i);
}
Op::Backdrop => {
enc.copy_texture_to_texture(self.scene.as_image_copy(), self.backdrop.as_image_copy(), wgpu::Extent3d { width: self.w, height: self.h, depth_or_array_layers: 1 });
}
}
}
{
let mut p = pass(&mut enc, &self.out.view, Some(wgpu::Color::BLACK), None);
p.set_pipeline(&self.resolve);
p.set_bind_group(0, &self.resolve_bg, &[]);
p.draw(0..3, 0..1);
}
self.out.copy(&mut enc);
self.queue.submit([enc.finish()]);
self.out.read(&self.device)
}
}
fn half(px: &[u8], w: u32, h: u32) -> Vec<u8> {
let (hw, hh) = (w / 2, h / 2);
let mut o = vec![0u8; (hw * hh * 4) as usize];
for y in 0..hh {
for x in 0..hw {
for c in 0..4 {
let s = |dx: u32, dy: u32| px[(((y * 2 + dy) * w + x * 2 + dx) * 4 + c) as usize] as u32;
o[((y * hw + x) * 4 + c) as usize] = ((s(0, 0) + s(1, 0) + s(0, 1) + s(1, 1) + 2) / 4) as u8;
}
}
}
o
}
fn strip_times(name: &str) -> (f32, f32) {
// (start, span) of the 8-frame strip.
match name {
"motion" => (0.0, 0.6),
"glow" => (0.0, 1.4),
"pulse" => (0.0, 1.4),
"distort" => (0.0, 0.9),
// Fills move slowly: eight frames over four seconds.
"liquid-metal" | "plastic" | "mesh-gradient" | "dither" | "grain-gradient" | "fluted-glass" | "fills" | "fill-presets" => (0.0, 4.0),
_ => (1.0, 1.0),
}
}
fn still_time(name: &str) -> f32 {
match name {
"glow" => 0.3,
"pulse" => 0.8,
"electric" => 1.37,
"fire" => 2.0,
"motion" => 0.1,
"distort" => 0.3,
"liquid-metal" | "plastic" | "mesh-gradient" | "dither" | "grain-gradient" | "fluted-glass" | "fills" | "fill-presets" => 1.2,
_ => 0.55,
}
}
fn render_effect(ctx: &mut Ctx, dir: &Path, name: &str) {
let (w, h) = (ctx.w, ctx.h);
let px = ctx.render(name, still_time(name), false);
write_png(&dir.join(format!("{name}.png")), w, h, &px).unwrap();
let px = ctx.render(name, still_time(name), true);
write_png(&dir.join(format!("{name}-reduced.png")), w / 2, h / 2, &half(&px, w, h)).unwrap();
let (t0, span) = strip_times(name);
let (fw, fh) = (w / 2, h / 2);
let mut strip = vec![0u8; (fw * 4 * fh * 2 * 4) as usize];
for i in 0..8u32 {
let t = t0 + span * i as f32 / 8.0;
let f = half(&ctx.render(name, t, false), w, h);
let (ox, oy) = ((i % 4) * fw, (i / 4) * fh);
for y in 0..fh {
let d = (((oy + y) * fw * 4 + ox) * 4) as usize;
let s = (y * fw * 4) as usize;
strip[d..d + (fw * 4) as usize].copy_from_slice(&f[s..s + (fw * 4) as usize]);
}
}
write_png(&dir.join(format!("{name}-strip.png")), fw * 4, fh * 2, &strip).unwrap();
eprintln!("wrote {name}");
}
// ------------------------------------------------------------------ timings
fn timing_layers() -> Vec<(&'static str, FxLayer)> {
let sh = Shape::rounded(60.0, 60.0, 480.0, 280.0, 24.0);
let t = 1.3;
let mut v: Vec<(&str, FxLayer)> = vec![
("glow soft", Fx::glow(GlowParams { radius: 24.0, ..Default::default() }).on(sh)),
("glow neon", Fx::glow(GlowParams { style: GlowStyle::Neon, radius: 24.0, inner: 0.4, ..Default::default() }).on(sh)),
("glow aura", Fx::glow(GlowParams { style: GlowStyle::Aura, radius: 24.0, inner: 0.5, ..Default::default() }).on(sh)),
("glow mask (text)", Fx::glow(GlowParams { style: GlowStyle::Mask, radius: 24.0, ..Default::default() }).on(sh).source(0, Rect::new(0.0, 0.0, 600.0, 400.0))),
("pulse radar", Fx::pulse(PulseParams { reach: 80.0, ..Default::default() }).on(sh)),
("pulse breathe", Fx::pulse(PulseParams { style: PulseStyle::Breathe, reach: 30.0, ..Default::default() }).on(sh)),
("pulse heartbeat", Fx::pulse(PulseParams { style: PulseStyle::Heartbeat, reach: 60.0, ..Default::default() }).on(sh)),
("pulse ripple", Fx::pulse(PulseParams { style: PulseStyle::Ripple { at: [200.0, 200.0] }, reach: 0.0, t0: 1.0, duration: 1.0, ..Default::default() }).on(sh)),
("electric arc (3 strands)", Fx::electric(ElectricParams { style: ElectricStyle::Arc { a: [20.0, 200.0], b: [580.0, 200.0] }, strands: 3, glow: 40.0, ..Default::default() }).on(sh)),
("electric border", Fx::electric(ElectricParams { glow: 30.0, ..Default::default() }).on(sh)),
("electric charged", Fx::electric(ElectricParams { glow: 30.0, ..ElectricParams::charged() }).on(sh)),
("fire top + 16 embers", Fx::fire(FireParams { height: 200.0, ..Default::default() }).on(Shape::rounded(60.0, 300.0, 480.0, 90.0, 16.0))),
("fire plasma border", Fx::fire(FireParams { height: 200.0, ..FireParams::plasma() }).on(sh)),
("fire heat (UI)", Fx::fire(FireParams { height: 200.0, ..FireParams::heat() }).on(Shape::rounded(60.0, 300.0, 480.0, 90.0, 16.0))),
("distort heat haze", Fx::distort(DistortParams::HeatHaze { height: 40.0, scale: 14.0, speed: 2.0, amount: 2.0, whole_shape: true }).on(Shape::rounded(0.0, 0.0, 600.0, 400.0, 0.0))),
("distort shockwave", Fx::distort(DistortParams::Shockwave { at: [300.0, 200.0], reach: 400.0, width: 14.0, amount: 9.0, chroma: 0.3, t0: 0.9, duration: 1.0 }).on(sh)),
("distort lens", Fx::lens(LensParams::default()).on(Shape::rounded(20.0, 20.0, 560.0, 360.0, 60.0))),
("distort lens + frost", Fx::lens(LensParams { frost: 0.6, ..Default::default() }).on(Shape::rounded(20.0, 20.0, 560.0, 360.0, 60.0))),
("distort CRT", Fx::distort(DistortParams::crt()).on(Shape::rounded(0.0, 0.0, 600.0, 400.0, 12.0))),
("distort chroma split", Fx::distort(DistortParams::chroma_split([2.0, 0.0])).on(Shape::rounded(0.0, 0.0, 600.0, 400.0, 12.0))),
("shimmer (shape)", Fx::shimmer(ShimmerParams::default()).on(Shape::rounded(0.0, 0.0, 600.0, 400.0, 12.0))),
("sparkles x9", Fx::sparkles(SparkleParams::default()).on(Shape::rounded(0.0, 0.0, 600.0, 400.0, 12.0))),
("aurora", Fx::aurora(AuroraParams::default()).on(Shape::rounded(0.0, 0.0, 600.0, 400.0, 12.0))),
("grain", Fx::grain(GrainParams::default()).on(Shape::rounded(0.0, 0.0, 600.0, 400.0, 12.0))),
("fill liquid metal", Fx::fill(LiquidMetalParams::chrome()).on(sh)),
("fill liquid metal, still", Fx::fill(LiquidMetalParams { flow: 0.0, ..LiquidMetalParams::chrome() }).on(sh)),
("fill liquid metal border 8", Fx::fill(LiquidMetalParams::gold().border(8.0)).on(sh)),
("fill liquid metal, element anchor", Fx::fill(LiquidMetalParams::chrome().anchor(FillAnchor::Element)).on(sh)),
("fill plastic glossy", Fx::fill(PlasticParams::glossy()).on(sh)),
("fill plastic matte", Fx::fill(PlasticParams::matte()).on(sh)),
("fill plastic border 8", Fx::fill(PlasticParams::glossy().border(8.0)).on(sh)),
("fill mesh gradient (5 colours)", Fx::fill(MeshGradientParams::dusk()).on(sh)),
("fill dither bayer (ramp)", Fx::fill(DitherParams::bayer()).on(sh)),
("fill dither blue noise (radial)", Fx::fill(DitherParams::grain()).on(sh)),
("fill dither palette (noise)", Fx::fill(DitherParams::handheld()).on(sh)),
("fill dither backdrop", Fx::fill(DitherParams::backdrop()).on(sh)),
("fill grain gradient", Fx::fill(GrainGradientParams::ember()).on(sh)),
("fill grain gradient conic, colour", Fx::fill(GrainGradientParams::sweep()).on(sh)),
("fill fluted glass", Fx::fill(FlutedGlassParams::reeded()).on(sh)),
("fill fluted glass + frost", Fx::fill(FlutedGlassParams::frosted()).on(sh)),
("fill metaballs x6", Fx::fill(MetaballParams::lava()).on(sh)),
("fill swirl", Fx::fill(SwirlParams::ink()).on(sh)),
("fill voronoi", Fx::fill(VoronoiParams::cells()).on(sh)),
("fill waves (5 bands)", Fx::fill(WaveParams::sea()).on(sh)),
("fill halftone (radial)", Fx::fill(HalftoneParams::print()).on(sh)),
("fill halftone backdrop", Fx::fill(HalftoneParams::backdrop()).on(sh)),
];
for (n, mode, angle) in [("motion shutter (fling peak)", BlurMode::Shutter, 360.0f32), ("motion directional", BlurMode::Directional, 360.0)] {
let rest = Rect::new(100.0, 100.0, 400.0, 200.0);
let p = MotionBlurParams { mode, shutter_angle: angle, ..Default::default() };
let s = MotionSamples::from_track(&p, rest, 0.02, S, fling);
v.push((n, Fx::motion_blur(p, s).on(Shape::rounded(rest.x, rest.y, rest.w, rest.h, 14.0)).source(1, rest.inflate(SRC_PAD))));
}
for (_, l) in v.iter_mut() {
l.time = t;
}
v
}
const DRAWS: u32 = 10;
fn timings() -> String {
let (w, h) = ((600.0 * S) as u32, (400.0 * S) as u32);
let mut ctx = Ctx::new(w, h);
if !ctx.timestamps {
return "timestamp queries unavailable on this adapter\n".into();
}
let (_st, src_view) = tex(&ctx.device, 808, 408, FMT, wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING);
let qs = ctx.device.create_query_set(&wgpu::QuerySetDescriptor { label: None, ty: wgpu::QueryType::Timestamp, count: 64 });
let qbuf = ctx.device.create_buffer(&wgpu::BufferDescriptor { label: None, size: 512, usage: wgpu::BufferUsages::QUERY_RESOLVE | wgpu::BufferUsages::COPY_SRC, mapped_at_creation: false });
let rbuf = ctx.device.create_buffer(&wgpu::BufferDescriptor { label: None, size: 512, usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, mapped_at_creation: false });
let period = ctx.queue.get_timestamp_period() as f64;
let mut out = String::from("| effect | covered px (2x) | reads/px | noise/px | backdrop | GPU ms per draw (median; 10 draws/pass) |\n|---|---:|---:|---:|:-:|---:|\n");
for (name, layer) in timing_layers() {
let layers = [layer];
let sources: Vec<&wgpu::TextureView> = vec![&ctx.pyramid.view, &src_view];
let frame = FxFrame { viewport: [w, h], scale: S, layers: &layers, backdrop: Some(&ctx.backdrop_view), sources: &sources };
let stats = ctx.fx.prepare(&ctx.device, &ctx.queue, &frame);
let mut samples = Vec::new();
for round in 0..4 {
let mut enc = ctx.device.create_command_encoder(&Default::default());
for k in 0..8u32 {
let tw = wgpu::RenderPassTimestampWrites { query_set: &qs, beginning_of_pass_write_index: Some(k * 2), end_of_pass_write_index: Some(k * 2 + 1) };
let mut p = pass(&mut enc, &ctx.scene_view, Some(wgpu::Color::BLACK), Some(tw));
for _ in 0..DRAWS {
ctx.fx.draw_layer(&mut p, 0);
}
}
enc.resolve_query_set(&qs, 0..16, &qbuf, 0);
enc.copy_buffer_to_buffer(&qbuf, 0, &rbuf, 0, 128);
ctx.queue.submit([enc.finish()]);
let sl = rbuf.slice(..128);
sl.map_async(wgpu::MapMode::Read, |_| {});
ctx.device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
{
let d = sl.get_mapped_range().unwrap();
let v: &[u64] = bytemuck::cast_slice(&d);
if round > 0 {
for k in 0..8 {
let d = v[k * 2 + 1].saturating_sub(v[k * 2]);
if d > 0 {
samples.push(d as f64 * period / 1e6 / DRAWS as f64);
}
}
}
}
rbuf.unmap();
}
samples.sort_by(|a, b| a.partial_cmp(b).unwrap());
let med = if samples.is_empty() { f64::NAN } else { samples[samples.len() / 2] };
let c = layers[0].fx.cost();
out += &format!("| {name} | {} | {} | {} | {} | {:.3} |\n", stats.pixels, c.samples, c.alu, if c.backdrop { "yes" } else { "" }, med);
}
// Empty pass baseline.
out
}
// ------------------------------------------------------------------ main
fn main() {
let args: Vec<String> = std::env::args().collect();
let get = |k: &str| args.iter().position(|a| a == k).and_then(|i| args.get(i + 1)).cloned();
let effect = get("--effect").or_else(|| get("--still"));
let still_only = args.iter().any(|a| a == "--still");
let dir = get("--out").map_or_else(|| PathBuf::from("demo/fx"), PathBuf::from);
if args.iter().any(|a| a == "--timings") {
let t = timings();
println!("{t}");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("timings.md"), t).unwrap();
return;
}
let mut ctx = Ctx::new((W * S) as u32, (H * S) as u32);
if let Some(dir) = get("--frames") {
let fps: f32 = get("--fps").map_or(60.0, |s| s.parse().unwrap());
let secs: f32 = get("--seconds").map_or(2.0, |s| s.parse().unwrap());
let start: f32 = get("--start").map_or(0.0, |s| s.parse().unwrap());
let name = effect.expect("--effect");
let reduced = args.iter().any(|a| a == "--reduced");
let n = (fps * secs).round() as u32;
for i in 0..n {
let px = ctx.render(&name, start + i as f32 / fps, reduced);
write_png(&Path::new(&dir).join(format!("{name}_{i:04}.png")), ctx.w, ctx.h, &px).unwrap();
}
eprintln!("wrote {n} frames to {dir}");
return;
}
if still_only {
let name = effect.as_deref().unwrap_or("blend");
std::fs::create_dir_all(&dir).unwrap();
let px = ctx.render(name, still_time(name), false);
write_png(&dir.join(format!("{name}.png")), ctx.w, ctx.h, &px).unwrap();
eprintln!("wrote {name}.png");
return;
}
let list: Vec<&str> = match &effect {
Some(e) => vec![e.as_str()],
None => EFFECTS.to_vec(),
};
for e in list {
render_effect(&mut ctx, &dir, e);
}
if effect.is_none() && !args.iter().any(|a| a == "--no-timings") {
let t = timings();
println!("{t}");
std::fs::write(dir.join("timings.md"), t).unwrap();
}
}
@@ -0,0 +1,33 @@
// Resolve: linear 16f -> sRGB 8-bit with TPDF dither (once, at the final write).
@group(0) @binding(0) var scene: texture_2d<f32>;
struct RV { @builtin(position) pos: vec4f }
@vertex
fn vs_full(@builtin(vertex_index) vi: u32) -> RV {
let p = vec2f(f32((vi << 1u) & 2u), f32(vi & 2u));
var o: RV;
o.pos = vec4f(p * 2.0 - 1.0, 0.0, 1.0);
return o;
}
fn pcg(v: u32) -> u32 {
let s = v * 747796405u + 2891336453u;
let w = ((s >> ((s >> 28u) + 4u)) ^ s) * 277803737u;
return (w >> 22u) ^ w;
}
fn u01(n: u32) -> f32 { return f32(pcg(n) >> 8u) * (1.0 / 16777216.0); }
fn to_srgb(c: vec3f) -> vec3f {
let lo = c * 12.92;
let hi = 1.055 * pow(max(c, vec3f(0.0)), vec3f(1.0 / 2.4)) - 0.055;
return select(hi, lo, c <= vec3f(0.0031308));
}
@fragment
fn fs_resolve(in: RV) -> @location(0) vec4f {
let ip = vec2u(in.pos.xy);
let c = textureLoad(scene, vec2i(ip), 0);
let n = u01(ip.x + pcg(ip.y)) + u01(ip.x * 7919u + pcg(ip.y + 104729u)) - 1.0;
let s = to_srgb(clamp(c.rgb, vec3f(0.0), vec3f(1.0))) + vec3f(n / 255.0);
return vec4f(clamp(s, vec3f(0.0), vec3f(1.0)), 1.0);
}
@@ -0,0 +1,500 @@
use super::*;
// ------------------------------------------------------------------ scenes
pub(super) fn fling(t: f32) -> Pose {
// Thrown in from off-frame left: critically damped spring (duration 0.6 s, bounce 0), released at t = 0.
let (x0, target, v0, d, ts) = (-150.0f32, 410.0f32, 3000.0f32, 0.6f32, 0.0f32);
let w = std::f32::consts::TAU / d;
let tau = (t - ts).max(0.0);
let a = x0 - target;
let b = v0 + w * a;
let e = (-w * tau).exp();
let x = target + (a + b * tau) * e;
let v = if t < ts { 0.0 } else { (b - w * (a + b * tau)) * e };
Pose { x, y: 0.0, rotation: v * 0.00005, scale: 1.0, opacity: 1.0 }
}
pub(super) fn scene(name: &str, b: &mut B) {
let t = b.t;
match name {
"glow" => {
b.background("Glow", "soft · neon that cools · aura · text bloom · hot core");
// A: breathing soft glow under a button.
let btn = Rect::new(56.0, 92.0, 150.0, 44.0);
b.fx(Fx::glow(GlowParams { radius: 16.0, intensity: 0.85, breathe: 0.4, breathe_period: 2.6, hot: 0.4, ..Default::default() })
.on(Shape::capsule(btn.x, btn.y, btn.w, btn.h)));
b.button(btn, "Generate", 0x8f72ff, 0x6646ee, 0xffffff);
b.caption(56.0, 166.0, "Soft · breathing");
// B: neon card; switched off at 0.35 s in the strip so it visibly cools.
let card = Rect::new(262.0, 70.0, 156.0, 96.0);
b.card(card, 14.0);
b.text(278.0, 98.0, "Neon", 14.0, 2, col(0xe6f9ff, 1.0));
b.lines(278.0, 116.0, 100.0, 3);
let mut heat = Heat::new(0.12, 0.32);
heat.set(-1.0, true);
heat.set(0.35, false);
let h = if t < 0.35 { 1.0 } else { heat.at(t) };
b.fx(Fx::glow(GlowParams {
style: GlowStyle::Neon,
color: rgb(0x22d3ee),
core: rgb(0xeafcff),
radius: 10.0,
intensity: 1.0,
inner: 0.35,
heat: h,
hot: 0.9,
rim_width: 0.55,
..Default::default()
})
.on(Shape::rounded(card.x, card.y, card.w, card.h, 14.0))
.over());
b.caption(262.0, 192.0, "Neon · lights cool, never cut");
// C: aura search field.
let cap = Rect::new(56.0, 236.0, 300.0, 48.0);
b.shadow(Rect::new(cap.x, cap.y + 6.0, cap.w, cap.h), 24.0, 12.0, [0.0, 0.0, 0.0, 0.5]);
b.rect(cap, 24.0, col(0x15171d, 1.0), col(0x111318, 1.0), col(0xffffff, 0.08), 0.5);
b.text(80.0, 265.0, "Ask anything…", 14.0, 0, col(0x7d8390, 1.0));
b.fx(Fx::glow(GlowParams {
style: GlowStyle::Aura,
color: rgb(0xff5fa2),
core: rgb(0x8b5cf6),
third: rgb(0x38bdf8),
radius: 12.0,
intensity: 0.9,
inner: 0.55,
hot: 0.55,
aura_speed: 0.15,
rim_width: 0.6,
occlusion: 0.1,
..Default::default()
})
.on(Shape::capsule(cap.x, cap.y, cap.w, cap.h))
.over());
b.caption(56.0, 308.0, "Aura · flowing spectrum");
// D: text bloom from a mask pyramid.
let (tx, ty) = (432.0, 292.0);
b.target = Target::Mask;
b.text(tx, ty, "Rune", 64.0, 2, col(0xffffff, 1.0));
b.target = Target::Main;
b.fx(Fx::glow(GlowParams {
style: GlowStyle::Mask,
color: rgb(0xff8a2a),
core: rgb(0xfff1d6),
radius: 10.0,
intensity: 1.1,
hot: 0.0,
breathe: 0.25,
breathe_period: 3.2,
..Default::default()
})
.on(Shape::rounded(tx, ty - 56.0, 160.0, 72.0, 0.0))
.source(0, Rect::new(0.0, 0.0, W, H)));
b.text(tx, ty, "Rune", 64.0, 2, col(0xfff4e6, 1.0));
b.caption(432.0, 320.0, "Mask · text bloom");
// E: hot core status dot.
let dot = Shape::circle(470.0, 112.0, 7.0);
b.fx(Fx::glow(GlowParams { color: rgb(0xffa630), core: rgb(0xfff6e0), radius: 9.0, intensity: 1.3, hot: 1.0, ..Default::default() }).on(dot));
b.rect(dot.rect, 7.0, col(0xfff3dc, 1.0), col(0xffd9a0, 1.0), [0.0; 4], 0.0);
b.text(490.0, 117.0, "Recording", 13.0, 1, col(0xd6d9df, 1.0));
b.caption(462.0, 166.0, "Hot core");
}
"pulse" => {
b.background("Pulses", "radar · breathing halo · heartbeat · ping that lands and ripples");
let rec = Shape::circle(96.0, 112.0, 18.0);
b.fx(Fx::pulse(PulseParams { color: rgb(0xff4d5e), core: rgb(0xffe4e6), reach: 46.0, width: 1.3, period: 2.2, ..Default::default() }).on(rec));
b.rect(rec.rect, 18.0, col(0xff5a68, 1.0), col(0xe5243b, 1.0), col(0xffffff, 0.2), 0.5);
b.rect(Rect::new(90.0, 106.0, 12.0, 12.0), 3.0, col(0xffffff, 0.95), col(0xffffff, 0.95), [0.0; 4], 0.0);
b.caption(76.0, 184.0, "Radar");
let av = Shape::circle(236.0, 112.0, 22.0);
b.fx(Fx::pulse(PulseParams { style: PulseStyle::Breathe, color: rgb(0x34d399), core: rgb(0xd1fae5), reach: 12.0, period: 2.8, intensity: 0.8, ..Default::default() }).on(av));
b.rect(av.rect, 22.0, col(0x3a4150, 1.0), col(0x262b35, 1.0), col(0x34d399, 0.9), 1.0);
b.text_c(236.0, 112.0, "KL", 14.0, 2, col(0xeef0f3, 1.0));
b.caption(196.0, 184.0, "Breathing halo");
let live = Rect::new(354.0, 98.0, 74.0, 28.0);
b.fx(Fx::pulse(PulseParams { style: PulseStyle::Heartbeat, color: rgb(0xff3b6b), core: rgb(0xffe4ec), reach: 26.0, width: 1.1, period: 1.1, ..Default::default() })
.on(Shape::capsule(live.x, live.y, live.w, live.h)));
b.rect(live, 14.0, col(0xf43f5e, 1.0), col(0xdb1f48, 1.0), col(0xffffff, 0.2), 0.5);
b.text_c(391.0, 112.0, "LIVE", 12.0, 2, col(0xffffff, 1.0));
b.caption(360.0, 184.0, "Heartbeat");
// Ping from the send button to the inbox card, which ripples on arrival.
let send = Shape::circle(84.0, 268.0, 16.0);
let inbox = Rect::new(446.0, 222.0, 150.0, 92.0);
b.card(inbox, 14.0);
b.text(462.0, 250.0, "Inbox", 14.0, 2, col(0xeef0f3, 1.0));
b.lines(462.0, 266.0, 96.0, 3);
b.fx(Fx::pulse(PulseParams {
style: PulseStyle::Ping { from: [104.0, 268.0], dir: [1.0, 0.0], travel: 332.0 },
color: rgb(0x60a5fa),
core: rgb(0xf0f7ff),
t0: 0.05,
duration: 0.62,
lag: 0.16,
head_radius: 2.6,
..Default::default()
})
.on(send));
b.button(send.rect, "", 0x4b8dff, 0x2f6fe8, 0xffffff);
b.text_c(84.0, 267.0, "→", 15.0, 2, col(0xffffff, 1.0));
b.fx(Fx::pulse(PulseParams { style: PulseStyle::Ripple { at: [452.0, 268.0] }, color: rgb(0x93c5fd), core: rgb(0xffffff), reach: 0.0, width: 2.2, t0: 0.62, duration: 0.9, intensity: 0.7, ..Default::default() })
.on(Shape::rounded(inbox.x, inbox.y, inbox.w, inbox.h, 14.0))
.over());
b.caption(64.0, 330.0, "Ping → ripple (anticipation, decelerating landing, cools)");
}
"electric" => {
b.background("Electricity", "arc with forks · border current · calm charged border");
let (a, c) = ([64.0f32, 96.0f32], [576.0f32, 96.0f32]);
b.fx(Fx::electric(ElectricParams { style: ElectricStyle::Arc { a: [a[0] + 6.0, a[1]], b: [c[0] - 6.0, c[1]] }, amplitude: 9.0, glow: 6.0, forks: 0.6, strands: 3, ..Default::default() })
.on(Shape::rounded(a[0], a[1] - 1.0, c[0] - a[0], 2.0, 0.0)));
for p in [a, c] {
b.rect(Rect::new(p[0] - 8.0, p[1] - 8.0, 16.0, 16.0), 8.0, col(0xb8c0cc, 1.0), col(0x4b5563, 1.0), col(0xffffff, 0.3), 0.5);
}
b.caption(64.0, 140.0, "Arc · forks shoot out and cool");
let card = Rect::new(64.0, 178.0, 236.0, 132.0);
b.card(card, 16.0);
b.text(84.0, 210.0, "Overload", 15.0, 2, col(0xeef0f3, 1.0));
b.lines(84.0, 228.0, 170.0, 4);
b.fx(Fx::electric(ElectricParams { amplitude: 4.0, gap: 3.0, fork_len: 22.0, glow: 5.0, ..Default::default() })
.on(Shape::rounded(card.x, card.y, card.w, card.h, 16.0))
.seed(7));
b.caption(64.0, 340.0, "Border current");
let btn = Rect::new(380.0, 222.0, 196.0, 50.0);
b.button(btn, "Charged", 0x1e2a44, 0x162036, 0xdbe8ff);
b.fx(Fx::electric(ElectricParams { color: rgb(0x60a5fa), ..ElectricParams::charged() })
.on(Shape::capsule(btn.x, btn.y, btn.w, btn.h))
.seed(3));
b.caption(380.0, 300.0, "Charged border (calm, for UI)");
}
"fire" => {
b.background("Fire & plasma", "flames + embers · plasma border · heat for a button");
let card = Rect::new(72.0, 204.0, 224.0, 124.0);
b.fx(Fx::fire(FireParams::default()).on(Shape::rounded(card.x, card.y, card.w, card.h, 16.0)).seed(5));
b.card(card, 16.0);
b.text(92.0, 236.0, "Hot take", 15.0, 2, col(0xfff1e6, 1.0));
b.lines(92.0, 254.0, 160.0, 4);
let cap = Rect::new(356.0, 118.0, 224.0, 56.0);
b.fx(Fx::fire(FireParams::plasma()).on(Shape::capsule(cap.x, cap.y, cap.w, cap.h)).seed(11));
b.rect(cap, 28.0, col(0x17142a, 1.0), col(0x100e1f, 1.0), col(0xb9a8ff, 0.25), 0.5);
b.text_c(cap.x + cap.w * 0.5, cap.y + cap.h * 0.5, "Plasma", 15.0, 2, col(0xe9e4ff, 1.0));
b.caption(356.0, 214.0, "Plasma border");
let btn = Rect::new(392.0, 266.0, 152.0, 44.0);
b.fx(Fx::fire(FireParams::heat()).on(Shape::capsule(btn.x, btn.y, btn.w, btn.h)).seed(2));
b.button(btn, "Deploy", 0xff8a3d, 0xe8590c, 0xffffff);
b.backdrop();
b.fx(Fx::distort(DistortParams::HeatHaze { height: 26.0, scale: 9.0, speed: 2.0, amount: 1.1, whole_shape: false })
.on(Shape::capsule(btn.x, btn.y, btn.w, btn.h)));
b.caption(392.0, 336.0, "Heat (UI) + haze");
b.caption(72.0, 350.0, "Flames + embers");
}
"motion" => {
b.background("Motion blur", "a card flung across the frame · none / directional / shutter 180°");
let rest = Rect::new(60.0, 0.0, 124.0, 74.0);
let lanes = [("No blur", 62.0f32, 0.0f32, BlurMode::Shutter), ("Directional (cheap fallback)", 162.0, 180.0, BlurMode::Directional), ("Shutter 180° (exact sub-frame poses)", 262.0, 180.0, BlurMode::Shutter)];
for (i, (label, y, angle, mode)) in lanes.iter().enumerate() {
let r = Rect::new(rest.x, *y, rest.w, rest.h);
b.caption(24.0, y + rest.h + 18.0, label);
if i == 0 {
// Card content, drawn once into the node layer at lane 0's rest rect.
b.src_rect = Some(r);
b.target = Target::Src;
b.shadow(Rect::new(r.x, r.y + 4.0, r.w, r.h), 14.0, 4.0, [0.0, 0.0, 0.0, 0.35]);
b.rect(r, 14.0, col(0x23262e, 1.0), col(0x1a1c22, 1.0), col(0xffffff, 0.1), 0.5);
b.rect(Rect::new(r.x + 12.0, r.y + 12.0, 26.0, 26.0), 13.0, col(0x9b7bff, 1.0), col(0x6d4cf5, 1.0), [0.0; 4], 0.0);
b.text(r.x + 46.0, r.y + 23.0, "Flight 204", 12.5, 2, col(0xf3f4f6, 1.0));
b.text(r.x + 46.0, r.y + 37.0, "Departing 9:41", 10.5, 0, col(0x9aa1ad, 1.0));
b.rect(Rect::new(r.x + 12.0, r.y + 56.0, r.w - 24.0, 5.0), 2.5, col(0x30343d, 1.0), col(0x30343d, 1.0), [0.0; 4], 0.0);
b.rect(Rect::new(r.x + 12.0, r.y + 56.0, (r.w - 24.0) * 0.62, 5.0), 2.5, col(0x34d399, 1.0), col(0x10b981, 1.0), [0.0; 4], 0.0);
b.target = Target::Main;
}
let src_rect = b.src_rect.unwrap().inflate(SRC_PAD);
let dy = y - 62.0;
let p = MotionBlurParams { mode: *mode, shutter_angle: *angle, ..Default::default() };
let sp = if b.reduced { MotionBlurParams { shutter_angle: 0.0, ..p } } else { p };
let samples = MotionSamples::from_track(&sp, b.src_rect.unwrap(), t, S, |tt| {
let mut q = fling(tt);
q.y += dy;
q
});
b.fx(Fx::motion_blur(p, samples).on(Shape::rounded(r.x, r.y, r.w, r.h, 14.0)).source(1, src_rect));
}
}
"distort" => {
b.background("Distortion", "liquid-glass lens (gooey union) · shockwave · CRT · chromatic split");
// Page content beneath.
let tiles = [(0x8b5cf6, 0x5b21b6), (0xfb923c, 0xea580c), (0x2dd4bf, 0x0f766e), (0xf472b6, 0xbe185d)];
for (i, (a, c)) in tiles.iter().enumerate() {
let x = 40.0 + i as f32 * 143.0;
b.rect(Rect::new(x, 60.0, 131.0, 64.0), 12.0, col(*a, 1.0), col(*c, 1.0), col(0xffffff, 0.15), 0.5);
b.text(x + 12.0, 112.0, ["Violet", "Ember", "Lagoon", "Orchid"][i], 13.0, 2, col(0xffffff, 0.95));
}
let para = ["Glass bends what is behind it: the rim squeezes the page,", "the middle stays sharp, and colour splits only at the edge.", "Rune samples the backdrop once per lens and lights the rim."];
for (i, l) in para.iter().enumerate() {
b.text(40.0, 152.0 + i as f32 * 20.0, l, 13.0, 0, col(0xb4b9c4, 1.0));
}
// CRT content.
let crt = Rect::new(40.0, 222.0, 250.0, 118.0);
b.rect(crt, 12.0, col(0x0d1a12, 1.0), col(0x07110b, 1.0), [0.0; 4], 0.0);
b.text(56.0, 250.0, "> rune build --release", 13.0, 1, col(0x4ade80, 1.0));
b.text(56.0, 270.0, " compiling rune-fx v0.0.1", 13.0, 0, col(0x86efac, 0.8));
b.text(56.0, 290.0, " finished in 1.84 s", 13.0, 0, col(0x86efac, 0.8));
b.rect(Rect::new(56.0, 304.0, 120.0, 14.0), 3.0, col(0x22c55e, 1.0), col(0x16a34a, 1.0), [0.0; 4], 0.0);
b.text(330.0, 300.0, "Chromatic", 40.0, 2, col(0xf3f4f6, 1.0));
// Lens: capsule + a droplet pulling away.
let lx = if b.reduced { 380.0 } else { 352.0 + 70.0 * (0.5 - 0.5 * (t * 2.2).cos()) };
b.backdrop();
b.fx(Fx::lens(LensParams { second: Some(Shape::circle(lx, 116.0, 30.0)), union_k: 26.0, ..Default::default() })
.on(Shape::capsule(140.0, 84.0, 200.0, 64.0)));
b.backdrop();
b.fx(Fx::lens(LensParams { frost: 1.0, ..Default::default() }).on(Shape::capsule(388.0, 92.0, 220.0, 66.0)));
b.backdrop();
b.fx(Fx::distort(DistortParams::shockwave([470.0, 150.0], 0.0)).on(Shape::rounded(0.0, 0.0, W, H, 0.0)));
b.backdrop();
b.fx(Fx::distort(DistortParams::crt()).on(Shape::rounded(crt.x, crt.y, crt.w, crt.h, 12.0)));
b.backdrop();
b.fx(Fx::distort(DistortParams::ChromaSplit { offset: [1.6, 0.0], glitch: 0.3, feather: 2.0 }).on(Shape::rounded(322.0, 256.0, 260.0, 60.0, 6.0)));
}
"extras" => {
b.background("Extras", "skeleton shimmer · text sheen · sparkles · aurora + grain");
let list = Rect::new(40.0, 62.0, 280.0, 186.0);
b.card(list, 16.0);
for i in 0..3 {
let y = list.y + 22.0 + i as f32 * 54.0;
for tgt in [Target::Main, Target::Mask] {
b.target = tgt;
let c = if tgt == Target::Main { col(0x22262e, 1.0) } else { col(0xffffff, 1.0) };
b.rect(Rect::new(list.x + 20.0, y, 32.0, 32.0), 16.0, c, c, [0.0; 4], 0.0);
b.rect(Rect::new(list.x + 64.0, y + 4.0, 160.0 - i as f32 * 24.0, 10.0), 5.0, c, c, [0.0; 4], 0.0);
b.rect(Rect::new(list.x + 64.0, y + 20.0, 104.0, 8.0), 4.0, c, c, [0.0; 4], 0.0);
}
b.target = Target::Main;
}
b.fx(Fx::shimmer(ShimmerParams { intensity: 0.11, band: 42.0, use_mask: true, ..Default::default() })
.on(Shape::rounded(list.x, list.y, list.w, list.h, 16.0))
.source(0, Rect::new(0.0, 0.0, W, H)));
b.caption(40.0, 272.0, "Skeleton shimmer");
b.text(40.0, 316.0, "Thinking…", 20.0, 1, col(0x8b919c, 1.0));
b.target = Target::Mask;
b.text(40.0, 316.0, "Thinking…", 20.0, 1, col(0xffffff, 1.0));
b.target = Target::Main;
b.fx(Fx::shimmer(ShimmerParams { intensity: 0.85, band: 18.0, period: 1.6, angle: 0.25, use_mask: true, ..Default::default() })
.on(Shape::rounded(36.0, 292.0, 110.0, 32.0, 0.0))
.source(0, Rect::new(0.0, 0.0, W, H)));
b.caption(40.0, 344.0, "Text sheen");
let au = Rect::new(352.0, 62.0, 248.0, 152.0);
b.card(au, 18.0);
b.fx(Fx::aurora(AuroraParams { intensity: 0.75, scale: 110.0, feather: 18.0, ..Default::default() }).on(Shape::rounded(au.x, au.y, au.w, au.h, 18.0)).over());
b.fx(Fx::grain(GrainParams { amount: 0.016, ..Default::default() }).on(Shape::rounded(au.x, au.y, au.w, au.h, 18.0)));
b.text(372.0, 196.0, "Aurora", 18.0, 2, col(0xf5f7fa, 1.0));
b.caption(352.0, 238.0, "Aurora + static grain");
let pro = Rect::new(432.0, 274.0, 88.0, 34.0);
b.rect(pro, 17.0, col(0xf7d98b, 1.0), col(0xcf9f38, 1.0), col(0xffffff, 0.4), 0.5);
b.text_c(476.0, 291.0, "PRO", 13.0, 2, col(0x3b2a06, 1.0));
b.fx(Fx::sparkles(SparkleParams { margin: 20.0, size: 8.0, count: 6, ..Default::default() }).on(Shape::capsule(pro.x, pro.y, pro.w, pro.h)).seed(4));
b.caption(432.0, 344.0, "Sparkles");
}
"liquid-metal" => {
b.background("Liquid metal", "chrome · gold · rose gold · gunmetal · as a border");
let shadow = |b: &mut B, r: Rect, radius: f32| b.shadow(Rect::new(r.x, r.y + 10.0, r.w, r.h), radius, 16.0, [0.0, 0.0, 0.0, 0.55]);
let slab = Rect::new(32.0, 58.0, 260.0, 160.0);
shadow(b, slab, 40.0);
b.fx(Fx::fill(LiquidMetalParams::chrome()).on(Shape::rounded(slab.x, slab.y, slab.w, slab.h, 40.0)));
b.caption(32.0, 238.0, "Chrome");
let btn = Rect::new(318.0, 62.0, 180.0, 52.0);
shadow(b, btn, 26.0);
b.fx(Fx::fill(LiquidMetalParams::gold()).on(Shape::capsule(btn.x, btn.y, btn.w, btn.h)));
b.caption(318.0, 134.0, "Gold");
shadow(b, Rect::new(534.0, 54.0, 68.0, 68.0), 34.0);
b.fx(Fx::fill(LiquidMetalParams::rose()).on(Shape::circle(568.0, 88.0, 34.0)));
b.caption(534.0, 134.0, "Rose gold");
let gm = Rect::new(318.0, 152.0, 290.0, 66.0);
shadow(b, gm, 18.0);
b.fx(Fx::fill(LiquidMetalParams::gunmetal()).on(Shape::rounded(gm.x, gm.y, gm.w, gm.h, 18.0)));
b.caption(318.0, 238.0, "Gunmetal");
// Borders: a chrome tube round a card, a gold ring round an avatar, a rose-gold capsule.
let card = Rect::new(32.0, 262.0, 260.0, 74.0);
b.card(card, 24.0);
b.fx(Fx::fill(LiquidMetalParams::chrome().border(7.0)).on(Shape::rounded(card.x, card.y, card.w, card.h, 24.0)));
b.text_c(card.center().x, card.center().y, "Chrome border", 15.0, 2, col(0xe8eaee, 1.0));
b.rect(Rect::new(330.0, 263.0, 72.0, 72.0), 36.0, col(0x7c5cff, 1.0), col(0x2b1b5a, 1.0), [0.0; 4], 0.0);
b.text_c(366.0, 299.0, "KL", 22.0, 2, col(0xffffff, 0.95));
b.fx(Fx::fill(LiquidMetalParams::gold().border(4.0)).on(Shape::circle(366.0, 299.0, 36.0)));
let cap = Rect::new(428.0, 272.0, 180.0, 54.0);
b.rect(cap, 27.0, col(0x1a1c22, 1.0), col(0x121419, 1.0), [0.0; 4], 0.0);
b.fx(Fx::fill(LiquidMetalParams::rose().border(5.0)).on(Shape::capsule(cap.x, cap.y, cap.w, cap.h)));
b.text_c(cap.center().x, cap.center().y, "Rose border", 14.0, 2, col(0xf2d4c8, 1.0));
}
"plastic" => {
b.background("Plastic", "glossy · matte and dished · liquid metal keys pinned to the window or to each key");
let colors = [0xece8de, 0x2e3036, 0xd7263d, 0xf46036, 0xffd60a, 0x2a9d8f, 0x3d6fd6, 0x7b5cd6];
let labels = ["Esc", "Q", "W", "E", "R", "T", "Y", "U"];
let rows = [(52.0, PlasticParams { roughness: 0.12, ..PlasticParams::glossy() }, "Glossy: roughness .12, dome .35"), (138.0, PlasticParams { roughness: 0.8, dome: -0.4, ..PlasticParams::glossy() }, "Matte, dished: roughness .8, dome −.4")];
for (y, p, caption) in rows {
for (k, (c, label)) in colors.into_iter().zip(labels).enumerate() {
let r = Rect::new(54.0 + k as f32 * 68.0, y, 56.0, 56.0);
b.shadow(Rect::new(r.x, r.y + 5.0, r.w, r.h), 10.0, 6.0, [0.0, 0.0, 0.0, 0.55]);
b.fx(Fx::fill(PlasticParams { color: rgb(c), ..p }).on(Shape::rounded(r.x, r.y, r.w, r.h, 10.0)));
let ink = if rgb(c).0.iter().sum::<f32>() > 1.2 { col(0x26272b, 0.85) } else { col(0xf4f4f6, 0.9) };
b.text_c(r.center().x, r.center().y, label, 13.0, 2, ink);
}
b.caption(54.0, y + 74.0, caption);
}
for (y, anchor, caption) in [(232.0, FillAnchor::World, "Liquid metal on 24 pt keys, anchor: world (default)"), (290.0, FillAnchor::Element, "Liquid metal on 24 pt keys, anchor: element")] {
for k in 0..18 {
let r = Rect::new(53.0 + k as f32 * 30.0, y, 24.0, 24.0);
b.shadow(Rect::new(r.x, r.y + 3.0, r.w, r.h), 5.0, 4.0, [0.0, 0.0, 0.0, 0.55]);
b.fx(Fx::fill(LiquidMetalParams::chrome().anchor(anchor)).on(Shape::rounded(r.x, r.y, r.w, r.h, 5.0)));
}
b.caption(54.0, y + 42.0, caption);
}
}
"mesh-gradient" => {
b.background("Mesh gradient", "dusk · lagoon · orchid · graphite: drifting points, blended in OKLab");
b.fx(Fx::fill(MeshGradientParams::dusk()).on(Shape::rounded(32.0, 58.0, 300.0, 272.0, 28.0)));
b.text(56.0, 306.0, "Dusk", 28.0, 2, col(0xffffff, 0.95));
for (k, (p, name)) in [(MeshGradientParams::lagoon(), "Lagoon"), (MeshGradientParams::orchid(), "Orchid"), (MeshGradientParams::graphite(), "Graphite")].into_iter().enumerate() {
let y = 58.0 + k as f32 * 94.0;
b.fx(Fx::fill(p).on(Shape::rounded(352.0, y, 256.0, 84.0, 18.0)).seed(k as u32 + 2));
b.text(372.0, y + 68.0, name, 15.0, 2, col(0xffffff, 0.92));
}
}
"dither" => {
b.background("Dither", "Bayer 2×2, 4×4, 8×8 · blue noise · of a ramp, noise or the backdrop");
let xs = [32.0, 182.0, 332.0, 482.0];
let tiles = [(DitherParams::bayer(), "Bayer 4×4, ramp"), (DitherParams::handheld(), "Palette, noise"), (DitherParams::grain(), "Blue noise, radial"), (DitherParams::backdrop(), "Backdrop")];
for (x, (p, name)) in xs.into_iter().zip(tiles) {
let r = Rect::new(x, 58.0, 140.0, 128.0);
if p.input == FillInput::Backdrop {
b.rect(r, 16.0, col(0xff7aa2, 1.0), col(0x3b2a8f, 1.0), [0.0; 4], 0.0);
b.rect(Rect::new(x + 62.0, 74.0, 64.0, 64.0), 32.0, col(0xfff1c2, 1.0), col(0xffb44d, 1.0), [0.0; 4], 0.0);
b.text(x + 14.0, 172.0, "Aa", 40.0, 2, col(0xffffff, 1.0));
b.backdrop();
}
b.fx(Fx::fill(p).on(Shape::rounded(r.x, r.y, r.w, r.h, 16.0)));
b.caption(x, 204.0, name);
}
let pats = [(DitherPattern::Bayer2, "Bayer 2×2"), (DitherPattern::Bayer4, "Bayer 4×4"), (DitherPattern::Bayer8, "Bayer 8×8"), (DitherPattern::White, "White noise")];
for (x, (pattern, name)) in xs.into_iter().zip(pats) {
let p = DitherParams { pattern, pixel: 3.0, angle: 0.0, colors: Stops::hex(&[0x1b1530, 0x9be7ff]), ..DitherParams::bayer() };
b.fx(Fx::fill(p).on(Shape::rounded(x, 222.0, 140.0, 96.0, 14.0)));
b.caption(x, 336.0, name);
}
}
"grain-gradient" => {
b.background("Grain gradient", "linear · radial · conic, with film grain (mono or colour)");
for (x, (p, name)) in [32.0, 229.0, 426.0].into_iter().zip([(GrainGradientParams::ember(), "Ember (linear, mono)"), (GrainGradientParams::halo(), "Halo (radial)"), (GrainGradientParams::sweep(), "Sweep (conic, colour grain)")]) {
b.fx(Fx::fill(p).on(Shape::rounded(x, 58.0, 182.0, 250.0, 22.0)));
b.caption(x, 328.0, name);
}
}
"fluted-glass" => {
b.background("Fluted glass", "reeded · fine · frosted · wide ribs, over moving content");
b.rect(Rect::new(24.0, 48.0, 592.0, 266.0), 24.0, col(0x1e2a5a, 1.0), col(0x0d1226, 1.0), [0.0; 4], 0.0);
let blobs = [(0xff8a3d, 0xe0451f, 140.0, 118.0, 54.0), (0x8b5cf6, 0x4c1d95, 255.0, 236.0, 62.0), (0x2dd4bf, 0x0f766e, 405.0, 112.0, 50.0), (0xf472b6, 0xbe185d, 548.0, 226.0, 58.0)];
for (k, (a, c, x, y, r)) in blobs.into_iter().enumerate() {
let dx = if b.reduced { 0.0 } else { 26.0 * (t * 0.9 + k as f32 * 1.7).sin() };
b.rect(Rect::new(x - r + dx, y - r, 2.0 * r, 2.0 * r), r, col(a, 1.0), col(c, 1.0), [0.0; 4], 0.0);
}
b.text(46.0, 214.0, "Fluted", 96.0, 2, col(0xffffff, 0.96));
for (x, (p, name)) in [40.0, 190.0, 340.0, 490.0].into_iter().zip([(FlutedGlassParams::reeded(), "Reeded"), (FlutedGlassParams::fine(), "Fine"), (FlutedGlassParams::frosted(), "Frosted"), (FlutedGlassParams::wide(), "Wide")]) {
b.backdrop();
b.fx(Fx::fill(p).on(Shape::rounded(x, 60.0, 120.0, 240.0, 16.0)));
b.caption(x, 324.0, name);
}
}
"fills" => {
b.background("More fills", "metaballs · swirl · voronoi · waves · halftone");
let xs = [32.0, 229.0, 426.0];
let row1: [(FillParams, &str); 3] = [(MetaballParams::lava().into(), "Metaballs"), (SwirlParams::ink().into(), "Swirl"), (VoronoiParams::stained().into(), "Voronoi")];
for (x, (p, name)) in xs.into_iter().zip(row1) {
b.fx(Fx::fill(p).on(Shape::rounded(x, 56.0, 182.0, 118.0, 18.0)));
b.caption(x, 192.0, name);
}
b.fx(Fx::fill(WaveParams::sea()).on(Shape::rounded(32.0, 208.0, 182.0, 118.0, 18.0)));
b.caption(32.0, 344.0, "Waves");
b.fx(Fx::fill(HalftoneParams::print()).on(Shape::rounded(229.0, 208.0, 182.0, 118.0, 18.0)));
b.caption(229.0, 344.0, "Halftone");
let r = Rect::new(426.0, 208.0, 182.0, 118.0);
b.rect(r, 18.0, col(0xf6d365, 1.0), col(0xfda085, 1.0), [0.0; 4], 0.0);
b.rect(Rect::new(470.0, 222.0, 90.0, 90.0), 45.0, col(0x5b8def, 1.0), col(0x1d2b64, 1.0), [0.0; 4], 0.0);
b.backdrop();
b.fx(Fx::fill(HalftoneParams::backdrop()).on(Shape::rounded(r.x, r.y, r.w, r.h, 18.0)));
b.caption(426.0, 344.0, "Halftone of the backdrop");
}
"fill-presets" => {
b.background("Fill presets", "every style and preset in the catalog");
let all: Vec<(&StyleInfo, &Preset)> = fill_styles().iter().flat_map(|s| s.presets.iter().map(move |p| (s, p))).collect();
for (k, (s, p)) in all.into_iter().enumerate() {
let (x, y) = (28.0 + (k % 8) as f32 * 74.0, 50.0 + (k / 8) as f32 * 78.0);
let r = Rect::new(x, y, 66.0, 44.0);
let f = p.fill();
if f.needs_backdrop() {
b.rect(r, 10.0, col(0x3b82f6, 1.0), col(0x1e1b4b, 1.0), [0.0; 4], 0.0);
b.rect(Rect::new(x + 8.0, y + 6.0, 30.0, 30.0), 15.0, col(0xffd166, 1.0), col(0xef476f, 1.0), [0.0; 4], 0.0);
b.text(x + 34.0, y + 36.0, "Aa", 22.0, 2, col(0xffffff, 1.0));
b.backdrop();
}
b.fx(Fx::fill(f).on(Shape::rounded(r.x, r.y, r.w, r.h, 10.0)).seed(k as u32));
b.text(x, y + 56.0, s.name, 9.0, 1, col(0x6b7280, 1.0));
b.text(x, y + 67.0, p.name, 9.0, 2, col(0xb4b9c4, 1.0));
}
}
"blend" => {
// Cream paper (#FAF7F2) backdrop for an onboarding hero and shader fills.
b.rect(Rect::new(0.0, 0.0, W, H), 0.0, col(0xfaf7f2, 1.0), col(0xf3ede3, 1.0), [0.0; 4], 0.0);
let tw = b.text(24.0, 34.0, "Blend", 15.0, 2, col(0x1f1c18, 1.0));
b.text(24.0 + tw + 8.0, 34.0, "warm glow & shader fill over #FAF7F2 cream paper", 12.0, 0, col(0x6e6559, 1.0));
let modes = [
("Normal", FxBlend::Normal),
("Multiply", FxBlend::Multiply),
("Screen", FxBlend::Screen),
("Overlay", FxBlend::Overlay),
("SoftLight", FxBlend::SoftLight),
];
for (idx, (label, _) ) in modes.iter().enumerate() {
let x = 24.0 + idx as f32 * 120.0;
// Subtle warm card rules on the cream paper so blend interaction with midtones is visible.
let well = Rect::new(x, 54.0, 112.0, 132.0);
b.rect(well, 12.0, col(0xfaf7f2, 1.0), col(0xf4efe6, 1.0), col(0x2b241c, 0.10), 1.0 / S);
for r in 0..3 {
let ry = 140.0 + r as f32 * 12.0;
b.rect(Rect::new(x + 16.0, ry, 80.0 - (r as f32 * 14.0), 4.0), 2.0, col(0xd8cfc2, 1.0), col(0xd8cfc2, 1.0), [0.0; 4], 0.0);
}
// Lower row: warm ruled paper card beneath a shader fill.
let card = Rect::new(x, 212.0, 112.0, 108.0);
b.rect(card, 12.0, col(0xf6f0e6, 1.0), col(0xebe2d3, 1.0), col(0x2b241c, 0.12), 1.0 / S);
b.rect(Rect::new(x + 12.0, 228.0, 56.0, 22.0), 6.0, col(0xd48b45, 0.35), col(0xb85d22, 0.35), [0.0; 4], 0.0);
b.text(x + 16.0, 274.0, "Paper", 13.0, 2, col(0x3a3128, 0.85));
for r in 0..2 {
let ry = 286.0 + r as f32 * 11.0;
b.rect(Rect::new(x + 16.0, ry, 76.0 - (r as f32 * 18.0), 4.0), 2.0, col(0x9c8e7b, 0.55), col(0x9c8e7b, 0.55), [0.0; 4], 0.0);
}
b.text_c(x + 56.0, 336.0, label, 11.0, 2, col(0x3f372e, 1.0));
}
b.backdrop();
for (idx, (_, mode)) in modes.iter().enumerate() {
let x = 24.0 + idx as f32 * 120.0;
let pill = Rect::new(x + 22.0, 92.0, 68.0, 32.0);
let glow = Fx::glow(GlowParams {
color: rgb(0xc85a14),
core: rgb(0xe88c28),
radius: 22.0,
intensity: 1.15,
inner: 0.65,
hot: 0.45,
..Default::default()
})
.on(Shape::capsule(pill.x, pill.y, pill.w, pill.h));
b.fx_with(glow, FxSlot::default().blend(*mode));
b.button(pill, "Hero", 0x2c2520, 0x1e1915, 0xfaf7f2);
let fill_shape = Shape::rounded(x + 8.0, 220.0, 96.0, 92.0, 10.0);
let fill = Fx::fill(GrainGradientParams::ember()).on(fill_shape).opacity(0.82);
b.fx_with(fill, FxSlot::default().blend(*mode));
}
}
_ => panic!("unknown effect {name}"),
}
}
+257
View File
@@ -0,0 +1,257 @@
//! Gallery-only UI stand-in: instanced rounded rects, shadows and Inter text from a CPU atlas.
use ab_glyph::{Font, FontRef, PxScale, ScaleFont};
use std::collections::HashMap;
pub const ATLAS: u32 = 2048;
#[repr(C)]
#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub struct UiInst {
pub rect: [f32; 4],
pub p: [f32; 4],
pub fill: [f32; 4],
pub fill2: [f32; 4],
pub border: [f32; 4],
pub uv: [f32; 4],
pub vp: [f32; 4],
}
/// sRGB hex + alpha -> premultiplied linear.
pub fn col(hex: u32, a: f32) -> [f32; 4] {
let f = |s: u32| rune::color::srgb_decode(((hex >> s) & 0xff) as f32 / 255.0) * a;
[f(16), f(8), f(0), a]
}
#[derive(Clone, Copy, Debug)]
pub struct TextRegion {
pub uv: [f32; 4],
pub w: f32,
pub h: f32,
/// Distance from the top of the region to the baseline, px.
pub ascent: f32,
}
pub struct TextAtlas {
fonts: Vec<FontRef<'static>>,
pub data: Vec<u8>,
map: HashMap<(String, u32, u8), TextRegion>,
x: u32,
y: u32,
row_h: u32,
pub dirty: bool,
}
impl TextAtlas {
pub fn new() -> TextAtlas {
let fonts = vec![
FontRef::try_from_slice(include_bytes!("../../../rune/assets/Inter-Regular.ttf")).unwrap(),
FontRef::try_from_slice(include_bytes!("../../../rune/assets/Inter-Medium.ttf")).unwrap(),
FontRef::try_from_slice(include_bytes!("../../../rune/assets/Inter-SemiBold.ttf")).unwrap(),
];
TextAtlas { fonts, data: vec![0; (ATLAS * ATLAS) as usize], map: HashMap::new(), x: 1, y: 1, row_h: 0, dirty: true }
}
/// Rasterise (once) and return the region. `weight`: 0 regular, 1 medium, 2 semibold.
pub fn get(&mut self, text: &str, size_px: f32, weight: u8) -> TextRegion {
let key = (text.to_string(), (size_px * 16.0) as u32, weight);
if let Some(r) = self.map.get(&key) {
return *r;
}
let font = &self.fonts[weight as usize];
let sf = font.as_scaled(PxScale::from(size_px));
let tracking = if size_px > 40.0 { -0.02 * size_px } else { 0.0 };
let mut pen = 0.0f32;
let mut glyphs = Vec::new();
let mut prev = None;
for ch in text.chars() {
let id = font.glyph_id(ch);
if let Some(p) = prev {
pen += sf.kern(p, id);
}
glyphs.push(id.with_scale_and_position(PxScale::from(size_px), ab_glyph::point(pen, sf.ascent())));
pen += sf.h_advance(id) + tracking;
prev = Some(id);
}
let w = (pen.ceil() as u32 + 4).max(1);
let h = (sf.ascent() - sf.descent()).ceil() as u32 + 4;
if self.x + w + 1 > ATLAS {
self.x = 1;
self.y += self.row_h + 1;
self.row_h = 0;
}
let (ox, oy) = (self.x + 2, self.y + 2);
for g in glyphs {
if let Some(og) = font.outline_glyph(g) {
let b = og.px_bounds();
og.draw(|gx, gy, c| {
let x = ox as i32 + b.min.x as i32 + gx as i32;
let y = oy as i32 + b.min.y as i32 + gy as i32;
if x >= 0 && y >= 0 && (x as u32) < ATLAS && (y as u32) < ATLAS {
let i = (y as u32 * ATLAS + x as u32) as usize;
self.data[i] = self.data[i].max((c * 255.0) as u8);
}
});
}
}
let r = TextRegion {
uv: [
self.x as f32 / ATLAS as f32,
self.y as f32 / ATLAS as f32,
(self.x + w) as f32 / ATLAS as f32,
(self.y + h) as f32 / ATLAS as f32,
],
w: w as f32,
h: h as f32,
ascent: sf.ascent() + 2.0,
};
self.x += w + 1;
self.row_h = self.row_h.max(h);
self.dirty = true;
self.map.insert(key, r);
r
}
}
pub struct UiRenderer {
pipeline: wgpu::RenderPipeline,
bgl: wgpu::BindGroupLayout,
bg: Option<wgpu::BindGroup>,
buf: wgpu::Buffer,
cap: usize,
pub atlas_tex: wgpu::Texture,
atlas_view: wgpu::TextureView,
sampler: wgpu::Sampler,
}
impl UiRenderer {
pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat) -> UiRenderer {
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("ui"),
source: wgpu::ShaderSource::Wgsl(include_str!("ui.wgsl").into()),
});
let fr = wgpu::ShaderStages::FRAGMENT;
let vf = wgpu::ShaderStages::VERTEX_FRAGMENT;
let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("ui"),
entries: &[
wgpu::BindGroupLayoutEntry {
binding: 0,
visibility: vf,
ty: wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: true },
has_dynamic_offset: false,
min_binding_size: None,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 1,
visibility: fr,
ty: wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
},
count: None,
},
wgpu::BindGroupLayoutEntry {
binding: 2,
visibility: fr,
ty: wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering),
count: None,
},
],
});
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("ui"),
bind_group_layouts: &[Some(&bgl)],
immediate_size: 0,
});
let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some("ui"),
layout: Some(&layout),
vertex: wgpu::VertexState { module: &module, 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: &module,
entry_point: Some("fs"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState {
format,
blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING),
write_mask: wgpu::ColorWrites::ALL,
})],
}),
multiview_mask: None,
cache: None,
});
let atlas_tex = device.create_texture(&wgpu::TextureDescriptor {
label: Some("atlas"),
size: wgpu::Extent3d { width: ATLAS, height: ATLAS, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::R8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST,
view_formats: &[],
});
let atlas_view = atlas_tex.create_view(&Default::default());
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
..Default::default()
});
let cap = 1024;
let buf = Self::buffer(device, cap);
UiRenderer { pipeline, bgl, bg: None, buf, cap, atlas_tex, atlas_view, sampler }
}
fn buffer(device: &wgpu::Device, cap: usize) -> wgpu::Buffer {
device.create_buffer(&wgpu::BufferDescriptor {
label: Some("ui insts"),
size: (cap * std::mem::size_of::<UiInst>()) as u64,
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
})
}
pub fn prepare(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, atlas: &mut TextAtlas, insts: &[UiInst]) {
if atlas.dirty {
queue.write_texture(
wgpu::TexelCopyTextureInfo { texture: &self.atlas_tex, mip_level: 0, origin: wgpu::Origin3d::ZERO, aspect: wgpu::TextureAspect::All },
&atlas.data,
wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(ATLAS), rows_per_image: None },
wgpu::Extent3d { width: ATLAS, height: ATLAS, depth_or_array_layers: 1 },
);
atlas.dirty = false;
}
if insts.len() > self.cap || self.bg.is_none() {
self.cap = self.cap.max(insts.len().next_power_of_two());
self.buf = Self::buffer(device, self.cap);
self.bg = Some(device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("ui"),
layout: &self.bgl,
entries: &[
wgpu::BindGroupEntry { binding: 0, resource: self.buf.as_entire_binding() },
wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(&self.atlas_view) },
wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::Sampler(&self.sampler) },
],
}));
}
if !insts.is_empty() {
queue.write_buffer(&self.buf, 0, bytemuck::cast_slice(insts));
}
}
pub fn draw(&self, pass: &mut wgpu::RenderPass<'_>, range: std::ops::Range<usize>) {
if range.is_empty() {
return;
}
pass.set_pipeline(&self.pipeline);
pass.set_bind_group(0, self.bg.as_ref().unwrap(), &[]);
pass.draw(0..4, range.start as u32..range.end as u32);
}
}
+76
View File
@@ -0,0 +1,76 @@
// Minimal UI stand-in for the gallery: rounded rects (gradient fill + hairline border), soft shadows, text.
struct U {
rect: vec4f, // px x, y, w, h
p: vec4f, // radius px, border px, kind (0 rect, 1 text, 2 shadow), sigma px
fill: vec4f, // premultiplied linear (top)
fill2: vec4f, // premultiplied linear (bottom)
border: vec4f, // premultiplied linear
uv: vec4f, // atlas uv rect
vp: vec4f, // viewport px
}
@group(0) @binding(0) var<storage, read> us: array<U>;
@group(0) @binding(1) var atlas: texture_2d<f32>;
@group(0) @binding(2) var smp: sampler;
struct V {
@builtin(position) pos: vec4f,
@location(0) @interpolate(flat) id: u32,
@location(1) px: vec2f,
}
@vertex
fn vs(@builtin(vertex_index) vi: u32, @builtin(instance_index) ii: u32) -> V {
let u = us[ii];
var m = 1.0;
if (u.p.z > 1.5) { m = u.p.w * 3.5 + 1.0; }
let corner = vec2f(f32(vi & 1u), f32((vi >> 1u) & 1u));
let px = u.rect.xy - m + (u.rect.zw + 2.0 * m) * corner;
var o: V;
o.pos = vec4f(px.x / u.vp.x * 2.0 - 1.0, 1.0 - px.y / u.vp.y * 2.0, 0.0, 1.0);
o.id = ii;
o.px = px;
return o;
}
fn sd_rrect(q: vec2f, half: vec2f, r: f32) -> f32 {
let rr = clamp(r, 0.0, min(half.x, half.y));
let k = abs(q) - half + rr;
return length(max(k, vec2f(0.0))) + min(max(k.x, k.y), 0.0) - rr;
}
fn erf_approx(x: f32) -> f32 {
let x2 = x * x;
let a = 0.147;
let v = sqrt(1.0 - exp(-x2 * (1.2732395 + a * x2) / (1.0 + a * x2)));
return select(-v, v, x >= 0.0);
}
@fragment
fn fs(in: V) -> @location(0) vec4f {
let u = us[in.id];
let half = u.rect.zw * 0.5;
let q = in.px - u.rect.xy - half;
let d = sd_rrect(q, half, u.p.x);
let kind = i32(u.p.z + 0.5);
if (kind == 1) {
let uv = mix(u.uv.xy, u.uv.zw, (in.px - u.rect.xy) / u.rect.zw);
let a = textureSampleLevel(atlas, smp, uv, 0.0).r;
return u.fill * pow(a, 0.85);
}
if (kind == 2) {
let a = 0.5 - 0.5 * erf_approx(d / (max(u.p.w, 0.1) * 1.41421));
return u.fill * a;
}
let cov = clamp(0.5 - d, 0.0, 1.0);
let t = clamp((in.px.y - u.rect.y) / max(u.rect.w, 1.0), 0.0, 1.0);
let fill = mix(u.fill, u.fill2, t);
let bw = u.p.y;
var o = fill * cov;
if (bw > 0.0) {
let inner = clamp(0.5 - (d + bw), 0.0, 1.0);
let band = cov - inner;
o = o * (1.0 - u.border.a * band) + u.border * band;
}
return o;
}
@@ -0,0 +1,19 @@
#!/bin/zsh
# Render PNG sequences for a few effects and encode them to MP4 into demo/fx (run on a build worker).
set -euo pipefail
export PATH=/opt/homebrew/bin:$PATH
cd "${0:A:h}/../.."
out=../../demo/fx
tmp=$(mktemp -d)
cargo build --release --example gallery
bin=${CARGO_TARGET_DIR:-../../target}/release/examples/gallery
for spec in "electric 0.0 2" "fire 0.0 2" "glow 0.0 2" "pulse 0.0 2" "motion 0.0 1" "distort 0.0 1.5" "extras 0.0 2"; do
set -- ${=spec}
$bin --frames $tmp/$1 --fps 60 --seconds $3 --start $2 --effect $1
ffmpeg -loglevel error -y -framerate 60 -i $tmp/$1/$1_%04d.png -c:v libx264 -pix_fmt yuv420p -crf 16 $out/$1.mp4
done
# Motion blur at quarter speed so the shutter is readable.
$bin --frames $tmp/motion-slow --fps 240 --seconds 0.7 --effect motion
ffmpeg -loglevel error -y -framerate 60 -i $tmp/motion-slow/motion_%04d.png -c:v libx264 -pix_fmt yuv420p -crf 16 $out/motion-quarter-speed.mp4
rm -rf $tmp
ls -la $out
+37
View File
@@ -0,0 +1,37 @@
//! Bind groups kept across frames, keyed on the resources they bind.
/// This frame's bind groups, indexed by `Prepared::bind`, plus last frame's for reuse.
/// A frame keeps at most its own groups and the previous frame's, so the set stays bounded.
pub(crate) struct BindSet<K> {
now: Vec<(K, wgpu::BindGroup)>,
last: Vec<(K, wgpu::BindGroup)>,
}
impl<K> BindSet<K> {
pub(crate) const fn new() -> Self {
BindSet { now: Vec::new(), last: Vec::new() }
}
/// Start a frame: last frame's groups become reusable, the older ones are dropped.
pub(crate) fn begin(&mut self) {
self.last.clear();
std::mem::swap(&mut self.now, &mut self.last);
}
/// The index of a group whose key passes `is`, reusing this or last frame's before calling `make`.
pub(crate) fn find(&mut self, is: impl Fn(&K) -> bool, make: impl FnOnce() -> (K, wgpu::BindGroup)) -> usize {
if let Some(i) = self.now.iter().position(|(k, _)| is(k)) {
return i;
}
let entry = match self.last.iter().position(|(k, _)| is(k)) {
Some(i) => self.last.swap_remove(i),
None => make(),
};
self.now.push(entry);
self.now.len() - 1
}
pub(crate) fn get(&self, i: usize) -> &wgpu::BindGroup {
&self.now[i].1
}
}
+501
View File
@@ -0,0 +1,501 @@
//! The fill catalog: each fill style's id, display name, params (with ranges and units) and named
//! presets, plus generic get/set by param id and Rust emission. A tool can build its style list,
//! inspector and code output from this instead of keeping its own schema.
//!
//! Param ids are the Rust field names, so `FillParams::to_rust` can write struct literals.
use crate::*;
/// How a number reads in an inspector.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Unit {
None,
/// Points.
Pt,
/// Radians (show as degrees).
Radians,
/// 0..1 of something (show as a percentage).
Fraction,
/// Per second (speeds, rates).
PerSecond,
}
/// One option of a choice param.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Choice {
pub id: &'static str,
pub name: &'static str,
/// The Rust path of the variant, for emitted code.
pub rust: &'static str,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ParamKind {
/// A float; `step` is a sensible slider step.
Number { min: f32, max: f32, step: f32, unit: Unit },
/// A whole number.
Count { min: u32, max: u32 },
Toggle,
Choice(&'static [Choice]),
Color,
/// An ordered colour list (`Stops`).
Colors { min: usize, max: usize },
/// A point in the shape's rect, 0..1 on each axis.
Point,
/// Up to `max` points in the shape's rect (one per colour of a `Colors` param).
Points { max: usize },
}
/// A tunable param. Its default is whatever the style's `Default` (or a preset) holds: read it
/// with `FillParams::get`.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct Param {
/// The Rust field name.
pub id: &'static str,
pub name: &'static str,
pub kind: ParamKind,
}
/// A param's value.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Value {
Number(f32),
Count(u32),
Toggle(bool),
/// Index into the param's `Choice` list.
Choice(usize),
Color(Rgb),
Colors(Stops),
Point([f32; 2]),
Points([[f32; 2]; MAX_STOPS]),
}
/// A named starting point for a style.
#[derive(Clone, Copy)]
pub struct Preset {
pub id: &'static str,
pub name: &'static str,
/// The Rust expression that builds it, for emitted code.
pub rust: &'static str,
pub(crate) make: fn() -> FillStyle,
}
impl Preset {
pub fn style(&self) -> FillStyle {
(self.make)()
}
pub fn fill(&self) -> FillParams {
FillParams::new(self.style())
}
}
impl std::fmt::Debug for Preset {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Preset").field("id", &self.id).finish()
}
}
/// A fill style as a catalog entry.
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct StyleInfo {
/// Stable id, snake_case (`"liquid_metal"`).
pub id: &'static str,
pub name: &'static str,
pub summary: &'static str,
/// The params type, for emitted code.
pub rust: &'static str,
/// The style's own params, in inspector order. `FillParams::COMMON` applies to every style.
pub params: &'static [Param],
/// Named presets; the first is the style's `Default`.
pub presets: &'static [Preset],
/// Whether the style may read the backdrop (always for glass; for some inputs otherwise).
/// `Fx::needs_backdrop` gives the answer for a given set of params.
pub reads_backdrop: bool,
}
impl StyleInfo {
pub fn preset(&self, id: &str) -> Option<&'static Preset> {
self.presets.iter().find(|p| p.id == id)
}
/// The style with its default params.
pub fn default_fill(&self) -> FillParams {
self.presets[0].fill()
}
}
/// Every fill style, in catalog order.
pub fn fill_styles() -> &'static [StyleInfo] {
FILL_STYLES
}
pub fn fill_style(id: &str) -> Option<&'static StyleInfo> {
FILL_STYLES.iter().find(|s| s.id == id)
}
// ---------------------------------------------------------------- values
pub(crate) trait ParamValue: Sized {
fn to_value(&self) -> Value;
fn from_value(v: Value) -> Option<Self>;
fn rust(&self) -> String;
}
fn float(v: f32) -> String {
let v = if v.is_finite() { v } else { 0.0 };
format!("{v:?}")
}
impl ParamValue for f32 {
fn to_value(&self) -> Value {
Value::Number(*self)
}
fn from_value(v: Value) -> Option<Self> {
match v {
Value::Number(x) if x.is_finite() => Some(x),
Value::Count(n) => Some(n as f32),
_ => None,
}
}
fn rust(&self) -> String {
float(*self)
}
}
impl ParamValue for u32 {
fn to_value(&self) -> Value {
Value::Count(*self)
}
fn from_value(v: Value) -> Option<Self> {
match v {
Value::Count(n) => Some(n),
Value::Number(x) if x.is_finite() => Some(x.round().max(0.0) as u32),
_ => None,
}
}
fn rust(&self) -> String {
self.to_string()
}
}
impl ParamValue for bool {
fn to_value(&self) -> Value {
Value::Toggle(*self)
}
fn from_value(v: Value) -> Option<Self> {
match v {
Value::Toggle(b) => Some(b),
_ => None,
}
}
fn rust(&self) -> String {
self.to_string()
}
}
impl Rgb {
/// To sRGB hex (0xRRGGBB), rounding.
pub fn hex(self) -> u32 {
let e = |c: f32| (rune_motion::srgb_encode(c.clamp(0.0, 1.0)) * 255.0).round() as u32;
(e(self.0[0]) << 16) | (e(self.0[1]) << 8) | e(self.0[2])
}
}
impl ParamValue for Rgb {
fn to_value(&self) -> Value {
Value::Color(*self)
}
fn from_value(v: Value) -> Option<Self> {
match v {
Value::Color(c) => Some(c),
_ => None,
}
}
fn rust(&self) -> String {
format!("rgb(0x{:06x})", self.hex())
}
}
impl ParamValue for Stops {
fn to_value(&self) -> Value {
Value::Colors(*self)
}
fn from_value(v: Value) -> Option<Self> {
match v {
Value::Colors(s) => Some(s),
_ => None,
}
}
fn rust(&self) -> String {
let hex: Vec<String> = self.as_slice().iter().map(|c| format!("0x{:06x}", c.hex())).collect();
format!("Stops::hex(&[{}])", hex.join(", "))
}
}
impl ParamValue for [f32; 2] {
fn to_value(&self) -> Value {
Value::Point(*self)
}
fn from_value(v: Value) -> Option<Self> {
match v {
Value::Point(p) if p[0].is_finite() && p[1].is_finite() => Some(p),
_ => None,
}
}
fn rust(&self) -> String {
format!("[{}, {}]", float(self[0]), float(self[1]))
}
}
impl ParamValue for [[f32; 2]; MAX_STOPS] {
fn to_value(&self) -> Value {
Value::Points(*self)
}
fn from_value(v: Value) -> Option<Self> {
match v {
Value::Points(p) if p.iter().flatten().all(|x| x.is_finite()) => Some(p),
_ => None,
}
}
fn rust(&self) -> String {
let v: Vec<String> = self.iter().map(|p| p.rust()).collect();
format!("[{}]", v.join(", "))
}
}
/// Choice params: an enum with a fixed list of options.
macro_rules! choices {
($ty:ident { $($v:ident = $id:literal $name:literal),* $(,)? }) => {
impl $ty {
pub const CHOICES: &'static [Choice] = &[$(Choice { id: $id, name: $name, rust: concat!(stringify!($ty), "::", stringify!($v)) }),*];
const ALL: &'static [$ty] = &[$($ty::$v),*];
}
impl ParamValue for $ty {
fn to_value(&self) -> Value {
Value::Choice($ty::ALL.iter().position(|x| x == self).unwrap_or(0))
}
fn from_value(v: Value) -> Option<Self> {
match v {
Value::Choice(i) => $ty::ALL.get(i).copied(),
_ => None,
}
}
fn rust(&self) -> String {
$ty::CHOICES[$ty::ALL.iter().position(|x| x == self).unwrap_or(0)].rust.to_string()
}
}
};
}
pub(crate) use choices;
/// A params struct's table: `PARAMS` plus get/set/emit by field name.
macro_rules! params {
($ty:ident { $($field:ident : $name:literal => $kind:expr),* $(,)? }) => {
impl $ty {
pub const PARAMS: &'static [Param] = &[$(Param { id: stringify!($field), name: $name, kind: $kind }),*];
pub(crate) fn get_param(&self, id: &str) -> Option<Value> {
match id {
$(stringify!($field) => Some(ParamValue::to_value(&self.$field)),)*
_ => None,
}
}
pub(crate) fn set_param(&mut self, id: &str, v: Value) -> bool {
match id {
$(stringify!($field) => match ParamValue::from_value(v) {
Some(x) => { self.$field = x; true }
None => false,
},)*
_ => false,
}
}
pub(crate) fn rust_field(&self, id: &str) -> Option<String> {
match id {
$(stringify!($field) => Some(ParamValue::rust(&self.$field)),)*
_ => None,
}
}
}
};
}
pub(crate) use params;
pub(crate) const fn num(min: f32, max: f32, step: f32, unit: Unit) -> ParamKind {
ParamKind::Number { min, max, step, unit }
}
// ---------------------------------------------------------------- FillParams by id
impl FillParams {
/// Params every fill style has.
pub const COMMON: &'static [Param] = &[
Param { id: "border", name: "Border", kind: num(0.0, 32.0, 0.5, Unit::Pt) },
Param { id: "intensity", name: "Intensity", kind: num(0.0, 1.0, 0.01, Unit::Fraction) },
];
/// This style's catalog entry.
pub fn info(&self) -> &'static StyleInfo {
&FILL_STYLES[self.style.index()]
}
/// A param's value, common or the style's own, by id.
pub fn get(&self, id: &str) -> Option<Value> {
match id {
"border" => Some(Value::Number(self.border)),
"intensity" => Some(Value::Number(self.intensity)),
_ => self.style.get_param(id),
}
}
/// Set a param by id. False when the id is unknown or the value has the wrong kind.
pub fn set(&mut self, id: &str, v: Value) -> bool {
match (id, f32::from_value(v)) {
("border", Some(x)) => self.border = x,
("intensity", Some(x)) => self.intensity = x,
("border" | "intensity", None) => return false,
_ => return self.style.set_param(id, v),
}
true
}
/// Rust that rebuilds these params: `Fx::fill(...)`, written against the closest preset.
pub fn to_rust(&self) -> String {
let info = self.info();
let mut best: Option<(usize, &Preset, Vec<String>)> = None;
for p in info.presets {
let base = p.style();
let diff: Vec<String> = info
.params
.iter()
.filter(|q| base.get_param(q.id) != self.style.get_param(q.id))
.filter_map(|q| self.style.rust_field(q.id).map(|v| format!("{}: {v}", q.id)))
.collect();
if best.as_ref().is_none_or(|b| diff.len() < b.0) {
best = Some((diff.len(), p, diff));
}
}
let (_, preset, diff) = best.expect("every style has a preset");
let mut s = if diff.is_empty() { preset.rust.to_string() } else { format!("{} {{ {}, ..{} }}", info.rust, diff.join(", "), preset.rust) };
if self.border != 0.0 {
s += &format!(".border({})", float(self.border));
}
if self.intensity != 1.0 {
s += &format!(".intensity({})", float(self.intensity));
}
format!("Fx::fill({s})")
}
}
// ---------------------------------------------------------------- the table
macro_rules! presets {
($style:ident($ty:ident) { $($id:literal $name:literal => $f:ident),* $(,)? }) => {
&[$(Preset { id: $id, name: $name, rust: concat!(stringify!($ty), "::", stringify!($f), "()"), make: || FillStyle::$style($ty::$f()) }),*]
};
}
static FILL_STYLES: &[StyleInfo] = &[
StyleInfo {
id: "liquid_metal",
name: "Liquid metal",
summary: "Polished metal reflecting a studio, flowing like liquid. Works as a fill or a tube-like border.",
rust: "LiquidMetalParams",
params: LiquidMetalParams::PARAMS,
presets: presets!(LiquidMetal(LiquidMetalParams) { "chrome" "Chrome" => chrome, "gold" "Gold" => gold, "rose" "Rose gold" => rose, "gunmetal" "Gunmetal" => gunmetal }),
reads_backdrop: false,
},
StyleInfo {
id: "mesh_gradient",
name: "Mesh gradient",
summary: "Up to six colours pinned to slowly drifting points, blended in OKLab.",
rust: "MeshGradientParams",
params: MeshGradientParams::PARAMS,
presets: presets!(MeshGradient(MeshGradientParams) { "dusk" "Dusk" => dusk, "lagoon" "Lagoon" => lagoon, "orchid" "Orchid" => orchid, "graphite" "Graphite" => graphite }),
reads_backdrop: false,
},
StyleInfo {
id: "dither",
name: "Dither",
summary: "Bayer or blue-noise dithering of a ramp, noise, the backdrop or an image into a palette.",
rust: "DitherParams",
params: DitherParams::PARAMS,
presets: presets!(Dither(DitherParams) { "bayer" "Bayer" => bayer, "handheld" "Handheld" => handheld, "grain" "Blue noise" => grain, "backdrop" "Backdrop" => backdrop }),
reads_backdrop: true,
},
StyleInfo {
id: "grain_gradient",
name: "Grain gradient",
summary: "A linear, radial or conic gradient scattered into film grain.",
rust: "GrainGradientParams",
params: GrainGradientParams::PARAMS,
presets: presets!(GrainGradient(GrainGradientParams) { "ember" "Ember" => ember, "halo" "Halo" => halo, "sweep" "Sweep" => sweep }),
reads_backdrop: false,
},
StyleInfo {
id: "fluted_glass",
name: "Fluted glass",
summary: "Reeded glass over the backdrop: each rib shows a squeezed, flipped strip of what is behind.",
rust: "FlutedGlassParams",
params: FlutedGlassParams::PARAMS,
presets: presets!(FlutedGlass(FlutedGlassParams) { "reeded" "Reeded" => reeded, "fine" "Fine" => fine, "frosted" "Frosted" => frosted, "wide" "Wide" => wide }),
reads_backdrop: true,
},
StyleInfo {
id: "metaballs",
name: "Metaballs",
summary: "Glossy blobs that drift and merge.",
rust: "MetaballParams",
params: MetaballParams::PARAMS,
presets: presets!(Metaballs(MetaballParams) { "lava" "Lava" => lava, "mint" "Mint" => mint }),
reads_backdrop: false,
},
StyleInfo {
id: "swirl",
name: "Swirl",
summary: "Colours stirred into a slow swirl.",
rust: "SwirlParams",
params: SwirlParams::PARAMS,
presets: presets!(Swirl(SwirlParams) { "ink" "Ink" => ink, "marble" "Marble" => marble }),
reads_backdrop: false,
},
StyleInfo {
id: "voronoi",
name: "Voronoi",
summary: "Cells around drifting seed points, with seams.",
rust: "VoronoiParams",
params: VoronoiParams::PARAMS,
presets: presets!(Voronoi(VoronoiParams) { "cells" "Cells" => cells, "stained" "Stained glass" => stained }),
reads_backdrop: false,
},
StyleInfo {
id: "waves",
name: "Waves",
summary: "Layered bands of colour with rolling edges.",
rust: "WaveParams",
params: WaveParams::PARAMS,
presets: presets!(Waves(WaveParams) { "sea" "Sea" => sea, "dunes" "Dunes" => dunes }),
reads_backdrop: false,
},
StyleInfo {
id: "halftone",
name: "Halftone",
summary: "Print dots on a rotated screen, sized by a ramp, noise, the backdrop or an image.",
rust: "HalftoneParams",
params: HalftoneParams::PARAMS,
presets: presets!(Halftone(HalftoneParams) { "print" "Print" => print, "backdrop" "Backdrop" => backdrop }),
reads_backdrop: true,
},
StyleInfo {
id: "plastic",
name: "Plastic",
summary: "Moulded plastic under a soft light: glossy to matte, domed or dished, with a rolled rim.",
rust: "PlasticParams",
params: PlasticParams::PARAMS,
presets: presets!(Plastic(PlasticParams) { "glossy" "Glossy" => glossy, "matte" "Matte" => matte, "dished" "Dished" => dished }),
reads_backdrop: false,
},
];
#[cfg(test)]
#[path = "catalog_tests.rs"]
mod tests;
+250
View File
@@ -0,0 +1,250 @@
use super::*;
#[test]
fn styles_are_in_variant_order_with_unique_ids() {
for (k, s) in fill_styles().iter().enumerate() {
assert_eq!(s.default_fill().style.index(), k, "{}", s.id);
assert_eq!(s.default_fill().info().id, s.id);
assert_eq!(fill_style(s.id).map(|x| x.id), Some(s.id));
assert!(!s.presets.is_empty() && !s.params.is_empty());
let mut ids: Vec<_> = s.params.iter().map(|p| p.id).chain(FillParams::COMMON.iter().map(|p| p.id)).collect();
ids.sort();
ids.dedup();
assert_eq!(ids.len(), s.params.len() + FillParams::COMMON.len(), "{}: unique param ids", s.id);
let mut ps: Vec<_> = s.presets.iter().map(|p| p.id).collect();
ps.sort();
ps.dedup();
assert_eq!(ps.len(), s.presets.len());
}
let mut ids: Vec<_> = fill_styles().iter().map(|s| s.id).collect();
ids.dedup();
assert_eq!(ids.len(), fill_styles().len());
assert!(fill_style("nope").is_none());
}
#[test]
fn first_preset_is_the_default() {
let d = [
FillStyle::from(LiquidMetalParams::default()),
MeshGradientParams::default().into(),
DitherParams::default().into(),
GrainGradientParams::default().into(),
FlutedGlassParams::default().into(),
MetaballParams::default().into(),
SwirlParams::default().into(),
VoronoiParams::default().into(),
WaveParams::default().into(),
HalftoneParams::default().into(),
PlasticParams::default().into(),
];
assert_eq!(d.len(), fill_styles().len());
for (s, d) in fill_styles().iter().zip(d) {
assert_eq!(s.presets[0].style(), d, "{}", s.id);
}
}
#[test]
fn every_param_gets_sets_and_sits_in_range() {
for s in fill_styles() {
for pr in s.presets {
let f = pr.fill();
for p in s.params.iter().chain(FillParams::COMMON) {
let v = f.get(p.id).unwrap_or_else(|| panic!("{}.{} reads", s.id, p.id));
match (p.kind, v) {
(ParamKind::Number { min, max, .. }, Value::Number(x)) => assert!((min..=max).contains(&x), "{}/{}.{} = {x} outside {min}..{max}", s.id, pr.id, p.id),
(ParamKind::Count { min, max }, Value::Count(n)) => assert!((min..=max).contains(&n), "{}.{}", s.id, p.id),
(ParamKind::Choice(c), Value::Choice(k)) => assert!(k < c.len()),
(ParamKind::Colors { min, max }, Value::Colors(c)) => assert!((min..=max).contains(&c.len()), "{}/{}.{}", s.id, pr.id, p.id),
(ParamKind::Toggle, Value::Toggle(_)) | (ParamKind::Color, Value::Color(_)) | (ParamKind::Point, Value::Point(_)) | (ParamKind::Points { .. }, Value::Points(_)) => {}
(k, v) => panic!("{}.{}: {k:?} holds {v:?}", s.id, p.id),
}
let mut g = f;
assert!(g.set(p.id, v), "{}.{} writes", s.id, p.id);
assert_eq!(g, f);
assert!(!g.set(p.id, Value::Point([9.0, 9.0])) || matches!(p.kind, ParamKind::Point), "{}.{} rejects the wrong kind", s.id, p.id);
assert!(!g.set(p.id, Value::Number(f32::NAN)), "{}.{} rejects NaN", s.id, p.id);
assert!(!g.set(p.id, Value::Number(f32::INFINITY)), "{}.{} rejects inf", s.id, p.id);
// Round-trip a distinct value for every param kind.
let alt = match (p.kind, v) {
(ParamKind::Number { min, max, .. }, Value::Number(x)) => Value::Number(if (x - max).abs() > 1e-4 { max } else { min }),
(ParamKind::Count { min, max }, Value::Count(n)) => Value::Count(if n != max { max } else { min }),
(ParamKind::Choice(c), Value::Choice(k)) => Value::Choice((k + 1) % c.len()),
(ParamKind::Toggle, Value::Toggle(b)) => Value::Toggle(!b),
(ParamKind::Color, _) => Value::Color(rgb(0x123456)),
(ParamKind::Colors { max, .. }, _) => Value::Colors(Stops::hex(&[0x112233, 0x445566, 0x778899, 0xaabbcc, 0xddeeff, 0x102030][..max])),
(ParamKind::Point, _) => Value::Point([0.25, 0.75]),
(ParamKind::Points { .. }, _) => Value::Points([[0.1, 0.2]; MAX_STOPS]),
_ => unreachable!(),
};
assert_ne!(alt, v, "{}.{} has a distinct test value", s.id, p.id);
assert!(g.set(p.id, alt), "{}.{} writes distinct value", s.id, p.id);
assert_eq!(g.get(p.id), Some(alt), "{}.{} round-trips distinct value", s.id, p.id);
assert_ne!(g, f, "{}.{} mutates FillParams", s.id, p.id);
}
assert!(f.get("nope").is_none());
}
}
}
#[test]
fn changing_a_param_changes_the_fill() {
let mut f = Fx::fill(LiquidMetalParams::gold());
let Fx::Fill(p) = &mut f else { unreachable!() };
assert!(p.set("flow", Value::Number(0.9)));
assert!(p.set("tint", Value::Color(rgb(0x808080))));
assert!(p.set("border", Value::Number(3.0)));
let FillStyle::LiquidMetal(m) = p.style else { unreachable!() };
assert_eq!(m.flow, 0.9);
assert_eq!(p.border, 3.0);
assert!(!p.set("pattern", Value::Choice(0)), "not a liquid metal param");
let mut d = FillParams::from(DitherParams::bayer());
assert!(d.set("pattern", Value::Choice(3)));
let FillStyle::Dither(dp) = d.style else { unreachable!() };
assert_eq!(dp.pattern, DitherPattern::BlueNoise);
}
/// Parse and evaluate the Rust subset emitted by `FillParams::to_rust()`.
fn eval_emitted_rust(code: &str) -> FillParams {
let mut s = code.strip_prefix("Fx::fill(").and_then(|s| s.strip_suffix(')')).expect(code);
let mut intensity = 1.0f32;
if let Some((base, arg)) = s.rsplit_once(".intensity(") {
intensity = arg.strip_suffix(')').expect(code).parse().expect(code);
s = base;
}
let mut border = 0.0f32;
if let Some((base, arg)) = s.rsplit_once(".border(") {
border = arg.strip_suffix(')').expect(code).parse().expect(code);
s = base;
}
let mut fill = if let Some((ty, body)) = s.split_once(" { ") {
let body = body.strip_suffix(" }").expect(code);
let (fields_str, preset_rust) = body.rsplit_once(", ..").expect(code);
let info = fill_styles().iter().find(|i| i.rust == ty.trim()).expect(ty);
let preset = info.presets.iter().find(|p| p.rust == preset_rust.trim()).expect(preset_rust);
let mut f = preset.fill();
// Split top-level `field: expr` pairs outside `[...]` and `(...)`.
let mut depth = 0i32;
let mut start = 0usize;
for (idx, ch) in fields_str.char_indices() {
match ch {
'[' | '(' => depth += 1,
']' | ')' => depth -= 1,
',' if depth == 0 => {
apply_field(&mut f, info, &fields_str[start..idx]);
start = idx + 1;
}
_ => {}
}
}
apply_field(&mut f, info, &fields_str[start..]);
f
} else {
fill_styles().iter().flat_map(|i| i.presets).find(|p| p.rust == s.trim()).expect(s).fill()
};
fill.border = border;
fill.intensity = intensity;
fill
}
fn parse_hex(s: &str) -> u32 {
let hex = s.trim().strip_prefix("0x").expect(s);
assert_eq!(hex.len(), 6, "6-digit hex literal: {s}");
u32::from_str_radix(hex, 16).expect(s)
}
fn parse_pt(s: &str) -> [f32; 2] {
let inner = s.trim().strip_prefix('[').and_then(|s| s.strip_suffix(']')).expect(s);
let (x, y) = inner.split_once(',').expect(s);
[x.trim().parse().expect(s), y.trim().parse().expect(s)]
}
fn apply_field(f: &mut FillParams, info: &StyleInfo, entry: &str) {
let (id, val) = entry.trim().split_once(": ").expect(entry);
let param = info.params.iter().find(|p| p.id == id).expect(id);
let v = match param.kind {
ParamKind::Number { .. } => {
assert!(val.contains('.') || val.contains('e'), "float literal has decimal or exp: {val}");
Value::Number(val.parse().expect(val))
}
ParamKind::Count { .. } => Value::Count(val.parse().expect(val)),
ParamKind::Toggle => Value::Toggle(val.parse().expect(val)),
ParamKind::Choice(choices) => {
let idx = choices.iter().position(|c| c.rust == val).expect(val);
Value::Choice(idx)
}
ParamKind::Color => {
let hex = val.strip_prefix("rgb(").and_then(|s| s.strip_suffix(')')).expect(val);
Value::Color(rgb(parse_hex(hex)))
}
ParamKind::Colors { .. } => {
let list = val.strip_prefix("Stops::hex(&[").and_then(|s| s.strip_suffix("])")).expect(val);
let hexes: Vec<u32> = list.split(',').map(parse_hex).collect();
Value::Colors(Stops::hex(&hexes))
}
ParamKind::Point => Value::Point(parse_pt(val)),
ParamKind::Points { .. } => {
let inner = val.strip_prefix('[').and_then(|s| s.strip_suffix(']')).expect(val);
let mut pts = [[0.0; 2]; MAX_STOPS];
let mut k = 0;
let mut start = 0;
let mut depth = 0;
for (i, ch) in inner.char_indices() {
match ch {
'[' => depth += 1,
']' => depth -= 1,
',' if depth == 0 => {
pts[k] = parse_pt(&inner[start..i]);
k += 1;
start = i + 1;
}
_ => {}
}
}
pts[k] = parse_pt(&inner[start..]);
assert_eq!(k + 1, MAX_STOPS);
Value::Points(pts)
}
};
assert!(f.set(id, v), "{}.{id}", info.id);
}
#[test]
fn rust_is_written_against_the_closest_preset_and_parses_back() {
assert_eq!(FillParams::from(LiquidMetalParams::gold()).to_rust(), "Fx::fill(LiquidMetalParams::gold())");
let f = FillParams::from(LiquidMetalParams { flow: 0.8, ..LiquidMetalParams::rose() }).border(4.0);
assert_eq!(f.to_rust(), "Fx::fill(LiquidMetalParams { flow: 0.8, ..LiquidMetalParams::rose() }.border(4.0))");
let d = FillParams::from(DitherParams { pattern: DitherPattern::Bayer8, colors: Stops::hex(&[0x000000, 0xffffff]), ..DitherParams::bayer() });
assert_eq!(d.to_rust(), "Fx::fill(DitherParams { pattern: DitherPattern::Bayer8, colors: Stops::hex(&[0x000000, 0xffffff]), ..DitherParams::bayer() })");
for s in fill_styles() {
for p in s.presets {
let base = p.fill();
assert_eq!(base.to_rust(), format!("Fx::fill({})", p.rust));
assert_eq!(eval_emitted_rust(&base.to_rust()), base);
let mut all_changed = base.border(3.5).intensity(0.75);
for param in s.params {
let alt = match param.kind {
ParamKind::Number { min, max, .. } => Value::Number((min + max) * 0.5 + 0.125),
ParamKind::Count { max, .. } => Value::Count(max),
ParamKind::Toggle => Value::Toggle(!matches!(base.get(param.id), Some(Value::Toggle(true)))),
ParamKind::Choice(c) => Value::Choice(c.len() - 1),
ParamKind::Color => Value::Color(rgb(0xabcdef)),
ParamKind::Colors { min, .. } => Value::Colors(Stops::hex(&[0x102030, 0x405060, 0x708090, 0xa0b0c0, 0xd0e0f0, 0x112233][..min])),
ParamKind::Point => Value::Point([0.3, 0.7]),
ParamKind::Points { .. } => Value::Points([[0.25, 0.75]; MAX_STOPS]),
};
let mut one = base;
assert!(one.set(param.id, alt));
assert_eq!(eval_emitted_rust(&one.to_rust()), one, "{}/{}.{}", s.id, p.id, param.id);
assert!(all_changed.set(param.id, alt));
}
assert_eq!(eval_emitted_rust(&all_changed.to_rust()), all_changed, "{}/{} all fields", s.id, p.id);
}
}
}
#[test]
fn colours_round_trip_through_hex() {
for h in [0x000000, 0xffffff, 0xf3c56b, 0x0b3d5c, 0x808080] {
assert_eq!(rgb(h).hex(), h);
}
}
+755
View File
@@ -0,0 +1,755 @@
//! Per-frame CPU tables: anything that is a 1D function of (time, seed) or a particle list is
//! evaluated here once per frame instead of once per pixel (bolt paths, forks, embers, sparkles,
//! aurora curtains). Same integer hashes as common.wgsl, so CPU and GPU noise agree.
use crate::*;
use std::f32::consts::{PI, SQRT_2, TAU};
#[inline]
fn pcg(v: u32) -> u32 {
let s = v.wrapping_mul(747796405).wrapping_add(2891336453);
let w = ((s >> ((s >> 28) + 4)) ^ s).wrapping_mul(277803737);
(w >> 22) ^ w
}
#[inline]
pub(crate) fn hu(a: u32, b: u32) -> u32 {
pcg(a ^ pcg(b.wrapping_add(0x9E3779B9)))
}
#[inline]
fn u01(n: u32) -> f32 {
(pcg(n) >> 8) as f32 * (1.0 / 16777216.0)
}
#[inline]
fn hcell(cx: i32, cy: i32, seed: u32) -> f32 {
(pcg((cx as u32) ^ pcg((cy as u32) ^ pcg(seed))) >> 8) as f32 * (1.0 / 16777216.0)
}
#[inline]
fn grad(cx: i32, cy: i32, seed: u32) -> (f32, f32) {
let a = hcell(cx, cy, seed) * TAU;
(a.cos(), a.sin())
}
#[inline]
fn fade(f: f32) -> f32 {
f * f * f * (f * (f * 6.0 - 15.0) + 10.0)
}
/// Gradient noise, ~[-1, 1]; `per` > 0 makes it periodic in x.
pub(crate) fn gnoise(x: f32, y: f32, per: i32, seed: u32) -> f32 {
let (ix, iy) = (x.floor() as i32, y.floor() as i32);
let (fx, fy) = (x - x.floor(), y - y.floor());
let (x0, x1) = if per > 0 {
let a = ix.rem_euclid(per);
(a, (a + 1) % per)
} else {
(ix, ix + 1)
};
let dot = |cx: i32, cy: i32, dx: f32, dy: f32| {
let g = grad(cx, cy, seed);
g.0 * dx + g.1 * dy
};
let a = dot(x0, iy, fx, fy);
let b = dot(x1, iy, fx - 1.0, fy);
let c = dot(x0, iy + 1, fx, fy - 1.0);
let d = dot(x1, iy + 1, fx - 1.0, fy - 1.0);
let (ux, uy) = (fade(fx), fade(fy));
let ab = a + (b - a) * ux;
let cd = c + (d - c) * ux;
(ab + (cd - ab) * uy) * SQRT_2
}
/// Multi-octave lateral displacement for bolts, ~[-1.6, 1.6].
fn disp(x0: f32, t0: f32, per0: i32, seed: u32, oct: u32) -> f32 {
let (mut x, mut t, mut a, mut s, mut n, mut per) = (x0, t0, 1.0f32, 0.0f32, 0.0f32, per0);
for o in 0..oct {
s += a * gnoise(x, t, per, seed.wrapping_add(o * 101));
n += a;
if per > 0 {
x *= 2.0;
per *= 2;
} else {
x *= 2.07;
}
t *= 1.55;
a *= 0.5;
}
s / n * 1.6
}
fn push_samples(data: &mut Vec<[f32; 4]>, v: &[f32]) {
for c in v.chunks(4) {
let mut q = [0.0; 4];
q[..c.len()].copy_from_slice(c);
data.push(q);
}
}
/// Approximate Gaussian blur (three box passes) of a sampled path, radius in samples.
/// `wrap`: periodic (border loops) or clamped (arcs).
fn blur3(v: &[f32], radius: f32, wrap: bool) -> Vec<f32> {
let n = v.len() as i64;
let r = ((radius * 0.58).round() as i64).clamp(0, n / 2 - 1);
if r == 0 {
return v.to_vec();
}
let mut a = v.to_vec();
let mut b = vec![0.0f32; v.len()];
let at = |a: &[f32], i: i64| -> f32 {
if wrap { a[i.rem_euclid(n) as usize] } else { a[i.clamp(0, n - 1) as usize] }
};
for _ in 0..3 {
let mut acc: f32 = (-r..=r).map(|k| at(&a, k)).sum();
let inv = 1.0 / (2 * r + 1) as f32;
for i in 0..n {
b[i as usize] = acc * inv;
acc += at(&a, i + r + 1) - at(&a, i - r);
}
std::mem::swap(&mut a, &mut b);
}
a
}
fn rrect_total(rect: Rect, r: f32) -> f32 {
let r = r.clamp(0.0, rect.w.min(rect.h) * 0.5);
let b = (rect.w * 0.5 - r, rect.h * 0.5 - r);
4.0 * (b.1 + r * PI * 0.5 + b.0)
}
const FORK_SAMPLES: usize = 16;
fn ss(a: f32, b: f32, x: f32) -> f32 {
let t = ((x - a) / (b - a)).clamp(0.0, 1.0);
t * t * (3.0 - 2.0 * t)
}
/// Roughly unit-variance gaussian from three uniforms.
fn gauss3(h: u32) -> f32 {
(u01(h) + u01(h.wrapping_add(1)) + u01(h.wrapping_add(2)) - 1.5) * 2.0
}
/// Strike timing. Strike `k` starts at `(k + jitter) * period`, so strikes hold for 0.65 to 1.35
/// periods. `period` = infinity (speed 0) is a single strike that never re-strikes.
struct Strikes {
period: f32,
seed: u32,
}
impl Strikes {
fn new(speed: f32, seed: u32) -> Strikes {
let period = if speed > 0.0 { (0.55 / speed).clamp(0.05, 4.0) } else { f32::INFINITY };
Strikes { period, seed: hu(seed, 0x5157) }
}
fn start(&self, k: i32) -> f32 {
if self.period.is_infinite() {
return if k <= 0 { 0.0 } else { f32::INFINITY };
}
(k as f32 + 0.35 * u01(hu(self.seed, k as u32))) * self.period
}
/// (current strike, its age, its duration)
fn at(&self, t: f32) -> (i32, f32, f32) {
if self.period.is_infinite() {
return (0, t.max(0.0), f32::INFINITY);
}
let mut k = (t / self.period).floor() as i32;
if t < self.start(k) {
k -= 1;
}
let s = self.start(k);
(k, t - s, self.start(k + 1) - s)
}
/// Re-strikes reuse the channel's coarse shape for a few strikes, then it wanders off.
fn channel(&self, k: i32) -> u32 {
let c = (k as f32 / 3.0 + 0.5 * u01(hu(self.seed, 77))).floor() as i32;
hu(self.seed ^ 0xC4A2, c as u32)
}
fn strike_seed(&self, k: i32) -> u32 {
hu(self.seed ^ 0x3D1F, k as u32)
}
}
/// Brightness of the live strike: a flash as the channel ionises, sometimes a return stroke down
/// the same channel, then a settle while it holds.
fn strike_env(age: f32, dur: f32, flicker: f32, h: u32) -> f32 {
let flash = 1.0 + 0.65 * (-age / 0.022).exp();
let a1 = if dur.is_finite() { dur * (0.3 + 0.4 * u01(h)) } else { f32::INFINITY };
let ret = if u01(h.wrapping_add(1)) < 0.6 && age > a1 { 0.7 * flicker * (-(age - a1) / 0.03).exp() } else { 0.0 };
let settle = 0.72 + 0.28 * (-age / 0.12).exp();
flash * settle + ret
}
/// A single zap: the strike's flash, usually one re-strike down the same channel a few frames
/// later, then the afterimage fades out by `ElectricParams::ZAP_LIFE`.
fn zap_env(age: f32, flicker: f32, reduced: bool, h: u32) -> f32 {
let out = 1.0 - ss(0.6, 1.0, age / ElectricParams::ZAP_LIFE);
if reduced {
return (-age / 0.15).exp() * out;
}
let a1 = 0.07 + 0.06 * u01(h);
let ret = if age > a1 { (0.5 + 0.5 * flicker) * (-(age - a1) / 0.035).exp() } else { 0.0 };
((1.0 + 0.65 * (-age / 0.022).exp()) * (-age / 0.11).exp() + ret) * out
}
/// Afterimage of a strike `g` seconds after it was replaced.
fn ghost_env(g: f32) -> f32 {
0.9 * (-g / 0.07).exp()
}
/// Midpoint displacement. `pts` are the coarse points (pinned arc ends, or a loop); every level
/// halves each segment and pushes the new midpoint sideways by `amp(level)` x gaussian. Levels
/// below `memory` follow the channel seed (shared by re-strikes), finer ones the strike's own.
fn mpd(mut pts: Vec<f32>, periodic: bool, levels: u32, amp: impl Fn(u32) -> f32, channel: u32, strike: u32, memory: u32) -> Vec<f32> {
for lv in 0..levels {
let m = pts.len();
let seg = if periodic { m } else { m - 1 };
let sd = hu(if lv < memory { channel } else { strike }, lv * 7919 + 1);
let a = amp(lv);
let mut next = Vec::with_capacity(seg * 2 + 1);
for i in 0..seg {
let (p0, p1) = (pts[i], pts[(i + 1) % m]);
next.push(p0);
next.push((p0 + p1) * 0.5 + a * gauss3(hu(sd, i as u32 * 3)));
}
if !periodic {
next.push(pts[m - 1]);
}
pts = next;
}
pts
}
/// Linear resample of control points: keeps the kinks sharp. `limit` soft-clamps the offset (0 flattens it).
fn resample(ctrl: &[f32], out: &mut [f32], periodic: bool, limit: f32) {
if limit <= 0.0 {
out.fill(0.0);
return;
}
let (m, n) = (ctrl.len(), out.len());
for (i, v) in out.iter_mut().enumerate() {
let x = if periodic { i as f32 / n as f32 * m as f32 } else { i as f32 / (n - 1) as f32 * (m - 1) as f32 };
let i0 = (x.floor() as usize).min(m - 1);
let f = x - i0 as f32;
let i1 = if periodic { (i0 + 1) % m } else { (i0 + 1).min(m - 1) };
let d = ctrl[i0] + (ctrl[i1] - ctrl[i0]) * f;
*v = limit * (d / limit).tanh();
}
}
/// A fork's sideways wander: a clamped random walk, so it kinks like the main bolt.
fn fork_walk(hk: u32, len: f32) -> [f32; FORK_SAMPLES] {
let mut s = [0.0f32; FORK_SAMPLES];
let mut acc = 0.0f32;
for (i, v) in s.iter_mut().enumerate().skip(1) {
acc = (acc + gauss3(hu(hk, 100 + i as u32)) * len * 0.07).clamp(-len * 0.3, len * 0.3);
*v = acc;
}
s
}
/// Fork envelope: (grow 0..1 as the branch shoots out, brightness, heat 1 -> 0 as it cools).
fn fork_env(age: f32, life: f32) -> (f32, f32, f32) {
let grow = 1.0 - (1.0 - (age / 0.035).min(1.0)).powi(3);
let lifee = ss(0.0, 0.01, age) * (-age / (life * 0.4)).exp() * (1.0 - ss(0.75 * life, life, age));
(grow, lifee, 1.0 - age / life)
}
/// Sideways scale of an arc's main bolt (pt).
fn arc_amp(p: &ElectricParams, l: f32) -> f32 {
p.amplitude * (l / 100.0).sqrt()
}
fn arc_fork_len(l: f32) -> f32 {
(l * 0.16).clamp(12.0, 80.0)
}
/// How far an arc's bolt and forks can reach off the A-B line, so bounds never clip them.
pub(crate) fn arc_reach(p: &ElectricParams, l: f32) -> f32 {
2.0 * arc_amp(p, l) + if p.forks > 0.0 { arc_fork_len(l) * 1.1 } else { 0.0 }
}
/// Electric tables. Layout at `first`: [N, strands, forks, 0], [strand brightness k0..k2, 0],
/// strands x N/4 displacement vec4s, strands x N/4 blurred displacement (halo path),
/// (border: strands x N/4 crawl vec4s), forks x 6 vec4s.
///
/// Arc and Border are lightning: a fractal (midpoint-displacement) bolt that strikes, holds,
/// and re-strikes, mostly down the same channel. Strand 0 is the live strike; strands 1 and 2
/// are the previous strikes' afterimages. Forks branch off at the strike and die away.
pub(crate) fn electric(p: &ElectricParams, shape: Shape, t: f32, seed: u32, reduced: bool, data: &mut Vec<[f32; 4]>) -> [f32; 4] {
let first = data.len() as f32;
let freq = p.frequency / 100.0;
let strands = if p.zap.is_some() { 1 } else { p.strands.clamp(1, 3) as usize };
let rate = if reduced { 0.0 } else { p.forks };
let st = Strikes::new(if reduced || p.zap.is_some() { 0.0 } else { p.speed }, seed);
let (k, age, dur) = if reduced && p.zap.is_none() { (0, 1.0, f32::INFINITY) } else { st.at(t - p.zap.unwrap_or(0.0)) };
// When each strike began, on the layer clock (a zap is strike 0 only).
let start = |ks: i32| match p.zap {
Some(t0) => if ks == 0 { t0 } else { f32::INFINITY },
None => st.start(ks),
};
let still = reduced || st.period.is_infinite();
let noise = |j: usize| if reduced { 1.0 } else { 1.0 - p.flicker * 0.25 * (0.5 + 0.5 * gnoise(t * 14.0, j as f32 * 3.7, 0, seed.wrapping_add(17))) };
let bright = match p.zap {
Some(_) => [zap_env(age, p.flicker, reduced, st.strike_seed(0)) * noise(0), 0.0, 0.0],
None => [
if reduced { 1.0 } else { strike_env(age, dur, p.flicker, st.strike_seed(k)) * noise(0) },
if still { 0.0 } else { ghost_env(age) * noise(1) },
if still { 0.0 } else { ghost_env(age + st.start(k) - st.start(k - 1)) * noise(2) },
],
};
let hdr = data.len();
data.push([0.0; 4]);
data.push([bright[0], bright[1], bright[2], 0.0]);
match p.style {
ElectricStyle::Arc { a, b } => {
let l = ((b[0] - a[0]).powi(2) + (b[1] - a[1]).powi(2)).sqrt().max(1.0);
let n = (l.ceil() as usize).clamp(32, 1024).next_multiple_of(4);
let step = l / (n - 1) as f32;
let amp = arc_amp(p, l);
let levels = ((l * freq * 6.0).max(8.0).log2().ceil() as u32).clamp(3, 8);
// Self-similar roughness: each halving keeps 2^-0.62 of the offset.
let path = |ks: i32| {
let ctrl = mpd(vec![0.0, 0.0], false, levels, |lv| amp * 0.65 * 2f32.powf(-0.62 * lv as f32), st.channel(ks), st.strike_seed(ks), 2);
let mut v = vec![0.0f32; n];
resample(&ctrl, &mut v, false, amp * 2.0);
v
};
let paths: Vec<Vec<f32>> = (0..strands.max(2) as i32).map(|j| path(k - j)).collect();
for v in &paths[..strands] {
push_samples(data, v);
}
// The halo follows the blurred path (a real bloom of the line), so it never striates.
for v in &paths[..strands] {
push_samples(data, &blur3(v, p.glow * 1.2 / step, false));
}
let dir = [(b[0] - a[0]) / l, (b[1] - a[1]) / l];
let nrm = [-dir[1], dir[0]];
let mut forks = 0;
'strikes: for j in 0..2 {
let ks = k - j;
let fage = t - start(ks);
for c in 0..3u32 {
if forks == 4 {
break 'strikes;
}
let hk = hu(st.strike_seed(ks) ^ 0xF04C, c);
let life = 0.07 + 0.13 * u01(hk + 2);
if u01(hk) > rate || fage > life || fage < 0.0 {
continue;
}
let path = &paths[j as usize];
let u0 = 0.12 + 0.73 * u01(hk + 3);
let i0 = ((u0 * (n - 1) as f32) as usize).clamp(2, n - 3);
let slope = (path[i0 + 2] - path[i0 - 2]) / (4.0 * step);
let side = if u01(hk + 4) > 0.5 { 1.0 } else { -1.0 };
// Branches lean on toward the far electrode, off the local direction of the bolt.
let ang = slope.atan() + (0.35 + 0.5 * u01(hk + 5)) * side;
let len = arc_fork_len(l) * (0.45 + 0.55 * u01(hk + 6));
let o = [a[0] + dir[0] * u0 * l + nrm[0] * path[i0], a[1] + dir[1] * u0 * l + nrm[1] * path[i0]];
let (sa, ca) = ang.sin_cos();
let fd = [dir[0] * ca - dir[1] * sa, dir[0] * sa + dir[1] * ca];
let (grow, lifee, heat) = fork_env(fage, life);
data.push([o[0], o[1], fd[0], fd[1]]);
data.push([len, grow, lifee * bright[0].max(0.6), heat]);
push_samples(data, &fork_walk(hk, len));
forks += 1;
}
}
data[hdr] = [n as f32, strands as f32, forks as f32, 0.0];
[first, n as f32, forks as f32, strands as f32]
}
ElectricStyle::Border => {
let total = rrect_total(shape.rect, shape.radius);
let n = (total.ceil() as usize).clamp(64, 2048).next_multiple_of(4);
let step = total / n as f32;
let cells = ((total * freq).round() as usize).max(3);
let path = |ks: i32| {
let ch = st.channel(ks);
let coarse: Vec<f32> = (0..cells).map(|i| p.amplitude * 0.7 * gauss3(hu(ch, i as u32 * 3 + 5))).collect();
let ctrl = mpd(coarse, true, 3, |lv| p.amplitude * 0.7 * 2f32.powf(-0.62 * (lv + 1) as f32), ch, st.strike_seed(ks), 1);
let mut v = vec![0.0f32; n];
resample(&ctrl, &mut v, true, p.amplitude * 1.7);
v
};
let paths: Vec<Vec<f32>> = (0..strands.max(2) as i32).map(|j| path(k - j)).collect();
for v in &paths[..strands] {
push_samples(data, v);
}
for v in &paths[..strands] {
push_samples(data, &blur3(v, p.glow * 1.2 / step, true));
}
let mut buf = vec![0.0f32; n];
for j in 0..strands {
crawl(&mut buf, cells, p.speed, t, seed.wrapping_add(j as u32 * 7919), j as f32, false);
push_samples(data, &buf);
}
let mut forks = 0;
'strikes: for j in 0..2 {
let ks = k - j;
let fage = t - start(ks);
for c in 0..3u32 {
if forks == 5 {
break 'strikes;
}
let hk = hu(st.strike_seed(ks) ^ 0xF04C, c);
let life = 0.07 + 0.13 * u01(hk + 2);
if u01(hk) > rate || fage > life || fage < 0.0 {
continue;
}
let i0 = ((u01(hk + 3) * n as f32) as usize).min(n - 1);
let len = p.fork_len * (0.6 + 0.6 * u01(hk + 4));
let (grow, lifee, heat) = fork_env(fage, life);
data.push([i0 as f32 * step, total, paths[j as usize][i0], 0.0]);
data.push([len, grow, lifee * bright[0].max(0.6), heat]);
push_samples(data, &fork_walk(hk, len));
forks += 1;
}
}
data[hdr] = [n as f32, strands as f32, forks as f32, 0.0];
[first, n as f32, forks as f32, strands as f32]
}
ElectricStyle::Charged => {
// The calm UI border keeps a continuously crawling hairline (no strikes).
data[hdr + 1] = [1.0, 0.0, 0.0, 0.0];
let total = rrect_total(shape.rect, shape.radius);
let n = (total.ceil() as usize).clamp(64, 2048).next_multiple_of(4);
let step = total / n as f32;
let cells = ((total * freq).round() as i32).max(3);
let sp = p.speed * 0.35;
let tm = if reduced { 0.0 } else { t };
let mut buf = vec![0.0f32; n];
for (i, v) in buf.iter_mut().enumerate() {
let x = i as f32 / n as f32 * cells as f32;
*v = disp(x, tm * sp, cells, seed, 3) * p.amplitude;
}
push_samples(data, &buf);
push_samples(data, &blur3(&buf, p.glow * 1.2 / step, true));
crawl(&mut buf, cells as usize, p.speed, tm, seed, 0.0, true);
push_samples(data, &buf);
let mut forks = 0;
for j in 0..5u32 {
let Some(f) = fork_slot(seed, j, t, rate * 0.5, 0.3, 0.25) else { continue };
let hk = f.hk;
let len = p.fork_len * 0.4 * (0.6 + 0.6 * u01(hk + 4));
let (grow, lifee, heat) = fork_env(f.age, f.life);
data.push([u01(hk + 3) * total, total, 0.0, 0.0]);
data.push([len, grow, lifee, heat]);
push_samples(data, &fork_walk(hk, len));
forks += 1;
}
data[hdr] = [n as f32, 1.0, forks as f32, 0.0];
[first, n as f32, forks as f32, 1.0]
}
}
}
/// Brightness travelling around a border loop, so the current visibly flows.
fn crawl(buf: &mut [f32], cells: usize, speed: f32, t: f32, seed: u32, k: f32, calm: bool) {
let n = buf.len();
let cc = (cells as i32 / 3).max(2);
let sp = if calm { speed * 0.35 } else { speed };
for (i, v) in buf.iter_mut().enumerate() {
let cx = i as f32 / n as f32 * cc as f32;
let c = 0.5 + 0.5 * gnoise(cx - t * sp * 0.08 * cc as f32, t * 0.35 + k * 5.0, cc, seed.wrapping_add(3));
*v = if calm { 0.45 + 0.55 * ss(0.2, 0.8, c) } else { 0.3 + 0.7 * ss(0.25, 0.75, c) };
}
}
struct ForkSlot {
hk: u32,
age: f32,
life: f32,
}
fn fork_slot(seed: u32, j: u32, t: f32, rate: f32, base_p: f32, var_p: f32) -> Option<ForkSlot> {
let hj = hu(seed, j * 977 + 13);
let p = base_p + var_p * u01(hj);
let tau = t / p + u01(hj + 1);
let kk = tau.floor();
let age = (tau - kk) * p;
let hk = hu(hj, kk as i32 as u32);
if u01(hk) > rate {
return None;
}
let life = 0.15 + 0.1 * u01(hk + 2);
if age > life {
return None;
}
Some(ForkSlot { hk, age, life })
}
/// Ember drag (1/s): flung out of the flame fast, they slow to a buoyant drift.
pub(crate) const EMBER_DRAG: f32 = 2.4;
/// Embers: two vec4 per live ember: (pos, streak), (size, temperature, 0, 0). Returns (first, count).
/// Each is flung up out of the flame, slows under drag toward a buoyant drift, sways in the
/// turbulence and cools (white -> orange -> red) until it vanishes.
pub(crate) fn embers(p: &FireParams, rect: Rect, radius: f32, t: f32, seed: u32, data: &mut Vec<[f32; 4]>) -> (f32, f32) {
let first = data.len() as f32;
let mut count = 0;
let life0 = p.ember_life.max(0.1);
let k = EMBER_DRAG;
for e in 0..p.embers.min(40) {
let hk0 = hu(seed.wrapping_add(991), e * 7 + 3);
let life = life0 * (0.6 + 0.8 * u01(hk0));
let tau = t / life + u01(hk0 + 1);
let kk = tau.floor();
let a = tau - kk;
let hk = hu(hk0, kk as i32 as u32);
let age = a * life;
let x0 = rect.x + radius * 0.6 + (rect.w - radius * 1.2) * u01(hk + 2);
let y0 = rect.y - p.height * (0.1 + 0.45 * u01(hk + 3));
let v0 = -p.ember_rise * (1.0 + 0.8 * u01(hk + 4));
let vt = -p.ember_rise * 0.32;
let ek = (-k * age).exp();
let y = y0 + vt * age + (v0 - vt) * (1.0 - ek) / k;
let vy = vt + (v0 - vt) * ek;
let sway = 2.5 + 5.0 * u01(hk + 5);
let fq = 3.0 + 4.0 * u01(hk + 6);
let ph = TAU * u01(hk + 7);
let drift = (u01(hk + 8) - 0.5) * 14.0;
let grow = 1.0 - (-age * 3.0).exp();
let x = x0 + drift * age + sway * (age * fq + ph).sin() * grow;
let vx = drift + sway * ((age * fq + ph).cos() * fq * grow + (age * fq + ph).sin() * 3.0 * (-age * 3.0).exp());
let sz = p.ember_size * (0.5 + 0.8 * u01(hk + 9)) * (1.0 - 0.4 * a);
let attack = (age / 0.05).clamp(0.0, 1.0);
let temp = (-age / (life * 0.42)).exp() * (1.0 - a * a) * (0.8 + 0.3 * u01(hk + 10)) * attack;
if temp < 0.004 {
continue;
}
let k_shutter = 0.6 / 60.0;
data.push([x, y, vx * k_shutter, vy * k_shutter]);
data.push([sz, temp, 0.0, 0.0]);
count += 1;
}
(first, count as f32)
}
/// Burst stars start within this many seconds of each other.
pub(crate) const SPARKLE_STAGGER: f32 = 0.16;
/// A burst star lives this fraction of `SparkleParams::life`.
pub(crate) const BURST_LIFE: f32 = 0.55;
/// Peak of a star's pop (overshoot before it settles), as a multiple of its size.
pub(crate) const SPARKLE_MAX_SCALE: f32 = 1.16 * 1.35;
/// A star's size over its life `a` (0..1): it pops in with a little overshoot, settles, holds,
/// then shrinks away.
fn star_scale(a: f32) -> f32 {
let x = (a / 0.22).min(1.0);
let c = 2.2;
let back = 1.0 + (c + 1.0) * (x - 1.0).powi(3) + c * (x - 1.0).powi(2);
back * (1.0 - ss(0.55, 1.0, a))
}
/// Sparkles: two vec4 each: (pos, size, brightness), (cos, sin, 0, 0).
/// A few four-point stars around the shape, each with its own size (mostly small, a few large),
/// twinkle rate and spin. Continuous stars rest between appearances so only some are lit at once;
/// a burst (`SparkleParams::burst`) pops every star once and flings it out a little.
pub(crate) fn sparkles(p: &SparkleParams, rect: Rect, t: f32, seed: u32, reduced: bool, data: &mut Vec<[f32; 4]>) -> (f32, f32) {
let first = data.len() as f32;
let mut count = 0;
let (cx, cy, hw, hh) = (rect.x + rect.w * 0.5, rect.y + rect.h * 0.5, rect.w * 0.5, rect.h * 0.5);
for k in 0..p.count.min(64) {
let h0 = hu(seed.wrapping_add(313), k * 11 + 1);
// (instance hash, age within its life, life)
let (hk, age, life) = match p.burst {
Some(t0) => {
let life = p.life * BURST_LIFE * (0.7 + 0.6 * u01(h0));
(h0, t - t0 - SPARKLE_STAGGER * u01(h0 + 1), life)
}
None if reduced => {
// Still: a fixed handful, lit at rest.
if u01(h0 + 9) > 0.6 {
continue;
}
(h0, 0.5, 1.0)
}
None => {
// Each cycle: lit for `life`, then dark for a while, so the stars take turns.
let life = p.life * (0.7 + 0.6 * u01(h0));
let cycle = life * (1.5 + 0.8 * u01(h0 + 2));
let tau = t / cycle + u01(h0 + 1);
let kk = tau.floor();
(hu(h0, kk as i32 as u32), (tau - kk) * cycle, life)
}
};
if age < 0.0 || age > life {
continue;
}
let a = age / life;
// Around the shape: a point on its outline, pushed out into the margin.
let th = TAU * u01(hk + 2);
let (dx, dy) = (th.cos(), th.sin());
let edge = 1.0 / (dx.abs() / hw.max(1.0)).max(dy.abs() / hh.max(1.0));
let mut out = p.margin * (0.15 + 0.85 * u01(hk + 3));
if p.burst.is_some() && !reduced {
out *= 0.35 + 0.65 * (1.0 - (-age * 5.0).exp());
}
let pos = [cx + dx * (edge + out), cy + dy * (edge + out)];
let v = u01(hk + 4);
let size = p.size * (0.45 + 0.9 * v * v);
let (sc, env) = if reduced {
(1.0, (PI * a).sin() * 0.7)
} else {
let fq = 5.0 + 4.0 * u01(hk + 5);
let tw = 0.5 + 0.5 * (TAU * fq * age + TAU * u01(hk + 6)).sin();
(star_scale(a), 1.0 - 0.3 * tw * tw)
};
if sc * env < 0.01 {
continue;
}
let spin = if reduced { 0.0 } else { (u01(hk + 7) - 0.5) * 1.2 * age };
let ang = (u01(hk + 8) - 0.5) * 0.35 + spin;
data.push([pos[0], pos[1], size * sc, env]);
data.push([ang.cos(), ang.sin(), 0.0, 0.0]);
count += 1;
}
(first, count as f32)
}
pub(crate) const AURORA_SAMPLES: usize = 64;
/// Aurora curtains: for k in 0..3, AURORA_SAMPLES heights then AURORA_SAMPLES warps, across the rect width.
pub(crate) fn aurora(p: &AuroraParams, rect: Rect, t: f32, seed: u32, data: &mut Vec<[f32; 4]>) -> f32 {
let first = data.len() as f32;
let tt = t * p.speed;
let mut ys = [0.0f32; AURORA_SAMPLES];
let mut ws = [0.0f32; AURORA_SAMPLES];
for k in 0..3u32 {
let fk = k as f32;
for i in 0..AURORA_SAMPLES {
let x = rect.x + rect.w * i as f32 / (AURORA_SAMPLES - 1) as f32;
let qx = x / p.scale.max(1.0);
let mut s = 0.0;
let mut a = 0.5;
let (mut px, mut py) = (qx * 0.55 + tt * (0.25 + 0.12 * fk), fk * 3.1 + tt * 0.07);
for o in 0..3u32 {
s += a * gnoise(px, py, 0, seed.wrapping_add(k).wrapping_add(o * 131));
let (nx, ny) = (0.8 * px - 0.6 * py, 0.6 * px + 0.8 * py);
px = nx * 2.02;
py = ny * 2.02;
a *= 0.5;
}
let wv = s / 0.875;
ws[i] = wv;
ys[i] = 0.3 + 0.2 * fk + 0.22 * wv;
}
push_samples(data, &ys);
push_samples(data, &ws);
}
first
}
/// Fold unbounded time into `0..=512` s with a continuous triangle wave (exact identity on
/// `0..=512`), so spatial noise coordinates keep full `f32` precision after hours of uptime.
pub(crate) fn fold_t(t: f32) -> f32 {
if !t.is_finite() {
return 0.0;
}
let u = (t as f64 * (1.0 / 1024.0)).rem_euclid(1.0);
(if u <= 0.5 { u * 1024.0 } else { (1.0 - u) * 1024.0 }) as f32
}
/// Mesh gradient control points at time `t`: each wanders from its rest point by up to `drift`.
pub(crate) fn mesh_points(p: &MeshGradientParams, t: f32, seed: u32) -> [[f32; 2]; MAX_STOPS] {
let tt = fold_t(t * p.speed * 0.5);
let drift = if p.drift.is_finite() { p.drift } else { 0.0 };
let mut out = p.points;
for (k, q) in out.iter_mut().enumerate() {
let s = seed.wrapping_add(k as u32 * 31);
let x = tt + k as f32 * 13.1;
q[0] += drift * 1.4 * gnoise(x, 0.5, 0, s);
q[1] += drift * 1.4 * gnoise(x, 7.5, 0, s.wrapping_add(97));
}
out
}
/// Metaball centres (pt), radii (pt) and colour index: one vec4 per ball.
pub(crate) fn metaballs(p: &MetaballParams, rect: Rect, t: f32, seed: u32, data: &mut Vec<[f32; 4]>) {
let n = p.count.clamp(1, 8);
let short = rect.w.min(rect.h).max(0.0);
let tt = fold_t(t * p.speed * 0.5);
let size = if p.size.is_finite() { p.size.max(0.0) } else { 0.0 };
let colors = p.colors.len() as u32;
for k in 0..n {
let h = hu(seed, k + 1);
let a = (k as f32 + u01(h) * 0.6) / n as f32 * TAU;
let base = [0.5 + 0.24 * a.cos(), 0.5 + 0.24 * a.sin()];
let x = tt + k as f32 * 7.3;
let wx = gnoise(x, 1.5, 0, h) * 0.5;
let wy = gnoise(x, 4.5, 0, h.wrapping_add(5)) * 0.5;
let r = size * short * (0.7 + 0.6 * u01(h + 2));
data.push([rect.x + rect.w * (base[0] + wx), rect.y + rect.h * (base[1] + wy), r, (k % colors) as f32]);
}
}
/// Side of the blue-noise tile.
pub(crate) const BLUE_N: usize = 32;
/// A BLUE_N × BLUE_N blue-noise threshold tile (ranks 0..1, row-major, 4 per vec4), built once by
/// void-and-cluster: Gaussian energy on a torus, relax an initial pattern, then rank every pixel
/// by removing tightest clusters and filling largest voids.
pub(crate) fn blue_noise() -> &'static [[f32; 4]] {
static TILE: std::sync::OnceLock<Vec<[f32; 4]>> = std::sync::OnceLock::new();
TILE.get_or_init(|| {
const N: usize = BLUE_N;
const M: usize = N * N;
let sigma = 1.5f32;
let mut kern = vec![0.0f32; M];
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;
kern[y * N + x] = (-(dx * dx + dy * dy) / (2.0 * sigma * sigma)).exp();
}
}
let mut on = vec![false; M];
let mut energy = vec![0.0f32; M];
let splat = |energy: &mut [f32], i: usize, sign: f32| {
let (ix, iy) = (i % N, i / N);
for y in 0..N {
for x in 0..N {
let k = ((y + N - iy) % N) * N + (x + N - ix) % N;
energy[y * N + x] += sign * kern[k];
}
}
};
let tightest = |on: &[bool], energy: &[f32]| (0..M).filter(|&i| on[i]).max_by(|&a, &b| energy[a].total_cmp(&energy[b])).unwrap();
let voidest = |on: &[bool], energy: &[f32]| (0..M).filter(|&i| !on[i]).min_by(|&a, &b| energy[a].total_cmp(&energy[b])).unwrap();
// Initial pattern: about a tenth of the pixels, from the shared hash.
let mut ones = 0;
for (i, o) in on.iter_mut().enumerate() {
if u01(hu(i as u32, 0xb10e)) < 0.1 {
*o = true;
ones += 1;
}
}
for i in 0..M {
if on[i] {
splat(&mut energy, i, 1.0);
}
}
for _ in 0..M {
let c = tightest(&on, &energy);
on[c] = false;
splat(&mut energy, c, -1.0);
let v = voidest(&on, &energy);
on[v] = true;
splat(&mut energy, v, 1.0);
if v == c {
break;
}
}
let mut rank = vec![0usize; M];
let (proto_on, proto_e) = (on.clone(), energy.clone());
for r in (0..ones).rev() {
let c = tightest(&on, &energy);
on[c] = false;
splat(&mut energy, c, -1.0);
rank[c] = r;
}
on = proto_on;
energy = proto_e;
for r in ones..M {
let v = voidest(&on, &energy);
on[v] = true;
splat(&mut energy, v, 1.0);
rank[v] = r;
}
let v: Vec<f32> = rank.iter().map(|&r| (r as f32 + 0.5) / M as f32).collect();
v.chunks(4).map(|c| [c[0], c[1], c[2], c[3]]).collect()
})
}
+286
View File
@@ -0,0 +1,286 @@
//! Fills: styles that paint a node's whole shape, or a band inside its edge as a stroke. They share
//! the shape mask (`FillParams::border`), colour lists (`Stops`, blended in OKLab) and one input
//! for the styles that re-tone something (`FillInput`: a ramp, noise, the backdrop or an image).
//!
//! Every style is a pure function of (pixel, params, time, seed). Under reduced motion each one
//! holds a single settled pose. `catalog` lists the styles, their params and presets.
use crate::catalog::*;
use crate::*;
mod pack;
mod styles;
pub use styles::DitherParams;
pub use styles::FlutedGlassParams;
pub use styles::GrainGradientParams;
pub use styles::HalftoneParams;
pub use styles::LiquidMetalParams;
pub use styles::MeshGradientParams;
pub use styles::MetaballParams;
pub use styles::PlasticParams;
pub use styles::SwirlParams;
pub use styles::VoronoiParams;
pub use styles::WaveParams;
// ---------------------------------------------------------------- colours
/// Most colours a `Stops` list holds.
pub const MAX_STOPS: usize = 6;
/// An ordered list of 1 to `MAX_STOPS` colours (linear light).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Stops {
n: u8,
c: [Rgb; MAX_STOPS],
}
impl Stops {
/// Keeps the first `MAX_STOPS`; an empty list is one black stop.
pub fn new(colors: &[Rgb]) -> Stops {
let mut c = [Rgb([0.0; 3]); MAX_STOPS];
let n = colors.len().clamp(1, MAX_STOPS);
for (d, s) in c.iter_mut().zip(colors) {
*d = *s;
}
Stops { n: n as u8, c }
}
/// From sRGB hex colours (0xRRGGBB).
pub fn hex(hex: &[u32]) -> Stops {
let v: Vec<Rgb> = hex.iter().map(|h| rgb(*h)).collect();
Stops::new(&v)
}
pub fn as_slice(&self) -> &[Rgb] {
&self.c[..self.n as usize]
}
pub fn len(&self) -> usize {
self.n as usize
}
pub fn is_empty(&self) -> bool {
false
}
}
// ---------------------------------------------------------------- shared choices
/// What a re-toning style (dither, halftone) reads as its tone.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FillInput {
/// A ramp across the shape along `angle`.
Linear,
/// Light at the centre, dark at the rim.
Radial,
/// Slowly drifting noise.
Noise,
/// Whatever is drawn behind the layer (needs a backdrop copy).
Backdrop,
/// The layer's source texture (`FxLayer::source`).
Image,
}
choices!(FillInput { Linear = "linear" "Linear", Radial = "radial" "Radial", Noise = "noise" "Noise", Backdrop = "backdrop" "Backdrop", Image = "image" "Image" });
impl FillInput {
pub(super) fn code(self) -> f32 {
match self {
FillInput::Linear => 0.0,
FillInput::Radial => 1.0,
FillInput::Noise => 2.0,
FillInput::Backdrop => 3.0,
FillInput::Image => 4.0,
}
}
fn animates(self) -> bool {
self == FillInput::Noise
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DitherPattern {
Bayer2,
Bayer4,
Bayer8,
/// A 32×32 void-and-cluster tile: no visible grid, even grain.
BlueNoise,
/// Independent random threshold per pixel.
White,
}
choices!(DitherPattern { Bayer2 = "bayer2" "Bayer 2×2", Bayer4 = "bayer4" "Bayer 4×4", Bayer8 = "bayer8" "Bayer 8×8", BlueNoise = "blue_noise" "Blue noise", White = "white" "White noise" });
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum GradientKind {
Linear,
Radial,
/// Sweeps around `center`, starting at `angle`.
Conic,
}
choices!(GradientKind { Linear = "linear" "Linear", Radial = "radial" "Radial", Conic = "conic" "Conic" });
/// Where a fill's pattern is pinned.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FillAnchor {
/// To the window: neighbouring shapes show neighbouring parts of one surface.
World,
/// To the shape: every shape of the same size, seed and time looks the same.
Element,
}
choices!(FillAnchor { World = "world" "World", Element = "element" "Element" });
// ---------------------------------------------------------------- FillStyle / FillParams
macro_rules! styles {
($($v:ident($p:ident) = $idx:literal),* $(,)?) => {
/// Which fill, with its params. The order is the catalog's (`fill_styles()`).
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub enum FillStyle {
$($v($p)),*
}
impl FillStyle {
/// Position in `fill_styles()`; also the shader variant.
pub(crate) fn index(&self) -> usize {
match self { $(FillStyle::$v(_) => $idx),* }
}
pub(crate) fn get_param(&self, id: &str) -> Option<Value> {
match self { $(FillStyle::$v(p) => p.get_param(id)),* }
}
pub(crate) fn set_param(&mut self, id: &str, v: Value) -> bool {
match self { $(FillStyle::$v(p) => p.set_param(id, v)),* }
}
pub(crate) fn rust_field(&self, id: &str) -> Option<String> {
match self { $(FillStyle::$v(p) => p.rust_field(id)),* }
}
}
$(
impl From<$p> for FillStyle {
fn from(p: $p) -> Self { FillStyle::$v(p) }
}
impl From<$p> for FillParams {
fn from(p: $p) -> Self { FillParams::new(FillStyle::$v(p)) }
}
impl $p {
/// Paint only a band this wide (pt) inside the shape's edge.
pub fn border(self, width: f32) -> FillParams { FillParams::from(self).border(width) }
/// Fill opacity, 0..1.
pub fn intensity(self, k: f32) -> FillParams { FillParams::from(self).intensity(k) }
}
)*
};
}
styles!(
LiquidMetal(LiquidMetalParams) = 0,
MeshGradient(MeshGradientParams) = 1,
Dither(DitherParams) = 2,
GrainGradient(GrainGradientParams) = 3,
FlutedGlass(FlutedGlassParams) = 4,
Metaballs(MetaballParams) = 5,
Swirl(SwirlParams) = 6,
Voronoi(VoronoiParams) = 7,
Waves(WaveParams) = 8,
Halftone(HalftoneParams) = 9,
Plastic(PlasticParams) = 10,
);
/// A fill: the style plus what every style shares. Build it with `FillParams::new`, `From` a
/// style's params, or a preset; more shared fields may come, so it has no struct literal.
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub struct FillParams {
pub style: FillStyle,
/// 0 fills the shape; above 0 paints only a band this wide (pt) inside the edge, as a stroke.
pub border: f32,
/// Opacity of the fill, 0..1.
pub intensity: f32,
}
impl FillParams {
pub fn new(style: FillStyle) -> FillParams {
FillParams { style, border: 0.0, intensity: 1.0 }
}
pub fn border(mut self, width: f32) -> FillParams {
self.border = width;
self
}
pub fn intensity(mut self, k: f32) -> FillParams {
self.intensity = k;
self
}
/// Whether this fill samples the backdrop (glass, or a dither or halftone of it).
pub fn needs_backdrop(&self) -> bool {
match self.style {
FillStyle::FlutedGlass(_) => true,
FillStyle::Dither(p) => p.input == FillInput::Backdrop,
FillStyle::Halftone(p) => p.input == FillInput::Backdrop,
_ => false,
}
}
fn needs_source(&self) -> bool {
match self.style {
FillStyle::Dither(p) => p.input == FillInput::Image,
FillStyle::Halftone(p) => p.input == FillInput::Image,
_ => false,
}
}
/// Whether the fill moves on its own (so the frame loop keeps ticking).
pub(crate) fn animates(&self) -> bool {
match self.style {
FillStyle::LiquidMetal(p) => p.speed > 0.0 && p.flow > 0.0,
FillStyle::MeshGradient(p) => p.speed > 0.0 && (p.drift > 0.0 || p.warp > 0.0),
FillStyle::Dither(p) => p.input.animates() && p.speed > 0.0,
FillStyle::GrainGradient(p) => p.fps > 0.0 && p.amount > 0.0,
FillStyle::FlutedGlass(_) => false,
FillStyle::Metaballs(p) => p.speed > 0.0,
FillStyle::Swirl(p) => p.speed > 0.0,
FillStyle::Voronoi(p) => p.speed > 0.0,
FillStyle::Waves(p) => p.speed > 0.0 && p.amplitude > 0.0,
FillStyle::Halftone(p) => p.input.animates() && p.speed > 0.0,
FillStyle::Plastic(_) => false,
}
}
pub(crate) fn cost(&self) -> FxCost {
// A ramp reads two stops; mesh and metaballs read every stop or ball.
let ramp = 2;
let input = |i: FillInput| match i {
FillInput::Noise => (0, 3),
FillInput::Backdrop | FillInput::Image => (1, 0),
_ => (0, 0),
};
let (samples, alu) = match self.style {
FillStyle::LiquidMetal(p) => (0, if p.flow > 0.0 { 8 } else { 0 }),
FillStyle::MeshGradient(p) => (p.colors.len() as u32 * 2, if p.warp > 0.0 { 2 } else { 0 }),
FillStyle::Dither(p) => {
let (s, a) = input(p.input);
(s + 1 + (p.pattern == DitherPattern::BlueNoise) as u32, a)
}
FillStyle::GrainGradient(_) => (ramp, 0),
FillStyle::FlutedGlass(p) => (if p.frost > 0.0 { 6 } else { 3 }, 0),
FillStyle::Metaballs(p) => (p.count.clamp(1, 8) * 2, 0),
FillStyle::Swirl(_) => (ramp, 9),
FillStyle::Voronoi(_) => (1, 0),
FillStyle::Waves(p) => (p.colors.len() as u32, 0),
// Four dots per pixel, each reading the tone.
FillStyle::Halftone(p) => {
let (s, a) = input(p.input);
(s * 4, a * 4)
}
FillStyle::Plastic(_) => (0, 0),
};
FxCost { passes: 1, samples, alu, backdrop: self.needs_backdrop(), source: self.needs_source() }
}
/// Whether the fill draws nothing on a shape of this rect, at any time.
pub(crate) fn draws_nothing(&self, r: Rect) -> bool {
!(self.intensity > 0.0) || !(self.border.is_finite() && self.border >= 0.0) || !(r.w > 0.0) || !(r.h > 0.0)
}
}
#[cfg(test)]
mod tests;
+145
View File
@@ -0,0 +1,145 @@
//! GPU instance and per-frame table packing for fill styles.
use super::*;
/// Linear sRGB to OKLab.
pub(super) fn oklab(c: Rgb) -> [f32; 3] {
let [r, g, b] = c.0;
let l = 0.412_221_46 * r + 0.536_332_55 * g + 0.051_445_995 * b;
let m = 0.211_903_5 * r + 0.680_699_5 * g + 0.107_396_96 * b;
let s = 0.088_302_46 * r + 0.281_718_85 * g + 0.629_978_7 * b;
let (l, m, s) = (l.max(0.0).cbrt(), m.max(0.0).cbrt(), s.max(0.0).cbrt());
[
0.210_454_26 * l + 0.793_617_8 * m - 0.004_072_047 * s,
1.977_998_5 * l - 2.428_592_2 * m + 0.450_593_7 * s,
0.025_904_037 * l + 0.782_771_77 * m - 0.808_675_77 * s,
]
}
impl FillParams {
/// Pack into `i` (kind is `KIND_FILL`); `None` when the fill draws nothing.
pub(crate) fn pack(&self, i: &mut InstRaw, rm: bool, time: f32) -> Option<Rect> {
let r = rect_of(i);
if self.draws_nothing(r) {
return None;
}
let fin = |x: f32, d: f32| if x.is_finite() { x } else { d };
// Looping styles settle on one pose under reduced motion, and fold large times to keep f32 precision.
i.t[0] = if rm { CALM_T } else { cpu::fold_t(time) };
i.t[2] = self.style.index() as f32;
i.aux = [self.border, self.intensity.min(1.0), 0.0, 0.0];
match self.style {
FillStyle::LiquidMetal(p) => {
i.c0 = p.tint.v4();
i.c1 = p.light.v4();
i.p0 = [fin(p.flow, 0.0).max(0.0), fin(p.scale, 100.0).max(1.0), fin(p.speed, 0.0), fin(p.bevel, 0.0).max(0.0)];
i.p1 = [fin(p.dome, 0.0), fin(p.angle, 0.0), fin(p.iridescence, 0.0).max(0.0), fin(p.contrast, 1.0).max(0.1)];
i.p2 = [(p.anchor == FillAnchor::Element) as u32 as f32, 0.0, 0.0, 0.0];
}
FillStyle::MeshGradient(p) => {
i.p0 = [p.drift, p.speed, p.sharpness.clamp(0.1, 8.0), p.warp];
}
FillStyle::Dither(p) => {
let pat = match p.pattern {
DitherPattern::Bayer2 => 1.0,
DitherPattern::Bayer4 => 2.0,
DitherPattern::Bayer8 => 3.0,
DitherPattern::BlueNoise => 4.0,
DitherPattern::White => 5.0,
};
i.p0 = [pat, p.input.code(), p.pixel.max(0.25), p.angle];
i.p1 = [p.scale.max(1.0), p.speed, p.bias, p.contrast];
}
FillStyle::GrainGradient(p) => {
let kind = match p.kind {
GradientKind::Linear => 0.0,
GradientKind::Radial => 1.0,
GradientKind::Conic => 2.0,
};
i.p0 = [kind, p.angle, p.center[0], p.center[1]];
i.p1 = [p.amount, p.size.max(0.25), p.mono as u32 as f32, if rm { 0.0 } else { p.fps }];
}
FillStyle::FlutedGlass(p) => {
i.c0 = p.tint.v4();
i.p0 = [p.rib.max(1.0), p.angle, p.refraction, p.frost];
i.p1 = [p.dispersion, p.highlight, p.tint_amount, 0.0];
}
FillStyle::Metaballs(p) => {
i.c0 = p.base.v4();
i.p0 = [p.count.clamp(1, 8) as f32, p.size, p.speed, p.gloss];
}
FillStyle::Swirl(p) => {
i.p0 = [p.scale.max(1.0), p.speed, p.twist, p.warp];
}
FillStyle::Voronoi(p) => {
i.c0 = p.edge_color.v4();
i.p0 = [p.scale.max(2.0), p.speed, p.edge, p.depth];
}
FillStyle::Waves(p) => {
i.p0 = [p.amplitude, p.frequency, p.speed, p.angle];
i.p1 = [p.softness, 0.0, 0.0, 0.0];
}
FillStyle::Halftone(p) => {
i.c0 = p.ink.v4();
i.c1 = p.base.v4();
i.p0 = [0.0, p.input.code(), p.cell.max(1.0), p.ramp_angle];
i.p1 = [p.scale.max(1.0), p.speed, p.bias, p.contrast];
i.p2 = [p.angle, 0.0, 0.0, 0.0];
}
FillStyle::Plastic(p) => {
i.c0 = p.color.v4();
i.p0 = [fin(p.roughness, 0.15).clamp(0.0, 1.0), fin(p.dome, 0.0), fin(p.bevel, 0.0).max(0.0), fin(p.angle, 0.0)];
}
}
Some(r.inflate(1.0))
}
/// Per-frame tables: colour stops (linear, then OKLab; mesh points ride in `w`), metaball
/// paths and the blue-noise tile. `xf` = (stops offset, stop count, extra offset, extra count).
pub(crate) fn tables(&self, i: &mut InstRaw, rect: Rect, t: f32, seed: u32, data: &mut Vec<[f32; 4]>) {
let stops = |data: &mut Vec<[f32; 4]>, s: &Stops, pts: Option<&[[f32; 2]]>| -> [f32; 2] {
let first = data.len() as f32;
for (k, c) in s.as_slice().iter().enumerate() {
let p = pts.map_or([0.0, 0.0], |v| v[k]);
let l = oklab(*c);
data.push([c.0[0], c.0[1], c.0[2], p[0]]);
data.push([l[0], l[1], l[2], p[1]]);
}
[first, s.len() as f32]
};
let [f, n] = match &self.style {
FillStyle::MeshGradient(p) => {
let pts = cpu::mesh_points(p, t, seed);
stops(data, &p.colors, Some(&pts))
}
FillStyle::Dither(p) => stops(data, &p.colors, None),
FillStyle::GrainGradient(p) => stops(data, &p.colors, None),
FillStyle::Metaballs(p) => stops(data, &p.colors, None),
FillStyle::Swirl(p) => stops(data, &p.colors, None),
FillStyle::Voronoi(p) => stops(data, &p.colors, None),
FillStyle::Waves(p) => stops(data, &p.colors, None),
_ => {
// Glass leaves `xf` to `blur_backdrop`, which marks the frost pyramid there.
return;
}
};
i.xf = [f, n, 0.0, 0.0];
match &self.style {
FillStyle::Dither(p) if p.pattern == DitherPattern::BlueNoise => {
i.xf[2] = data.len() as f32;
i.xf[3] = cpu::BLUE_N as f32;
data.extend_from_slice(cpu::blue_noise());
}
FillStyle::Metaballs(p) => {
i.xf[2] = data.len() as f32;
i.xf[3] = p.count.clamp(1, 8) as f32;
cpu::metaballs(p, rect, t, seed, data);
}
_ => {}
}
}
}
fn rect_of(i: &InstRaw) -> Rect {
Rect::new(i.rect[0], i.rect[1], i.rect[2], i.rect[3])
}
+541
View File
@@ -0,0 +1,541 @@
//! Per-style fill parameter structs, presets, and catalog parameter tables.
use std::f32::consts::PI;
use super::{DitherPattern, FillAnchor, FillInput, GradientKind, MAX_STOPS, Stops};
use crate::catalog::*;
use crate::{Rgb, rgb};
/// Polished metal reflecting a studio: a soft overhead key light, a strip light, a bright sky
/// that falls to a hard horizon over a dark floor. The face is gently domed so the horizon
/// crosses it, the rim rolls off over `bevel`, and the surface flows like liquid.
/// As a border (`.border(w)`) it is a round tube.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct LiquidMetalParams {
/// Reflectance at normal incidence: near white for chrome, warm for gold.
pub tint: Rgb,
/// The studio lights' colour.
pub light: Rgb,
/// How far the surface ripples (0 = a still, polished slab).
pub flow: f32,
/// Ripple size, pt.
pub scale: f32,
pub speed: f32,
/// Width of the rolled rim, pt.
pub bevel: f32,
/// How domed the face is: 0 flat (one reflection everywhere), 1 strongly curved.
pub dome: f32,
/// Tilt of the studio around the view axis, radians.
pub angle: f32,
/// Thin-film colour where the surface bends hardest.
pub iridescence: f32,
/// 1 = studio as lit; higher deepens the floor and sharpens the lights.
pub contrast: f32,
/// Where the ripples are pinned: `World` (default) flows one surface across neighbouring
/// shapes; `Element` gives every shape of the same size its own identical copy, so a row of
/// keys matches.
pub anchor: FillAnchor,
}
impl Default for LiquidMetalParams {
fn default() -> Self {
LiquidMetalParams::chrome()
}
}
impl LiquidMetalParams {
pub fn chrome() -> Self {
LiquidMetalParams {
tint: rgb(0xe9ecf0),
light: rgb(0xffffff),
flow: 0.6,
scale: 100.0,
speed: 0.35,
bevel: 14.0,
dome: 0.55,
angle: -0.12,
iridescence: 0.08,
contrast: 1.0,
anchor: FillAnchor::World,
}
}
/// `LiquidMetalParams::chrome().anchor(FillAnchor::Element)`.
pub fn anchor(mut self, anchor: FillAnchor) -> Self {
self.anchor = anchor;
self
}
pub fn gold() -> Self {
LiquidMetalParams { tint: rgb(0xf3c56b), light: rgb(0xfff4dc), iridescence: 0.0, ..Self::chrome() }
}
pub fn rose() -> Self {
LiquidMetalParams { tint: rgb(0xf2b7a2), light: rgb(0xfff0ea), iridescence: 0.05, ..Self::chrome() }
}
pub fn gunmetal() -> Self {
LiquidMetalParams { tint: rgb(0x8d949e), light: rgb(0xe8f0ff), contrast: 1.35, iridescence: 0.12, ..Self::chrome() }
}
}
params!(LiquidMetalParams {
tint: "Tint" => ParamKind::Color,
light: "Light" => ParamKind::Color,
flow: "Flow" => num(0.0, 1.5, 0.01, Unit::None),
scale: "Scale" => num(16.0, 480.0, 1.0, Unit::Pt),
speed: "Speed" => num(0.0, 2.0, 0.01, Unit::PerSecond),
bevel: "Bevel" => num(0.0, 48.0, 0.5, Unit::Pt),
dome: "Dome" => num(0.0, 1.0, 0.01, Unit::Fraction),
angle: "Angle" => num(-PI, PI, 0.01, Unit::Radians),
iridescence: "Iridescence" => num(0.0, 1.0, 0.01, Unit::Fraction),
contrast: "Contrast" => num(0.5, 2.0, 0.01, Unit::None),
anchor: "Anchor" => ParamKind::Choice(FillAnchor::CHOICES),
});
/// Moulded plastic under one soft light: a diffuse base in `color`, a specular highlight that is
/// small and bright when glossy and broad and faint when matte, the dome's curvature shading, a
/// rim rolled over `bevel` that catches the light, and a faint reflection at grazing angles. The
/// face's flat centre shows `color`. Uses liquid metal's dome and bevel; it never animates.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct PlasticParams {
pub color: Rgb,
/// 0 polished, 1 matte: the highlight's size and softness.
pub roughness: f32,
/// How curved the face is: positive bulges, negative is dished like a keycap's top.
pub dome: f32,
/// Width of the rolled rim, pt.
pub bevel: f32,
/// Where the light comes from, radians around the view axis: 0 from above, negative from the left.
pub angle: f32,
}
impl Default for PlasticParams {
fn default() -> Self {
PlasticParams::glossy()
}
}
impl PlasticParams {
pub fn glossy() -> Self {
PlasticParams { color: rgb(0xece8de), roughness: 0.15, dome: 0.35, bevel: 6.0, angle: -0.5 }
}
pub fn matte() -> Self {
PlasticParams { color: rgb(0x2e3036), roughness: 0.8, ..Self::glossy() }
}
/// A matte face dished like a keycap's top.
pub fn dished() -> Self {
PlasticParams { color: rgb(0xd8d2c4), roughness: 0.7, dome: -0.45, ..Self::glossy() }
}
}
params!(PlasticParams {
color: "Colour" => ParamKind::Color,
roughness: "Roughness" => num(0.05, 1.0, 0.01, Unit::Fraction),
dome: "Dome" => num(-1.0, 1.0, 0.01, Unit::None),
bevel: "Bevel" => num(0.0, 48.0, 0.5, Unit::Pt),
angle: "Light angle" => num(-PI, PI, 0.01, Unit::Radians),
});
/// Colours pinned to points that drift slowly, blended smoothly in OKLab.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MeshGradientParams {
pub colors: Stops,
/// Each colour's rest point, 0..1 across the shape's rect.
pub points: [[f32; 2]; MAX_STOPS],
/// How far the points wander from rest, as a fraction of the rect.
pub drift: f32,
pub speed: f32,
/// 1 = wide soft blends; higher keeps each colour to its own region.
pub sharpness: f32,
/// Organic bend of the blend field.
pub warp: f32,
}
const MESH_POINTS: [[f32; 2]; MAX_STOPS] = [[0.12, 0.18], [0.86, 0.12], [0.5, 0.55], [0.14, 0.9], [0.9, 0.86], [0.62, 0.3]];
impl Default for MeshGradientParams {
fn default() -> Self {
MeshGradientParams::dusk()
}
}
impl MeshGradientParams {
pub fn dusk() -> Self {
MeshGradientParams { colors: Stops::hex(&[0x2b1b5a, 0xff6f91, 0xffc46b, 0x6a4cff, 0xff9a5a]), points: MESH_POINTS, drift: 0.12, speed: 0.25, sharpness: 1.6, warp: 0.35 }
}
pub fn lagoon() -> Self {
MeshGradientParams { colors: Stops::hex(&[0x0b3d5c, 0x2ec4b6, 0xcbf3f0, 0x1b6ca8]), ..Self::dusk() }
}
pub fn orchid() -> Self {
MeshGradientParams { colors: Stops::hex(&[0xf9d5e5, 0xc06c84, 0x6c5b7b, 0xf8b195, 0x355c7d, 0xeeac99]), sharpness: 2.0, ..Self::dusk() }
}
pub fn graphite() -> Self {
MeshGradientParams { colors: Stops::hex(&[0x15171c, 0x3a3f4b, 0x8a93a3, 0x22262e]), drift: 0.08, warp: 0.2, ..Self::dusk() }
}
}
params!(MeshGradientParams {
colors: "Colours" => ParamKind::Colors { min: 2, max: MAX_STOPS },
points: "Points" => ParamKind::Points { max: MAX_STOPS },
drift: "Drift" => num(0.0, 0.4, 0.01, Unit::Fraction),
speed: "Speed" => num(0.0, 2.0, 0.01, Unit::PerSecond),
sharpness: "Sharpness" => num(0.5, 4.0, 0.01, Unit::None),
warp: "Warp" => num(0.0, 1.0, 0.01, Unit::None),
});
/// Ordered dithering of a tone into a palette, in square pixels anchored to the shape.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct DitherParams {
pub pattern: DitherPattern,
pub input: FillInput,
/// Dark to light. Two colours is one-bit; more is a palette.
pub colors: Stops,
/// Size of one dither pixel, pt.
pub pixel: f32,
/// Linear input: ramp direction, radians.
pub angle: f32,
/// Noise input: feature size, pt.
pub scale: f32,
/// Noise input: drift speed.
pub speed: f32,
/// Shifts the tone before quantising (-1..1).
pub bias: f32,
pub contrast: f32,
}
impl Default for DitherParams {
fn default() -> Self {
DitherParams::bayer()
}
}
impl DitherParams {
/// One-bit Bayer 4×4 over a diagonal ramp.
pub fn bayer() -> Self {
DitherParams { pattern: DitherPattern::Bayer4, input: FillInput::Linear, colors: Stops::hex(&[0x14161c, 0xe8e4d8]), pixel: 2.0, angle: 0.6, scale: 90.0, speed: 0.2, bias: 0.0, contrast: 1.0 }
}
/// Four greens, Bayer 8×8, over drifting noise.
pub fn handheld() -> Self {
DitherParams { pattern: DitherPattern::Bayer8, input: FillInput::Noise, colors: Stops::hex(&[0x0f380f, 0x306230, 0x8bac0f, 0x9bbc0f]), pixel: 3.0, ..Self::bayer() }
}
/// Blue-noise one-bit over a radial ramp.
pub fn grain() -> Self {
DitherParams { pattern: DitherPattern::BlueNoise, input: FillInput::Radial, colors: Stops::hex(&[0x1b1530, 0xffd7a8]), pixel: 1.0, ..Self::bayer() }
}
/// Re-tones whatever is behind the layer in two inks.
pub fn backdrop() -> Self {
DitherParams { pattern: DitherPattern::Bayer4, input: FillInput::Backdrop, colors: Stops::hex(&[0x101418, 0xf2efe6]), pixel: 2.0, contrast: 1.35, bias: -0.1, ..Self::bayer() }
}
}
params!(DitherParams {
pattern: "Pattern" => ParamKind::Choice(DitherPattern::CHOICES),
input: "Input" => ParamKind::Choice(FillInput::CHOICES),
colors: "Colours" => ParamKind::Colors { min: 2, max: MAX_STOPS },
pixel: "Pixel" => num(0.5, 16.0, 0.5, Unit::Pt),
angle: "Angle" => num(-PI, PI, 0.01, Unit::Radians),
scale: "Noise scale" => num(8.0, 400.0, 1.0, Unit::Pt),
speed: "Speed" => num(0.0, 2.0, 0.01, Unit::PerSecond),
bias: "Bias" => num(-1.0, 1.0, 0.01, Unit::None),
contrast: "Contrast" => num(0.2, 4.0, 0.01, Unit::None),
});
/// A linear, radial or conic gradient whose colours scatter into film grain. A conic gradient
/// loops: its last colour blends back into the first.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct GrainGradientParams {
pub kind: GradientKind,
pub colors: Stops,
/// Linear: direction; conic: start, radians.
pub angle: f32,
/// Radial and conic centre, 0..1 across the rect.
pub center: [f32; 2],
/// How far grain scatters the gradient and its brightness (0..1).
pub amount: f32,
/// Grain size, pt.
pub size: f32,
/// One grain value for all channels; off gives colour grain.
pub mono: bool,
/// Grain re-rolls per second (0 = static).
pub fps: f32,
}
impl Default for GrainGradientParams {
fn default() -> Self {
GrainGradientParams::ember()
}
}
impl GrainGradientParams {
pub fn ember() -> Self {
GrainGradientParams { kind: GradientKind::Linear, colors: Stops::hex(&[0x1a0b2e, 0xc2185b, 0xff8a3d, 0xffe1a8]), angle: 1.2, center: [0.5, 0.5], amount: 0.4, size: 0.5, mono: true, fps: 12.0 }
}
pub fn halo() -> Self {
GrainGradientParams { kind: GradientKind::Radial, colors: Stops::hex(&[0xe9f1ff, 0x7aa2ff, 0x2a2f7a, 0x0b0d1f]), center: [0.5, 0.35], ..Self::ember() }
}
pub fn sweep() -> Self {
GrainGradientParams { kind: GradientKind::Conic, colors: Stops::hex(&[0x00c2a8, 0x3a86ff, 0x8338ec, 0xff006e, 0xffbe0b]), angle: -1.57, mono: false, ..Self::ember() }
}
}
params!(GrainGradientParams {
kind: "Kind" => ParamKind::Choice(GradientKind::CHOICES),
colors: "Colours" => ParamKind::Colors { min: 2, max: MAX_STOPS },
angle: "Angle" => num(-PI, PI, 0.01, Unit::Radians),
center: "Centre" => ParamKind::Point,
amount: "Grain" => num(0.0, 1.0, 0.01, Unit::Fraction),
size: "Grain size" => num(0.5, 8.0, 0.25, Unit::Pt),
mono: "Mono" => ParamKind::Toggle,
fps: "Grain rate" => num(0.0, 30.0, 1.0, Unit::PerSecond),
});
/// Reeded glass over the backdrop: parallel convex ribs, each showing a squeezed, flipped strip of
/// what is behind.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FlutedGlassParams {
/// Rib width, pt.
pub rib: f32,
/// Rib direction, radians (0 = vertical ribs).
pub angle: f32,
/// How far each rib bends the image sideways, pt.
pub refraction: f32,
/// 0..1: clear to frosted (reads the blurred backdrop like a frosted lens).
pub frost: f32,
/// Colour split toward the rib edges.
pub dispersion: f32,
/// Sheen along each rib's lit side.
pub highlight: f32,
pub tint: Rgb,
pub tint_amount: f32,
}
impl Default for FlutedGlassParams {
fn default() -> Self {
FlutedGlassParams::reeded()
}
}
impl FlutedGlassParams {
pub fn reeded() -> Self {
FlutedGlassParams { rib: 14.0, angle: 0.0, refraction: 9.0, frost: 0.0, dispersion: 0.15, highlight: 0.5, tint: rgb(0xffffff), tint_amount: 0.0 }
}
pub fn fine() -> Self {
FlutedGlassParams { rib: 6.0, refraction: 5.0, ..Self::reeded() }
}
pub fn frosted() -> Self {
FlutedGlassParams { frost: 0.6, ..Self::reeded() }
}
pub fn wide() -> Self {
FlutedGlassParams { rib: 32.0, refraction: 18.0, dispersion: 0.25, ..Self::reeded() }
}
}
params!(FlutedGlassParams {
rib: "Rib width" => num(2.0, 64.0, 0.5, Unit::Pt),
angle: "Angle" => num(-PI, PI, 0.01, Unit::Radians),
refraction: "Refraction" => num(0.0, 40.0, 0.5, Unit::Pt),
frost: "Frost" => num(0.0, 1.0, 0.01, Unit::Fraction),
dispersion: "Dispersion" => num(0.0, 1.0, 0.01, Unit::Fraction),
highlight: "Highlight" => num(0.0, 1.0, 0.01, Unit::Fraction),
tint: "Tint" => ParamKind::Color,
tint_amount: "Tint amount" => num(0.0, 1.0, 0.01, Unit::Fraction),
});
/// Glossy blobs that drift and merge, over a base colour.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct MetaballParams {
/// Blob colours (each blob takes one in turn).
pub colors: Stops,
pub base: Rgb,
pub count: u32,
/// Blob radius as a fraction of the rect's shorter side.
pub size: f32,
pub speed: f32,
/// Sheen on the blobs.
pub gloss: f32,
}
impl Default for MetaballParams {
fn default() -> Self {
MetaballParams::lava()
}
}
impl MetaballParams {
pub fn lava() -> Self {
MetaballParams { colors: Stops::hex(&[0xff5e3a, 0xff9a3c, 0xff2d6f]), base: rgb(0x1a0f1f), count: 6, size: 0.2, speed: 0.4, gloss: 0.5 }
}
pub fn mint() -> Self {
MetaballParams { colors: Stops::hex(&[0x7cf2c4, 0x37d0e8, 0xb8f36b]), base: rgb(0x0d1b1e), ..Self::lava() }
}
}
params!(MetaballParams {
colors: "Colours" => ParamKind::Colors { min: 1, max: MAX_STOPS },
base: "Base" => ParamKind::Color,
count: "Count" => ParamKind::Count { min: 1, max: 8 },
size: "Size" => num(0.05, 0.5, 0.01, Unit::Fraction),
speed: "Speed" => num(0.0, 2.0, 0.01, Unit::PerSecond),
gloss: "Gloss" => num(0.0, 1.0, 0.01, Unit::Fraction),
});
/// Colours stirred into a slow swirl (warped noise through a ramp).
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct SwirlParams {
pub colors: Stops,
/// Feature size, pt.
pub scale: f32,
pub speed: f32,
/// Twist around the centre, turns at the middle.
pub twist: f32,
/// How much the noise folds into itself.
pub warp: f32,
}
impl Default for SwirlParams {
fn default() -> Self {
SwirlParams::ink()
}
}
impl SwirlParams {
pub fn ink() -> Self {
SwirlParams { colors: Stops::hex(&[0x0b1026, 0x3b2c85, 0x2fb3c9, 0xf2f6ff]), scale: 140.0, speed: 0.2, twist: 0.6, warp: 1.0 }
}
pub fn marble() -> Self {
SwirlParams { colors: Stops::hex(&[0xf4f1ea, 0xc9c2b4, 0x6f6a61, 0xf4f1ea]), scale: 90.0, twist: 0.3, warp: 1.6, ..Self::ink() }
}
}
params!(SwirlParams {
colors: "Colours" => ParamKind::Colors { min: 2, max: MAX_STOPS },
scale: "Scale" => num(16.0, 480.0, 1.0, Unit::Pt),
speed: "Speed" => num(0.0, 2.0, 0.01, Unit::PerSecond),
twist: "Twist" => num(-2.0, 2.0, 0.01, Unit::None),
warp: "Warp" => num(0.0, 2.5, 0.01, Unit::None),
});
/// Cells around drifting seed points, with optional seams.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct VoronoiParams {
pub colors: Stops,
/// Seam colour.
pub edge_color: Rgb,
/// Cell size, pt.
pub scale: f32,
pub speed: f32,
/// Seam width, pt (0 = none).
pub edge: f32,
/// Shading toward each cell's rim (0 = flat cells).
pub depth: f32,
}
impl Default for VoronoiParams {
fn default() -> Self {
VoronoiParams::cells()
}
}
impl VoronoiParams {
pub fn cells() -> Self {
VoronoiParams { colors: Stops::hex(&[0x1f2a44, 0x2c3e66, 0x3d5a8a, 0x5577b0]), edge_color: rgb(0x0b0f1a), scale: 36.0, speed: 0.25, edge: 1.5, depth: 0.4 }
}
pub fn stained() -> Self {
VoronoiParams { colors: Stops::hex(&[0xd7263d, 0xf46036, 0x2e294e, 0x1b998b, 0xc5d86d]), edge_color: rgb(0x111111), scale: 20.0, edge: 2.0, depth: 0.25, ..Self::cells() }
}
}
params!(VoronoiParams {
colors: "Colours" => ParamKind::Colors { min: 1, max: MAX_STOPS },
edge_color: "Seam colour" => ParamKind::Color,
scale: "Cell size" => num(6.0, 200.0, 1.0, Unit::Pt),
speed: "Speed" => num(0.0, 2.0, 0.01, Unit::PerSecond),
edge: "Seam" => num(0.0, 8.0, 0.25, Unit::Pt),
depth: "Depth" => num(0.0, 1.0, 0.01, Unit::Fraction),
});
/// Layered bands of colour with rolling, swaying edges.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct WaveParams {
/// One band per colour, back to front.
pub colors: Stops,
/// Edge height, as a fraction of the rect.
pub amplitude: f32,
/// Crests across the rect.
pub frequency: f32,
pub speed: f32,
/// Direction the bands stack along, radians (0 = top to bottom).
pub angle: f32,
/// Edge softness, as a fraction of the rect.
pub softness: f32,
}
impl Default for WaveParams {
fn default() -> Self {
WaveParams::sea()
}
}
impl WaveParams {
pub fn sea() -> Self {
WaveParams { colors: Stops::hex(&[0xbfe7ff, 0x5fb3e8, 0x2a7bbf, 0x154a85, 0x0a2649]), amplitude: 0.05, frequency: 1.6, speed: 0.4, angle: 0.0, softness: 0.006 }
}
pub fn dunes() -> Self {
WaveParams { colors: Stops::hex(&[0xfde6c4, 0xf4b77c, 0xe08a4f, 0xb35a3a, 0x6e3226]), amplitude: 0.07, frequency: 1.1, speed: 0.15, ..Self::sea() }
}
}
params!(WaveParams {
colors: "Colours" => ParamKind::Colors { min: 2, max: MAX_STOPS },
amplitude: "Amplitude" => num(0.0, 0.25, 0.005, Unit::Fraction),
frequency: "Frequency" => num(0.2, 6.0, 0.05, Unit::None),
speed: "Speed" => num(0.0, 2.0, 0.01, Unit::PerSecond),
angle: "Angle" => num(-PI, PI, 0.01, Unit::Radians),
softness: "Softness" => num(0.0, 0.1, 0.001, Unit::Fraction),
});
/// Print-style dots on a rotated grid, sized by a tone.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct HalftoneParams {
pub input: FillInput,
pub ink: Rgb,
/// The colour between the dots.
pub base: Rgb,
/// Dot pitch, pt.
pub cell: f32,
/// Screen angle, radians.
pub angle: f32,
/// Linear input: ramp direction, radians.
pub ramp_angle: f32,
/// Noise input: feature size, pt.
pub scale: f32,
pub speed: f32,
pub bias: f32,
pub contrast: f32,
}
impl Default for HalftoneParams {
fn default() -> Self {
HalftoneParams::print()
}
}
impl HalftoneParams {
pub fn print() -> Self {
HalftoneParams { input: FillInput::Radial, ink: rgb(0x1b1b1f), base: rgb(0xf1ece1), cell: 6.0, angle: 0.785, ramp_angle: 0.6, scale: 90.0, speed: 0.2, bias: 0.0, contrast: 1.0 }
}
/// Re-screens whatever is behind the layer.
pub fn backdrop() -> Self {
HalftoneParams { input: FillInput::Backdrop, cell: 4.0, ..Self::print() }
}
}
params!(HalftoneParams {
input: "Input" => ParamKind::Choice(FillInput::CHOICES),
ink: "Ink" => ParamKind::Color,
base: "Base" => ParamKind::Color,
cell: "Dot pitch" => num(2.0, 32.0, 0.5, Unit::Pt),
angle: "Screen angle" => num(-PI, PI, 0.01, Unit::Radians),
ramp_angle: "Ramp angle" => num(-PI, PI, 0.01, Unit::Radians),
scale: "Noise scale" => num(8.0, 400.0, 1.0, Unit::Pt),
speed: "Speed" => num(0.0, 2.0, 0.01, Unit::PerSecond),
bias: "Bias" => num(-1.0, 1.0, 0.01, Unit::None),
contrast: "Contrast" => num(0.2, 4.0, 0.01, Unit::None),
});
+218
View File
@@ -0,0 +1,218 @@
use super::pack::oklab;
use super::*;
fn card() -> Shape {
Shape::rounded(100.0, 100.0, 240.0, 140.0, 18.0)
}
fn every_preset() -> impl Iterator<Item = (&'static StyleInfo, &'static Preset)> {
fill_styles().iter().flat_map(|s| s.presets.iter().map(move |p| (s, p)))
}
fn packed(l: &FxLayer) -> Option<(InstRaw, Vec<[f32; 4]>)> {
let (_, mut i, _) = l.pack()?;
let mut data = Vec::new();
l.fill(&mut i, &mut data);
Some((i, data))
}
fn bits(i: &InstRaw) -> Vec<u32> {
bytemuck::bytes_of(i).chunks(4).map(|c| u32::from_le_bytes([c[0], c[1], c[2], c[3]])).collect()
}
#[test]
fn idle_fills_are_culled() {
for (s, p) in every_preset() {
assert!(Fx::fill(p.fill().intensity(0.0)).on(card()).pack().is_none(), "{} {}", s.id, p.id);
assert!(Fx::fill(p.fill().intensity(f32::NAN)).on(card()).pack().is_none(), "{} {}", s.id, p.id);
assert!(Fx::fill(p.fill().border(-1.0)).on(card()).pack().is_none());
assert!(Fx::fill(p.fill().border(f32::NAN)).on(card()).pack().is_none());
assert!(Fx::fill(p.fill().border(f32::INFINITY)).on(card()).pack().is_none());
assert!(Fx::fill(p.fill()).on(Shape::rounded(10.0, 10.0, 0.0, 40.0, 0.0)).pack().is_none(), "{} {}: zero width", s.id, p.id);
assert!(Fx::fill(p.fill()).on(Shape::rounded(10.0, 10.0, 40.0, 0.0, 0.0)).pack().is_none(), "{} {}: zero height", s.id, p.id);
assert!(Fx::fill(p.fill()).on(card()).pack().is_some());
}
}
#[test]
fn reduced_motion_holds_one_pose() {
for (s, p) in every_preset() {
let l = Fx::fill(p.fill()).on(card()).seed(3).reduced(true);
assert!(!l.is_animating(), "{} {}", s.id, p.id);
let (a, da) = packed(&l.at(0.5)).unwrap();
let (b, db) = packed(&l.at(7.25)).unwrap();
assert_eq!(bits(&a), bits(&b), "{} {}: same instance at any time", s.id, p.id);
assert_eq!(da, db, "{} {}: same tables at any time", s.id, p.id);
}
}
#[test]
fn invisible_fills_never_animate() {
for (s, p) in every_preset() {
let off = Fx::fill(FillParams { intensity: 0.0, ..p.fill() }).on(card()).seed(11);
assert!(!off.is_animating() && off.pack().is_none(), "{} {}", s.id, p.id);
assert!(!Fx::fill(p.fill()).on(card()).opacity(0.0).is_animating(), "{} {}", s.id, p.id);
}
assert!(every_preset().any(|(_, p)| p.fill().animates()));
}
#[test]
fn moving_fills_animate_and_are_deterministic() {
for (s, p) in every_preset() {
let l = Fx::fill(p.fill()).on(card()).seed(11);
assert_eq!(l.is_animating(), p.fill().animates(), "{} {}", s.id, p.id);
let (a, da) = packed(&l.at(1.5)).unwrap();
let (b, db) = packed(&l.at(1.5)).unwrap();
assert_eq!(bits(&a), bits(&b));
assert_eq!(da, db);
assert!(da.iter().flatten().all(|v| v.is_finite()), "{} {}", s.id, p.id);
}
let moving = |s: FillStyle| FillParams::new(s).animates();
assert!(moving(LiquidMetalParams::gold().into()));
assert!(!moving(LiquidMetalParams { flow: 0.0, ..LiquidMetalParams::gold() }.into()));
assert!(!moving(FlutedGlassParams::reeded().into()));
assert!(!moving(DitherParams::bayer().into()), "a ramp holds still");
assert!(!moving(WaveParams { amplitude: 0.0, ..WaveParams::sea() }.into()), "flat waves hold still");
}
#[test]
fn large_times_fold_without_precision_loss_or_jump() {
assert_eq!(cpu::fold_t(0.0), 0.0);
assert_eq!(cpu::fold_t(1.2), 1.2);
assert_eq!(cpu::fold_t(512.0), 512.0);
for t in [1e4f32, 1e5, -1e5] {
let a = cpu::fold_t(t);
let b = cpu::fold_t(t + 1.0 / 60.0);
assert!((0.0..=512.0).contains(&a) && (0.0..=512.0).contains(&b), "{t} -> {a}");
assert!((b - a).abs() > 1e-3 && (b - a).abs() < 0.05, "smooth step at {t}: {a} -> {b}");
}
for (s, p) in every_preset() {
let l = Fx::fill(p.fill()).on(card()).seed(7);
let (i0, d0) = packed(&l.at(1e5)).unwrap();
let (i1, d1) = packed(&l.at(1e5 + 0.25)).unwrap();
assert!(i0.t[0] >= 0.0 && i0.t[0] <= 512.0, "{} {}", s.id, p.id);
assert!(d0.iter().flatten().all(|v| v.is_finite()), "{} {}", s.id, p.id);
if p.fill().animates() {
assert!(i0.t[0] != i1.t[0] || d0 != d1, "{} {} still moves at t = 1e5", s.id, p.id);
}
}
}
#[test]
fn backdrop_and_placement_follow_the_input() {
for (s, p) in every_preset() {
let f = p.fill();
if f.needs_backdrop() {
assert!(s.reads_backdrop, "{} {}", s.id, p.id);
}
let l = Fx::fill(f).on(card());
assert_eq!(l.fx.needs_backdrop(), f.needs_backdrop());
assert_eq!(l.place, if f.needs_backdrop() { Place::Over } else { Place::Under });
assert_eq!(l.fx.cost().backdrop, f.needs_backdrop());
}
assert!(Fx::fill(DitherParams::backdrop()).needs_backdrop());
assert!(!Fx::fill(DitherParams::bayer()).needs_backdrop());
}
#[test]
fn element_anchor_only_moves_the_anchor_slot() {
assert_eq!(LiquidMetalParams::default().anchor, FillAnchor::World);
let world = packed(&Fx::fill(LiquidMetalParams::gold()).on(card()).at(3.0)).unwrap().0;
let element = packed(&Fx::fill(LiquidMetalParams::gold().anchor(FillAnchor::Element)).on(card()).at(3.0)).unwrap().0;
assert_eq!(world.p2, [0.0; 4]);
assert_eq!(element.p2, [1.0, 0.0, 0.0, 0.0]);
assert_eq!(bits(&InstRaw { p2: [0.0; 4], ..element }), bits(&world));
}
#[test]
fn plastic_holds_still() {
for p in [PlasticParams::glossy(), PlasticParams::matte(), PlasticParams::dished()] {
assert!(!FillParams::from(p).animates());
assert!(!Fx::fill(p).on(card()).at(2.0).is_animating());
assert_eq!(Fx::fill(p).cost(), FxCost { passes: 1, samples: 0, alu: 0, backdrop: false, source: false });
}
let non_finite_plastic = PlasticParams { roughness: f32::NAN, dome: f32::INFINITY, bevel: f32::NEG_INFINITY, angle: f32::NAN, ..PlasticParams::glossy() };
let non_finite_metal = LiquidMetalParams {
flow: f32::NAN,
scale: f32::NAN,
speed: f32::INFINITY,
bevel: f32::NAN,
dome: f32::NEG_INFINITY,
angle: f32::NAN,
iridescence: f32::INFINITY,
contrast: f32::NAN,
..LiquidMetalParams::chrome()
};
for fx in [Fx::fill(non_finite_plastic), Fx::fill(non_finite_metal)] {
let (i, _) = packed(&fx.on(card()).at(1.0)).unwrap();
assert!(i.p0.iter().chain(&i.p1).chain(&i.p2).all(|v| v.is_finite()), "{i:?}");
}
}
#[test]
fn mesh_points_wander_within_drift() {
let p = MeshGradientParams::dusk();
for k in 0..40 {
let pts = cpu::mesh_points(&p, k as f32 * 0.37, 5);
for (q, r) in pts.iter().zip(p.points) {
assert!((q[0] - r[0]).abs() <= p.drift * 1.5 && (q[1] - r[1]).abs() <= p.drift * 1.5, "{q:?} {r:?}");
}
}
let still = MeshGradientParams { drift: 0.0, ..p };
assert_eq!(cpu::mesh_points(&still, 3.0, 5), p.points);
}
#[test]
fn blue_noise_tile_ranks_every_pixel_once() {
let t = cpu::blue_noise();
assert_eq!(t.len() * 4, cpu::BLUE_N * cpu::BLUE_N);
let mut v: Vec<f32> = t.iter().flatten().copied().collect();
v.sort_by(f32::total_cmp);
for (k, x) in v.iter().enumerate() {
assert!((x - (k as f32 + 0.5) / v.len() as f32).abs() < 1e-6);
}
// Blue: 2x2 box means stay near 0.5 (white noise would spread them far wider).
let n = cpu::BLUE_N;
let at = |x: usize, y: usize| t[(y % n * n + x % n) / 4][(y % n * n + x % n) % 4];
let worst = (0..n * n).map(|i| (i % n, i / n)).map(|(x, y)| ((at(x, y) + at(x + 1, y) + at(x, y + 1) + at(x + 1, y + 1)) / 4.0 - 0.5).abs()).fold(0.0f32, f32::max);
assert!(worst < 0.36, "{worst}");
}
#[test]
fn oklab_of_white_and_grey_is_neutral() {
let w = oklab(Rgb([1.0; 3]));
assert!((w[0] - 1.0).abs() < 1e-3 && w[1].abs() < 1e-3 && w[2].abs() < 1e-3, "{w:?}");
let g = oklab(rgb(0x777777));
assert!(g[1].abs() < 1e-3 && g[2].abs() < 1e-3);
}
#[test]
fn oklab_matches_canonical_for_non_negative_rgb_and_clamps_negative_lms() {
assert_eq!(0.412_221_46f32.to_bits(), 0.412_221_47f32.to_bits());
for v in 0..=255u8 {
let c = rune_motion::srgb_decode(v as f32 / 255.0);
for rgb in [[c, c, c], [c, 0.0, 0.0], [0.0, c, 0.0], [0.0, 0.0, c], [c, 1.0 - c, 0.5 * c]] {
let got = oklab(Rgb(rgb));
let canon = rune_motion::linear_to_oklab(rgb[0], rgb[1], rgb[2]);
assert_eq!(got.map(f32::to_bits), canon.map(f32::to_bits), "{rgb:?}");
}
}
for rgb in [[0.0, 0.0, 0.0], [2.5, 1.2, 0.4], [0.001, 0.999, 0.123]] {
let got = oklab(Rgb(rgb));
let canon = rune_motion::linear_to_oklab(rgb[0], rgb[1], rgb[2]);
assert_eq!(got.map(f32::to_bits), canon.map(f32::to_bits), "{rgb:?}");
}
// Negative inputs can make LMS negative before `cbrt`, where `pack::oklab` clamps LMS to 0.
let neg = [-0.5f32, 0.2, 0.1];
assert_ne!(oklab(Rgb(neg)), rune_motion::linear_to_oklab(neg[0], neg[1], neg[2]));
assert_ne!(oklab(Rgb(neg)), rune_motion::linear_to_oklab(neg[0].max(0.0), neg[1].max(0.0), neg[2].max(0.0)));
}
#[test]
fn stops_keep_order_and_cap() {
let s = Stops::hex(&[0xff0000, 0x00ff00, 0x0000ff]);
assert_eq!(s.len(), 3);
assert_eq!(s.as_slice()[1].hex(), 0x00ff00);
assert_eq!(Stops::hex(&[0; 9]).len(), MAX_STOPS);
assert_eq!(Stops::new(&[]).len(), 1);
}
+497
View File
@@ -0,0 +1,497 @@
//! rune-fx: composable GPU effect layers for Rune (glow, pulses, electricity, fire, motion blur,
//! distortion, shimmer, sparkles, aurora, grain) and fills (liquid metal, mesh gradient, dither,
//! grain gradient, fluted glass and more; see `fill_styles()`).
//!
//! Contract (see README): a layer = effect params + node shape (rounded rect / capsule / circle,
//! in points) + time (Rune's clock) + seed (+ optional source texture, backdrop, motion samples).
//! Output is a premultiplied, linear-light colour layer drawn over or under the node.
//! Invariants for the next agent:
//! - Every effect is a pure function of (pixel, params, time, seed). No hidden state, no RNG.
//! - Intensity 0 or bounds off the viewport => the layer is culled in `prepare` (no draw, no cost).
//! - Speeds never multiply raw time inside a shader without going through `Phase` on the caller side
//! when the speed animates; otherwise the phase jumps (no phase jump on speed change).
#![forbid(unsafe_code)]
mod binds;
mod catalog;
mod cpu;
mod fill;
mod pack;
mod params;
mod pipes;
mod renderer;
mod sim;
#[cfg(test)]
mod tests;
pub use catalog::Choice;
pub use catalog::Param;
pub use catalog::ParamKind;
pub use catalog::Preset;
pub use catalog::StyleInfo;
pub use catalog::Unit;
pub use catalog::Value;
pub use catalog::fill_style;
pub use catalog::fill_styles;
pub use fill::DitherParams;
pub use fill::DitherPattern;
pub use fill::FillAnchor;
pub use fill::FillInput;
pub use fill::FillParams;
pub use fill::FillStyle;
pub use fill::FlutedGlassParams;
pub use fill::GradientKind;
pub use fill::GrainGradientParams;
pub use fill::HalftoneParams;
pub use fill::LiquidMetalParams;
pub use fill::MAX_STOPS;
pub use fill::MeshGradientParams;
pub use fill::MetaballParams;
pub use fill::PlasticParams;
pub use fill::Stops;
pub use fill::SwirlParams;
pub use fill::VoronoiParams;
pub use fill::WaveParams;
pub use params::AuroraParams;
pub use params::BlurMode;
pub use params::DistortParams;
pub use params::ElectricParams;
pub use params::ElectricStyle;
pub use params::FireParams;
pub use params::FireStyle;
pub use params::GlowParams;
pub use params::GlowStyle;
pub use params::GrainParams;
pub use params::Knob;
pub use params::LensParams;
pub use params::MAX_MOTION_SAMPLES;
pub use params::MotionBlurParams;
pub use params::MotionSamples;
pub use params::Pose;
pub use params::PulseParams;
pub use params::PulseStyle;
pub use params::ShimmerParams;
pub use params::SparkleParams;
pub use renderer::FxFrame;
pub use renderer::FxOptions;
pub use renderer::FxRenderer;
pub use renderer::FxStats;
pub use renderer::MaskPyramid;
pub use rune_motion::Rect;
pub(crate) use pack::*;
pub(crate) use params::corners;
// ---------------------------------------------------------------- geometry / colour
/// The node's shape, in points. Capsules and circles are rounded rects with radius = min(w, h) / 2.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Shape {
pub rect: Rect,
pub radius: f32,
}
impl Shape {
pub fn rounded(x: f32, y: f32, w: f32, h: f32, radius: f32) -> Shape {
Shape { rect: Rect::new(x, y, w, h), radius }
}
pub fn capsule(x: f32, y: f32, w: f32, h: f32) -> Shape {
Shape { rect: Rect::new(x, y, w, h), radius: w.min(h) * 0.5 }
}
pub fn circle(cx: f32, cy: f32, r: f32) -> Shape {
Shape { rect: Rect::new(cx - r, cy - r, 2.0 * r, 2.0 * r), radius: r }
}
}
/// Linear-light RGB.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Rgb(pub [f32; 3]);
/// sRGB hex (0xRRGGBB) to linear.
pub fn rgb(hex: u32) -> Rgb {
let f = |s: u32| rune_motion::srgb_decode(((hex >> s) & 0xff) as f32 / 255.0);
Rgb([f(16), f(8), f(0)])
}
impl Rgb {
fn v4(self) -> [f32; 4] {
[self.0[0], self.0[1], self.0[2], 1.0]
}
}
// ---------------------------------------------------------------- time helpers
/// Continuous phase clock for effects whose speed animates: `at(t)` never jumps when `set_speed`
/// is called (no phase jump when a speed changes).
#[derive(Clone, Copy, Debug)]
pub struct Phase {
pub speed: f32,
pub offset: f32,
}
impl Phase {
pub fn new(speed: f32) -> Phase {
Phase { speed, offset: 0.0 }
}
/// Effect time to pass as the layer's time (the shaders multiply by their own nominal rates).
pub fn at(&self, t: f32) -> f32 {
t * self.speed + self.offset
}
pub fn set_speed(&mut self, t: f32, speed: f32) {
self.offset += t * (self.speed - speed);
self.speed = speed;
}
}
/// Heat of a light that is switched on/off: rises over `attack` s, cools exponentially with
/// time constant `cool` s once off. Feed into `GlowParams::heat`: lights cool, never cut.
#[derive(Clone, Copy, Debug)]
pub struct Heat {
pub attack: f32,
pub cool: f32,
switch: Switch,
}
/// How a [`Heat`] was last switched: at time `since`, from heat `from`.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Switch {
/// Cooling exponentially toward 0.
Off { since: f32, from: f32 },
/// Warming over `attack` to 1, then holding there.
On { since: f32, from: f32 },
}
impl Heat {
pub fn new(attack: f32, cool: f32) -> Heat {
Heat { attack, cool, switch: Switch::Off { since: 0.0, from: 0.0 } }
}
pub fn set(&mut self, t: f32, on: bool) {
self.switch = match (self.switch, on) {
(Switch::Off { .. }, true) => Switch::On { since: t, from: self.at(t) },
(Switch::On { .. }, false) => Switch::Off { since: t, from: self.at(t) },
(unchanged, _) => unchanged,
};
}
pub fn at(&self, t: f32) -> f32 {
match self.switch {
Switch::On { since, from } => {
let k = ((t - since).max(0.0) / self.attack()).min(1.0);
let e = 1.0 - (1.0 - k).powi(3);
from + (1.0 - from) * e
}
Switch::Off { since, from } => from * (-(t - since).max(0.0) / self.cool.max(1e-3)).exp(),
}
}
/// Still changing, so worth ticking frames for: warming up, or not yet cooled to nothing.
/// A light that has finished warming holds still.
pub fn is_active(&self, t: f32) -> bool {
match self.switch {
Switch::On { since, .. } => t < since + self.attack(),
Switch::Off { .. } => self.at(t) > 1.0 / 512.0,
}
}
fn attack(&self) -> f32 {
self.attack.max(1e-3)
}
}
/// Overlapping one-shot effects: taps, pings, shockwaves, zaps, sparkle bursts.
///
/// Every `trigger` starts its own instance, which lives out its whole life beside the ones already
/// running, so a quick double tap shows two ripples instead of restarting one. The pool is bounded:
/// when `cap` instances are live, the oldest one fades out over `FADE` seconds instead of being cut.
/// Feed each live instance's opacity to `FxLayer::opacity`.
#[derive(Clone, Debug)]
pub struct OneShots<T> {
cap: usize,
shots: Vec<OneShot<T>>,
count: u32,
}
#[derive(Clone, Copy, Debug)]
pub struct OneShot<T> {
/// Start time on the layer's clock.
pub t0: f32,
pub data: T,
/// Distinct per instance, so overlapping instances don't look identical.
pub seed: u32,
retired: Option<f32>,
}
impl<T: Copy> OneShots<T> {
/// How long a retired instance takes to fade out.
pub const FADE: f32 = 0.16;
pub fn new(cap: usize) -> Self {
OneShots { cap: cap.max(1), shots: Vec::new(), count: 0 }
}
pub fn trigger(&mut self, t: f32, data: T) {
self.shots.retain(|s| s.retired.is_none_or(|r| t - r < Self::FADE));
let active = self.shots.iter().filter(|s| s.retired.is_none()).count();
if active >= self.cap
&& let Some(old) = self.shots.iter_mut().filter(|s| s.retired.is_none()).min_by(|a, b| a.t0.total_cmp(&b.t0))
{
old.retired = Some(t);
}
// Retired instances are fading; under a storm of triggers drop the most faded first.
while self.shots.len() >= self.cap * 2 {
let i = (0..self.shots.len()).min_by(|&a, &b| self.shots[a].retired.unwrap_or(f32::MAX).total_cmp(&self.shots[b].retired.unwrap_or(f32::MAX))).unwrap();
self.shots.remove(i);
}
self.count = self.count.wrapping_add(1);
self.shots.push(OneShot { t0: t, data, seed: cpu::hu(self.count, 0x51ed), retired: None });
}
/// Instances alive at `t` (started less than `life` seconds ago) with their opacity.
pub fn live(&self, t: f32, life: f32) -> impl Iterator<Item = (&OneShot<T>, f32)> {
self.shots.iter().filter_map(move |s| {
let k = match s.retired {
Some(r) => {
let x = ((t - r) / Self::FADE).clamp(0.0, 1.0);
1.0 - x * x * (3.0 - 2.0 * x)
}
None => 1.0,
};
(t - s.t0 < life && k > 0.0).then_some((s, k))
})
}
/// Drop instances that finished (older than `life`) or faded out.
pub fn prune(&mut self, t: f32, life: f32) {
self.shots.retain(|s| t - s.t0 < life && s.retired.is_none_or(|r| t - r < Self::FADE));
}
pub fn is_animating(&self, t: f32, life: f32) -> bool {
self.live(t, life).next().is_some()
}
pub fn clear(&mut self) {
self.shots.clear();
}
}
// ---------------------------------------------------------------- Fx / layers
#[derive(Clone, Copy, Debug)]
pub enum Fx {
Glow(GlowParams),
Pulse(PulseParams),
Electric(ElectricParams),
Fire(FireParams),
Distort(DistortParams),
MotionBlur(MotionBlurParams, MotionSamples),
Shimmer(ShimmerParams),
Sparkles(SparkleParams),
Aurora(AuroraParams),
Grain(GrainParams),
/// A fill style (`FillParams`): paints the shape or a border band inside its edge.
Fill(FillParams),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Place {
Under,
Over,
}
/// Which texture a layer samples (`FxFrame::sources[slot]`) and the rect (pt) it covers.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Source {
pub slot: u32,
pub rect: Rect,
}
/// Default unclipped rectangle for [`FxSlot::clip`], matching `rune::render::NO_CLIP`.
pub const NO_CLIP: [f32; 4] = [-1e6, -1e6, 1e6, 1e6];
#[derive(Clone, Copy, Debug)]
pub struct FxLayer {
pub fx: Fx,
pub shape: Shape,
pub place: Place,
pub time: f32,
pub seed: u32,
pub reduced_motion: bool,
pub source: Option<Source>,
/// 0..1, scales the layer's whole output (a retiring one-shot fades out with it).
pub opacity: f32,
}
/// How an effect layer composites onto the target beneath it (`FxSlot::blend`).
///
/// `Normal` uses premultiplied source-over (allowing additive light where `rgb > a`).
/// `Multiply`, `Screen`, `Overlay`, and `SoftLight` evaluate the W3C Compositing and Blending
/// separable formulas in the frame's working colour space: linear light by default, or sRGB
/// when `FxRenderer::set_srgb_blend(true)` matches `rune::Tx::set_srgb_blend`.
///
/// `Screen` uses fixed-function `wgpu::BlendState` with zero backdrop reads.
/// `Multiply`, `Overlay` and `SoftLight` sample the backdrop (`FxFrame::backdrop` or `EffectSite::backdrop`
/// via `set_layer_backdrop` / `blur_backdrop`) and fall back to `Normal` when no backdrop is
/// available (for example, on a target without `COPY_SRC`).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum FxBlend {
#[default]
Normal,
Multiply,
Screen,
Overlay,
SoftLight,
}
impl FxBlend {
/// True when the blend mode samples the backdrop texture in the fragment shader.
pub const fn needs_backdrop(self) -> bool {
matches!(self, Self::Multiply | Self::Overlay | Self::SoftLight)
}
/// Additional per-pixel cost of this blend mode on top of the effect's own `Fx::cost`.
pub const fn cost(self) -> FxCost {
match self {
Self::Normal | Self::Screen => {
FxCost { passes: 0, samples: 0, alu: 0, backdrop: false, source: false }
}
Self::Multiply | Self::Overlay | Self::SoftLight => {
FxCost { passes: 0, samples: 1, alu: 1, backdrop: true, source: false }
}
}
}
pub(crate) const fn code(self) -> u32 {
match self {
Self::Normal => 0,
Self::Multiply => 1,
Self::Screen => 2,
Self::Overlay => 3,
Self::SoftLight => 4,
}
}
}
/// Per-layer placement in a Rune effect slot. Passed separately to
/// [`FxRenderer::prepare_with_slots`] so existing `FxLayer` and `FxFrame` literals stay valid.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FxSlot {
pub(crate) scale: f32,
pub(crate) clip: [f32; 4],
pub(crate) fade: [u32; 4],
pub(crate) backdrop_srgb: Option<bool>,
pub(crate) blend: FxBlend,
}
impl Default for FxSlot {
fn default() -> Self {
Self { scale: 0.0, clip: NO_CLIP, fade: [0; 4], backdrop_srgb: None, blend: FxBlend::Normal }
}
}
impl FxSlot {
/// Whether backdrop samples need software sRGB decoding. Default: `FxFrame::backdrop`
/// samples are linear; per-slot copies use the frame's blend encoding. Set false for an
/// `*Srgb` view (which hardware decodes) or a linear `Rgba16Float` input, even in sRGB mode.
pub fn backdrop_srgb(mut self, on: bool) -> Self { self.backdrop_srgb = Some(on); self }
/// Device pixels per point (`EffectSite::scale`); zero uses `FxFrame::scale`.
pub fn scale(mut self, scale: f32) -> Self { self.scale = scale; self }
/// Window device-pixel clip and packed soft-edge / rounded-clip words.
pub fn clip(mut self, clip: [f32; 4], fade: [u32; 4]) -> Self {
self.clip = clip;
self.fade = fade;
self
}
/// Blend mode for compositing this layer onto the target beneath it.
pub fn blend(mut self, blend: FxBlend) -> Self {
self.blend = blend;
self
}
}
impl Fx {
pub fn glow(p: GlowParams) -> Fx { Fx::Glow(p) }
pub fn pulse(p: PulseParams) -> Fx { Fx::Pulse(p) }
pub fn electric(p: ElectricParams) -> Fx { Fx::Electric(p) }
pub fn fire(p: FireParams) -> Fx { Fx::Fire(p) }
pub fn distort(p: DistortParams) -> Fx { Fx::Distort(p) }
pub fn lens(p: LensParams) -> Fx { Fx::Distort(DistortParams::Lens(p)) }
pub fn motion_blur(p: MotionBlurParams, s: MotionSamples) -> Fx { Fx::MotionBlur(p, s) }
pub fn shimmer(p: ShimmerParams) -> Fx { Fx::Shimmer(p) }
pub fn sparkles(p: SparkleParams) -> Fx { Fx::Sparkles(p) }
pub fn aurora(p: AuroraParams) -> Fx { Fx::Aurora(p) }
pub fn grain(p: GrainParams) -> Fx { Fx::Grain(p) }
/// `Fx::fill(LiquidMetalParams::gold())`, `Fx::fill(DitherParams::bayer().border(3.0))`.
pub fn fill(p: impl Into<FillParams>) -> Fx { Fx::Fill(p.into()) }
/// Attach to a node shape. Defaults: under the node for light that spills out (glow, pulse,
/// fire), over it for things that replace or overlay pixels (distortion, motion blur, extras).
/// Fills go under the node, as its background, unless they read the backdrop (glass, or a
/// dither or halftone of what is behind), which goes over.
pub fn on(self, shape: Shape) -> FxLayer {
let place = match self {
Fx::Glow(_) | Fx::Pulse(_) | Fx::Fire(_) | Fx::Aurora(_) => Place::Under,
Fx::Fill(p) if !p.needs_backdrop() => Place::Under,
Fx::Electric(_) => Place::Over,
_ => Place::Over,
};
FxLayer { fx: self, shape, place, time: 0.0, seed: 1, reduced_motion: false, source: None, opacity: 1.0 }
}
pub fn needs_backdrop(&self) -> bool {
match self {
Fx::Distort(_) => true,
Fx::Fill(p) => p.needs_backdrop(),
_ => false,
}
}
/// Static cost declaration per covered pixel: `samples` = texture taps + CPU-table reads,
/// `alu` = gradient-noise evaluations.
pub fn cost(&self) -> FxCost {
let c = |samples, alu| FxCost { passes: 1, samples, alu, backdrop: false, source: false };
match self {
Fx::Glow(p) => match p.style {
GlowStyle::Mask => FxCost { samples: 13, source: true, ..c(13, 0) },
GlowStyle::Aura => c(0, 1),
_ => c(0, 0),
},
Fx::Pulse(_) => c(0, 0),
Fx::Electric(p) => {
// Paths/forks are CPU tables: per pixel = table reads, no noise.
let s = p.strands.clamp(1, 3);
match p.style {
ElectricStyle::Arc { .. } => c(1 + s * 4 + 4 * 6, 0),
ElectricStyle::Border => c(1 + s * 6 + 5 * 6, 0),
ElectricStyle::Charged => c(1 + 6 + 5 * 6, 0),
}
}
Fx::Fire(p) => c(p.embers.min(40) * 2, match p.style { FireStyle::Embers => 0, FireStyle::Border => 3, _ => 8 }),
Fx::Distort(d) => {
let (s, a) = match d {
DistortParams::HeatHaze { .. } => (1, 6),
DistortParams::Shockwave { .. } => (3, 0),
DistortParams::Lens(l) => (if l.frost > 0.0 { 12 } else { 4 + 8 }, 0),
DistortParams::Crt { .. } => (7, 0),
DistortParams::ChromaSplit { .. } => (3, 0),
};
FxCost { passes: 1, samples: s, alu: a, backdrop: true, source: false }
}
Fx::MotionBlur(_, s) => FxCost { passes: 1, samples: s.count, alu: 0, backdrop: false, source: true },
Fx::Shimmer(p) => FxCost { source: p.use_mask, ..c(p.use_mask as u32, 0) },
Fx::Sparkles(p) => c(p.count.min(64) * 2, 0),
Fx::Aurora(_) => c(12, 3),
Fx::Grain(_) => c(0, 0),
Fx::Fill(p) => p.cost(),
}
}
}
/// What a layer costs per covered pixel (plus the quad area reported by `FxStats`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct FxCost {
pub passes: u32,
pub samples: u32,
pub alu: u32,
pub backdrop: bool,
pub source: bool,
}
+388
View File
@@ -0,0 +1,388 @@
//! Per-layer state over time and packing into GPU instances.
use crate::*;
impl FxLayer {
pub fn at(mut self, t: f32) -> Self { self.time = t; self }
pub fn seed(mut self, s: u32) -> Self { self.seed = s; self }
pub fn over(mut self) -> Self { self.place = Place::Over; self }
pub fn under(mut self) -> Self { self.place = Place::Under; self }
pub fn reduced(mut self, on: bool) -> Self { self.reduced_motion = on; self }
pub fn source(mut self, slot: u32, rect: Rect) -> Self { self.source = Some(Source { slot, rect }); self }
pub fn opacity(mut self, k: f32) -> Self { self.opacity = k; self }
/// Whether this layer still changes over time (the frame loop may stop ticking when false).
/// A layer that draws nothing at any time (zero opacity or amplitude) is not animating.
pub fn is_animating(&self) -> bool {
if self.silent() {
return false;
}
let t = self.time;
let rm = self.reduced_motion;
match &self.fx {
Fx::Glow(p) => (p.breathe > 0.0 && !rm) || p.style == GlowStyle::Aura && p.aura_speed > 0.0 && !rm,
Fx::Pulse(p) => match p.style {
PulseStyle::Ping { .. } => p.repeat > 0.0 || t < p.t0 + p.duration * PING_LIFE,
PulseStyle::Ripple { .. } => t < p.t0 + p.duration,
_ => !rm,
},
Fx::Distort(DistortParams::Shockwave { t0, duration, .. }) => t < t0 + duration,
Fx::Distort(DistortParams::Lens(_)) => false,
Fx::Distort(DistortParams::ChromaSplit { glitch, .. }) => *glitch > 0.0 && !rm,
Fx::MotionBlur(_, s) => s.is_moving(),
Fx::Grain(g) => g.fps > 0.0 && !rm,
Fx::Fill(p) => p.animates() && !rm,
Fx::Electric(ElectricParams { zap: Some(t0), .. }) => t < t0 + ElectricParams::ZAP_LIFE,
Fx::Sparkles(p @ SparkleParams { burst: Some(t0), .. }) => t < t0 + p.burst_life(),
_ => !rm,
}
}
/// Whether the layer draws nothing whatever the time: no opacity, or an amplitude of zero.
fn silent(&self) -> bool {
if !(self.opacity > 0.0) {
return true;
}
match &self.fx {
Fx::Glow(p) => p.intensity <= 0.0 || p.heat <= 0.0,
Fx::Pulse(p) => p.intensity <= 0.0,
Fx::Electric(p) => p.intensity <= 0.0,
Fx::Fire(p) => p.intensity <= 0.0,
Fx::Distort(DistortParams::HeatHaze { amount, .. } | DistortParams::Shockwave { amount, .. }) => *amount <= 0.0,
Fx::Distort(DistortParams::ChromaSplit { offset, glitch, .. }) => *offset == [0.0, 0.0] && *glitch <= 0.0,
Fx::Distort(DistortParams::Lens(_) | DistortParams::Crt { .. }) => false,
Fx::MotionBlur(..) => self.source.is_none(),
Fx::Shimmer(p) => p.intensity <= 0.0 && p.base_alpha <= 0.0,
Fx::Sparkles(p) => p.intensity <= 0.0 || p.count == 0,
Fx::Aurora(p) => p.intensity <= 0.0,
Fx::Grain(p) => p.amount <= 0.0,
Fx::Fill(p) => p.draws_nothing(self.shape.rect),
}
}
}
/// A ping's life in multiples of its duration: the head arrives at 1, then blooms and cools.
/// `pulse.wgsl` stops drawing a shot at the same age.
const PING_LIFE: f32 = 2.2;
// ---------------------------------------------------------------- packing
#[repr(C)]
#[derive(Clone, Copy, Debug, bytemuck::Pod, bytemuck::Zeroable)]
pub(crate) struct InstRaw {
pub rect: [f32; 4],
pub shape: [f32; 4],
pub bounds: [f32; 4],
pub c0: [f32; 4],
pub c1: [f32; 4],
pub c2: [f32; 4],
pub p0: [f32; 4],
pub p1: [f32; 4],
pub p2: [f32; 4],
pub p3: [f32; 4],
pub t: [f32; 4],
pub aux: [f32; 4],
pub aux2: [f32; 4],
pub xf: [f32; 4],
pub clip: [f32; 4],
pub fade: [u32; 4],
}
const _: () = {
assert!(std::mem::size_of::<InstRaw>() == 256);
assert!(std::mem::offset_of!(InstRaw, rect) == 0);
assert!(std::mem::offset_of!(InstRaw, shape) == 16);
assert!(std::mem::offset_of!(InstRaw, bounds) == 32);
assert!(std::mem::offset_of!(InstRaw, c0) == 48);
assert!(std::mem::offset_of!(InstRaw, c1) == 64);
assert!(std::mem::offset_of!(InstRaw, c2) == 80);
assert!(std::mem::offset_of!(InstRaw, p0) == 96);
assert!(std::mem::offset_of!(InstRaw, p1) == 112);
assert!(std::mem::offset_of!(InstRaw, p2) == 128);
assert!(std::mem::offset_of!(InstRaw, p3) == 144);
assert!(std::mem::offset_of!(InstRaw, t) == 160);
assert!(std::mem::offset_of!(InstRaw, aux) == 176);
assert!(std::mem::offset_of!(InstRaw, aux2) == 192);
assert!(std::mem::offset_of!(InstRaw, xf) == 208);
assert!(std::mem::offset_of!(InstRaw, clip) == 224);
assert!(std::mem::offset_of!(InstRaw, fade) == 240);
};
const KIND_GLOW: usize = 0;
const KIND_PULSE: usize = 1;
const KIND_ELECTRIC: usize = 2;
const KIND_FIRE: usize = 3;
const KIND_DISTORT: usize = 4;
const KIND_MOTION: usize = 5;
const KIND_EXTRAS: usize = 6;
pub(crate) const KIND_FILL: usize = 7;
pub(crate) const KINDS: usize = 8;
/// Blur sigma (pt) of a fully frosted lens (`LensParams::frost = 1`).
pub(crate) const LENS_FROST_SIGMA: f32 = 18.0;
/// Calm pose for looping noise effects under reduced motion: frozen at a fixed, pleasant time.
pub(crate) const CALM_T: f32 = 2.37;
impl FxLayer {
/// Pack into an instance; `None` when the layer is idle (intensity 0, finished one-shot).
/// Returns (kind, instance without bounds, bounds in pt).
pub(crate) fn pack(&self) -> Option<(usize, InstRaw, Rect)> {
if self.silent() {
return None;
}
let s = self.shape;
let r = s.rect;
let mut i = InstRaw {
rect: r.xywh(),
shape: [s.radius.min(r.w * 0.5).min(r.h * 0.5).max(0.0), 1.0, self.opacity.min(1.0), 0.0],
bounds: [0.0; 4],
c0: [0.0; 4],
c1: [0.0; 4],
c2: [0.0; 4],
p0: [0.0; 4],
p1: [0.0; 4],
p2: [0.0; 4],
p3: [0.0; 4],
t: [self.time, (self.seed % 65_536) as f32, 0.0, if self.reduced_motion { 1.0 } else { 0.0 }],
aux: [0.0; 4],
aux2: self.source.map(|s| s.rect.xywh()).unwrap_or([0.0, 0.0, 1.0, 1.0]),
xf: [0.0; 4],
clip: NO_CLIP,
fade: [0; 4],
};
let rm = self.reduced_motion;
let looped_t = if rm { CALM_T } else { self.time };
let (kind, bounds) = match &self.fx {
Fx::Glow(p) => {
i.t[2] = match p.style { GlowStyle::Soft => 0.0, GlowStyle::Neon => 1.0, GlowStyle::Aura => 2.0, GlowStyle::Mask => 3.0 };
i.c0 = p.color.v4();
i.c1 = p.core.v4();
i.c2 = p.third.v4();
i.p0 = [p.radius, p.intensity, p.inner, p.occlusion];
i.p1 = [p.breathe, p.breathe_period, p.heat.clamp(0.0, 1.0), p.hot];
i.p2 = [p.aura_speed, p.rim_width, p.reach, 0.0];
(KIND_GLOW, r.inflate(p.radius * p.reach * (1.0 + 0.22 * p.breathe)))
}
Fx::Pulse(p) => {
i.c0 = p.color.v4();
i.c1 = p.core.v4();
i.p0 = [p.count as f32, p.period, p.reach, p.width];
i.p1 = [p.intensity, p.t0, p.duration, p.repeat];
i.p2 = [0.0, p.lag, p.head_radius, p.occlusion];
let (v, b) = match p.style {
PulseStyle::Radar => (0.0, r.inflate(p.reach + p.width * 3.2 * 4.0)),
PulseStyle::Breathe => (1.0, r.inflate(p.reach * 5.0)),
PulseStyle::Heartbeat => (2.0, r.inflate(p.reach + p.width * 16.0 + 2.0)),
PulseStyle::Ping { from, dir, travel } => {
if p.repeat <= 0.0 && (self.time < p.t0 || self.time > p.t0 + p.duration * PING_LIFE) {
return None;
}
// A zero direction points right rather than nowhere (the shader would normalise it to NaN).
let l = (dir[0] * dir[0] + dir[1] * dir[1]).sqrt();
let d = if l > 1e-6 { [dir[0] / l, dir[1] / l] } else { [1.0, 0.0] };
i.aux = [from[0], from[1], d[0], d[1]];
i.p2[0] = travel;
let to = [from[0] + d[0] * travel, from[1] + d[1] * travel];
let back = [from[0] - d[0] * travel * 0.06, from[1] - d[1] * travel * 0.06];
(3.0, Rect::from_points(back, to).inflate(p.head_radius * 10.0 + 30.0))
}
PulseStyle::Ripple { at } => {
if self.time < p.t0 || self.time > p.t0 + p.duration {
return None;
}
i.aux = [at[0], at[1], 0.0, 0.0];
if p.reach <= 0.0 {
let far = corners(r).iter().map(|c| ((c[0] - at[0]).powi(2) + (c[1] - at[1]).powi(2)).sqrt()).fold(0.0, f32::max);
i.p0[2] = far;
}
(4.0, r.inflate(1.0))
}
};
i.t[2] = v;
(KIND_PULSE, b)
}
Fx::Electric(p) => {
i.t[0] = looped_t;
if let Some(t0) = p.zap {
if self.time < t0 || self.time > t0 + ElectricParams::ZAP_LIFE {
return None;
}
i.t[0] = self.time;
}
i.c0 = p.color.v4();
i.c1 = p.core.v4();
i.c2 = p.cool.v4();
i.p0 = [p.amplitude, p.frequency, p.speed, p.core_width];
i.p1 = [p.intensity, p.glow, p.forks, p.flicker];
i.p2 = [p.strands.clamp(1, 3) as f32, p.gap, p.fork_len, p.occlusion];
let m = p.amplitude * 1.7 + p.glow * 5.0;
match p.style {
ElectricStyle::Arc { a, b } => {
i.t[2] = 0.0;
i.aux = [a[0], a[1], b[0], b[1]];
let len = ((b[0] - a[0]).powi(2) + (b[1] - a[1]).powi(2)).sqrt().max(1.0);
(KIND_ELECTRIC, Rect::from_points(a, b).inflate(p.glow * 5.0 + p.core_width * 3.0 + cpu::arc_reach(p, len)))
}
ElectricStyle::Border => {
i.t[2] = 1.0;
(KIND_ELECTRIC, r.inflate(m + p.gap.max(0.0) + p.fork_len * 1.3))
}
ElectricStyle::Charged => {
i.t[2] = 2.0;
(KIND_ELECTRIC, r.inflate(m + p.gap.max(0.0) + p.fork_len * 0.6))
}
}
}
Fx::Fire(p) => {
i.t[0] = looped_t;
i.t[2] = match p.style { FireStyle::Top => 0.0, FireStyle::Border => 1.0, FireStyle::Heat => 0.0, FireStyle::Embers => 3.0 };
i.c0 = p.low.v4();
i.c1 = p.mid.v4();
i.c2 = p.hot.v4();
i.p0 = [p.height, p.scale, p.speed, p.intensity];
i.p1 = [if rm { 0.0 } else { p.embers.min(40) as f32 }, p.ember_rise, p.ember_size, p.ember_life];
i.p2 = [p.warp, p.sides, p.base_glow, p.occlusion];
i.p3 = [p.swirl, 0.0, 0.0, 0.0];
// Embers: spawn up to 0.55 H, fly (v0 - vt) / drag, then drift vt for the rest of life.
let ember_up = if p.embers > 0 && !rm {
let life = p.ember_life.max(0.1) * 1.4;
p.height * 0.55 + p.ember_rise * (1.48 / cpu::EMBER_DRAG + 0.32 * life) + p.ember_size * 4.0
} else {
0.0
};
let ember_side = if p.embers > 0 && !rm { 7.5 * p.ember_life.max(0.1) * 1.4 + 9.0 } else { 0.0 };
let b = match p.style {
FireStyle::Border => r.inflate((p.height * p.sides * 0.3).max(2.5) * 4.6 + 2.0),
_ => {
// Room above the flames for the smoke they leave (simulated fire).
let up = (p.height * 2.6 + 8.0).max(ember_up) + 4.0;
Rect::new(r.x - ember_side, r.y - up, r.w + 2.0 * ember_side, up + 4.0)
}
};
(KIND_FIRE, b)
}
Fx::Distort(d) => {
let b = match *d {
DistortParams::HeatHaze { height, scale, speed, amount, whole_shape } => {
i.t[0] = looped_t;
i.t[2] = 0.0;
i.p0 = [height, scale, speed, amount];
i.p1 = [whole_shape as u32 as f32, 0.0, 0.0, 0.0];
if whole_shape { r.inflate(amount + 2.0) } else { Rect::new(r.x - 4.0, r.y - height - 4.0, r.w + 8.0, height + 12.0) }
}
DistortParams::Shockwave { at, reach, width, amount, chroma, t0, duration } => {
if self.time < t0 || self.time > t0 + duration {
return None;
}
i.t[2] = 1.0;
i.aux = [at[0], at[1], 0.0, 0.0];
i.p0 = [reach, width, amount, chroma];
i.p1 = [t0, duration, 0.0, 0.0];
Rect::new(at[0], at[1], 0.0, 0.0).inflate(reach + width * 5.0 + amount)
}
DistortParams::Lens(l) => {
i.t[2] = 2.0;
i.c0 = l.tint.v4();
i.p0 = [l.bevel, l.depth, l.dispersion, l.magnification];
i.p1 = [l.presence.clamp(0.0, 1.0), l.frost, l.shadow, l.rim];
let mut b = r;
if let Some(s2) = l.second {
i.p2 = [l.light_angle, l.tint_amount, l.union_k, s2.radius.min(s2.rect.w * 0.5).min(s2.rect.h * 0.5)];
i.p3 = s2.rect.xywh();
i.shape[3] = l.morph;
b = b.union(s2.rect);
} else {
i.p2 = [l.light_angle, l.tint_amount, 0.0, 0.0];
}
b.inflate(28.0)
}
DistortParams::Crt { bulge, scanline, scan_depth, chroma, vignette, glow, roll, feather } => {
i.t[2] = 3.0;
i.p0 = [bulge, scanline, scan_depth, chroma];
i.p1 = [vignette, glow, roll, feather];
r.inflate(feather)
}
DistortParams::ChromaSplit { offset, glitch, feather } => {
i.t[2] = 4.0;
i.p0 = [offset[0], offset[1], glitch, feather];
r.inflate(feather)
}
};
(KIND_DISTORT, b)
}
Fx::MotionBlur(_, ms) => {
i.xf = [0.0, ms.count as f32, if ms.mode == BlurMode::Shutter { 0.0 } else { 1.0 }, 0.0];
i.aux = [ms.blur[0], ms.blur[1], 0.0, 0.0];
(KIND_MOTION, ms.bounds.inflate(2.0))
}
Fx::Shimmer(p) => {
i.t[2] = 0.0;
i.c0 = p.color.v4();
i.c1 = [p.base.0[0], p.base.0[1], p.base.0[2], p.base_alpha];
i.p0 = [p.period, p.band, p.angle, p.intensity];
i.p1 = [p.use_mask as u32 as f32, p.pause, p.feather, 0.0];
(KIND_EXTRAS, r.inflate(1.0))
}
Fx::Sparkles(p) => {
if let Some(t0) = p.burst
&& (self.time < t0 || self.time > t0 + p.burst_life())
{
return None;
}
i.t[2] = 1.0;
i.c0 = p.color.v4();
i.p0 = [p.count.min(64) as f32, p.life, p.size, p.intensity];
i.p1 = [p.margin, 0.0, 0.0, 0.0];
(KIND_EXTRAS, r.inflate(p.margin + p.size * cpu::SPARKLE_MAX_SCALE + 2.0))
}
Fx::Aurora(p) => {
i.t[2] = 2.0;
i.c0 = p.a.v4();
i.c1 = p.b.v4();
i.c2 = p.c.v4();
i.p0 = [p.scale, p.speed, p.intensity, p.feather];
(KIND_EXTRAS, r.inflate(1.0))
}
Fx::Grain(p) => {
i.t[2] = 3.0;
i.p0 = [p.amount, p.fps, p.feather, 0.0];
(KIND_EXTRAS, r.inflate(1.0))
}
Fx::Fill(p) => (KIND_FILL, p.pack(&mut i, rm, self.time)?),
};
Some((kind, i, bounds))
}
/// Second stage, only for layers that survived culling: per-frame CPU tables into `data`.
pub(crate) fn fill(&self, i: &mut InstRaw, data: &mut Vec<[f32; 4]>) {
let t = i.t[0];
let rm = self.reduced_motion;
match &self.fx {
Fx::MotionBlur(_, ms) => {
i.xf[0] = data.len() as f32;
for x in &ms.xforms[..ms.count as usize] {
data.push([x[0], x[1], x[2], x[3]]);
data.push([x[4], x[5], x[6], x[7]]);
}
}
Fx::Electric(p) => i.xf = cpu::electric(p, self.shape, t, self.seed, rm, data),
Fx::Fire(p) => {
if !rm && p.embers > 0 {
let (f, n) = cpu::embers(p, self.shape.rect, i.shape[0], t, self.seed, data);
i.xf = [f, n, 0.0, 0.0];
}
}
Fx::Sparkles(p) => {
let (f, n) = cpu::sparkles(p, self.shape.rect, t, self.seed, rm, data);
i.xf = [f, n, 0.0, 0.0];
}
Fx::Aurora(p) => {
let tt = if rm { CALM_T } else { t };
i.xf = [cpu::aurora(p, self.shape.rect, tt, self.seed, data), cpu::AURORA_SAMPLES as f32, 0.0, 0.0];
}
Fx::Fill(p) => p.tables(i, self.shape.rect, t, self.seed, data),
_ => {}
}
}
}
+721
View File
@@ -0,0 +1,721 @@
use crate::{Rect, Rgb, Shape, cpu, rgb};
// ---------------------------------------------------------------- knobs
/// A tunable parameter with its range, for knobs panels.
#[derive(Clone, Copy, Debug)]
pub struct Knob {
pub name: &'static str,
pub min: f32,
pub max: f32,
pub default: f32,
}
const fn k(name: &'static str, min: f32, max: f32, default: f32) -> Knob {
Knob { name, min, max, default }
}
// ---------------------------------------------------------------- params
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum GlowStyle {
/// Soft bloom outside the shape.
Soft,
/// Neon tube: white-hot hairline core on the border, coloured bloom both sides.
Neon,
/// Spectrum flowing around the border (inner rim light + outer bloom).
Aura,
/// Bloom of a mask texture (text, icons): needs `FxLayer::source` pointing at a `MaskPyramid`.
Mask,
}
#[derive(Clone, Copy, Debug)]
pub struct GlowParams {
pub style: GlowStyle,
pub color: Rgb,
pub core: Rgb,
/// Aura only: the third palette colour (`color`, `core`, `third` flow around the border).
pub third: Rgb,
pub radius: f32,
pub intensity: f32,
pub inner: f32,
pub occlusion: f32,
pub breathe: f32,
pub breathe_period: f32,
/// 1 = fully lit; animate toward 0 to cool (see `Heat`).
pub heat: f32,
pub hot: f32,
pub aura_speed: f32,
pub rim_width: f32,
pub reach: f32,
}
impl Default for GlowParams {
fn default() -> Self {
GlowParams {
style: GlowStyle::Soft,
color: rgb(0x7c5cff),
core: rgb(0xf4f0ff),
third: rgb(0x22d3ee),
radius: 14.0,
intensity: 1.0,
inner: 0.0,
occlusion: 0.15,
breathe: 0.0,
breathe_period: 2.6,
heat: 1.0,
hot: 0.6,
aura_speed: 0.12,
rim_width: 0.6,
reach: 4.5,
}
}
}
impl GlowParams {
pub const KNOBS: &'static [Knob] = &[
k("radius", 1.0, 64.0, 14.0),
k("intensity", 0.0, 3.0, 1.0),
k("inner", 0.0, 1.0, 0.0),
k("occlusion", 0.0, 1.0, 0.15),
k("breathe", 0.0, 1.0, 0.0),
k("breathe_period", 0.4, 8.0, 2.6),
k("heat", 0.0, 1.0, 1.0),
k("hot", 0.0, 1.0, 0.6),
k("aura_speed", 0.0, 1.0, 0.12),
k("rim_width", 0.2, 3.0, 0.6),
k("reach", 2.0, 8.0, 4.5),
];
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum PulseStyle {
/// Rings expand outward from the shape edge.
Radar,
/// A halo that breathes.
Breathe,
/// Lub-dub glow with a short ring per beat.
Heartbeat,
/// A comet that launches from `from` along `dir`, travels `travel` pt with anticipation and a
/// decelerating landing, then blooms and cools at its destination.
Ping { from: [f32; 2], dir: [f32; 2], travel: f32 },
/// Ripple from a tap point, confined to the shape.
Ripple { at: [f32; 2] },
}
#[derive(Clone, Copy, Debug)]
pub struct PulseParams {
pub style: PulseStyle,
pub color: Rgb,
pub core: Rgb,
pub count: u32,
pub period: f32,
pub reach: f32,
pub width: f32,
pub intensity: f32,
/// One-shots (ping, ripple): start time on the layer's clock.
pub t0: f32,
pub duration: f32,
/// Ping: repeat interval (0 = once).
pub repeat: f32,
pub lag: f32,
pub head_radius: f32,
pub occlusion: f32,
}
impl Default for PulseParams {
fn default() -> Self {
PulseParams {
style: PulseStyle::Radar,
color: rgb(0x3b82f6),
core: rgb(0xe8f1ff),
count: 3,
period: 2.4,
reach: 36.0,
width: 1.6,
intensity: 1.0,
t0: 0.0,
duration: 0.75,
repeat: 0.0,
lag: 0.16,
head_radius: 2.6,
occlusion: 0.15,
}
}
}
impl PulseParams {
pub const KNOBS: &'static [Knob] = &[
k("count", 1.0, 6.0, 3.0),
k("period", 0.3, 6.0, 2.4),
k("reach", 4.0, 200.0, 36.0),
k("width", 0.3, 8.0, 1.6),
k("intensity", 0.0, 3.0, 1.0),
k("duration", 0.1, 3.0, 0.75),
k("repeat", 0.0, 6.0, 0.0),
k("lag", 0.02, 0.5, 0.16),
k("head_radius", 0.5, 12.0, 2.6),
k("occlusion", 0.0, 1.0, 0.15),
];
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum ElectricStyle {
Arc { a: [f32; 2], b: [f32; 2] },
Border,
/// Calm UI variant: low amplitude, slow crawl, travelling beads of charge, rare tiny sparks.
Charged,
}
#[derive(Clone, Copy, Debug)]
pub struct ElectricParams {
pub style: ElectricStyle,
pub color: Rgb,
pub core: Rgb,
pub cool: Rgb,
pub amplitude: f32,
pub frequency: f32,
pub speed: f32,
pub core_width: f32,
pub intensity: f32,
pub glow: f32,
pub forks: f32,
pub flicker: f32,
pub strands: u32,
pub gap: f32,
pub fork_len: f32,
pub occlusion: f32,
/// One strike at this time (layer clock) instead of a continuous arc: it flashes, may
/// re-strike down the same channel, then its afterimage fades within `ZAP_LIFE`. Overlapping
/// zaps: one layer per `OneShots` instance, seeded with the instance's seed.
pub zap: Option<f32>,
}
impl Default for ElectricParams {
fn default() -> Self {
ElectricParams {
style: ElectricStyle::Border,
color: rgb(0x4f8dff),
core: rgb(0xeaf3ff),
cool: rgb(0x7a4dff),
amplitude: 5.0,
frequency: 2.4,
speed: 3.2,
core_width: 0.6,
intensity: 1.0,
glow: 5.0,
forks: 0.55,
flicker: 0.45,
strands: 2,
gap: 2.0,
fork_len: 20.0,
occlusion: 0.12,
zap: None,
}
}
}
impl ElectricParams {
/// How long a zap lasts (s).
pub const ZAP_LIFE: f32 = 0.5;
pub const KNOBS: &'static [Knob] = &[
k("amplitude", 0.0, 24.0, 5.0),
k("frequency", 0.5, 8.0, 2.4),
k("speed", 0.0, 10.0, 3.2),
k("core_width", 0.2, 3.0, 0.6),
k("intensity", 0.0, 3.0, 1.0),
k("glow", 1.0, 20.0, 5.0),
k("forks", 0.0, 1.0, 0.55),
k("flicker", 0.0, 1.0, 0.45),
k("strands", 1.0, 3.0, 2.0),
k("gap", -6.0, 12.0, 2.0),
k("fork_len", 2.0, 60.0, 20.0),
k("occlusion", 0.0, 1.0, 0.12),
];
/// The calm border for UI: a charged hairline that crawls.
pub fn charged() -> ElectricParams {
ElectricParams {
style: ElectricStyle::Charged,
amplitude: 1.1,
frequency: 3.0,
speed: 2.0,
core_width: 0.5,
glow: 4.0,
forks: 0.25,
flicker: 0.0,
strands: 1,
gap: 0.5,
fork_len: 14.0,
intensity: 0.9,
..Default::default()
}
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FireStyle {
Top,
Border,
/// Subtle warm tongues for UI (use `FireParams::heat()`).
Heat,
Embers,
}
#[derive(Clone, Copy, Debug)]
pub struct FireParams {
pub style: FireStyle,
pub low: Rgb,
pub mid: Rgb,
pub hot: Rgb,
pub height: f32,
pub scale: f32,
pub speed: f32,
pub intensity: f32,
pub embers: u32,
pub ember_rise: f32,
pub ember_size: f32,
pub ember_life: f32,
pub warp: f32,
pub sides: f32,
pub base_glow: f32,
pub occlusion: f32,
pub swirl: f32,
/// How much smoke the cooling flame leaves (simulated fire only; see `FxRenderer::set_fire_sim`).
pub smoke: f32,
}
impl Default for FireParams {
fn default() -> Self {
FireParams {
style: FireStyle::Top,
low: rgb(0x8a1405),
mid: rgb(0xff5a14),
hot: rgb(0xffc65a),
height: 54.0,
scale: 20.0,
speed: 1.5,
intensity: 1.0,
embers: 16,
ember_rise: 58.0,
ember_size: 0.8,
ember_life: 1.5,
warp: 1.0,
sides: 0.32,
base_glow: 0.5,
occlusion: 0.25,
swirl: 0.0,
smoke: 0.5,
}
}
}
impl FireParams {
pub const KNOBS: &'static [Knob] = &[
k("height", 4.0, 160.0, 54.0),
k("scale", 4.0, 80.0, 20.0),
k("speed", 0.0, 5.0, 1.5),
k("intensity", 0.0, 3.0, 1.0),
k("embers", 0.0, 40.0, 16.0),
k("ember_rise", 0.0, 200.0, 58.0),
k("ember_size", 0.2, 3.0, 0.8),
k("ember_life", 0.2, 4.0, 1.5),
k("warp", 0.0, 3.0, 1.0),
k("sides", 0.0, 1.0, 0.32),
k("base_glow", 0.0, 2.0, 0.5),
k("occlusion", 0.0, 1.0, 0.25),
k("swirl", 0.0, 3.0, 0.0),
k("smoke", 0.0, 2.0, 0.5),
];
pub fn heat() -> FireParams {
FireParams {
style: FireStyle::Heat,
low: rgb(0x7a1606),
mid: rgb(0xf0601a),
hot: rgb(0xffc062),
height: 15.0,
scale: 7.0,
speed: 1.3,
intensity: 0.8,
embers: 4,
ember_rise: 30.0,
ember_size: 0.55,
ember_life: 1.1,
warp: 0.8,
base_glow: 0.35,
occlusion: 0.1,
..Default::default()
}
}
/// Plasma: cool palette, swirling, around the border.
pub fn plasma() -> FireParams {
FireParams {
style: FireStyle::Border,
low: rgb(0x3a1690),
mid: rgb(0x7b5cff),
hot: rgb(0x9fe8ff),
height: 30.0,
scale: 16.0,
speed: 1.1,
intensity: 0.95,
embers: 0,
warp: 1.0,
sides: 0.55,
base_glow: 0.6,
swirl: 0.8,
..Default::default()
}
}
}
#[derive(Clone, Copy, Debug)]
pub struct LensParams {
pub bevel: f32,
pub depth: f32,
pub dispersion: f32,
pub magnification: f32,
/// 0..1: glass materialises by lensing (refraction, rim and shadow ramp together), not fading.
pub presence: f32,
pub frost: f32,
pub shadow: f32,
pub rim: f32,
pub light_angle: f32,
pub tint: Rgb,
pub tint_amount: f32,
/// A second glass shape smooth-unioned with the first (gooey merge), or `None`.
pub second: Option<Shape>,
pub union_k: f32,
/// 0..1: morph the union toward `second` alone.
pub morph: f32,
}
impl Default for LensParams {
fn default() -> Self {
LensParams {
bevel: 14.0,
depth: 16.0,
dispersion: 0.14,
magnification: 1.04,
presence: 1.0,
frost: 0.0,
shadow: 0.35,
rim: 1.6,
light_angle: -2.09,
tint: rgb(0xffffff),
tint_amount: 0.0,
second: None,
union_k: 22.0,
morph: 0.0,
}
}
}
#[derive(Clone, Copy, Debug)]
pub enum DistortParams {
HeatHaze { height: f32, scale: f32, speed: f32, amount: f32, whole_shape: bool },
Shockwave { at: [f32; 2], reach: f32, width: f32, amount: f32, chroma: f32, t0: f32, duration: f32 },
Lens(LensParams),
Crt { bulge: f32, scanline: f32, scan_depth: f32, chroma: f32, vignette: f32, glow: f32, roll: f32, feather: f32 },
ChromaSplit { offset: [f32; 2], glitch: f32, feather: f32 },
}
impl DistortParams {
pub fn shockwave(at: [f32; 2], t0: f32) -> Self {
DistortParams::Shockwave { at, reach: 160.0, width: 14.0, amount: 9.0, chroma: 0.35, t0, duration: 0.9 }
}
pub fn crt() -> Self {
DistortParams::Crt { bulge: 0.08, scanline: 1.5, scan_depth: 0.28, chroma: 0.8, vignette: 0.6, glow: 0.35, roll: 1.0, feather: 2.0 }
}
pub fn chroma_split(offset: [f32; 2]) -> Self {
DistortParams::ChromaSplit { offset, glitch: 0.0, feather: 2.0 }
}
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum BlurMode {
/// True shutter blur: exact sub-frame poses from the analytic track.
Shutter,
/// Cheap fallback: taps along the instantaneous velocity from the current pose only (no track).
Directional,
}
#[derive(Clone, Copy, Debug)]
pub struct MotionBlurParams {
pub mode: BlurMode,
/// Degrees of the frame interval the shutter is open (180 = film look).
pub shutter_angle: f32,
pub frame_dt: f32,
pub max_samples: u32,
/// Target spacing between sub-frame samples, in device pixels.
pub px_per_sample: f32,
/// Raised-cosine shutter (soft trail ends) instead of a box.
pub smooth_shutter: bool,
}
impl Default for MotionBlurParams {
fn default() -> Self {
MotionBlurParams {
mode: BlurMode::Shutter,
shutter_angle: 180.0,
frame_dt: 1.0 / 60.0,
max_samples: 48,
px_per_sample: 1.25,
smooth_shutter: true,
}
}
}
impl MotionBlurParams {
pub const KNOBS: &'static [Knob] = &[
k("shutter_angle", 0.0, 360.0, 180.0),
k("max_samples", 1.0, 64.0, 48.0),
k("px_per_sample", 0.5, 6.0, 1.25),
];
}
/// A node's pose relative to its rest rect: translate, rotate and scale about the rect centre.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Pose {
pub x: f32,
pub y: f32,
pub rotation: f32,
pub scale: f32,
pub opacity: f32,
}
impl Default for Pose {
fn default() -> Self {
Pose { x: 0.0, y: 0.0, rotation: 0.0, scale: 1.0, opacity: 1.0 }
}
}
impl Pose {
/// Forward affine (a, b, c, d, tx, ty): screen = [a c; b d] * local + t.
pub(crate) fn affine(&self, rest: Rect) -> [f32; 6] {
let rune_motion::Vec2 { x: cx, y: cy } = rest.center();
let (s, c) = self.rotation.sin_cos();
let a = c * self.scale;
let b = s * self.scale;
let cc = -s * self.scale;
let d = c * self.scale;
let tx = cx + self.x - (a * cx + cc * cy);
let ty = cy + self.y - (b * cx + d * cy);
[a, b, cc, d, tx, ty]
}
pub fn apply(&self, rest: Rect, p: [f32; 2]) -> [f32; 2] {
let [a, b, c, d, tx, ty] = self.affine(rest);
[a * p[0] + c * p[1] + tx, b * p[0] + d * p[1] + ty]
}
}
pub const MAX_MOTION_SAMPLES: usize = 64;
/// Sub-frame poses for one frame, sampled from the node's analytic track.
#[derive(Clone, Copy, Debug)]
pub struct MotionSamples {
pub count: u32,
pub mode: BlurMode,
/// Per sample: inverse affine (ia, ib, ic, id, itx, ity), weight * opacity, 0.
pub xforms: [[f32; 8]; MAX_MOTION_SAMPLES],
/// Union of all sampled node rects (pt).
pub bounds: Rect,
/// Directional mode: blur vector over the whole shutter (pt).
pub blur: [f32; 2],
/// Largest corner travel across the shutter, in device px.
pub travel_px: f32,
}
pub(crate) fn invert(m: [f32; 6]) -> [f32; 6] {
let [a, b, c, d, tx, ty] = m;
let det = a * d - b * c;
let id = 1.0 / if det.abs() < 1e-9 { 1e-9 } else { det };
let ia = d * id;
let ib = -b * id;
let ic = -c * id;
let idd = a * id;
[ia, ib, ic, idd, -(ia * tx + ic * ty), -(ib * tx + idd * ty)]
}
pub(crate) fn corners(r: Rect) -> [[f32; 2]; 4] {
[[r.x, r.y], [r.x + r.w, r.y], [r.x, r.y + r.h], [r.x + r.w, r.y + r.h]]
}
impl MotionSamples {
/// Sample `track` (a pose for any time) inside the shutter interval centred on `t`.
/// The sample count scales with on-screen travel: 1 at rest, so a resting node costs nothing
/// extra (`is_moving()` is false and the caller draws the node normally).
pub fn from_track(p: &MotionBlurParams, rest: Rect, t: f32, scale: f32, track: impl Fn(f32) -> Pose) -> MotionSamples {
let open = p.frame_dt * p.shutter_angle / 360.0;
let t0 = t - open * 0.5;
let t1 = t + open * 0.5;
let pa = track(t0);
let pb = track(t1);
let pm = track(t);
// Travel: max corner displacement between open, middle and close (catches rotation arcs).
let mut travel = 0.0f32;
for c in corners(rest) {
let a = pa.apply(rest, c);
let m = pm.apply(rest, c);
let b = pb.apply(rest, c);
let d1 = ((m[0] - a[0]).powi(2) + (m[1] - a[1]).powi(2)).sqrt();
let d2 = ((b[0] - m[0]).powi(2) + (b[1] - m[1]).powi(2)).sqrt();
travel = travel.max(d1 + d2);
}
let travel_px = travel * scale;
let mut s = MotionSamples {
count: 1,
mode: p.mode,
xforms: [[0.0; 8]; MAX_MOTION_SAMPLES],
bounds: rest,
blur: [0.0, 0.0],
travel_px,
};
let max = (p.max_samples as usize).clamp(1, MAX_MOTION_SAMPLES);
let want = ((travel_px / p.px_per_sample.max(0.25)).ceil() as usize).clamp(1, max);
let put = |s: &mut MotionSamples, i: usize, pose: &Pose, w: f32| {
let inv = invert(pose.affine(rest));
s.xforms[i] = [inv[0], inv[1], inv[2], inv[3], inv[4], inv[5], w * pose.opacity, 0.0];
let mut b: Option<Rect> = None;
for c in corners(rest) {
let q = pose.apply(rest, c);
let r = Rect::new(q[0], q[1], 0.0, 0.0);
b = Some(b.map_or(r, |bb| bb.union(r)));
}
s.bounds = if i == 0 { b.unwrap() } else { s.bounds.union(b.unwrap()) };
};
if want <= 1 || open <= 0.0 {
put(&mut s, 0, &pm, 1.0);
return s;
}
match p.mode {
BlurMode::Shutter => {
let mut w = [0.0f32; MAX_MOTION_SAMPLES];
let mut sum = 0.0;
for (i, wi) in w.iter_mut().enumerate().take(want) {
let u = (i as f32 + 0.5) / want as f32;
*wi = if p.smooth_shutter { 0.5 - 0.5 * (std::f32::consts::TAU * u).cos() } else { 1.0 };
sum += *wi;
}
for i in 0..want {
let u = (i as f32 + 0.5) / want as f32;
let pose = track(t0 + (t1 - t0) * u);
put(&mut s, i, &pose, w[i] / sum);
}
s.count = want as u32;
}
BlurMode::Directional => {
put(&mut s, 0, &pm, 1.0);
s.blur = [pb.x - pa.x, pb.y - pa.y];
let taps = want.min(32);
s.count = taps as u32;
// Bounds: current rect swept along the blur vector.
let half = [s.blur[0] * 0.5, s.blur[1] * 0.5];
let r = s.bounds;
let a = Rect::new(r.x - half[0], r.y - half[1], r.w, r.h);
let b = Rect::new(r.x + half[0], r.y + half[1], r.w, r.h);
s.bounds = a.union(b);
}
}
s
}
pub fn is_moving(&self) -> bool {
self.count > 1
}
}
#[derive(Clone, Copy, Debug)]
pub struct ShimmerParams {
pub color: Rgb,
pub base: Rgb,
pub base_alpha: f32,
pub period: f32,
pub band: f32,
pub angle: f32,
pub intensity: f32,
/// Sweep a mask texture (text) instead of the shape: needs `FxLayer::source`.
pub use_mask: bool,
pub pause: f32,
pub feather: f32,
}
impl Default for ShimmerParams {
fn default() -> Self {
ShimmerParams {
color: rgb(0xffffff),
base: rgb(0x1c1f26),
base_alpha: 0.0,
period: 1.8,
band: 28.0,
angle: 0.35,
intensity: 0.16,
use_mask: false,
pause: 0.3,
feather: 0.0,
}
}
}
#[derive(Clone, Copy, Debug)]
pub struct SparkleParams {
pub color: Rgb,
pub count: u32,
pub life: f32,
pub size: f32,
pub intensity: f32,
pub margin: f32,
/// A one-shot burst starting at this time (layer clock): every star pops once, flies a little
/// way out from the shape and twinkles out within `burst_life()`. `None` twinkles forever.
pub burst: Option<f32>,
}
impl Default for SparkleParams {
fn default() -> Self {
SparkleParams { color: rgb(0xffe6a8), count: 6, life: 1.5, size: 7.0, intensity: 1.0, margin: 10.0, burst: None }
}
}
impl SparkleParams {
/// Seconds from the start of a burst until its last star is gone.
pub fn burst_life(&self) -> f32 {
cpu::SPARKLE_STAGGER + self.life * cpu::BURST_LIFE * 1.3
}
}
#[derive(Clone, Copy, Debug)]
pub struct AuroraParams {
pub a: Rgb,
pub b: Rgb,
pub c: Rgb,
pub scale: f32,
pub speed: f32,
pub intensity: f32,
pub feather: f32,
}
impl Default for AuroraParams {
fn default() -> Self {
AuroraParams {
a: rgb(0x16c79a),
b: rgb(0x3b6cff),
c: rgb(0xa23bff),
scale: 120.0,
speed: 0.25,
intensity: 0.5,
feather: 40.0,
}
}
}
#[derive(Clone, Copy, Debug)]
pub struct GrainParams {
pub amount: f32,
/// 0 = static grain (no temporal shimmer); otherwise re-rolls at this rate.
pub fps: f32,
pub feather: f32,
}
impl Default for GrainParams {
fn default() -> Self {
GrainParams { amount: 0.03, fps: 0.0, feather: 0.0 }
}
}
+206
View File
@@ -0,0 +1,206 @@
//! The effect pipelines: one per effect family, blend and target format, each built the first
//! time a frame draws it. On a cold Metal shader cache a pipeline costs 20 to 150 ms of GPU code
//! generation, a blend state or a format as much as a family, so a renderer that only ever glows
//! builds one pipeline, not all sixteen of every format. Those a frame needs at once build in
//! parallel. The mask pyramid's and the backdrop blur's passes (`Passes`) wait for first use too.
use std::sync::OnceLock;
use crate::FxBlend;
use crate::pack::KINDS;
pub(crate) const CLIP: &str = include_str!("../../rune/src/shaders/clip.wgsl");
pub(crate) const COMMON: &str = include_str!("shaders/common.wgsl");
pub(crate) const SOURCES: [(&str, &str); KINDS] = [
("glow", include_str!("shaders/glow.wgsl")),
("pulse", include_str!("shaders/pulse.wgsl")),
("electric", include_str!("shaders/electric.wgsl")),
("fire", include_str!("shaders/fire.wgsl")),
("distort", include_str!("shaders/distort.wgsl")),
("motion", include_str!("shaders/motion.wgsl")),
("extras", include_str!("shaders/extras.wgsl")),
("fill", include_str!("shaders/fill.wgsl")),
];
pub(crate) const BLENDS: usize = 2;
/// The pipeline index for `blend`: premultiplied over, or screen.
pub(crate) fn blend_index(blend: FxBlend) -> usize {
match blend {
FxBlend::Screen => 1,
FxBlend::Normal | FxBlend::Multiply | FxBlend::Overlay | FxBlend::SoftLight => 0,
}
}
fn blend_state(index: usize) -> wgpu::BlendState {
if index == 0 {
return wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING;
}
wgpu::BlendState {
color: wgpu::BlendComponent {
src_factor: wgpu::BlendFactor::One,
dst_factor: wgpu::BlendFactor::OneMinusSrc,
operation: wgpu::BlendOperation::Add,
},
alpha: wgpu::BlendComponent::OVER,
}
}
/// One target format's pipelines, by family and blend.
pub(crate) struct Target {
pub(crate) format: wgpu::TextureFormat,
built: [[OnceLock<wgpu::RenderPipeline>; BLENDS]; KINDS],
}
/// What every pipeline is built from, and the formats they're built for.
pub(crate) struct Pipes {
device: wgpu::Device,
layout: wgpu::PipelineLayout,
modules: [OnceLock<wgpu::ShaderModule>; KINDS],
targets: Vec<Target>,
}
impl Pipes {
pub(crate) fn new(device: &wgpu::Device, layout: wgpu::PipelineLayout, format: wgpu::TextureFormat) -> Pipes {
let mut pipes = Pipes { device: device.clone(), layout, modules: Default::default(), targets: Vec::new() };
pipes.add(format);
pipes
}
/// Makes room for `format`'s pipelines; none is built until a frame draws it.
pub(crate) fn add(&mut self, format: wgpu::TextureFormat) {
if !self.targets.iter().any(|t| t.format == format) {
self.targets.push(Target { format, built: Default::default() });
}
}
pub(crate) fn target(&self, format: wgpu::TextureFormat) -> Option<&Target> {
self.targets.iter().find(|t| t.format == format)
}
/// `kind`'s pipeline for `target` and `blend` (an index from `blend_index`), built now if no
/// frame has drawn it yet.
pub(crate) fn get<'a>(&self, target: &'a Target, kind: usize, blend: usize) -> &'a wgpu::RenderPipeline {
target.built[kind][blend].get_or_init(|| self.build(kind, blend, target.format))
}
/// Builds the pipelines `wanted` names for `format` that aren't built yet, in parallel when
/// there's more than one.
pub(crate) fn warm(&self, format: wgpu::TextureFormat, wanted: impl IntoIterator<Item = (usize, usize)>) {
let Some(target) = self.target(format) else { return };
let mut missing: Vec<(usize, usize)> = wanted.into_iter().filter(|&(k, b)| target.built[k][b].get().is_none()).collect();
missing.sort_unstable();
missing.dedup();
in_parallel(&missing, |&(k, b)| {
self.get(target, k, b);
});
}
/// Every pipeline of every format added so far.
pub(crate) fn warm_all(&self) {
for t in &self.targets {
self.warm(t.format, (0..KINDS).flat_map(|k| (0..BLENDS).map(move |b| (k, b))));
}
}
/// How many pipelines are built, across formats.
pub(crate) fn built(&self) -> usize {
self.targets.iter().flat_map(|t| t.built.iter().flatten()).filter(|p| p.get().is_some()).count()
}
fn module(&self, kind: usize) -> &wgpu::ShaderModule {
self.modules[kind].get_or_init(|| {
let (name, src) = SOURCES[kind];
self.device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some(name),
source: wgpu::ShaderSource::Wgsl(format!("{CLIP}\n{COMMON}\n{src}").into()),
})
})
}
fn build(&self, kind: usize, blend: usize, format: wgpu::TextureFormat) -> wgpu::RenderPipeline {
let module = self.module(kind);
self.device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(SOURCES[kind].0),
layout: Some(&self.layout),
vertex: wgpu::VertexState { module, 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,
entry_point: Some("fs"),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState { format, blend: Some(blend_state(blend)), write_mask: wgpu::ColorWrites::ALL })],
}),
multiview_mask: None,
cache: None,
})
}
}
/// A full-screen pass's pipelines, one per fragment entry point, all built (in parallel) the
/// first time one is needed.
pub(crate) struct Passes<const N: usize> {
device: wgpu::Device,
layout: wgpu::PipelineLayout,
label: &'static str,
source: &'static str,
entries: [&'static str; N],
format: wgpu::TextureFormat,
built: OnceLock<[wgpu::RenderPipeline; N]>,
}
impl<const N: usize> Passes<N> {
pub(crate) fn new(device: &wgpu::Device, layout: wgpu::PipelineLayout, label: &'static str, source: &'static str, entries: [&'static str; N], format: wgpu::TextureFormat) -> Self {
Passes { device: device.clone(), layout, label, source, entries, format, built: OnceLock::new() }
}
pub(crate) fn get(&self) -> &[wgpu::RenderPipeline; N] {
self.built.get_or_init(|| {
let module = self.device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some(self.label), source: wgpu::ShaderSource::Wgsl(self.source.into()) });
let slots: [OnceLock<wgpu::RenderPipeline>; N] = std::array::from_fn(|_| OnceLock::new());
let indices: [usize; N] = std::array::from_fn(|i| i);
in_parallel(&indices, |&i| {
let entry = self.entries[i];
let pipeline = self.device.create_render_pipeline(&wgpu::RenderPipelineDescriptor {
label: Some(if N == 1 { self.label } else { entry }),
layout: Some(&self.layout),
vertex: wgpu::VertexState { module: &module, entry_point: Some("vs"), compilation_options: Default::default(), buffers: &[] },
primitive: Default::default(),
depth_stencil: None,
multisample: Default::default(),
fragment: Some(wgpu::FragmentState {
module: &module,
entry_point: Some(entry),
compilation_options: Default::default(),
targets: &[Some(wgpu::ColorTargetState { format: self.format, blend: None, write_mask: wgpu::ColorWrites::ALL })],
}),
multiview_mask: None,
cache: None,
});
slots[i].set(pipeline).ok();
});
slots.map(|s| s.into_inner().expect("built"))
})
}
}
/// Runs `f` on every item, the first on this thread and the rest on their own (Metal compiles
/// pipelines concurrently), or one after another where there are no threads.
fn in_parallel<T: Sync>(items: &[T], f: impl Fn(&T) + Sync) {
#[cfg(not(target_arch = "wasm32"))]
if let [first, rest @ ..] = items
&& !rest.is_empty()
{
let f = &f;
std::thread::scope(|s| {
for item in rest {
s.spawn(move || f(item));
}
f(first);
});
return;
}
items.iter().for_each(f);
}
+649
View File
@@ -0,0 +1,649 @@
//! FxRenderer: one pipeline per effect family (built at first draw, `pipes`), one storage buffer of
//! instances, one of motion poses. `prepare` uploads and culls; `draw_layer` / `draw_all` encode
//! into the caller's render pass (target must not be the backdrop texture).
use crate::*;
use crate::binds::BindSet;
use crate::pipes::{Passes, Pipes, blend_index};
use wgpu::util::DeviceExt;
#[path = "renderer_prepare.rs"]
mod prepare;
/// Everything one frame of effects needs.
pub struct FxFrame<'a> {
pub viewport: [u32; 2],
/// Device px per pt.
pub scale: f32,
pub layers: &'a [FxLayer],
/// The target's content beneath the layers (for distortion and glass). Must not be the render
/// target. Samples are linear by default (including hardware-decoded `*Srgb` views).
/// For sRGB-encoded premultiplied samples, use `prepare_with_slots` with
/// `FxSlot::backdrop_srgb(true)`. A frame prepared with `None` instead defaults per-slot
/// copies (`set_layer_backdrop` / `blur_backdrop`) to the frame's blend encoding, matching
/// `EffectSite::backdrop`, including `Rgba16Float` isolated layers.
pub backdrop: Option<&'a wgpu::TextureView>,
/// Source textures layers refer to by `Source::slot` (mask pyramids, node layers).
pub sources: &'a [&'a wgpu::TextureView],
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct FxStats {
pub drawn: u32,
pub culled_idle: u32,
pub culled_offscreen: u32,
/// Covered device pixels across drawn quads.
pub pixels: u64,
pub needs_backdrop: bool,
}
#[derive(Clone, Copy, Debug, Default)]
pub struct FxOptions {
/// Add TPDF dither in the effect shaders (set for 8-bit targets; leave off for 16f targets
/// that dither once at the final resolve).
pub dither: bool,
}
#[derive(Clone, Copy)]
struct Prepared {
kind: usize,
instance: u32,
bind: usize,
/// Drawn quad, device px (x0, y0, x1, y1).
bounds: [f32; 4],
/// Frosted lens: blur sigma in device px (0 = no backdrop blur).
blur_px: f32,
needs_backdrop: bool,
backdrop_srgb: bool,
blend: FxBlend,
}
/// Backdrop blur pyramid: half-resolution mip chains for the dual-filter down and up passes.
struct BlurPyramid {
size: [u32; 2],
down: Vec<wgpu::TextureView>,
up: Vec<wgpu::TextureView>,
/// Up chain level 0 (half resolution): what a frosted lens samples.
result: wgpu::TextureView,
/// Down pass into mip m + 1 (from mip m); the pass into mip 0 reads the backdrop.
down_binds: Vec<wgpu::BindGroup>,
/// Up pass into mip m from down mip m + 1 (the coarsest level used) or from up mip m + 1.
up_binds: Vec<(wgpu::BindGroup, Option<wgpu::BindGroup>)>,
}
const BLUR_MIPS: u32 = 6;
const BLUR_SLOTS: usize = 64;
/// Group 1's resources: backdrop, source and blurred backdrop views, and the backdrop encoding.
pub(crate) type Fx1Key = ([wgpu::TextureView; 3], usize);
/// The index of a group binding `views` and encoding `enc`, made only when no group of this or last frame does.
pub(crate) fn fx1(
binds: &mut BindSet<Fx1Key>,
device: &wgpu::Device,
bgl: &wgpu::BindGroupLayout,
sampler: &wgpu::Sampler,
encoding: &[wgpu::Buffer; 4],
views: [&wgpu::TextureView; 3],
enc: usize,
) -> usize {
let is = |(v, e): &Fx1Key| *e == enc && v[0] == *views[0] && v[1] == *views[1] && v[2] == *views[2];
binds.find(is, || {
let bg = device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("fx1"),
layout: bgl,
entries: &[
wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(views[0]) },
wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(views[1]) },
wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::Sampler(sampler) },
wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(views[2]) },
wgpu::BindGroupEntry { binding: 4, resource: encoding[enc].as_entire_binding() },
],
});
((views.map(Clone::clone), enc), bg)
})
}
/// A blur pass's inputs; the uniform slot is a dynamic offset.
fn blur_bind(device: &wgpu::Device, bgl: &wgpu::BindGroupLayout, src: &wgpu::TextureView, fine: &wgpu::TextureView, sampler: &wgpu::Sampler, uniforms: &wgpu::Buffer) -> wgpu::BindGroup {
device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("fx blur"),
layout: bgl,
entries: &[
wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(src) },
wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(fine) },
wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::Sampler(sampler) },
wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { buffer: uniforms, offset: 0, size: wgpu::BufferSize::new(16) }) },
],
})
}
impl BlurPyramid {
fn new(device: &wgpu::Device, viewport: [u32; 2], bgl: &wgpu::BindGroupLayout, dummy: &wgpu::TextureView, sampler: &wgpu::Sampler, uniforms: &wgpu::Buffer) -> BlurPyramid {
let size = [viewport[0].div_ceil(2).max(1), viewport[1].div_ceil(2).max(1)];
let mips = BLUR_MIPS.min(32 - size[0].max(size[1]).leading_zeros());
let make = |label| {
let t = device.create_texture(&wgpu::TextureDescriptor {
label: Some(label),
size: wgpu::Extent3d { width: size[0], height: size[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: &[],
});
(0..mips)
.map(|m| t.create_view(&wgpu::TextureViewDescriptor { base_mip_level: m, mip_level_count: Some(1), ..Default::default() }))
.collect::<Vec<_>>()
};
let down = make("fx blur down");
let up = make("fx blur up");
let result = up[0].clone();
let bind = |src, fine| blur_bind(device, bgl, src, fine, sampler, uniforms);
let m = down.len();
let down_binds = (1..m).map(|k| bind(&down[k - 1], dummy)).collect();
let up_binds = (0..m - 1).map(|k| (bind(&down[k + 1], &down[k]), (k + 2 < m).then(|| bind(&up[k + 1], &down[k])))).collect();
BlurPyramid { size: viewport, down, up, result, down_binds, up_binds }
}
}
pub struct FxRenderer {
/// The effect pipelines for the frame target's `format` and those `add_format` adds.
pipes: Pipes,
format: wgpu::TextureFormat,
srgb: Option<bool>,
bgl0: wgpu::BindGroupLayout,
bgl1: wgpu::BindGroupLayout,
backdrop_encoding: [wgpu::Buffer; 4],
bg0: Option<wgpu::BindGroup>,
globals: wgpu::Buffer,
insts: rune_staging::GrowBuffer,
xforms: rune_staging::GrowBuffer,
sampler: wgpu::Sampler,
dummy: wgpu::TextureView,
binds: BindSet<Fx1Key>,
/// The blur pyramid's first pass per backdrop.
blur_binds: BindSet<wgpu::TextureView>,
prepared: Vec<Option<Prepared>>,
scratch: Vec<InstRaw>,
scratch_xf: Vec<[f32; 4]>,
/// The mask pyramid's downsampler, built by the first `build_mips`.
mip: Passes<1>,
mip_bgl: wgpu::BindGroupLayout,
blur: Option<BlurPyramid>,
/// The backdrop blur's down and up passes, built by the first frame with a frosted layer.
blur_passes: Passes<2>,
blur_bgl: wgpu::BindGroupLayout,
blur_uniforms: wgpu::Buffer,
blur_slot: usize,
viewport: [u32; 2],
opts: FxOptions,
sims: Option<crate::sim::Sims>,
/// Upload staging, made by the first `prepare`, and the globals it last wrote.
staging: Option<(rune_staging::Staging, Globals)>,
/// Packed explicit scroll-fade stops (`rune::Runtime::fade_stops`) uploaded into `backdrop_encoding.zw`.
fade_stops: [f32; 2],
uploaded_fade_stops: [f32; 2],
}
const INST_SIZE: usize = std::mem::size_of::<InstRaw>();
#[repr(C)]
#[derive(Clone, Copy, Debug, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
pub(crate) struct Globals {
pub viewport: [f32; 2],
pub dither: f32,
pub srgb: f32,
}
const _: () = {
assert!(std::mem::size_of::<Globals>() == 16);
assert!(std::mem::offset_of!(Globals, viewport) == 0);
assert!(std::mem::offset_of!(Globals, dither) == 8);
assert!(std::mem::offset_of!(Globals, srgb) == 12);
};
impl FxRenderer {
pub fn new(device: &wgpu::Device, format: wgpu::TextureFormat, opts: FxOptions) -> FxRenderer {
let entry = |binding, visibility, ty| wgpu::BindGroupLayoutEntry { binding, visibility, ty, count: None };
let vf = wgpu::ShaderStages::VERTEX_FRAGMENT;
let fr = wgpu::ShaderStages::FRAGMENT;
let storage = wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Storage { read_only: true },
has_dynamic_offset: false,
min_binding_size: None,
};
let bgl0 = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("fx0"),
entries: &[
entry(
0,
vf,
wgpu::BindingType::Buffer {
ty: wgpu::BufferBindingType::Uniform,
has_dynamic_offset: false,
min_binding_size: None,
},
),
entry(1, vf, storage),
entry(2, fr, storage),
],
});
let tex = wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: true },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
};
let bgl1 = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("fx1"),
entries: &[
entry(0, fr, tex),
entry(1, fr, tex),
entry(2, fr, wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering)),
entry(3, fr, tex),
entry(4, fr, wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: wgpu::BufferSize::new(16) }),
],
});
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("fx"),
bind_group_layouts: &[Some(&bgl0), Some(&bgl1)],
immediate_size: 0,
});
let backdrop_encoding = [(0.0f32, 0.0f32), (1.0, 0.0), (0.0, 1.0), (1.0, 1.0)].map(|(encoded, present)| {
device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
label: Some("fx backdrop encoding"),
contents: bytemuck::cast_slice(&[encoded, present, 0.0, 0.0]),
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
})
});
let pipes = Pipes::new(device, layout, format);
let globals = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("fx globals"),
size: std::mem::size_of::<Globals>() as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let sampler = device.create_sampler(&wgpu::SamplerDescriptor {
label: Some("fx linear"),
address_mode_u: wgpu::AddressMode::ClampToEdge,
address_mode_v: wgpu::AddressMode::ClampToEdge,
address_mode_w: wgpu::AddressMode::ClampToEdge,
mag_filter: wgpu::FilterMode::Linear,
min_filter: wgpu::FilterMode::Linear,
mipmap_filter: wgpu::MipmapFilterMode::Linear,
..Default::default()
});
let dummy = device
.create_texture(&wgpu::TextureDescriptor {
label: Some("fx dummy"),
size: wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: wgpu::TextureFormat::Rgba8Unorm,
usage: wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
})
.create_view(&Default::default());
// Mask pyramid downsampler (Rgba16Float levels).
let mip_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("fx mip"),
entries: &[entry(0, fr, tex), entry(1, fr, wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering))],
});
let mip_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("fx mip"),
bind_group_layouts: &[Some(&mip_bgl)],
immediate_size: 0,
});
let mip = Passes::new(device, mip_layout, "fx mip", include_str!("shaders/mip.wgsl"), ["fs"], MaskPyramid::FORMAT);
// Backdrop blur pyramid (frosted glass).
let blur_bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("fx blur"),
entries: &[
entry(0, fr, tex),
entry(1, fr, tex),
entry(2, fr, wgpu::BindingType::Sampler(wgpu::SamplerBindingType::Filtering)),
entry(3, fr, wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: true, min_binding_size: wgpu::BufferSize::new(16) }),
],
});
let blur_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("fx blur"),
bind_group_layouts: &[Some(&blur_bgl)],
immediate_size: 0,
});
let blur_passes = Passes::new(device, blur_layout, "fx blur", include_str!("shaders/blur.wgsl"), ["fs_down", "fs_up"], wgpu::TextureFormat::Rgba16Float);
let blur_uniforms = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("fx blur params"),
size: (BLUR_SLOTS * 256) as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let storage_usage = wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST;
FxRenderer {
pipes,
format,
srgb: None,
bgl0,
bgl1,
backdrop_encoding,
bg0: None,
globals,
insts: rune_staging::GrowBuffer::new(device, "fx insts", storage_usage, INST_SIZE, 64, 256),
xforms: rune_staging::GrowBuffer::new(device, "fx xforms", storage_usage, 16, 4096, 256),
sampler,
dummy,
binds: BindSet::new(),
blur_binds: BindSet::new(),
prepared: Vec::new(),
scratch: Vec::new(),
scratch_xf: Vec::new(),
mip,
mip_bgl,
blur: None,
blur_passes,
blur_bgl,
blur_uniforms,
blur_slot: 0,
viewport: [0, 0],
opts,
sims: None,
staging: None,
fade_stops: [0.0; 2],
uploaded_fade_stops: [0.0; 2],
}
}
/// Lets this renderer draw into targets of another format too, so one renderer serves a
/// window target and the `Rgba16Float` target of an isolated layer alike (`draw_layer_in`).
/// Each effect's pipeline for it is built the first time a layer draws into it.
pub fn add_format(&mut self, _device: &wgpu::Device, format: wgpu::TextureFormat) {
self.pipes.add(format);
}
/// Builds every pipeline: each effect's for every format added so far, the mask pyramid's
/// and the backdrop blur's. For the test that checks they're all precompiled.
#[doc(hidden)]
pub fn build_every_pipeline(&self) {
self.pipes.warm_all();
self.mip.get();
self.blur_passes.get();
}
/// How many effect pipelines are built so far, across formats. For tests.
#[doc(hidden)]
pub fn built_pipelines(&self) -> usize {
self.pipes.built()
}
/// Match the frame's blend mode (`rune::Frame::srgb_blend`): when true, the premultiplied
/// output is sRGB-encoded for a non-sRGB target. Per-slot copies default to that same
/// encoding when prepared without `FxFrame::backdrop`; explicit frame inputs retain their
/// linear-samples contract. `FxSlot::backdrop_srgb` overrides either convention.
/// Takes effect at the next `prepare`.
pub fn set_srgb_blend(&mut self, on: bool) {
self.srgb = Some(on);
}
/// Match the frame's explicit scroll-fade stop curve (`rune::Frame::fade_stops` /
/// `rune::render::EffectSite::fade_stops`) so effect slots inside a stops-faded scroller
/// fade along the same piecewise-linear curve as surrounding content. Takes effect at the next
/// `prepare`.
pub fn set_fade_stops(&mut self, stops: [f32; 2]) {
self.fade_stops = stops;
}
fn set_format(&mut self, format: wgpu::TextureFormat) {
self.pipes.add(format);
self.format = format;
}
/// Simulate fire and smoke (styles `Top` and `Heat`) as small fluid grids instead of noise.
/// Off by default; when on, call `simulate` every frame after `prepare` and before drawing.
pub fn set_fire_sim(&mut self, device: &wgpu::Device, on: bool) {
match (on, self.sims.is_some()) {
(true, false) => self.sims = Some(crate::sim::Sims::new(device)),
(false, true) => self.sims = None,
_ => {}
}
}
/// Whether `simulate` has steps to record this frame (false when every fire is frozen or culled).
pub fn simulate_pending(&self) -> bool {
self.sims.as_ref().is_some_and(|s| s.pending())
}
/// Record this frame's fire simulation steps (fixed 1/60 s steps) as one compute pass. Call
/// after `prepare`, outside any render pass, before drawing the fire layers. Returns false and
/// records nothing when no step is due.
pub fn simulate(&mut self, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, timestamps: Option<wgpu::ComputePassTimestampWrites<'_>>) -> bool {
self.sims.as_mut().is_some_and(|s| s.record(self.staging.as_ref().map(|(s, _)| s), queue, encoder, timestamps))
}
/// The group-1 bind group `layer` was prepared with; `None` when it was culled. For tests.
#[doc(hidden)]
pub fn layer_bind_group(&self, layer: usize) -> Option<&wgpu::BindGroup> {
let p = self.prepared.get(layer).copied().flatten()?;
Some(self.binds.get(p.bind))
}
/// Draw one prepared layer (no-op when it was culled).
pub fn draw_layer(&self, pass: &mut wgpu::RenderPass<'_>, layer: usize) {
self.draw_layer_in(pass, self.format, [0.0; 2], layer);
}
/// `draw_layer` into a pass whose target has `format` (the renderer's own, or one from
/// `add_format`) and whose top-left pixel sits at `origin` in window device pixels: zero for
/// the frame target, `rune::render::EffectSite::origin` inside an isolated layer. Effects are
/// shaded in window coordinates; the viewport is shifted so they land in that target, so they
/// take the layer's opacity, blur and clip when it composites. Resets the viewport after.
pub fn draw_layer_in(&self, pass: &mut wgpu::RenderPass<'_>, format: wgpu::TextureFormat, origin: [f32; 2], layer: usize) {
let Some(Some(p)) = self.prepared.get(layer) else { return };
let target = self.pipes.target(format).expect("FxRenderer::add_format first");
let shifted = origin != [0.0; 2];
if shifted {
pass.set_viewport(-origin[0], -origin[1], self.viewport[0] as f32, self.viewport[1] as f32, 0.0, 1.0);
}
pass.set_pipeline(self.pipes.get(target, p.kind, blend_index(p.blend)));
pass.set_bind_group(0, self.bg0.as_ref().unwrap(), &[]);
pass.set_bind_group(1, self.binds.get(p.bind), &[]);
pass.draw(0..4, p.instance..p.instance + 1);
if shifted {
pass.set_viewport(0.0, 0.0, self.viewport[0] as f32, self.viewport[1] as f32, 0.0, 1.0);
}
}
/// Draw every prepared layer with `place` in order.
pub fn draw_all(&self, pass: &mut wgpu::RenderPass<'_>, layers: &[FxLayer], place: Option<Place>) {
for (i, l) in layers.iter().enumerate() {
if place.is_none_or(|p| p == l.place) {
self.draw_layer(pass, i);
}
}
}
/// Bind a per-slot `backdrop` (`EffectSite::backdrop`) to `layer`. `blur_backdrop` calls this
/// automatically, so call it directly only when drawing a backdrop layer without `blur_backdrop`.
/// Uses the encoding chosen at `prepare` (`FxSlot::backdrop_srgb`); when prepared without
/// a frame backdrop, the default expects `EffectSite::backdrop` in the pass's own format.
pub fn set_layer_backdrop(&mut self, device: &wgpu::Device, backdrop: &wgpu::TextureView, layer: usize) {
let Some(Some(p)) = self.prepared.get(layer).copied() else { return };
if !p.needs_backdrop { return; }
let blurred = if p.blur_px > 0.0 {
self.blur.as_ref().map_or(&self.dummy, |b| &b.result)
} else {
&self.dummy
};
let enc = 2 | usize::from(p.backdrop_srgb);
let bind = fx1(&mut self.binds, device, &self.bgl1, &self.sampler, &self.backdrop_encoding, [backdrop, &self.dummy, blurred], enc);
self.prepared[layer].as_mut().unwrap().bind = bind;
}
/// Bind `backdrop` to `layer` and blur it for frosted glass (`LensParams::frost` or
/// `FlutedGlassParams::frost` above 0), scissored to the layer.
///
/// Call it after copying the backdrop for layer `layer` (for instance from the `EffectPhase::Backdrop`
/// callback of `Renderer::draw_with_backdrop` / `Renderer::encode_layers_with_backdrop` with
/// `EffectSite::backdrop`) and before drawing that layer, outside any render pass. Returns
/// false (after still binding `backdrop` when the layer reads it) for non-frosted layers; a
/// frosted lens drawn without it falls back to a small in-shader blur.
pub fn blur_backdrop(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, backdrop: &wgpu::TextureView, layer: usize) -> bool {
let staging = self.staging(device, queue);
self.set_layer_backdrop(device, backdrop, layer);
let Some(Some(p)) = self.prepared.get(layer) else { return false };
let (Some(pyr), true) = (self.blur.as_ref(), p.blur_px > 0.0) else { return false };
let mips = pyr.down.len();
if mips < 2 || self.blur_slot + mips > BLUR_SLOTS {
return false;
}
// Pyramid level (half-res mip) whose blur matches the sigma; the fraction crossfades levels.
let level = (p.blur_px / 2.0).max(1.0).log2().clamp(0.0, (mips - 1) as f32);
let n = (level.ceil() as usize).clamp(1, mips - 1);
let frac = (level - (n - 1) as f32).clamp(0.0, 1.0);
let margin = p.blur_px * 3.0 + 8.0;
let [vw, vh] = self.viewport;
let region = [(p.bounds[0] - margin).max(0.0), (p.bounds[1] - margin).max(0.0), (p.bounds[2] + margin).min(vw as f32), (p.bounds[3] + margin).min(vh as f32)];
let base = self.blur_slot;
self.blur_slot += mips;
let mut params = [0u8; BLUR_MIPS as usize * 256];
for k in 0..mips {
let w: f32 = if k + 1 == n { frac } else { 1.0 };
params[k * 256..k * 256 + 4].copy_from_slice(&w.to_le_bytes());
}
staging.write_buffer(&self.blur_uniforms, (base * 256) as u64, &params[..mips * 256]);
// Tell the lens shader the pyramid is ready (xf.x), and how much of it to use (xf.y).
let xf = [1.0f32, (p.blur_px / 3.0).min(1.0), 0.0, 0.0];
let off = p.instance as usize * INST_SIZE + std::mem::offset_of!(InstRaw, xf);
staging.write_buffer(self.insts.buffer(), off as u64, bytemuck::cast_slice(&xf));
staging.flush(encoder);
let scissor = |m: usize| {
let k = (2u32 << m) as f32;
let w = (vw.div_ceil(2) >> m).max(1);
let h = (vh.div_ceil(2) >> m).max(1);
let x0 = ((region[0] / k).floor() as u32).saturating_sub(2).min(w - 1);
let y0 = ((region[1] / k).floor() as u32).saturating_sub(2).min(h - 1);
let x1 = ((region[2] / k).ceil() as u32 + 2).min(w);
let y1 = ((region[3] / k).ceil() as u32 + 2).min(h);
(x0, y0, x1.max(x0 + 1) - x0, y1.max(y0 + 1) - y0)
};
let first = self.blur_binds.find(|k| k == backdrop, || {
(backdrop.clone(), blur_bind(device, &self.blur_bgl, backdrop, &self.dummy, &self.sampler, &self.blur_uniforms))
});
let first = self.blur_binds.get(first);
let mut run = |pipe: &wgpu::RenderPipeline, dst: &wgpu::TextureView, bg: &wgpu::BindGroup, slot: usize, m: usize| {
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("fx blur"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: dst,
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,
});
let (x, y, w, h) = scissor(m);
pass.set_scissor_rect(x, y, w, h);
pass.set_pipeline(pipe);
pass.set_bind_group(0, bg, &[(slot * 256) as u32]);
pass.draw(0..3, 0..1);
};
let [blur_down, blur_up] = self.blur_passes.get();
for m in 0..=n {
let bg = if m == 0 { first } else { &pyr.down_binds[m - 1] };
run(blur_down, &pyr.down[m], bg, base + m, m);
}
for m in (0..n).rev() {
let (from_down, from_up) = &pyr.up_binds[m];
let bg = if m + 1 == n { from_down } else { from_up.as_ref().unwrap() };
run(blur_up, &pyr.up[m], bg, base + m, m);
}
true
}
/// Fill mips 1.. of a mask pyramid from its level 0 (render the mask into `pyramid.level(0)` first).
pub fn build_mips(&self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, pyramid: &MaskPyramid) {
let binds = pyramid.binds.get_or_init(|| {
(1..pyramid.mips)
.map(|lvl| {
device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("fx mip"),
layout: &self.mip_bgl,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::TextureView(&pyramid.levels[(lvl - 1) as usize]),
},
wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::Sampler(&self.sampler) },
],
})
})
.collect()
});
let [mip] = self.mip.get();
for (lvl, bg) in (1..pyramid.mips).zip(binds) {
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("fx mip"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &pyramid.levels[lvl as usize],
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), store: wgpu::StoreOp::Store },
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
pass.set_pipeline(mip);
pass.set_bind_group(0, bg, &[]);
pass.draw(0..3, 0..1);
}
}
}
/// A mask (text, icon) and its blur pyramid, for `GlowStyle::Mask` and mask shimmer.
pub struct MaskPyramid {
pub texture: wgpu::Texture,
/// All mips: bind this as the layer source.
pub view: wgpu::TextureView,
/// One view per mip level (level 0 is the render target for the mask itself).
pub levels: Vec<wgpu::TextureView>,
pub mips: u32,
pub size: [u32; 2],
binds: std::sync::OnceLock<Vec<wgpu::BindGroup>>,
}
impl MaskPyramid {
pub const FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba16Float;
pub fn new(device: &wgpu::Device, width: u32, height: u32) -> MaskPyramid {
let mips = (32 - width.max(height).leading_zeros()).clamp(1, 7);
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: Some("fx mask pyramid"),
size: wgpu::Extent3d { width, height, depth_or_array_layers: 1 },
mip_level_count: mips,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: Self::FORMAT,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
});
let view = texture.create_view(&Default::default());
let levels = (0..mips)
.map(|m| {
texture.create_view(&wgpu::TextureViewDescriptor {
base_mip_level: m,
mip_level_count: Some(1),
..Default::default()
})
})
.collect();
MaskPyramid { texture, view, levels, mips, size: [width, height], binds: std::sync::OnceLock::new() }
}
}
+144
View File
@@ -0,0 +1,144 @@
//! `FxRenderer::prepare`: cull, pack and upload a frame's effects.
use super::*;
impl FxRenderer {
/// Cull, pack and upload. Layer `i` of `frame.layers` can then be drawn with `draw_layer(pass, i)`.
pub fn prepare(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, frame: &FxFrame) -> FxStats {
self.prepare_with_slots(device, queue, frame, &[])
}
/// Like `prepare`, with device scale and clipping for each layer's effect slot.
/// Entries correspond to `frame.layers`; missing entries use `FxSlot::default()`.
pub fn prepare_with_slots(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, frame: &FxFrame, slots: &[FxSlot]) -> FxStats {
if let Some(srgb) = self.srgb {
let target = if srgb { self.format.remove_srgb_suffix() } else { self.format.add_srgb_suffix() };
self.set_format(target);
}
let mut stats = FxStats::default();
self.scratch.clear();
self.scratch_xf.clear();
self.prepared.clear();
self.binds.begin();
self.blur_binds.begin();
let vw = frame.viewport[0] as f32;
let vh = frame.viewport[1] as f32;
self.viewport = frame.viewport;
self.blur_slot = 0;
let wants_blur = |l: &FxLayer| match l.fx {
Fx::Distort(DistortParams::Lens(p)) => p.frost > 0.0,
Fx::Fill(FillParams { style: FillStyle::FlutedGlass(p), .. }) => p.frost > 0.0,
_ => false,
};
if frame.layers.iter().any(wants_blur) {
self.blur_passes.get();
if self.blur.as_ref().is_none_or(|b| b.size != frame.viewport) {
self.blur = Some(BlurPyramid::new(device, frame.viewport, &self.blur_bgl, &self.dummy, &self.sampler, &self.blur_uniforms));
}
}
if let Some(sims) = self.sims.as_mut() {
sims.begin_frame();
}
for (index, layer) in frame.layers.iter().enumerate() {
let slot = slots.get(index).copied().unwrap_or_default();
let Some((kind, mut inst, b)) = layer.pack() else {
stats.culled_idle += 1;
self.prepared.push(None);
continue;
};
let s = if slot.scale > 0.0 { slot.scale } else { frame.scale };
let x0 = (b.x * s).floor().max(slot.clip[0].floor()).max(0.0);
let y0 = (b.y * s).floor().max(slot.clip[1].floor()).max(0.0);
let x1 = ((b.x + b.w) * s).ceil().min(slot.clip[2].ceil()).min(vw);
let y1 = ((b.y + b.h) * s).ceil().min(slot.clip[3].ceil()).min(vh);
if x1 <= x0 || y1 <= y0 {
stats.culled_offscreen += 1;
self.prepared.push(None);
continue;
}
layer.fill(&mut inst, &mut self.scratch_xf);
let grid = match (&layer.fx, self.sims.as_mut()) {
(Fx::Fire(p), Some(sims)) if matches!(p.style, FireStyle::Top | FireStyle::Heat) => {
let (g, ext) = sims.plan(device, layer, p, b, layer.reduced_motion);
inst.t[2] = 4.0;
inst.aux = [b.x, b.y, ext[0], ext[1]];
inst.p3[1] = b.w;
inst.p3[2] = b.h;
Some(g)
}
_ => None,
};
inst.bounds = [x0, y0, x1, y1];
inst.clip = slot.clip;
inst.fade = slot.fade;
inst.shape[1] = s;
inst.t[3] = ((inst.t[3] as u32) | (slot.blend.code() << 1)) as f32;
let needs_bd = layer.fx.needs_backdrop() || slot.blend.needs_backdrop();
stats.needs_backdrop |= needs_bd;
let blur_px = match layer.fx {
Fx::Distort(DistortParams::Lens(p)) => (p.frost.clamp(0.0, 1.0) * LENS_FROST_SIGMA * s).max(0.0),
Fx::Fill(FillParams { style: FillStyle::FlutedGlass(p), .. }) => (p.frost.clamp(0.0, 1.0) * LENS_FROST_SIGMA * s).max(0.0),
_ => 0.0,
};
// Layers that bind the same resources share one group, kept across frames.
let reads_bd = needs_bd && frame.backdrop.is_some();
let bd = if reads_bd { frame.backdrop.unwrap() } else { &self.dummy };
let src = match (grid, self.sims.as_ref()) {
(Some(g), Some(sims)) => sims.final_view(g),
_ => layer.source.and_then(|s| frame.sources.get(s.slot as usize).copied()).unwrap_or(&self.dummy),
};
let blurred = if blur_px > 0.0 && frame.backdrop.is_some() { self.blur.as_ref().map_or(&self.dummy, |b| &b.result) } else { &self.dummy };
let enc = (usize::from(reads_bd) << 1) | usize::from(slot.backdrop_srgb.unwrap_or(false));
let bind = fx1(&mut self.binds, device, &self.bgl1, &self.sampler, &self.backdrop_encoding, [bd, src, blurred], enc);
stats.drawn += 1;
stats.pixels += ((x1 - x0) * (y1 - y0)) as u64;
self.prepared.push(Some(Prepared { kind, instance: self.scratch.len() as u32, bind, bounds: [x0, y0, x1, y1], blur_px, needs_backdrop: needs_bd,
backdrop_srgb: slot.backdrop_srgb.unwrap_or(frame.backdrop.is_none() && self.srgb.unwrap_or(false)), blend: slot.blend }));
self.scratch.push(inst);
}
let mut regrow = self.bg0.is_none();
regrow |= self.insts.ensure(device, self.scratch.len());
regrow |= self.xforms.ensure(device, self.scratch_xf.len());
if regrow {
self.bg0 = Some(device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("fx0"),
layout: &self.bgl0,
entries: &[
wgpu::BindGroupEntry { binding: 0, resource: self.globals.as_entire_binding() },
wgpu::BindGroupEntry { binding: 1, resource: self.insts.as_entire_binding() },
wgpu::BindGroupEntry { binding: 2, resource: self.xforms.as_entire_binding() },
],
}));
}
let staging = self.staging(device, queue);
staging.write_buffer(self.insts.buffer(), 0, bytemuck::cast_slice(&self.scratch));
staging.write_buffer(self.xforms.buffer(), 0, bytemuck::cast_slice(&self.scratch_xf));
let g = Globals {
viewport: [vw, vh],
dither: if self.opts.dither { 1.0 } else { 0.0 },
srgb: if self.srgb.unwrap_or(false) { 1.0 } else { 0.0 },
};
let written = &mut self.staging.as_mut().unwrap().1;
if *written != g {
*written = g;
staging.write_buffer(&self.globals, 0, bytemuck::bytes_of(&g));
}
if self.uploaded_fade_stops != self.fade_stops {
let stops = self.fade_stops;
for (buf, (encoded, present)) in self.backdrop_encoding.iter().zip([(0.0f32, 0.0f32), (1.0, 0.0), (0.0, 1.0), (1.0, 1.0)]) {
staging.write_buffer(buf, 0, bytemuck::cast_slice(&[encoded, present, stops[0], stops[1]]));
}
self.uploaded_fade_stops = stops;
}
// Submitted now, ahead of the frame that draws them, as queue writes would be.
staging.submit();
self.pipes.warm(self.format, self.prepared.iter().flatten().map(|p| (p.kind, blend_index(p.blend))));
stats
}
/// The upload staging; its globals start unknown (NaN), so the first `prepare` writes them.
pub(super) fn staging(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) -> rune_staging::Staging {
let nan = Globals { viewport: [f32::NAN; 2], dither: f32::NAN, srgb: f32::NAN };
self.staging.get_or_insert_with(|| (rune_staging::Staging::new(device, queue), nan)).0.clone()
}
}
+57
View File
@@ -0,0 +1,57 @@
// Backdrop blur pyramid (dual filter): Jimenez 13-tap downsample chain, then a 9-tap tent
// upsample chain back to half resolution. The level where the up chain starts sets the blur
// width; `w` crossfades that level with the next finer one so an animated frost never steps.
@group(0) @binding(0) var src: texture_2d<f32>;
@group(0) @binding(1) var fine: texture_2d<f32>;
@group(0) @binding(2) var smp: sampler;
@group(0) @binding(3) var<uniform> u: vec4f; // w (coarse share), _, _, _
struct V {
@builtin(position) pos: vec4f,
@location(0) uv: vec2f,
}
@vertex
fn vs(@builtin(vertex_index) vi: u32) -> V {
let p = vec2f(f32((vi << 1u) & 2u), f32(vi & 2u));
var o: V;
o.pos = vec4f(p * 2.0 - 1.0, 0.0, 1.0);
o.uv = vec2f(p.x, 1.0 - p.y);
return o;
}
fn s(uv: vec2f) -> vec4f { return textureSampleLevel(src, smp, uv, 0.0); }
@fragment
fn fs_down(in: V) -> @location(0) vec4f {
let t = 1.0 / vec2f(textureDimensions(src, 0));
let uv = in.uv;
let a = s(uv + t * vec2f(-2.0, -2.0));
let b = s(uv + t * vec2f(0.0, -2.0));
let c = s(uv + t * vec2f(2.0, -2.0));
let d = s(uv + t * vec2f(-1.0, -1.0));
let e = s(uv + t * vec2f(1.0, -1.0));
let f = s(uv + t * vec2f(-2.0, 0.0));
let g = s(uv);
let h = s(uv + t * vec2f(2.0, 0.0));
let i = s(uv + t * vec2f(-1.0, 1.0));
let j = s(uv + t * vec2f(1.0, 1.0));
let k = s(uv + t * vec2f(-2.0, 2.0));
let l = s(uv + t * vec2f(0.0, 2.0));
let m = s(uv + t * vec2f(2.0, 2.0));
return (d + e + i + j) * 0.125 + (a + b + g + f) * 0.03125 + (b + c + h + g) * 0.03125
+ (f + g + l + k) * 0.03125 + (g + h + m + l) * 0.03125;
}
@fragment
fn fs_up(in: V) -> @location(0) vec4f {
// Tent (3x3) of the coarser level, at that level's texel spacing.
let t = 1.0 / vec2f(textureDimensions(src, 0));
let uv = in.uv;
var c = s(uv) * 4.0;
c += (s(uv + vec2f(t.x, 0.0)) + s(uv - vec2f(t.x, 0.0)) + s(uv + vec2f(0.0, t.y)) + s(uv - vec2f(0.0, t.y))) * 2.0;
c += s(uv + t) + s(uv - t) + s(uv + vec2f(t.x, -t.y)) + s(uv + vec2f(-t.x, t.y));
c /= 16.0;
let f = textureSampleLevel(fine, smp, uv, 0.0);
return mix(f, c, u.x);
}
+337
View File
@@ -0,0 +1,337 @@
// rune-fx common prelude. Concatenated in front of every effect module.
// Invariants:
// - All effect maths runs in points (pt); `px = pt * scale`. Params arrive in pt.
// - Colours are linear-light; output is premultiplied (rgb may exceed a: additive light).
// - Everything is a pure function of (pixel, instance, time, seed): integer hashes only, no sin-hash,
// so goldens are deterministic on every GPU modulo FMA.
struct Globals {
viewport: vec2f, // target size in px
dither: f32, // 1 = add TPDF dither (8-bit targets)
srgb: f32, // 1 = sRGB-blended frame: encode the premultiplied output for a non-sRGB target
}
struct Inst {
rect: vec4f, // node rect pt (x, y, w, h)
shape: vec4f, // corner radius pt, scale px/pt, layer opacity, morph
bounds: vec4f, // drawn quad px (x0, y0, x1, y1), already clipped to the viewport
c0: vec4f,
c1: vec4f,
c2: vec4f,
p0: vec4f,
p1: vec4f,
p2: vec4f,
p3: vec4f,
t: vec4f, // time s, seed, variant, flags (bit0 reduced motion)
aux: vec4f,
aux2: vec4f, // source rect pt (x, y, w, h): what the bound source texture covers
xf: vec4f, // CPU table: first vec4, counts... (per effect)
clip: vec4f, // window device-px clip rect (x0, y0, x1, y1)
fade: vec4u, // packed soft-edge and rounded-clip words (CLIP_WGSL)
}
@group(0) @binding(0) var<uniform> g: Globals;
@group(0) @binding(1) var<storage, read> insts: array<Inst>;
// Per-layer CPU tables (bolt paths, forks, embers, motion poses...), indexed from Inst.xf.x.
@group(0) @binding(2) var<storage, read> data: array<vec4f>;
fn dat1(base: u32, i: u32) -> f32 { return data[base + (i >> 2u)][i & 3u]; }
@group(1) @binding(0) var backdrop: texture_2d<f32>;
@group(1) @binding(1) var source: texture_2d<f32>;
@group(1) @binding(2) var samp: sampler;
// The backdrop's blur pyramid result (frosted glass only; see FxRenderer::blur_backdrop).
@group(1) @binding(3) var blurred: texture_2d<f32>;
@group(1) @binding(4) var<uniform> backdrop_encoding: vec4f;
// ---------- colour ----------
fn to_srgb(c: vec3f) -> vec3f {
let lo = c * 12.92;
let hi = 1.055 * pow(max(c, vec3f(0.0)), vec3f(1.0 / 2.4)) - 0.055;
return select(hi, lo, c <= vec3f(0.0031308));
}
fn to_lin(c: vec3f) -> vec3f {
let lo = c / 12.92;
let hi = pow((max(c, vec3f(0.0)) + 0.055) / 1.055, vec3f(2.4));
return select(hi, lo, c <= vec3f(0.04045));
}
// In an sRGB-blended frame (`g.srgb > 0.5`), both a non-sRGB frame target and an `Rgba16Float`
// isolated layer hold sRGB-encoded premultiplied values (`to_srgb(straight) * a, a`). Decode to
// linear premultiplied light on sample so glass, lens, distort and backdrop dither/halftone shade
// in linear light before `fs` encodes once for the target.
fn bd_lin(c: vec4f) -> vec4f {
if (backdrop_encoding.x > 0.5) {
let a = max(c.a, 0.0);
let straight = select(vec3f(0.0), c.rgb / a, a > 1e-6);
return vec4f(to_lin(straight) * a, a);
}
return c;
}
// The backdrop at p (pt), sharp and blurred.
fn bd(p: vec2f, scale: f32) -> vec4f {
return bd_lin(textureSampleLevel(backdrop, samp, p * scale / g.viewport, 0.0));
}
fn bdb(p: vec2f, scale: f32) -> vec3f {
return bd_lin(textureSampleLevel(blurred, samp, p * scale / g.viewport, 0.0)).rgb;
}
struct VOut {
@builtin(position) pos: vec4f,
@location(0) @interpolate(flat) id: u32,
@location(1) px: vec2f,
}
@vertex
fn vs(@builtin(vertex_index) vi: u32, @builtin(instance_index) ii: u32) -> VOut {
let b = insts[ii].bounds;
let corner = vec2f(f32(vi & 1u), f32((vi >> 1u) & 1u));
let px = mix(b.xy, b.zw, corner);
var o: VOut;
o.pos = vec4f(px.x / g.viewport.x * 2.0 - 1.0, 1.0 - px.y / g.viewport.y * 2.0, 0.0, 1.0);
o.id = ii;
o.px = px;
return o;
}
// The fragment's pixel centre in px, exactly: the interpolated `px` drifts by a few ulps that
// differ between quads, so two equal shapes at different places would shade a little apart. The
// draw origin is recovered from it to 1/256 px.
fn pixel(in: VOut) -> vec2f {
return in.pos.xy + round((in.px - in.pos.xy) * 256.0) / 256.0;
}
fn effective_blend_mode(i: Inst) -> u32 {
let m = (u32(i.t.w) >> 1u) & 7u;
if ((m == 1u || m == 3u || m == 4u) && backdrop_encoding.y < 0.5) {
return 0u;
}
return m;
}
fn blend_overlay_ch(b: f32, s: f32) -> f32 {
return select(1.0 - 2.0 * (1.0 - b) * (1.0 - s), 2.0 * b * s, b <= 0.5);
}
fn blend_overlay(b: vec3f, s: vec3f) -> vec3f {
return vec3f(blend_overlay_ch(b.r, s.r), blend_overlay_ch(b.g, s.g), blend_overlay_ch(b.b, s.b));
}
fn blend_soft_light_ch(b: f32, s: f32) -> f32 {
if (s <= 0.5) {
return b - (1.0 - 2.0 * s) * b * (1.0 - b);
}
let d = select(sqrt(max(b, 0.0)), ((16.0 * b - 12.0) * b + 4.0) * b, b <= 0.25);
return b + (2.0 * s - 1.0) * (d - b);
}
fn blend_soft_light(b: vec3f, s: vec3f) -> vec3f {
return vec3f(blend_soft_light_ch(b.r, s.r), blend_soft_light_ch(b.g, s.g), blend_soft_light_ch(b.b, s.b));
}
// Every effect module defines `shade`; the layer's opacity (shape.z) scales its premultiplied
// output, so a retiring one-shot fades instead of cutting.
@fragment
fn fs(in: VOut) -> @location(0) vec4f {
let i = insts[in.id];
let px = pixel(in);
let ca = clip_alpha_stops(px, i.clip, i.fade, backdrop_encoding.zw);
if (ca <= 0.0) { return vec4f(0.0); }
let c = shade(i, px) * i.shape.z;
let mode = effective_blend_mode(i);
if (mode == 0u) {
if (g.srgb > 0.5) {
// Premultiplied light may exceed alpha: a covering colour (up to alpha) plus added light.
// Encode the straight covering colour times alpha, and the added light as over black, so
// light doesn't dim as a glow's occlusion takes its alpha from zero to a little.
let cover = min(max(c.rgb, vec3f(0.0)), vec3f(c.a));
let straight = select(vec3f(0.0), cover / c.a, c.a > 1e-6);
return vec4f(to_srgb(straight) * c.a + to_srgb(max(c.rgb, vec3f(0.0)) - cover), c.a) * ca;
}
return c * ca;
}
let m = max(c.a, max(c.r, max(c.g, c.b)));
let as_ = clamp(m * ca, 0.0, 1.0);
if (as_ <= 0.0) { return vec4f(0.0); }
let cs_lin = select(vec3f(0.0), clamp(c.rgb / m, vec3f(0.0), vec3f(1.0)), m > 1e-6);
let cs = select(cs_lin, to_srgb(cs_lin), g.srgb > 0.5);
if (mode == 2u) {
return vec4f(cs * as_, as_);
}
let b_lin = bd(px, 1.0);
let ab = clamp(b_lin.a, 0.0, 1.0);
let cb_lin = select(vec3f(0.0), clamp(b_lin.rgb / ab, vec3f(0.0), vec3f(1.0)), ab > 1e-6);
let cb = select(cb_lin, to_srgb(cb_lin), g.srgb > 0.5);
var blended = cb * cs;
if (mode == 3u) { blended = blend_overlay(cb, cs); }
if (mode == 4u) { blended = blend_soft_light(cb, cs); }
return vec4f(mix(cs, blended, ab) * as_, as_);
}
const TAU: f32 = 6.2831853;
const PI: f32 = 3.14159265;
// ---------- hashing / noise (integer, deterministic) ----------
fn pcg(v: u32) -> u32 {
let s = v * 747796405u + 2891336453u;
let w = ((s >> ((s >> 28u) + 4u)) ^ s) * 277803737u;
return (w >> 22u) ^ w;
}
fn hu(a: u32, b: u32) -> u32 { return pcg(a ^ pcg(b + 0x9E3779B9u)); }
fn u01(n: u32) -> f32 { return f32(pcg(n) >> 8u) * (1.0 / 16777216.0); }
fn hcell(c: vec2i, seed: u32) -> f32 {
return f32(pcg(bitcast<u32>(c.x) ^ pcg(bitcast<u32>(c.y) ^ pcg(seed))) >> 8u) * (1.0 / 16777216.0);
}
fn grad2(c: vec2i, seed: u32) -> vec2f {
let a = hcell(c, seed) * TAU;
return vec2f(cos(a), sin(a));
}
// Gradient noise, ~[-1, 1].
fn gnoise(p: vec2f, seed: u32) -> f32 {
let i = vec2i(floor(p));
let f = p - floor(p);
let u = f * f * f * (f * (f * 6.0 - 15.0) + 10.0);
let a = dot(grad2(i, seed), f);
let b = dot(grad2(i + vec2i(1, 0), seed), f - vec2f(1.0, 0.0));
let c = dot(grad2(i + vec2i(0, 1), seed), f - vec2f(0.0, 1.0));
let d = dot(grad2(i + vec2i(1, 1), seed), f - vec2f(1.0, 1.0));
return mix(mix(a, b, u.x), mix(c, d, u.x), u.y) * 1.41421;
}
// Gradient noise periodic in x with integer period `per` (> 0).
fn pgnoise(p: vec2f, per: i32, seed: u32) -> f32 {
let i = vec2i(floor(p));
let f = p - floor(p);
let u = f * f * f * (f * (f * 6.0 - 15.0) + 10.0);
let x0 = ((i.x % per) + per) % per;
let x1 = (x0 + 1) % per;
let a = dot(grad2(vec2i(x0, i.y), seed), f);
let b = dot(grad2(vec2i(x1, i.y), seed), f - vec2f(1.0, 0.0));
let c = dot(grad2(vec2i(x0, i.y + 1), seed), f - vec2f(0.0, 1.0));
let d = dot(grad2(vec2i(x1, i.y + 1), seed), f - vec2f(1.0, 1.0));
return mix(mix(a, b, u.x), mix(c, d, u.x), u.y) * 1.41421;
}
const ROT: mat2x2f = mat2x2f(0.8, 0.6, -0.6, 0.8);
fn fbm3(p0: vec2f, seed: u32) -> f32 {
var p = p0; var a = 0.5; var s = 0.0;
for (var o = 0u; o < 3u; o++) { s += a * gnoise(p, seed + o * 131u); p = ROT * p * 2.02; a *= 0.5; }
return s / 0.875;
}
fn fbm5(p0: vec2f, seed: u32) -> f32 {
var p = p0; var a = 0.5; var s = 0.0;
for (var o = 0u; o < 5u; o++) { s += a * gnoise(p, seed + o * 131u); p = ROT * p * 2.02; a *= 0.5; }
return s / 0.96875;
}
// Interleaved gradient noise (Jimenez), static per pixel: jitter that never shimmers.
fn ign(px: vec2f) -> f32 { return fract(52.9829189 * fract(dot(floor(px), vec2f(0.06711056, 0.00583715)))); }
// ---------- shapes ----------
fn sd_rrect(q: vec2f, half: vec2f, r: f32) -> f32 {
let rr = clamp(r, 0.0, min(half.x, half.y));
let k = abs(q) - half + rr;
return length(max(k, vec2f(0.0))) + min(max(k.x, k.y), 0.0) - rr;
}
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;
}
// Arc-length coordinate of the closest boundary point of a centred rounded rect.
// Returns (s, total perimeter). Continuous everywhere except the single seam at s = 0 = total.
fn rrect_perim(q: vec2f, half: vec2f, r0: f32) -> vec2f {
let r = clamp(r0, 0.0, min(half.x, half.y));
let b = half - r;
let a = abs(q);
let lq = b.y + r * PI * 0.5 + b.x;
var s: f32;
if (a.x > b.x && a.y > b.y) {
s = b.y + r * atan2(a.y - b.y, a.x - b.x);
} else if ((a.x - b.x) > (a.y - b.y)) {
s = min(a.y, b.y);
} else {
s = b.y + r * PI * 0.5 + (b.x - min(a.x, b.x));
}
var o: f32;
if (q.x >= 0.0 && q.y >= 0.0) { o = s; }
else if (q.x < 0.0 && q.y >= 0.0) { o = 2.0 * lq - s; }
else if (q.x < 0.0) { o = 2.0 * lq + s; }
else { o = 4.0 * lq - s; }
return vec2f(o, 4.0 * lq);
}
// Shape context for the current instance.
struct Ctx {
p: vec2f, // pt
q: vec2f, // pt relative to node centre
c: vec2f, // node centre pt
half: vec2f,
r: f32,
scale: f32,
aa: f32, // one px in pt
d: f32, // signed distance to the node shape, pt
t: f32,
seed: u32,
variant: i32,
reduced: bool,
}
fn ctx(i: Inst, px: vec2f) -> Ctx {
var c: Ctx;
c.scale = i.shape.y;
c.p = px / c.scale;
c.half = i.rect.zw * 0.5;
c.c = i.rect.xy + c.half;
c.q = (px - c.c * c.scale) / c.scale;
c.r = i.shape.x;
c.aa = 1.0 / c.scale;
c.d = sd_rrect(c.q, c.half, c.r);
c.t = i.t.x;
c.seed = u32(i.t.y);
c.variant = i32(i.t.z + 0.5);
c.reduced = (u32(i.t.w) & 1u) != 0u;
return c;
}
fn sd_grad(c: Ctx) -> vec2f {
let e = 0.35;
let dx = sd_rrect(c.q + vec2f(e, 0.0), c.half, c.r) - sd_rrect(c.q - vec2f(e, 0.0), c.half, c.r);
let dy = sd_rrect(c.q + vec2f(0.0, e), c.half, c.r) - sd_rrect(c.q - vec2f(0.0, e), c.half, c.r);
let gv = vec2f(dx, dy);
return gv / max(length(gv), 1e-5);
}
// ---------- light profiles ----------
fn erf_approx(x: f32) -> f32 {
let x2 = x * x;
let a = 0.147;
let v = sqrt(1.0 - exp(-x2 * (1.2732395 + a * x2) / (1.0 + a * x2)));
return select(-v, v, x >= 0.0);
}
// Coverage of a half-plane blurred by a Gaussian of sigma s, at signed distance d.
fn cov(d: f32, s: f32) -> f32 { return 0.5 - 0.5 * erf_approx(d / (max(s, 1e-3) * 1.41421)); }
// Bloom of a shape edge: a tight lobe that carries most of the light plus a wider one, both
// Gaussian so the light is gone by ~2.5 r (heavy tails read as a uniform haze over dark UI).
// Windowed to `reach` so the quad edge never shows. Continuous through d = 0 (inside saturates).
fn bloom(d: f32, r: f32, reach: f32) -> f32 {
let o = max(d, 0.0);
let w = 1.0 - smoothstep(reach * 0.5, reach, o);
return (0.65 * gauss(o, r * 0.35) + 0.35 * gauss(o, r * 1.2)) * w;
}
// Soft knee for light energy: linear when dim, approaching 1 when bright, so a tinted glow
// keeps its hue instead of clipping toward white.
fn knee(x: f32) -> f32 { return 1.0 - exp(-max(x, 0.0)); }
fn gauss(x: f32, w: f32) -> f32 { return exp(-(x * x) / max(w * w, 1e-6)); }
fn lum(c: vec3f) -> f32 { return dot(c, vec3f(0.2126, 0.7152, 0.0722)); }
// A colour as its light cools: dims and deepens (saturates) instead of just fading.
fn cooled(c: vec3f, heat: f32) -> vec3f {
let deep = c * c / max(max(c.r, max(c.g, c.b)), 0.02);
return mix(deep * 0.55, c, smoothstep(0.0, 0.75, heat));
}
fn segdist(p: vec2f, a: vec2f, b: vec2f) -> vec2f {
let ab = b - a;
let h = clamp(dot(p - a, ab) / max(dot(ab, ab), 1e-6), 0.0, 1.0);
return vec2f(length(p - a - ab * h), h);
}
// Final write: clamp, optional TPDF dither (applied in sRGB space, only where there is signal).
fn finish(c0: vec4f, px: vec2f) -> vec4f {
var c = max(c0, vec4f(0.0));
c.a = min(c.a, 1.0);
if (g.dither > 0.5) {
let ip = vec2u(px);
let n = (u01(ip.x + pcg(ip.y)) + u01(ip.x * 7919u + pcg(ip.y + 104729u))) - 1.0;
let s = to_srgb(c.rgb);
let gate = smoothstep(0.0, 3.0 / 255.0, max(s.r, max(s.g, s.b)));
c = vec4f(to_lin(max(s + vec3f(n / 255.0 * gate), vec3f(0.0))), c.a);
}
return c;
}
+216
View File
@@ -0,0 +1,216 @@
// Distortion of the backdrop (needs `backdrop` = target content right before this layer).
// variant: 0 heat haze, 1 shockwave, 2 liquid-glass lens, 3 CRT, 4 chromatic split.
//
// heat: p0 (height pt, scale pt, speed, amount pt) p1 (full rect 0/1, _, _, _)
// shock: p0 (reach pt, width pt, amount pt, chroma) p1 (t0, duration, _, _) aux: origin
// lens: p0 (bevel pt, depth pt, dispersion, magnification) p1 (presence, frost, shadow, rim)
// p2 (light angle rad, tint, union k pt, radius B) p3 rect B (w = 0: none) shape.w morph A->B
// c0 tint
// crt: p0 (bulge, scanline period pt, scanline depth, chroma pt) p1 (vignette, glow, roll, feather)
// split: p0 (offset x pt, offset y pt, glitch, feather)
// Frosted material, after Apple's "regular" glass: a saturation boost puts back the colour that
// blur and scrim take out, and a compressive transfer lifts dark backdrops while light ones
// barely move (macOS 26 Control Center measures sRGB L' = 0.58 L + 0.134; iOS keeps more of
// the colour, so this sits a little above that). k = 0..1.
fn frosted(c: vec3f, k: f32) -> vec3f {
let l = lum(c);
let sat = max(mix(vec3f(l), c, 1.0 + 0.9 * k), vec3f(0.0));
let e = to_srgb(sat);
return to_lin(e * (1.0 - 0.32 * k) + vec3f(0.11 * k));
}
fn lens_sd(c: Ctx, i: Inst, q: vec2f) -> f32 {
let da = sd_rrect(q, c.half, c.r);
if (i.p3.z <= 0.0) { return da; }
let cb = i.p3.xy + i.p3.zw * 0.5 - c.c;
let db = sd_rrect(q - cb, i.p3.zw * 0.5, i.p2.w);
return mix(smin(da, db, i.p2.z), db, i.shape.w);
}
// Thin-surface optics (psychopomp math/optics.rs): sideways travel per unit depth through a surface
// whose tilt rises from vertical at the rim to flat (superellipse bevel, power 3).
fn bend_at(t: f32) -> f32 {
let u = clamp(1.0 - t, 0.0, 0.9999);
let pw = 3.0;
let slope = pow(u, pw - 1.0) * pow(max(1.0 - pow(u, pw), 1e-6), 1.0 / pw - 1.0);
let tilt = atan(min(slope, 1e4));
let bent = asin(sin(tilt) / 1.5);
return tan(tilt - bent);
}
fn shade(i: Inst, px: vec2f) -> vec4f {
let c = ctx(i, px);
let s = c.scale;
if (c.variant == 0) {
let H = i.p0.x;
var m: f32;
if (i.p1.x > 0.5) {
m = smoothstep(c.aa, -c.aa * 8.0, c.d);
} else {
let above = i.rect.y - c.p.y;
let side = smoothstep(c.half.x + 2.0, c.half.x - c.r - 4.0, abs(c.q.x));
// Starts just clear of the edge so the shape itself never wobbles, and is strongest a
// little up the column where the hot air has risen off the flame tips.
m = smoothstep(1.0, 1.0 + H * 0.3, above) * (1.0 - smoothstep(H * 0.45, H, above)) * side;
}
if (m <= 0.0) { return vec4f(0.0); }
var t = c.t;
if (c.reduced) { t = 0.0; }
let q = c.p / max(i.p0.y, 1.0) + vec2f(0.0, t * i.p0.z);
let o = vec2f(fbm3(q, c.seed), fbm3(q * vec2f(1.0, 0.7) + vec2f(7.3, 2.1), c.seed + 5u)) * i.p0.w;
let col = bd(c.p + o * m, s);
return vec4f(col.rgb, 1.0) * smoothstep(0.0, 0.02, m);
}
if (c.variant == 1) {
let age = c.t - i.p1.x;
let dur = max(i.p1.y, 0.05);
if (age < 0.0 || age > dur) { return vec4f(0.0); }
let u = age / dur;
let rel = c.p - i.aux.xy;
let r = length(rel);
let dir = rel / max(r, 1e-3);
let fade = (1.0 - u) * (1.0 - u);
if (c.reduced) {
// No travel: a soft brightening at the origin that cools.
let gl = gauss(r, i.p0.x * 0.25) * 0.12 * fade * smoothstep(0.0, 0.1, u);
return vec4f(bd(c.p, s).rgb * gl, 0.0);
}
let R = i.p0.x * (1.0 - pow(1.0 - u, 2.6));
let w = i.p0.y * (1.0 + 1.5 * u);
let x = (r - R) / w;
let f = x * exp(-x * x) * 2.33;
let off = -dir * f * i.p0.z * fade;
let ca = i.p0.w * abs(f) * fade;
let rr = bd(c.p + off * (1.0 + ca), s).r;
let gg = bd(c.p + off, s).g;
let bb = bd(c.p + off * (1.0 - ca), s).b;
// Highlight only where there is content to catch it (no grey donut over empty space).
let lit = max(-f, 0.0) * 0.12 * fade * lum(vec3f(rr, gg, bb));
let m = smoothstep(0.0, 0.01, abs(f) * fade);
return vec4f(vec3f(rr, gg, bb) + lit, 1.0) * m;
}
if (c.variant == 2) {
let d = lens_sd(c, i, c.q);
let presence = i.p1.x;
let e = 0.5;
let gx = lens_sd(c, i, c.q + vec2f(e, 0.0)) - lens_sd(c, i, c.q - vec2f(e, 0.0));
let gy = lens_sd(c, i, c.q + vec2f(0.0, e)) - lens_sd(c, i, c.q - vec2f(0.0, e));
let nrm = vec2f(gx, gy) / max(length(vec2f(gx, gy)), 1e-5);
let coverage = clamp(0.5 - d * s, 0.0, 1.0);
// Drop shadow + contact (outside), scaled by presence: glass materialises by lensing.
let sd = lens_sd(c, i, c.q - vec2f(0.0, 5.0 * presence));
let fall = exp(-pow(max(sd + 2.0, 0.0), 2.0) / (2.0 * 9.0 * 9.0));
let contact = exp(-pow(max(d, 0.0), 2.0) / 6.0);
let dark = min(i.p1.z * presence * (0.55 * fall + 0.45 * contact), 1.0) * (1.0 - coverage);
if (coverage <= 0.0) {
return vec4f(0.0, 0.0, 0.0, dark);
}
let depth = -d;
let bevel = max(i.p0.x, 0.5);
let tt = clamp(depth / bevel, 0.0, 1.0);
let bend = i.p0.y * bend_at(tt) * presence;
let mag = mix(1.0, i.p0.w, presence);
let ctr = c.c;
let inward = -nrm;
let dsp = i.p0.z;
let local = c.p - ctr;
let srcg = ctr + (local + inward * bend) / mag;
let srcr = ctr + (local + inward * bend * (1.0 - dsp)) / mag;
let srcb = ctr + (local + inward * bend * (1.0 + dsp)) / mag;
var col = vec3f(bd(srcr, s).r, bd(srcg, s).g, bd(srcb, s).b);
let frost = i.p1.y;
if (frost > 0.0 && i.xf.x > 0.5) {
// Frosted: the dual-filter pyramid, refracted like the clear image (so the rim still
// bends and splits), then the material transfer and a static grain against banding.
let blr = vec3f(bdb(srcr, s).r, bdb(srcg, s).g, bdb(srcb, s).b);
col = mix(col, blr, i.xf.y);
let k = presence * smoothstep(0.0, 0.6, frost);
col = frosted(col, k);
let ip = vec2u(px);
let n = u01(ip.x + pcg(ip.y + 7u)) - u01(ip.x * 7919u + pcg(ip.y + 31u));
col = to_lin(max(to_srgb(col) + vec3f(n * 1.6 / 255.0 * k), vec3f(0.0)));
} else {
// Rim softening where the page is squeezed into a thin band (+ a small fallback frost
// when no pyramid was built).
let rim = bend / max(1.118 * i.p0.y, 1e-3);
let soften = min(pow(rim, 1.5) * 0.55, 1.0);
if (soften > 1e-3 || frost > 0.0) {
let rad = mix(1.2, 10.0, frost);
let j = ign(px) * TAU;
var acc = vec3f(0.0);
for (var k = 0; k < 8; k++) {
let a = j + f32(k) * 2.39996;
let rr = rad * sqrt((f32(k) + 0.5) / 8.0);
acc += bd(srcg + vec2f(cos(a), sin(a)) * rr, s).rgb;
}
acc /= 8.0;
col = mix(col, acc, clamp(max(soften, frost), 0.0, 1.0));
}
}
col = mix(col, col * i.c0.rgb, i.p2.y * presence);
// Light: sky sheen, crisp specular where the rim faces the light, a fainter counter-line, hairline.
let la = i.p2.x;
let L = vec2f(cos(la), sin(la));
let facing = max(dot(nrm, L), 0.0);
let away = max(-dot(nrm, L), 0.0);
let sky = clamp(0.5 - 0.5 * c.q.y / c.half.y, 0.0, 1.0);
let rimk = i.p1.w;
let fres = pow(1.0 - tt, 3.0) * 0.05 * (0.25 + 0.75 * sky);
let line = gauss(depth - 0.75, 0.55);
let glow = gauss(depth - 1.4, 2.4);
let spec = line * (0.9 * pow(facing, 2.5) + 0.35 * pow(away, 3.0)) + glow * 0.1 * pow(facing, 4.0);
let inner = gauss(tt - 0.32, 0.18) * away * away * 0.06;
let edge = gauss(depth - 0.3, 0.45) * 0.12;
let light = (0.004 + fres + spec + inner + edge) * presence * rimk;
col = col * (1.0 - 0.04 * presence) + vec3f(light);
// Coverage blends glass over the untouched backdrop + shadow.
let base = bd(c.p, s).rgb * (1.0 - dark);
return vec4f(mix(base, col, coverage), 1.0);
}
if (c.variant == 3) {
let feather = max(i.p1.w, c.aa);
let m = smoothstep(feather * 0.5, -feather * 0.5, c.d);
if (m <= 0.0) { return vec4f(0.0); }
let uv = c.q / c.half;
let k = i.p0.x;
let bu = uv * (1.0 + k * dot(uv, uv)) / (1.0 + k);
let inside = smoothstep(1.0, 0.985, max(abs(bu.x), abs(bu.y)));
let src = c.c + bu * c.half;
let ca = i.p0.w;
var col = vec3f(bd(src + vec2f(ca, 0.0), s).r, bd(src, s).g, bd(src - vec2f(ca, 0.0), s).b);
// Glow: cheap 4-tap bloom of the source.
let gw = 3.0;
let gl = (bd(src + vec2f(gw, 0.0), s).rgb + bd(src - vec2f(gw, 0.0), s).rgb + bd(src + vec2f(0.0, gw), s).rgb + bd(src - vec2f(0.0, gw), s).rgb) * 0.25;
col += gl * i.p1.y;
let per = max(i.p0.y, 3.0 * c.aa);
let sl = 0.5 + 0.5 * cos(TAU * (c.p.y - i.rect.y) / per);
col *= 1.0 - i.p0.z * (1.0 - sl);
// Aperture grille, very subtle.
let col3 = u32(floor(px.x)) % 3u;
let grille = select(select(vec3f(0.94, 0.94, 1.0), vec3f(0.94, 1.0, 0.94), col3 == 1u), vec3f(1.0, 0.94, 0.94), col3 == 0u);
col *= grille;
var roll = 0.0;
if (!c.reduced) { roll = gauss(fract((c.p.y - i.rect.y) / i.rect.w - c.t * 0.12) - 0.5, 0.06) * i.p1.z; }
col += vec3f(roll) * 0.06;
col *= 1.0 - i.p1.x * pow(dot(uv, uv) * 0.5, 1.5);
col *= inside;
return vec4f(col, 1.0) * m;
}
// Chromatic split with optional glitch slices.
let feather = max(i.p0.w, c.aa);
let m = smoothstep(feather * 0.5, -feather * 0.5, c.d);
if (m <= 0.0) { return vec4f(0.0); }
var o = i.p0.xy;
var gx = 0.0;
if (i.p0.z > 0.0 && !c.reduced) {
let slice = floor((c.p.y - i.rect.y) / 6.0);
let fr = floor(c.t * 12.0);
let hsl = hu(c.seed + bitcast<u32>(i32(slice)), bitcast<u32>(i32(fr)));
if (u01(hsl) < 0.12 * i.p0.z) { gx = (u01(hsl + 1u) - 0.5) * 16.0 * i.p0.z; }
}
let p = c.p + vec2f(gx, 0.0);
let col = vec3f(bd(p + o, s).r, bd(p, s).g, bd(p - o, s).b);
return vec4f(col, 1.0) * m;
}
+165
View File
@@ -0,0 +1,165 @@
// Electricity. variant: 0 arc A -> B, 1 around the border, 2 charged border (calm UI variant).
// Bolt paths, crawl and forks are CPU tables (cpu.rs::electric); the shader only measures distance
// to them and lights it. xf = (first, N samples, forks, strands).
// c0 glow tint, c1 hot core, c2 cooled fork colour
// p0 (amplitude pt, frequency cells/100pt, speed, core width pt)
// p1 (intensity, glow radius pt, fork rate 0..1, flicker 0..1)
// p2 (strands, gap pt (border offset), fork length pt, occlusion)
// aux: A xy, B xy (arc)
struct Bolt { core: f32, halo: f32 }
fn shade_bolt(dist: f32, w: f32, gr: f32) -> Bolt {
var b: Bolt;
b.core = gauss(dist, w);
let o = dist / gr;
// A narrow coloured sheath plus a faint 1/(1+d^2) tail: the air right around the channel glows,
// not a wide haze.
b.halo = 0.35 / (1.0 + o * o) * (1.0 - smoothstep(gr * 2.5, gr * 5.0, dist)) + 0.65 * gauss(dist, gr * 0.6);
return b;
}
// Lateral distance to a sampled path, slope-corrected but capped so steep jags never smear
// into streaks.
fn lat(dv: f32, a: f32, b: f32, step: f32) -> f32 {
let s = (b - a) / step;
// Near field: perpendicular distance to the local segment. Far field: the plain lateral offset
// (already a good distance there), so the halo never streaks along steep jags.
let k = inverseSqrt(1.0 + min(s * s, 3.0));
return dv * mix(k, 1.0, smoothstep(1.5, 8.0, abs(dv)));
}
fn fork_col(i: Inst, heat: f32) -> vec3f {
return mix(mix(i.c2.rgb, i.c0.rgb, smoothstep(0.0, 0.5, heat)), i.c1.rgb, smoothstep(0.6, 1.0, heat));
}
fn shade(i: Inst, px: vec2f) -> vec4f {
let c = ctx(i, px);
let w = max(i.p0.w, c.aa * 0.7);
let inten = i.p1.x;
let gr = max(i.p1.y, 1e-3);
let gap = i.p2.y;
let first = u32(i.xf.x);
let n = u32(i.xf.y);
let nf = u32(i.xf.z);
let ns = u32(i.xf.w);
let q4 = n >> 2u;
let fl = data[first + 1u];
let base = first + 2u;
var core = 0.0;
var halo = 0.0;
var fork_hot = vec3f(0.0);
if (c.variant == 0) {
let a = i.aux.xy;
let bb = i.aux.zw;
let L = max(length(bb - a), 1.0);
let dir = (bb - a) / L;
let nrm = vec2f(-dir.y, dir.x);
let rel = c.p - a;
let u = dot(rel, dir) / L;
let v = dot(rel, nrm);
let uc = clamp(u, 0.0, 1.0);
let fi = uc * f32(n - 1u);
let i0 = min(u32(fi), n - 2u);
let f = fi - f32(i0);
let step = L / f32(n - 1u);
for (var k = 0u; k < ns; k++) {
let sb = base + k * q4;
let d0 = dat1(sb, i0);
let d1 = dat1(sb, i0 + 1u);
let dd = length(vec2f((u - uc) * L, lat(v - mix(d0, d1, f), d0, d1, step)));
let hb = base + (ns + k) * q4;
let dh = length(vec2f((u - uc) * L, v - mix(dat1(hb, i0), dat1(hb, i0 + 1u), f)));
let bw = select(w * 0.6, w, k == 0u);
var bo = shade_bolt(dd, bw, gr);
bo.halo = 0.4 * shade_bolt(dh, bw, gr).halo + 0.6 * shade_bolt(dd, bw, gr * 0.3).halo;
let kb = select(0.32, 1.0, k == 0u) * fl[k];
core += bo.core * kb;
halo += bo.halo * kb;
}
// Electrode hot spots.
halo += 0.6 * (gauss(length(c.p - a), gr * 0.8) + gauss(length(c.p - bb), gr * 0.8));
core += 0.5 * (gauss(length(c.p - a), w * 2.5) + gauss(length(c.p - bb), w * 2.5));
var fb = base + 2u * ns * q4;
for (var j = 0u; j < nf; j++) {
let h0 = data[fb];
let h1 = data[fb + 1u];
let o = h0.xy;
let fd = h0.zw;
let len = h1.x;
let fr = c.p - o;
let fu = dot(fr, fd) / len;
let fv = dot(fr, vec2f(-fd.y, fd.x));
let fuc = clamp(fu, 0.0, h1.y);
let ffi = fuc * 15.0;
let j0 = min(u32(ffi), 14u);
let s0 = dat1(fb + 2u, j0);
let s1 = dat1(fb + 2u, j0 + 1u);
let fdist = length(vec2f((fu - fuc) * len, lat(fv - mix(s0, s1, ffi - f32(j0)), s0, s1, len / 15.0)));
let taper = 1.0 - 0.7 * fuc;
let bo = shade_bolt(fdist, w * 0.6 * taper, gr * 0.55);
fork_hot += fork_col(i, h1.w) * (bo.core * 1.1 + bo.halo * 0.45) * h1.z * taper;
fb += 6u;
}
} else {
let pr = rrect_perim(c.q, c.half, c.r);
let s = pr.x;
let total = pr.y;
let calm = c.variant == 2;
let fi = s / total * f32(n);
let i0 = u32(floor(fi)) % n;
let i1 = (i0 + 1u) % n;
let f = fi - floor(fi);
let step = total / f32(n);
for (var k = 0u; k < ns; k++) {
let sb = base + k * q4;
let d0 = dat1(sb, i0);
let d1 = dat1(sb, i1);
let dd = abs(lat(c.d - gap - mix(d0, d1, f), d0, d1, step));
let hb = base + (ns + k) * q4;
let dh = abs(c.d - gap - mix(dat1(hb, i0), dat1(hb, i1), f));
let cb = base + (2u * ns + k) * q4;
let crawl = mix(dat1(cb, i0), dat1(cb, i1), f);
let bw = select(w * 0.6, w, k == 0u);
var bo = shade_bolt(dd, bw, gr);
bo.halo = 0.4 * shade_bolt(dh, bw, gr).halo + 0.6 * shade_bolt(dd, bw, gr * 0.3).halo;
let kb = select(0.32, 1.0, k == 0u) * fl[k] * crawl;
core += bo.core * kb;
halo += bo.halo * kb;
}
if (calm) {
// Beads of charge travelling one way around the border.
let sp = i.p0.z * 0.35;
let bu = fract(s / total - c.t * 0.07 * sp);
for (var k = 0; k < 3; k++) {
let x = fract(bu - f32(k) / 3.0 + 0.5) - 0.5;
let bead = gauss(x * total, 18.0);
halo += bead * gauss(c.d - gap, gr * 0.8) * 0.9;
core += bead * gauss(c.d - gap, w * 1.5) * 0.6;
}
}
var fb = base + 3u * ns * q4;
for (var j = 0u; j < nf; j++) {
let h0 = data[fb];
let h1 = data[fb + 1u];
let len = h1.x;
var dsv = s - h0.x;
dsv -= total * round(dsv / total);
let fu = (c.d - gap - h0.z) / len;
let fuc = clamp(fu, 0.0, h1.y);
let ffi = fuc * 15.0;
let j0 = min(u32(ffi), 14u);
let s0 = dat1(fb + 2u, j0);
let s1 = dat1(fb + 2u, j0 + 1u);
let fdist = length(vec2f((fu - fuc) * len, lat(dsv - mix(s0, s1, ffi - f32(j0)), s0, s1, len / 15.0)));
let taper = 1.0 - 0.7 * fuc;
let bo = shade_bolt(fdist, w * 0.6 * taper, gr * 0.55);
fork_hot += fork_col(i, h1.w) * (bo.core * 1.1 + bo.halo * 0.45) * h1.z * taper;
fb += 6u;
}
}
let occl = select(1.0, i.p2.w, effective_blend_mode(i) == 0u);
let rgb = (i.c1.rgb * core * 1.3 + i.c0.rgb * halo * 0.75 + fork_hot) * inten;
let a = (core * 0.7 + halo * occl + lum(fork_hot) * 0.5) * inten;
return finish(vec4f(rgb, a), px);
}
+108
View File
@@ -0,0 +1,108 @@
// Extras. variant: 0 shimmer/sheen sweep, 1 sparkles, 2 aurora, 3 grain.
// shimmer: c0 sheen, c1 base (a = 0: none) p0 (period, band pt, angle rad, intensity) p1 (use mask, pause, feather, _)
// sparkle: c0 colour p0 (count, life s, size pt, intensity) p1 (margin pt, _, _, _)
// aurora: c0 c1 c2 curtains p0 (scale pt, speed, intensity, feather pt)
// grain: p0 (amount, fps (0 = static), feather, _)
// Inner feather: fully inside the shape, so overlays never leak past the node's edge.
fn cover(c: Ctx, feather: f32) -> f32 { return smoothstep(c.aa * 0.5, -max(feather, c.aa), c.d); }
fn shade(i: Inst, px: vec2f) -> vec4f {
let c = ctx(i, px);
if (c.variant == 0) {
var m: f32;
if (i.p1.x > 0.5) {
m = textureSampleLevel(source, samp, (c.p - i.aux2.xy) / i.aux2.zw, 0.0).a;
} else {
m = cover(c, max(i.p1.z, c.aa * 1.5));
}
if (m <= 0.0) { return vec4f(0.0); }
let ta = tan(i.p0.z);
let span = c.half.x + c.half.y * abs(ta) + i.p0.y * 2.5;
let x = c.q.x + c.q.y * ta;
var sheen: f32;
if (c.reduced) {
// Calm: the whole surface breathes slightly instead of a travelling band.
sheen = 0.35 * (0.5 - 0.5 * cos(TAU * c.t / max(i.p0.x, 0.1)));
} else {
let ph = fract(c.t / max(i.p0.x, 0.1));
let travel = clamp(ph / max(1.0 - i.p1.y, 0.05), 0.0, 1.0);
let e = travel * travel * (3.0 - 2.0 * travel);
let xc = mix(-span, span, e);
sheen = gauss(x - xc, i.p0.y) + 0.35 * gauss(x - xc, i.p0.y * 2.6);
}
let base = i.c1.rgb * i.c1.a;
return finish(vec4f(base * m + i.c0.rgb * sheen * i.p0.w * m, i.c1.a * m + sheen * i.p0.w * m * 0.2), px);
}
if (c.variant == 1) {
let f0 = u32(i.xf.x);
let n = u32(i.xf.y);
var body = 0.0;
var hot = 0.0;
var halo = 0.0;
for (var k = 0u; k < n; k++) {
let a = data[f0 + k * 2u];
let b = data[f0 + k * 2u + 1u];
let S = max(a.z, 0.01);
let env = a.w;
let rel = c.p - a.xy;
let r = length(rel);
if (r > S * 1.6) { continue; }
let l = vec2f(b.x * rel.x - b.y * rel.y, b.y * rel.x + b.x * rel.y);
// Four-point star: |x|^p + |y|^p = 1 with p < 1 gives concave sides and needle tips.
// g is homogeneous of degree 1, so (g - 1) * S is roughly a distance in points.
let ax = max(abs(l) / S, vec2f(1e-6));
let g = pow(pow(ax.x, 0.55) + pow(ax.y, 0.55), 1.0 / 0.55);
let w = c.aa * 0.75 / S;
let m = 1.0 - smoothstep(1.0 - w, 1.0 + w, g);
body += env * m;
hot += env * m * (1.0 - g) * (1.0 - g);
halo += env * gauss(r, S * 0.32);
}
let tint = i.c0.rgb;
let col = mix(tint, vec3f(1.0), 0.3) * body + vec3f(1.0) * hot * 0.8 + tint * halo * 0.12;
return finish(vec4f(col * i.p0.w, min(body * 0.9 + halo * 0.05, 1.0) * i.p0.w), px);
}
if (c.variant == 2) {
let m = cover(c, max(i.p0.w, c.aa));
if (m <= 0.0) { return vec4f(0.0); }
let sc = max(i.p0.x, 1.0);
let q = c.p / sc;
var t = c.t * i.p0.y;
if (c.reduced) { t = 0.0; }
let uy = (c.p.y - i.rect.y) / i.rect.w;
var col = vec3f(0.0);
let cols = array<vec3f, 3>(i.c0.rgb, i.c1.rgb, i.c2.rgb);
// Curtain heights and warps across the width are CPU tables (cpu.rs::aurora).
let f0 = u32(i.xf.x);
let ns = u32(i.xf.y);
let fx = clamp((c.p.x - i.rect.x) / i.rect.z, 0.0, 1.0) * f32(ns - 1u);
let x0 = min(u32(fx), ns - 2u);
let fr = fx - f32(x0);
for (var k = 0; k < 3; k++) {
let fk = f32(k);
let yb = f0 + u32(k) * 2u * (ns >> 2u);
let wb = yb + (ns >> 2u);
let wv = mix(dat1(wb, x0), dat1(wb, x0 + 1u), fr);
let yk = mix(dat1(yb, x0), dat1(yb, x0 + 1u), fr);
let band = gauss(uy - yk, 0.13 + 0.05 * fk);
let rays = 0.65 + 0.35 * gnoise(vec2f(q.x * 5.0 + wv * 3.0, t * 0.5 + fk), c.seed + 9u);
// Curtains have a bright lower hem and fade upward.
let hem = smoothstep(yk + 0.16, yk - 0.02, uy) * 0.5 + 0.5;
col += cols[k] * band * rays * hem;
}
let a = select(min(max(col.r, max(col.g, col.b)), 1.0), lum(col) * 0.4, effective_blend_mode(i) == 0u);
return finish(vec4f(col * i.p0.z * m, a * i.p0.z * m), px);
}
// Grain.
let m = cover(c, max(i.p0.z, c.aa));
if (m <= 0.0) { return vec4f(0.0); }
var frame = 0u;
if (i.p0.y > 0.0 && !c.reduced) { frame = u32(floor(c.t * i.p0.y)); }
let ip = vec2u(px);
let n = u01(ip.x + pcg(ip.y + pcg(frame + c.seed))) + u01(ip.y * 7919u + pcg(ip.x + 17u + frame)) - 1.0;
let a = i.p0.x * m;
if (n >= 0.0) { return vec4f(vec3f(n * a), n * a); }
return vec4f(0.0, 0.0, 0.0, -n * a);
}
+550
View File
@@ -0,0 +1,550 @@
// Fills: styles that paint the node's shape, or a band inside its edge (aux.x = border pt, 0 = whole
// shape). aux.y = intensity. Colour lists live in the CPU table: for stop k, data[xf.x + 2k] is
// linear rgb (w: mesh point x), data[xf.x + 2k + 1] is OKLab (w: mesh point y); xf.y stops.
// variant:
// 0 liquid metal c0 tint c1 light p0 (flow, scale pt, speed, bevel pt) p1 (dome, angle, iridescence, contrast)
// p2 (anchor: 0 window, 1 shape, _, _, _)
// 1 mesh p0 (drift, speed, sharpness, warp) (points are animated on the CPU)
// 2 dither p0 (pattern, input, pixel pt, ramp angle) p1 (noise scale pt, speed, bias, contrast)
// xf.zw blue-noise tile (offset, side)
// 3 grain grad. p0 (kind, angle, centre x, centre y) p1 (amount, size pt, mono, fps)
// 4 fluted glass c0 tint p0 (rib pt, angle, refraction pt, frost) p1 (dispersion, highlight, tint amount, _)
// xf.xy frost pyramid (set by FxRenderer::blur_backdrop)
// 5 metaballs c0 base p0 (count, size, speed, gloss) xf.z balls: (x pt, y pt, r pt, stop)
// 6 swirl p0 (scale pt, speed, twist, warp)
// 7 voronoi c0 seam p0 (cell pt, speed, seam pt, depth)
// 8 waves p0 (amplitude, frequency, speed, angle) p1 (softness, _, _, _)
// 9 halftone c0 ink c1 base p0 (_, input, pitch pt, ramp angle) p1 as dither p2 (screen angle, _, _, _)
// 10 plastic c0 colour p0 (roughness, dome, bevel pt, light angle)
// Shape coverage: the whole shape, or (border > 0) a band of that width inside the edge.
fn fill_mask(c: Ctx, border: f32) -> f32 {
let inside = clamp(0.5 - c.d * c.scale, 0.0, 1.0);
if (border <= 0.0) { return inside; }
return inside * clamp(0.5 + (c.d + border) * c.scale, 0.0, 1.0);
}
fn rot2(v: vec2f, a: f32) -> vec2f {
let cs = cos(a);
let sn = sin(a);
return vec2f(cs * v.x - sn * v.y, sn * v.x + cs * v.y);
}
// ---------- colour lists ----------
fn stop_lin(f0: u32, k: u32) -> vec3f { return data[f0 + 2u * k].rgb; }
fn stop_lab(f0: u32, k: u32) -> vec3f { return data[f0 + 2u * k + 1u].rgb; }
fn stop_pt(f0: u32, k: u32) -> vec2f { return vec2f(data[f0 + 2u * k].w, data[f0 + 2u * k + 1u].w); }
fn oklab_to_lin(c: vec3f) -> vec3f {
let l = c.x + 0.39633778 * c.y + 0.21580376 * c.z;
let m = c.x - 0.10556135 * c.y - 0.06385417 * c.z;
let s = c.x - 0.08948418 * c.y - 1.29148555 * c.z;
let l3 = l * l * l;
let m3 = m * m * m;
let s3 = s * s * s;
return max(vec3f(
4.07674166 * l3 - 3.30771159 * m3 + 0.23096993 * s3,
-1.26843800 * l3 + 2.60975740 * m3 - 0.34131940 * s3,
-0.00419609 * l3 - 0.70341861 * m3 + 1.70761470 * s3,
), vec3f(0.0));
}
// The colour list as an even ramp over x in 0..1, blended in OKLab.
fn palette_ramp(f0: u32, n: u32, x: f32) -> vec3f {
if (n <= 1u) { return stop_lin(f0, 0u); }
let fx = clamp(x, 0.0, 1.0) * f32(n - 1u);
let k = min(u32(fx), n - 2u);
return oklab_to_lin(mix(stop_lab(f0, k), stop_lab(f0, k + 1u), fx - f32(k)));
}
// The colour list as a closed loop over x in 0..1: the last colour blends back into the first.
fn ramp_loop(f0: u32, n: u32, x: f32) -> vec3f {
if (n <= 1u) { return stop_lin(f0, 0u); }
let fx = fract(x) * f32(n);
let k = min(u32(fx), n - 1u);
return oklab_to_lin(mix(stop_lab(f0, k), stop_lab(f0, (k + 1u) % n), fx - f32(k)));
}
// Premultiplied output with the fill's coverage and intensity.
fn paint(col: vec3f, m: f32, i: Inst, px: vec2f) -> vec4f {
let a = m * clamp(i.aux.y, 0.0, 1.0);
return finish(vec4f(col * a, a), px);
}
// ---------- tone inputs (dither, halftone) ----------
// Perceptual tone 0..1 at `p` for input `kind`: 0 linear ramp, 1 radial, 2 noise, 3 backdrop, 4 image.
fn tone_at(i: Inst, c: Ctx, p: vec2f, kind: i32, angle: f32) -> f32 {
var v: f32;
let q = p - c.c;
if (kind == 0) {
let dir = vec2f(cos(angle), sin(angle));
let ext = abs(c.half.x * dir.x) + abs(c.half.y * dir.y);
v = dot(q, dir) / max(ext, 1e-3) * 0.5 + 0.5;
} else if (kind == 1) {
v = 1.0 - clamp(length(q / max(c.half, vec2f(1e-3))) / 1.3, 0.0, 1.0);
} else if (kind == 2) {
let t = c.t * i.p1.y;
v = 0.5 + 0.62 * fbm3(p / max(i.p1.x, 1.0) + vec2f(t * 0.31, t * 0.17), c.seed);
} else if (kind == 3) {
v = to_srgb(vec3f(lum(bd(p, c.scale).rgb))).x;
} else {
let s = textureSampleLevel(source, samp, (p - i.aux2.xy) / max(i.aux2.zw, vec2f(1e-3)), 0.0);
v = to_srgb(vec3f(lum(s.rgb))).x;
}
return clamp((v - 0.5) * i.p1.w + 0.5 + i.p1.z * 0.5, 0.0, 1.0);
}
// Ordered-dither threshold of an n×n Bayer matrix (n = 2^bits), from the bit-interleave recurrence.
fn bayer(cell: vec2u, bits: u32) -> f32 {
var v = 0u;
for (var b = 0u; b < bits; b++) {
let x = (cell.x >> b) & 1u;
let y = (cell.y >> b) & 1u;
let sh = 2u * (bits - 1u - b);
v |= (((x ^ y) << 1u) | y) << sh;
}
return (f32(v) + 0.5) / f32(1u << (2u * bits));
}
// ---------- lit slabs (liquid metal, plastic) ----------
// Slope of a slab's surface normal as (x, y) plus how far onto the rim it is (0..1). With a border
// the band is a round tube; otherwise the edge rolls off in a quarter round over `bevel` pt and
// the face is domed (negative `dome` dishes it).
fn slab_tilt(c: Ctx, border: f32, bevel: f32, dome: f32) -> vec3f {
let depth = -c.d;
let gv = sd_grad(c);
var tilt = vec2f(0.0);
var rim = 0.0;
if (border > 0.0) {
let x = clamp((depth - border * 0.5) / max(border * 0.5, 1e-3), -0.97, 0.97);
tilt = -gv * x / sqrt(1.0 - x * x);
rim = abs(x);
} else {
let bev = max(bevel, 0.5);
let x = clamp(1.0 - depth / bev, 0.0, 0.92);
tilt = gv * x / sqrt(1.0 - x * x);
rim = x;
}
let qn = c.q / max(c.half, vec2f(1.0));
tilt += vec2f(qn.x * 0.55, qn.y) * dome * select(0.8, 0.25, border > 0.0);
return vec3f(tilt, rim);
}
// ---------- liquid metal ----------
// Height of the flowing surface (in units of `scale`), domain-warped so ripples curl and pool.
fn flow_h(u: vec2f, w: vec2f, t: f32, seed: u32) -> f32 {
let p = u + w;
return gnoise(p + vec2f(0.0, t * 0.11), seed + 3u) + 0.5 * gnoise(ROT * p * 2.03 - vec2f(t * 0.07, 0.0), seed + 17u);
}
// A photo studio seen from a polished object, by reflected direction r (screen y points down, +z
// toward the viewer): a bright sky that is lightest just above a hard horizon, an overhead soft
// box, a tall strip light on the right and a dim one on the left, over a dark floor that lightens
// away from the horizon. White lights; the caller tints them.
fn studio(r: vec3f, contrast: f32) -> vec3f {
let up = -r.y;
let e = up + 0.1; // elevation above the horizon (which sits a little below eye level)
let w = 0.014;
let sky = 0.2 + 0.6 * exp(-max(e, 0.0) * 3.2) + 0.45 * exp(-max(e, 0.0) * 24.0);
let key = smoothstep(0.80, 0.95, dot(r, normalize(vec3f(-0.3, -0.82, 0.5)))) * 2.4;
let strip = gauss(r.x - 0.6, 0.075) * smoothstep(-0.05, 0.2, e) * (1.0 - smoothstep(0.55, 0.9, up)) * 1.7;
let fill_l = gauss(r.x + 0.72, 0.045) * smoothstep(0.0, 0.25, e) * (1.0 - smoothstep(0.4, 0.8, up)) * 0.55;
let lights = (key + strip + fill_l) * contrast;
// The floor: near black under the horizon, lifting toward the camera, with a soft pool of
// bounced light off to the left.
let fl = smoothstep(0.05, 1.0, -e);
let pool = 0.16 * gauss(r.x + 0.25, 0.35) * smoothstep(0.25, 0.9, -e);
let ground = (0.014 + 0.3 * fl * fl + pool + 0.05 * gauss(e + 0.06, 0.04)) / (contrast * contrast);
let h = smoothstep(-w, w, e);
let skyc = (sky * mix(1.0, 0.82, clamp(contrast - 1.0, 0.0, 1.0)) + lights) * vec3f(0.97, 0.99, 1.03);
let floorc = ground * vec3f(1.04, 1.0, 0.95);
return mix(floorc, skyc, h);
}
// Gentle shoulder so lights roll off instead of clipping (per channel: hot gold goes pale).
fn shoulder(c: vec3f) -> vec3f {
let k = 0.78;
return select(c, k + (1.0 - k) * (1.0 - exp(-(c - k) / (1.0 - k))), c > vec3f(k));
}
fn liquid_metal(i: Inst, c: Ctx, m: f32, px: vec2f) -> vec4f {
let flow = i.p0.x;
let sc = max(i.p0.y, 1.0);
let t = c.t * i.p0.z;
// Tilt of the surface normal (where it leans, as a slope): rim or tube + dome + liquid ripples.
let slab = slab_tilt(c, i.aux.x, i.p0.w, i.p1.x);
var tilt = slab.xy;
let rim = slab.z;
var hgt = 0.0;
var bend = 0.0;
if (flow > 0.0) {
// Pinned to the window, or to the shape's centre so equal shapes ripple alike.
let u = select(c.p, c.q, i.p2.x > 0.5) / sc;
let wv = vec2f(gnoise(u * 0.6 + vec2f(t * 0.05, 1.7), c.seed + 7u), gnoise(u * 0.6 + vec2f(4.3, -t * 0.06), c.seed + 11u)) * 0.9;
let e = 0.04;
hgt = flow_h(u, wv, t, c.seed);
let hx = flow_h(u + vec2f(e, 0.0), wv, t, c.seed) - hgt;
let hy = flow_h(u + vec2f(0.0, e), wv, t, c.seed) - hgt;
let grad = vec2f(hx, hy) / e;
// Ripples calm toward the rim so the silhouette stays crisp.
let k = flow * 0.42 * (1.0 - 0.6 * rim * rim);
tilt -= grad * k;
bend = length(grad) * k;
}
let n = normalize(vec3f(tilt, 1.0));
var r = vec3f(2.0 * n.z * n.xy, 2.0 * n.z * n.z - 1.0);
r = vec3f(rot2(r.xy, i.p1.y), r.z);
let contrast = max(i.p1.w, 0.1);
let env = studio(normalize(r), contrast) * i.c1.rgb;
// Conductor Fresnel (Schlick): the tint at normal incidence, rising to white at grazing angles.
let f0 = i.c0.rgb;
let cz = clamp(1.0 - n.z, 0.0, 1.0);
let cz2 = cz * cz;
var f = f0 + (vec3f(1.0) - f0) * (cz2 * cz2 * cz);
let ir = i.p1.z;
if (ir > 0.0) {
// Thin-film colour where the surface bends hardest.
let ph = 1.6 * (1.0 - n.z) + 0.35 * hgt;
let film = 0.5 + 0.5 * cos(TAU * (vec3f(ph) + vec3f(0.0, 0.33, 0.67)));
let k = ir * clamp(smoothstep(0.04, 0.45, 1.0 - n.z) + bend * 0.8, 0.0, 1.0);
f *= mix(vec3f(1.0), 0.55 + 0.9 * film, k);
}
let col = shoulder(f * env);
return paint(col, m, i, px);
}
// ---------- plastic ----------
// A dielectric under one soft light from `angle` (50° up), seen head on. The diffuse base keeps the
// colour on a flat face, darkens away from the light and lightens toward white facing it. The
// highlight is a GGX lobe widened by the light's size (so a polished face shows a soft spot, not a
// pinpoint) and the grazing-angle reflection is a faint sky. Both fill the headroom left above the
// base, so the colour never exceeds coverage and the fill blends alike in either blend mode.
fn plastic(i: Inst, c: Ctx, m: f32, px: vec2f) -> vec4f {
let slab = slab_tilt(c, i.aux.x, i.p0.z, i.p0.y);
let n = normalize(vec3f(slab.xy, 1.0));
let l = vec3f(rot2(vec2f(0.0, -1.0), i.p0.w) * 0.6428, 0.766);
let nl = dot(n, l);
let base = clamp(i.c0.rgb, vec3f(0.0), vec3f(1.0));
// 0.4 ambient + 0.6 direct on a flat face (n.l = 0.766).
let shade = 0.4 + 0.7833 * max(nl, 0.0);
var col = mix(base * min(shade, 1.0), vec3f(1.0), clamp((shade - 1.0) * 0.6, 0.0, 1.0));
let rough = clamp(i.p0.x, 0.02, 1.0);
let a = min(rough * rough + 0.1, 1.0);
let a2 = a * a;
let h = normalize(l + vec3f(0.0, 0.0, 1.0));
let nh = max(dot(n, h), 0.0);
let dd = nh * nh * (a2 - 1.0) + 1.0;
let ndf = a2 / (PI * dd * dd);
let fh = 1.0 - h.z;
let spec = ndf * (0.04 + 0.96 * fh * fh * fh * fh * fh) * max(nl, 0.0) * 2.5;
let fz = 1.0 - clamp(n.z, 0.0, 1.0);
let sky = 0.55 + 0.45 * smoothstep(-0.5, 0.5, -n.y);
let edge = 0.96 * fz * fz * fz * fz * fz * sky * (1.0 - 0.5 * rough);
col += (vec3f(1.0) - col) * knee(spec + edge);
return paint(col, m, i, px);
}
// ---------- fluted glass ----------
fn fluted(i: Inst, c: Ctx, m: f32, px: vec2f) -> vec4f {
let s = c.scale;
let rib = max(i.p0.x, 1.0);
let across = vec2f(cos(i.p0.y), sin(i.p0.y));
let u = dot(c.p - c.c, across) / rib;
let local = fract(u) - 0.5;
let x = local * 2.0; // -1..1 across one rib
// A convex rib acts as a cylindrical lens: the strip under it comes back squeezed and flipped.
let o = -x * (1.0 + 0.35 * x * x) * i.p0.z;
let dsp = i.p1.x * 0.3 * abs(x);
let srcg = c.p + across * o;
let srcr = c.p + across * o * (1.0 + dsp);
let srcb = c.p + across * o * (1.0 - dsp);
var col = vec3f(bd(srcr, s).r, bd(srcg, s).g, bd(srcb, s).b);
let frost = i.p0.w;
if (frost > 0.0) {
if (i.xf.x > 0.5) {
let blr = vec3f(bdb(srcr, s).r, bdb(srcg, s).g, bdb(srcb, s).b);
col = mix(col, blr, i.xf.y);
} else {
// No pyramid this frame: a small blur along the ribs.
let along = vec2f(-across.y, across.x);
let j = ign(px) - 0.5;
var acc = vec3f(0.0);
for (var k = 0; k < 4; k++) {
acc += bd(srcg + along * (f32(k) - 1.5 + j) * 3.0 * frost, s).rgb;
}
col = mix(col, acc * 0.25, frost);
}
let k = smoothstep(0.0, 0.6, frost);
let l = lum(col);
let sat = max(mix(vec3f(l), col, 1.0 + 0.5 * k), vec3f(0.0));
col = to_lin(to_srgb(sat) * (1.0 - 0.2 * k) + vec3f(0.07 * k));
}
col = mix(col, col * i.c0.rgb, i.p1.z);
// Light: a sheen down each rib's lit side, a shaded groove between ribs with a bright lip.
let hl = i.p1.y;
let aa = c.aa / rib;
let groove = 1.0 - smoothstep(0.0, max(0.06, aa * 2.0), 0.5 - abs(local));
// The sheen scales with what is behind (glass reflects little over black) plus a faint floor.
let sheen = gauss(local + 0.22, 0.13) * 0.1 + gauss(local + 0.34, 0.03) * 0.1;
let lip = gauss(local - 0.44, max(0.025, aa)) * 0.06;
let lift = 0.35 + 0.65 * sqrt(clamp(lum(col), 0.0, 1.0));
col = col * (1.0 - 0.28 * hl * groove) + vec3f((sheen + lip) * hl * lift);
let a = m * clamp(i.aux.y, 0.0, 1.0);
return vec4f(col * a, a);
}
// ---------- the rest ----------
fn mesh_gradient(i: Inst, c: Ctx, m: f32, px: vec2f) -> vec4f {
let f0 = u32(i.xf.x);
let n = u32(i.xf.y);
var uv = (c.p - i.rect.xy) / max(i.rect.zw, vec2f(1.0));
let t = c.t * i.p0.y;
let warp = i.p0.w;
if (warp > 0.0) {
uv += warp * 0.09 * vec2f(gnoise(uv * 2.1 + vec2f(t * 0.11, 0.0), c.seed + 5u), gnoise(uv * 2.1 + vec2f(3.7, -t * 0.09), c.seed + 9u));
}
let aspect = i.rect.zw / max(max(i.rect.z, i.rect.w), 1.0);
let sharp = clamp(i.p0.z, 0.1, 8.0);
var lab = vec3f(0.0);
var wsum = 0.0;
for (var k = 0u; k < n; k++) {
let d = (uv - stop_pt(f0, k)) * aspect;
// Shepard weights: each colour owns its point, blends fall off smoothly.
let w = pow(dot(d, d) + 0.004, -sharp);
lab += stop_lab(f0, k) * w;
wsum += w;
}
return paint(oklab_to_lin(lab / max(wsum, 1e-6)), m, i, px);
}
fn dither(i: Inst, c: Ctx, m: f32) -> vec4f {
let f0 = u32(i.xf.x);
let n = max(u32(i.xf.y), 1u);
let pix = max(i.p0.z, 0.25);
let rel = c.p - i.rect.xy;
let cell = floor(rel / pix);
let ci = bitcast<vec2u>(vec2i(cell));
let tone = tone_at(i, c, i.rect.xy + (cell + 0.5) * pix, i32(i.p0.y + 0.5), i.p0.w);
let pat = clamp(i32(i.p0.x + 0.5), 1, 5);
var th: f32;
if (pat <= 3) {
th = bayer(ci, u32(pat));
} else if (pat == 4) {
let side = max(u32(i.xf.w), 1u);
th = dat1(u32(i.xf.z), (ci.y % side) * side + ci.x % side);
} else {
th = u01(ci.x * 7919u + pcg(ci.y + c.seed));
}
let lv = f32(max(n, 2u) - 1u);
let v = tone * lv;
let k = min(u32(floor(v) + select(0.0, 1.0, fract(v) > th)), n - 1u);
let a = m * clamp(i.aux.y, 0.0, 1.0);
return vec4f(stop_lin(f0, k) * a, a);
}
fn grain_gradient(i: Inst, c: Ctx, m: f32, px: vec2f) -> vec4f {
let f0 = u32(i.xf.x);
let n = u32(i.xf.y);
let kind = i32(i.p0.x + 0.5);
let ang = i.p0.y;
let ctr = i.rect.xy + i.p0.zw * i.rect.zw;
var x: f32;
if (kind == 0) {
let dir = vec2f(cos(ang), sin(ang));
let ext = abs(c.half.x * dir.x) + abs(c.half.y * dir.y);
x = dot(c.q, dir) / max(ext, 1e-3) * 0.5 + 0.5;
} else if (kind == 1) {
x = length(c.p - ctr) / max(length(c.half), 1e-3);
} else {
let d = c.p - ctr;
let th = select(0.0, atan2(d.y, d.x), any(d != vec2f(0.0)));
x = fract((th - ang) / TAU);
}
let amount = i.p1.x;
let size = max(i.p1.y, 0.25);
var frame = 0u;
if (i.p1.w > 0.0) { frame = u32(floor(c.t * i.p1.w)); }
let gc = bitcast<vec2u>(vec2i(floor((c.p - i.rect.xy) / size)));
let h = pcg(gc.x + pcg(gc.y + pcg(frame + c.seed * 977u)));
// Triangular noise scatters the ramp position: colours stipple into each other.
let nx = u01(h) + u01(h + 1u) - 1.0;
var col = palette_ramp(f0, n, x + nx * amount * 0.2);
if (kind == 2) {
col = ramp_loop(f0, n, x + nx * amount * 0.2);
}
let nb = u01(h + 2u) + u01(h + 3u) - 1.0;
if (i.p1.z > 0.5) {
col *= 1.0 + nb * amount * 0.18;
} else {
let nc = vec3f(nb, u01(h + 4u) + u01(h + 5u) - 1.0, u01(h + 6u) + u01(h + 7u) - 1.0);
col *= vec3f(1.0) + nc * amount * 0.18;
}
return paint(col, m, i, px);
}
fn metaballs(i: Inst, c: Ctx, m: f32, px: vec2f) -> vec4f {
let f0 = u32(i.xf.x);
let b0 = u32(i.xf.z);
let nb = u32(i.xf.w);
var field = 0.0;
var grad = vec2f(0.0);
var lab = vec3f(0.0);
var rsum = 0.0;
for (var k = 0u; k < nb; k++) {
let b = data[b0 + k];
let d = c.p - b.xy;
let r2 = b.z * b.z;
let dd = dot(d, d) + 1e-3;
let f = r2 / dd;
field += f;
grad += -2.0 * f / dd * d;
lab += stop_lab(f0, u32(b.w)) * f;
rsum += b.z * f;
}
let base = i.c0.rgb;
let col = select(base, oklab_to_lin(lab / max(field, 1e-6)), field > 1e-5);
let ravg = rsum / max(field, 1e-6);
// Distance to the iso-surface field = 1, roughly (1 - field) * r / 2 near the edge.
let cov = select(0.0, clamp(0.5 + (field - 1.0) * ravg * 0.5 * c.scale, 0.0, 1.0), field > 1e-3);
// Glossy body: the field's slope tilts the normal near the rim, flat in the middle.
let steep = 1.0 - smoothstep(1.0, 2.6, field);
let nxy = -grad / sqrt(dot(grad, grad) + 1e-6) * steep * 0.9;
let nrm = normalize(vec3f(nxy, 1.0));
let l = normalize(vec3f(-0.45, -0.6, 0.66));
let diff = max(dot(nrm, l), 0.0);
let spec = pow(max(dot(reflect(-l, nrm), vec3f(0.0, 0.0, 1.0)), 1e-4), 28.0);
let body = col * (0.6 + 0.5 * diff) + vec3f(spec * i.p0.w * 0.8);
// A soft glow of each blob's colour into the base.
let halo = col * smoothstep(0.25, 1.0, field) * 0.18;
return paint(mix(base + halo, body, cov), m, i, px);
}
fn swirl(i: Inst, c: Ctx, m: f32, px: vec2f) -> vec4f {
let f0 = u32(i.xf.x);
let n = u32(i.xf.y);
let sc = max(i.p0.x, 1.0);
let t = c.t * i.p0.y;
let rr = length(c.q) / max(min(c.half.x, c.half.y), 1.0);
let q = rot2(c.q, i.p0.z * TAU * exp(-rr * rr * 0.8)) / sc;
let w1 = vec2f(fbm3(q + vec2f(t * 0.1, 0.0), c.seed), fbm3(q + vec2f(5.2, 1.3 - t * 0.08), c.seed + 3u));
let v = fbm3(q + w1 * i.p0.w * 1.5 + vec2f(0.0, t * 0.05), c.seed + 7u);
return paint(palette_ramp(f0, n, 0.5 + 0.75 * v), m, i, px);
}
fn voronoi(i: Inst, c: Ctx, m: f32, px: vec2f) -> vec4f {
let f0 = u32(i.xf.x);
let n = u32(i.xf.y);
let sc = max(i.p0.x, 2.0);
let t = c.t * i.p0.y;
let t0 = fract(t * (1.0 / TAU)) * TAU;
let t1 = fract(t * (0.8 / TAU)) * TAU;
let p = (c.p - i.rect.xy) / sc;
let ip = floor(p);
// Each cell's seed point orbits its own spot.
var best = 8.0;
var bc = vec2i(0);
var bo = vec2f(0.0);
for (var y = -1; y <= 1; y++) {
for (var x = -1; x <= 1; x++) {
let cc = vec2i(ip) + vec2i(x, y);
let h = hcell(cc, c.seed);
let h2 = hcell(cc, c.seed + 1u);
let o = vec2f(0.5) + 0.38 * vec2f(sin(t0 + TAU * h), cos(t1 + TAU * h2));
let d = vec2f(cc) + o - p;
let dd = dot(d, d);
if (dd < best) { best = dd; bc = cc; bo = d; }
}
}
// Distance to the nearest seam: to the bisector with each neighbour. Seed points stay within
// 0.12..0.88 of their cell, so the eight cells round the winner are enough in practice.
var edge = 8.0;
for (var y = -1; y <= 1; y++) {
for (var x = -1; x <= 1; x++) {
let cc = bc + vec2i(x, y);
if (x == 0 && y == 0) { continue; }
let h = hcell(cc, c.seed);
let h2 = hcell(cc, c.seed + 1u);
let o = vec2f(0.5) + 0.38 * vec2f(sin(t0 + TAU * h), cos(t1 + TAU * h2));
let d = vec2f(cc) + o - p;
let dv = d - bo;
if (dot(dv, dv) > 1e-6) { edge = min(edge, dot(0.5 * (bo + d), normalize(dv))); }
}
}
let k = u32(hcell(bc, c.seed + 2u) * f32(n)) % max(n, 1u);
var col = stop_lin(f0, k) * (1.0 - i.p0.w * 0.55 * clamp(best * 1.6, 0.0, 1.0));
let seam = i.p0.z * 0.5;
if (seam > 0.0) {
let e = clamp(0.5 + (edge * sc - seam) * c.scale, 0.0, 1.0);
col = mix(i.c0.rgb, col, e);
}
return paint(col, m, i, px);
}
fn waves(i: Inst, c: Ctx, m: f32, px: vec2f) -> vec4f {
let f0 = u32(i.xf.x);
let n = u32(i.xf.y);
let ang = i.p0.w;
let dir = vec2f(-sin(ang), cos(ang));
let along = vec2f(cos(ang), sin(ang));
let ext = abs(c.half.x * dir.x) + abs(c.half.y * dir.y);
let ext2 = abs(c.half.x * along.x) + abs(c.half.y * along.y);
let v = dot(c.q, dir) / max(2.0 * ext, 1e-3) + 0.5;
let s = dot(c.q, along) / max(2.0 * ext2, 1e-3) + 0.5;
let aa = c.aa / max(2.0 * ext, 1e-3);
let soft = max(i.p1.x, aa);
let t = c.t * i.p0.z;
var col = stop_lin(f0, 0u);
for (var k = 1u; k < n; k++) {
let fk = f32(k);
let h = hcell(vec2i(i32(k), 3), c.seed);
let fq = i.p0.y * (0.8 + 0.4 * h);
let ph1 = fract(t * 0.2 * (1.0 + 0.3 * fk) + h);
let ph2 = fract(-t * 0.13) * TAU + 1.7 * fk;
let y = fk / f32(n) + i.p0.x * (0.7 * sin(TAU * (fq * s + ph1)) + 0.3 * sin(TAU * fq * 2.3 * s + ph2));
// The front band shades the one behind it just above its crest.
let shade = exp(-max(y - v, 0.0) / 0.025) * 0.18 * step(v, y);
col *= 1.0 - shade;
col = mix(col, stop_lin(f0, k), smoothstep(y - soft, y + soft, v));
}
return paint(col, m, i, px);
}
fn halftone(i: Inst, c: Ctx, m: f32, px: vec2f) -> vec4f {
let pitch = max(i.p0.z, 1.0);
let ang = i.p2.x;
let r = rot2(c.p - c.c, -ang) / pitch;
let base = floor(r - 0.5);
let kind = i32(i.p0.y + 0.5);
var ink = 0.0;
// The four nearest dots, so big dots merge across cell lines.
for (var y = 0; y <= 1; y++) {
for (var x = 0; x <= 1; x++) {
let cc = base + vec2f(f32(x), f32(y)) + 0.5;
let w = c.c + rot2(cc * pitch, ang);
let cov = 1.0 - tone_at(i, c, w, kind, i.p0.w);
let rad = sqrt(cov / PI) * 1.12;
let d = (length(r - cc) - rad) * pitch;
ink = max(ink, clamp(0.5 - d * c.scale, 0.0, 1.0));
}
}
return paint(mix(i.c1.rgb, i.c0.rgb, ink), m, i, px);
}
fn shade(i: Inst, px: vec2f) -> vec4f {
let c = ctx(i, px);
let m = fill_mask(c, i.aux.x);
if (m <= 0.0) { return vec4f(0.0); }
switch c.variant {
case 0: { return liquid_metal(i, c, m, px); }
case 1: { return mesh_gradient(i, c, m, px); }
case 2: { return dither(i, c, m); }
case 3: { return grain_gradient(i, c, m, px); }
case 4: { return fluted(i, c, m, px); }
case 5: { return metaballs(i, c, m, px); }
case 6: { return swirl(i, c, m, px); }
case 7: { return voronoi(i, c, m, px); }
case 8: { return waves(i, c, m, px); }
case 9: { return halftone(i, c, m, px); }
default: { return plastic(i, c, m, px); }
}
}
+187
View File
@@ -0,0 +1,187 @@
// Fire / plasma. variant: 0 flames off the top edge (also Heat), 1 plasma hugging the border, 3 embers only,
// 4 simulated flames + smoke (`source` = the sim state: velocity, temperature, smoke; aux = its rect in pt).
// Embers are a CPU particle table (cpu.rs::embers): xf = (first, count).
// c0 ramp low (deep red / plasma envelope), c1 ramp mid, c2 ramp hot
// p0 (height pt, scale pt, speed (scale units/s), intensity)
// p1 (ember count, ember rise pt/s, ember size pt, ember life s)
// p2 (warp, sides (plasma band thickness share), base glow, occlusion)
// p3 (swirl, _, _, _)
// Temperature to colour: smoke-dark -> deep red -> orange -> yellow -> white-yellow core.
fn fire_ramp(T: f32, c0: vec3f, c1: vec3f, c2: vec3f) -> vec3f {
var col = mix(vec3f(0.012, 0.009, 0.008), c0, smoothstep(0.04, 0.22, T));
col = mix(col, c1, smoothstep(0.2, 0.5, T));
col = mix(col, c2, smoothstep(0.45, 0.78, T));
col = mix(col, vec3f(1.0, 0.92, 0.74), smoothstep(0.8, 1.08, T));
return col;
}
fn fbm4(p0: vec2f, seed: u32) -> f32 {
var p = p0; var a = 0.5; var s = 0.0;
for (var o = 0u; o < 4u; o++) { s += a * gnoise(p, seed + o * 131u); p = ROT * p * 2.03; a *= 0.5; }
return s / 0.9375;
}
fn flames(c: Ctx, i: Inst) -> vec4f {
let H = i.p0.x;
let sc = max(i.p0.y, 1.0);
let tr = c.t * i.p0.z;
let nrm = sd_grad(c);
let up = clamp(-nrm.y, 0.0, 1.0);
// Top edge only: fades over the rounded corners and never past the sides.
let span = smoothstep(c.half.x + 2.0, c.half.x - c.r * 0.9 - 2.0, abs(c.q.x));
let hl = H * smoothstep(0.15, 0.95, up) * span;
if (hl < 0.5) { return vec4f(0.0); }
let y = c.d + 1.5; // height above the edge (the base tucks under the node)
let yn = y / hl;
if (yn > 1.6 || yn < -0.2) { return vec4f(0.0); }
let x = c.p.x / sc;
// Flicker: tongue heights breathe slowly and jitter at ~8 Hz, per column.
let fl = 1.0 + 0.2 * gnoise(vec2f(x * 0.45, c.t * 1.3), c.seed + 7u) + 0.07 * gnoise(vec2f(x * 1.1 + 9.0, c.t * 8.0), c.seed + 8u);
let yh = yn / max(fl, 0.4);
// Rising, domain-warped turbulence; the warp grows with height, so tongues curl and tear.
var sw = vec2f(0.0);
if (i.p3.x > 0.0) { sw = i.p3.x * vec2f(sin(y / sc * 0.7 + tr * 0.4), 0.0); }
let wq = vec2f(x * 0.7, y / sc * 0.45 - tr * 1.05);
let w = vec2f(gnoise(wq, c.seed), gnoise(wq + vec2f(3.7, 1.9), c.seed + 1u)) * i.p2.x * (0.2 + 0.8 * yh);
let n = fbm4(vec2f(x * 1.05, y / sc * 0.5 - tr * 1.6) + w + sw, c.seed + 2u);
// Density: full at the base, falling with height; the noise carves it into tongues that narrow
// as only the strongest plumes survive higher up.
let dens = (1.0 - yh) * 1.2 + n * 0.8 - 0.08;
let body = smoothstep(0.0, 0.06, dens) * smoothstep(-0.2, 0.05, yn);
// Hottest low down and inside a plume; the tips cool to red.
// Only the dense heart of a plume near the base reaches the white-yellow core.
let T = clamp(dens * (0.95 - 0.5 * yh), 0.0, 1.1);
let col = fire_ramp(T, i.c0.rgb, i.c1.rgb, i.c2.rgb);
let e = body * (0.3 + 0.75 * T * T);
var emis = col * e;
// Smoke: a faint dark veil just past the tips (only visible over lighter content).
let smoke = smoothstep(-0.32, -0.02, dens) * (1.0 - body) * smoothstep(0.35, 0.9, yh) * 0.12;
// A little of the fire's light on the edge it sits on.
let bg = i.p2.z * 0.22 * exp(-max(c.d, 0.0) / max(hl * 0.12, 1.0)) * smoothstep(-1.0, 0.5, c.d) * span;
emis += i.c1.rgb * bg;
let occl = select(1.0, i.p2.w, effective_blend_mode(i) == 0u);
return vec4f(emis, body * occl + smoke);
}
// Blackbody colour (linear) for a flame temperature in kelvin (Tanner Helland's fit, 1000-4000 K).
fn blackbody(k: f32) -> vec3f {
let t = k / 100.0;
let g = clamp((99.4708 * log(t) - 161.1196) / 255.0, 0.0, 1.0);
let b = select(clamp((138.5177 * log(max(t - 10.0, 1.0)) - 305.0448) / 255.0, 0.0, 1.0), 0.0, t <= 19.0);
return to_lin(vec3f(1.0, g, b));
}
// Light a flame of temperature T (0..~1.2) emits: colour from 1000 K (dim red tips) to ~2700 K
// (near-white core), brightness rising steeply with temperature, then a per-channel shoulder so
// the hottest parts go pale yellow-white the way a camera sees them instead of clipping flat.
fn flame_light(T: f32, gain: f32) -> vec3f {
let x = max(T, 0.0);
let e = gain * x * x * x * smoothstep(0.08, 0.3, x);
return vec3f(1.0) - exp(-blackbody(1000.0 + 1700.0 * min(x, 1.3)) * e);
}
// Cubic B-spline sample of the sim state from 4 bilinear taps: smooth isolines, no grid diamonds.
fn sim_at(uv: vec2f) -> vec4f {
let dim = vec2f(textureDimensions(source, 0));
let g = uv * dim - 0.5;
let i = floor(g);
let f = g - 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 w3 = f * f * f / 6.0;
let w2 = 1.0 - w0 - w1 - w3;
let s0 = w0 + w1;
let s1 = w2 + w3;
let o0 = (i - 0.5 + w1 / s0) / dim;
let o1 = (i + 1.5 + w3 / s1) / dim;
let a = textureSampleLevel(source, samp, vec2f(o0.x, o0.y), 0.0);
let b = textureSampleLevel(source, samp, vec2f(o1.x, o0.y), 0.0);
let c = textureSampleLevel(source, samp, vec2f(o0.x, o1.y), 0.0);
let d = textureSampleLevel(source, samp, vec2f(o1.x, o1.y), 0.0);
return mix(mix(a, b, s1.x), mix(c, d, s1.x), s1.y);
}
// Simulated fire: flames are additive light from the temperature field; smoke is a separate
// density that partly covers what is behind it and is lit warm from below by the flames.
fn sim_flames(c: Ctx, i: Inst) -> vec4f {
let ext = i.aux.zw;
let uv = (c.p - i.aux.xy) / ext;
if (any(uv < vec2f(0.0)) || any(uv > vec2f(1.0))) { return vec4f(0.0); }
let s = sim_at(uv);
let T = s.z;
// Fade out well before the drawn quad's top and sides (p3.yz = its size).
let m = min(min(c.p.x - i.aux.x, i.aux.x + i.p3.y - c.p.x), c.p.y - i.aux.y);
let win = smoothstep(0.0, 18.0, m);
var rgb = flame_light(T, 6.0) * win;
// Smoke, lit by the flame below it: march a few taps down toward the fire.
let sm = s.w * win;
var a = 0.0;
if (sm > 0.002) {
a = (1.0 - exp(-sm * 1.2)) * i.p2.w * 1.6;
var lit = 0.0;
for (var k = 1; k < 5; k++) {
let tk = sim_at(uv + vec2f(0.0, f32(k) * 7.0 / ext.y)).z;
lit += tk * tk / f32(k);
}
let warm = vec3f(1.0, 0.45, 0.18) * min(lit, 1.0) * 0.3;
rgb += a * (vec3f(0.11, 0.11, 0.115) + warm);
}
// Flames themselves cover a little of what is behind them (occlusion).
let vis = smoothstep(0.12, 0.35, T) * win;
return vec4f(rgb, min(a + vis * i.p2.w * 0.5, 1.0));
}
// Plasma: contained energy hugging the shape. A thin band centred just outside the edge, with
// ridged filaments flowing along the perimeter, a tight outer falloff and slow breathing.
fn plasma(c: Ctx, i: Inst) -> vec4f {
let sc = max(i.p0.y, 1.0);
let thick = max(i.p0.x * i.p2.y * 0.3, 2.5);
let pr = rrect_perim(c.q, c.half, c.r);
let u = pr.x / pr.y;
let d = c.d - thick * 0.45;
if (abs(d) > thick * 4.0) { return vec4f(0.0); }
let P = max(round(pr.y / (sc * 2.5)), 3.0);
let flow = c.t * i.p0.z * (0.35 + 0.25 * i.p3.x);
let warp = 0.6 * pgnoise(vec2f(u * P - flow * 0.6, c.t * 0.35), i32(P), c.seed + 3u);
// Ridges stretched along the perimeter: filaments run with the flow instead of netting.
let r1 = 1.0 - abs(pgnoise(vec2f(u * P - flow * 1.4, d / sc * 3.2 + warp), i32(P), c.seed));
let r2 = 1.0 - abs(pgnoise(vec2f(u * P * 2.0 + flow * 1.1, d / sc * 4.5 - warp - c.t * 0.6), i32(P * 2.0), c.seed + 1u));
let fil = pow(r1, 10.0) + 0.45 * pow(r2, 12.0);
let breathe = 0.78 + 0.22 * pgnoise(vec2f(u * 3.0 - c.t * 0.25, c.t * 0.2), 3, c.seed + 5u);
let env = exp(-(d * d) / (thick * thick));
let halo = exp(-max(d, 0.0) / (thick * 0.9)) * smoothstep(-thick, 0.0, d);
let E = env * (0.18 + 1.2 * fil) * breathe;
let rgb = i.c0.rgb * halo * 0.28 + i.c1.rgb * E * 0.55 + i.c2.rgb * fil * env * breathe * 0.9
+ vec3f(1.0) * pow(fil, 3.0) * env * breathe * 0.35;
return vec4f(rgb, (E * 0.5 + halo * 0.1) * i.p2.w * 2.0);
}
fn shade(i: Inst, px: vec2f) -> vec4f {
let c = ctx(i, px);
let inten = i.p0.w;
var o = vec4f(0.0);
if (c.variant == 0) {
o = flames(c, i);
} else if (c.variant == 1) {
o = plasma(c, i);
} else if (c.variant == 4) {
o = sim_flames(c, i);
}
var emis = o.rgb;
var alpha = o.a;
// Embers: short shutter streaks with a hot core, cooling white -> orange -> red as they rise.
let ef = u32(i.xf.x);
let en = u32(i.xf.y);
for (var k = 0u; k < en; k++) {
let a = data[ef + k * 2u];
let b = data[ef + k * 2u + 1u];
let sd = segdist(c.p, a.xy - a.zw, a.xy);
let T = b.y;
let core = gauss(sd.x, b.x);
let halo = gauss(sd.x, b.x * 3.0) * 0.12;
emis += flame_light(0.45 + T * 0.75, 6.0) * (core * 1.4 + halo) * T;
alpha += core * T * 0.5;
}
return finish(vec4f(emis * inten, min(alpha, 1.0) * inten), px);
}
+253
View File
@@ -0,0 +1,253 @@
// Fire and smoke as a small 2D stable-fluids simulation (Stam 1999), one grid per fire layer.
// State S (rgba16f): velocity (pt/s, screen axes, y down), temperature (0..~1.2), smoke density.
// One step = curl -> forces (buoyancy, vorticity confinement, sway, emission, cooling, smoke)
// -> divergence -> Jacobi pressure -> projection -> MacCormack advection.
struct P {
dims: vec4f, // nx, ny, cell (pt), dt
origin: vec4f, // domain x0, y0 (pt), time (s), reset (1 = treat previous state as empty)
shape: vec4f, // centre x, y, half w, half h (pt)
shape2: vec4f, // radius, seed, rise speed (pt/s), tongue spacing (pt)
fire: vec4f, // buoyancy (pt/s^2), cooling (1/s), smoke rate, vorticity
fire2: vec4f, // sway (pt/s^2), flicker speed, smoke fade (1/s), source depth (pt)
}
@group(0) @binding(0) var<uniform> u: P;
@group(0) @binding(1) var s_in: texture_2d<f32>;
@group(0) @binding(3) var s_out: texture_storage_2d<rgba16float, write>;
@group(0) @binding(4) var a_in: texture_2d<f32>;
@group(0) @binding(5) var b_in: texture_2d<f32>;
@group(0) @binding(6) var r_out: texture_storage_2d<r32float, write>;
fn n() -> vec2i { return vec2i(u.dims.xy); }
fn inside(c: vec2i) -> bool { return all(c >= vec2i(0)) && all(c < n()); }
fn cl(c: vec2i) -> vec2i { return clamp(c, vec2i(0), n() - 1); }
fn ld(c: vec2i) -> vec4f {
if (u.origin.w > 0.5) { return vec4f(0.0); }
return textureLoad(s_in, cl(c), 0);
}
fn la(c: vec2i) -> f32 { return textureLoad(a_in, cl(c), 0).r; }
fn lb(c: vec2i) -> f32 { return textureLoad(b_in, cl(c), 0).r; }
fn pos(c: vec2i) -> vec2f { return u.origin.xy + (vec2f(c) + 0.5) * u.dims.z; }
fn sd_rrect(p: vec2f) -> f32 {
let r = min(u.shape2.x, min(u.shape.z, u.shape.w));
let q = abs(p - u.shape.xy) - u.shape.zw + r;
return length(max(q, vec2f(0.0))) + min(max(q.x, q.y), 0.0) - r;
}
fn solid(c: vec2i) -> bool { return sd_rrect(pos(c)) < -u.fire2.w - 1.0; }
fn pcg(v: u32) -> u32 {
let s = v * 747796405u + 2891336453u;
let w = ((s >> ((s >> 28u) + 4u)) ^ s) * 277803737u;
return (w >> 22u) ^ w;
}
fn hash2(c: vec2i, seed: u32) -> f32 {
return f32(pcg(u32(c.x) ^ pcg(u32(c.y) ^ pcg(seed))) >> 8u) * (1.0 / 16777216.0);
}
fn vnoise(p: vec2f, seed: u32) -> f32 {
let i = vec2i(floor(p));
let f = fract(p);
let w = f * f * (3.0 - 2.0 * f);
let a = hash2(i, seed);
let b = hash2(i + vec2i(1, 0), seed);
let c = hash2(i + vec2i(0, 1), seed);
let d = hash2(i + vec2i(1, 1), seed);
return mix(mix(a, b, w.x), mix(c, d, w.x), w.y) * 2.0 - 1.0;
}
@compute @workgroup_size(8, 8)
fn curl(@builtin(global_invocation_id) id: vec3u) {
let c = vec2i(id.xy);
if (!inside(c)) { return; }
let h = u.dims.z;
let w = (ld(c + vec2i(1, 0)).y - ld(c - vec2i(1, 0)).y - ld(c + vec2i(0, 1)).x + ld(c - vec2i(0, 1)).x) / (2.0 * h);
textureStore(r_out, c, vec4f(w, 0.0, 0.0, 0.0));
}
// Fuel along the edge: tongues of uneven strength with dark gaps between them, which wander and
// pulse slowly, plus a fast flicker so tongues pinch off.
fn emission(x: f32, t: f32, seed: u32) -> f32 {
let sp = max(u.shape2.w * 0.32, 3.5);
let fs = u.fire2.y;
let slow = vnoise(vec2f(x / sp, t * 0.55 * fs), seed) * 0.7 + vnoise(vec2f(x / sp * 2.3 + 5.1, t * 1.1 * fs), seed + 1u) * 0.3;
let fast = vnoise(vec2f(x / sp * 1.7 + 11.0, t * 6.0 * fs), seed + 2u);
// Thinner and shorter toward the rounded ends, gone before the sides.
let r = min(u.shape2.x, min(u.shape.z, u.shape.w));
let ends = 1.0 - smoothstep(u.shape.z - r * 1.6, u.shape.z - r * 0.35, abs(x - u.shape.x));
return smoothstep(-0.1, 0.4, slow + 0.25 * fast) * ends;
}
// Where fuel burns: a thin band along the upward-facing edge, under the node's border.
fn fuel_band(p: vec2f) -> f32 {
let h = u.dims.z;
let d = sd_rrect(p);
let e2 = vec2f(0.5 * h, 0.0);
let gx = sd_rrect(p + e2) - sd_rrect(p - e2);
let gy = sd_rrect(p + e2.yx) - sd_rrect(p - e2.yx);
let up = clamp(-gy / max(length(vec2f(gx, gy)), 1e-4), 0.0, 1.0);
let depth = u.fire2.w;
return smoothstep(-depth - 1.5, -depth + 0.5, d) * (1.0 - smoothstep(0.0, h + 1.5, d)) * smoothstep(0.35, 0.8, up);
}
@compute @workgroup_size(8, 8)
fn forces(@builtin(global_invocation_id) id: vec3u) {
let c = vec2i(id.xy);
if (!inside(c)) { return; }
let dt = u.dims.w;
let h = u.dims.z;
let t = u.origin.z;
let seed = u32(u.shape2.y);
var s = ld(c);
var v = s.xy;
var T = s.z;
var sm = s.w;
let p = pos(c);
// Buoyancy: hot gas rises, smoke is a little heavy.
v.y -= dt * (u.fire.x * T - u.fire.x * 0.12 * sm);
// Vorticity confinement puts back the small curls numerical diffusion removes.
if (u.origin.w < 0.5) {
let wl = abs(la(c - vec2i(1, 0)));
let wr = abs(la(c + vec2i(1, 0)));
let wu = abs(la(c - vec2i(0, 1)));
let wd = abs(la(c + vec2i(0, 1)));
var g = vec2f(wr - wl, wd - wu) / (2.0 * h);
let gl = length(g);
if (gl > 1e-4) {
g /= gl;
let w = la(c);
// Smooth near the base, more broken higher up (as in real flames).
let lift = clamp((u.shape.y - u.shape.w - pos(c).y) / max(u.shape2.z * 0.4, 8.0), 0.15, 1.0);
v += dt * u.fire.w * lift * h * vec2f(g.y * w, -g.x * w);
}
}
// Slow sideways sway of the whole column, stronger higher up.
let above = u.shape.y - u.shape.w - p.y;
let sway = vnoise(vec2f(p.x / 90.0, t * 0.35 * u.fire2.y), seed + 9u) + 0.5 * vnoise(vec2f(p.x / 30.0 + 3.0, p.y / 40.0 - t * 0.9 * u.fire2.y), seed + 10u);
v.x += dt * u.fire2.x * sway * clamp(above / 40.0, 0.0, 1.0);
let band = fuel_band(p);
if (band > 0.0) {
let e = emission(p.x, t, seed) * band;
T = max(T, e * (0.95 + 0.25 * vnoise(vec2f(p.x / 3.0, t * 9.0), seed + 4u)));
v.y = mix(v.y, -u.shape2.z * (0.6 + 0.6 * e), e * 0.6);
}
// Cooling, and the smoke the cooling flame leaves behind.
let cool = 1.0 - exp(-dt * u.fire.y);
let lost = T * cool;
T -= lost;
// Smoke is what is left once the flame has cooled past visible.
sm += lost * u.fire.z * (1.0 - smoothstep(0.25, 0.55, T));
sm *= exp(-dt * u.fire2.z);
if (solid(c)) {
v = vec2f(0.0);
T *= 0.5;
sm = 0.0;
}
// Hot gas is carried up far faster than it drifts sideways: damping sideways motion where
// it burns keeps tongues upright instead of the whole row merging into one plume.
v.x *= exp(-dt * 7.0 * smoothstep(0.1, 0.6, T));
// Let everything leave cleanly through the top and sides.
let edge = min(min(f32(c.x), f32(n().x - 1 - c.x)), f32(c.y));
let fade = smoothstep(0.0, 4.0, edge);
T *= fade;
sm *= fade;
textureStore(s_out, c, vec4f(v, T, sm));
}
@compute @workgroup_size(8, 8)
fn divergence(@builtin(global_invocation_id) id: vec3u) {
let c = vec2i(id.xy);
if (!inside(c)) { return; }
let h = u.dims.z;
let l = select(textureLoad(s_in, cl(c - vec2i(1, 0)), 0).x, 0.0, solid(c - vec2i(1, 0)));
let r = select(textureLoad(s_in, cl(c + vec2i(1, 0)), 0).x, 0.0, solid(c + vec2i(1, 0)));
let t = select(textureLoad(s_in, cl(c - vec2i(0, 1)), 0).y, 0.0, solid(c - vec2i(0, 1)));
let b = select(textureLoad(s_in, cl(c + vec2i(0, 1)), 0).y, 0.0, solid(c + vec2i(0, 1)));
// Burning gas expands: the fuel band is a source, so the projection pushes the flame up and
// away from the edge instead of cancelling the rise against the wall below.
let src = fuel_band(pos(c)) * emission(pos(c).x, u.origin.z, u32(u.shape2.y)) * u.shape2.z * 0.2 / h;
textureStore(r_out, c, vec4f((r - l + b - t) / (2.0 * h) - src, 0.0, 0.0, 0.0));
}
// a_in = pressure, b_in = divergence. Open (p = 0) above the domain, closed elsewhere.
fn pn(c: vec2i, centre: f32) -> f32 {
if (c.y < 0) { return 0.0; }
if (!inside(c) || solid(c)) { return centre; }
return la(c);
}
@compute @workgroup_size(8, 8)
fn jacobi(@builtin(global_invocation_id) id: vec3u) {
let c = vec2i(id.xy);
if (!inside(c)) { return; }
let h = u.dims.z;
let pc = la(c);
let s = pn(c - vec2i(1, 0), pc) + pn(c + vec2i(1, 0), pc) + pn(c - vec2i(0, 1), pc) + pn(c + vec2i(0, 1), pc);
textureStore(r_out, c, vec4f((s - h * h * lb(c)) * 0.25, 0.0, 0.0, 0.0));
}
@compute @workgroup_size(8, 8)
fn project(@builtin(global_invocation_id) id: vec3u) {
let c = vec2i(id.xy);
if (!inside(c)) { return; }
let h = u.dims.z;
var s = textureLoad(s_in, c, 0);
let pc = la(c);
let g = vec2f(pn(c + vec2i(1, 0), pc) - pn(c - vec2i(1, 0), pc), pn(c + vec2i(0, 1), pc) - pn(c - vec2i(0, 1), pc)) / (2.0 * h);
var v = s.xy - g;
if (solid(c)) { v = vec2f(0.0); }
// Keep a hitch from blowing the sim up.
let vl = length(v);
let vmax = 2.0 * h / u.dims.w;
if (vl > vmax) { v *= vmax / vl; }
textureStore(s_out, c, vec4f(v, s.z, s.w));
}
fn cr(t: f32) -> vec4f {
// Catmull-Rom weights for the 4 taps around t in [0, 1).
let t2 = t * t;
let t3 = t2 * t;
return vec4f(-0.5 * t3 + t2 - 0.5 * t, 1.5 * t3 - 2.5 * t2 + 1.0, -1.5 * t3 + 2.0 * t2 + 0.5 * t, 0.5 * t3 - 0.5 * t2);
}
// Monotone cubic sample (Catmull-Rom clamped to the 4 nearest texels): far less smearing than
// bilinear, so tongues stay sharp as they rise, and no overshoot.
fn sample_cubic(p: vec2f) -> vec4f {
let g = (p - u.origin.xy) / u.dims.z - 0.5;
let i0 = vec2i(floor(g));
let f = g - floor(g);
let wx = cr(f.x);
let wy = cr(f.y);
var acc = vec4f(0.0);
for (var y = 0; y < 4; y++) {
var row = vec4f(0.0);
for (var x = 0; x < 4; x++) {
row += wx[x] * textureLoad(s_in, cl(i0 + vec2i(x - 1, y - 1)), 0);
}
acc += wy[y] * row;
}
let q0 = textureLoad(s_in, cl(i0), 0);
let q1 = textureLoad(s_in, cl(i0 + vec2i(1, 0)), 0);
let q2 = textureLoad(s_in, cl(i0 + vec2i(0, 1)), 0);
let q3 = textureLoad(s_in, cl(i0 + vec2i(1, 1)), 0);
return clamp(acc, min(min(q0, q1), min(q2, q3)), max(max(q0, q1), max(q2, q3)));
}
@compute @workgroup_size(8, 8)
fn advect(@builtin(global_invocation_id) id: vec3u) {
let c = vec2i(id.xy);
if (!inside(c)) { return; }
let p = pos(c);
let v = textureLoad(s_in, c, 0).xy;
// Two-stage (midpoint) back-trace so curling flow doesn't spiral outward.
let mid = p - 0.5 * u.dims.w * v;
let vm = sample_cubic(mid).xy;
let r = sample_cubic(p - u.dims.w * vm);
textureStore(s_out, c, vec4f(r.xy, max(r.z, 0.0), max(r.w, 0.0)));
}
+107
View File
@@ -0,0 +1,107 @@
// Glow / bloom. variant: 0 soft, 1 neon (hot core rim), 2 aura (spectrum around the border), 3 mask (texture).
// c0 tint, c1 hot core, c2 aura third colour
// p0 (radius, intensity, inner, occlusion)
// p1 (breathe_amp, breathe_period, heat, hot)
// p2 (aura_speed, rim_width, reach_mul, _)
fn aura_palette(u: f32, a: vec3f, b: vec3f, c: vec3f) -> vec3f {
// Three colours around a loop, smooth (cosine) blend.
let x = fract(u) * 3.0;
let w0 = smoothstep(1.0, 0.0, min(x, 3.0 - x));
let w1 = smoothstep(1.0, 0.0, abs(x - 1.0));
let w2 = smoothstep(1.0, 0.0, abs(x - 2.0));
return (a * w0 + b * w1 + c * w2) / max(w0 + w1 + w2, 1e-4);
}
fn mask_tent(uv: vec2f, lod: f32) -> f32 {
// Bilinear taps at ±0.5 texel of the chosen level: a tent upsample, no blocky mip seams.
let dims = vec2f(textureDimensions(source, 0));
let texel = exp2(lod) / dims;
let o = texel * 0.5;
var s = textureSampleLevel(source, samp, uv + vec2f(o.x, o.y), lod).a;
s += textureSampleLevel(source, samp, uv + vec2f(-o.x, o.y), lod).a;
s += textureSampleLevel(source, samp, uv + vec2f(o.x, -o.y), lod).a;
s += textureSampleLevel(source, samp, uv + vec2f(-o.x, -o.y), lod).a;
return s * 0.25;
}
fn shade(i: Inst, px: vec2f) -> vec4f {
let c = ctx(i, px);
var radius = i.p0.x;
var intensity = i.p0.y;
let inner = i.p0.z;
let occl = select(1.0, i.p0.w, effective_blend_mode(i) == 0u);
let heat = i.p1.z;
let hot = i.p1.w;
// Breathing: phase comes from the caller's continuous phase clock (t), so speed changes never jump.
var b = 0.0;
if (!c.reduced && i.p1.y > 0.0) {
b = 0.5 - 0.5 * cos(TAU * c.t / i.p1.y);
b = b * b * (3.0 - 2.0 * b);
}
let amp = i.p1.x;
intensity *= (1.0 - amp) + amp * b;
radius *= 1.0 + 0.22 * amp * b;
// Cooling: shrink and deepen as the light loses heat.
radius *= mix(0.72, 1.0, heat);
intensity *= pow(heat, 1.6);
let tint = cooled(i.c0.rgb, heat);
let reach = radius * i.p2.z;
var light = vec3f(0.0);
var alpha = 0.0;
let edge = smoothstep(-c.aa, c.aa, c.d); // 0 inside, 1 outside
if (c.variant == 3) {
// Mask glow from the mip pyramid in `source` (covers aux2 rect).
let uv = (c.p - i.aux2.xy) / i.aux2.zw;
let rpx = radius * c.scale;
let base = log2(max(rpx, 1.0)) - 0.6;
let m = 0.45 * mask_tent(uv, max(base - 1.0, 0.0)) + 0.35 * mask_tent(uv, max(base, 0.0))
+ 0.2 * mask_tent(uv, base + 1.3);
let core = textureSampleLevel(source, samp, uv, 0.0).a;
let g = knee(m * 1.25 * intensity) * 1.1;
let hotc = core * hot * smoothstep(0.55, 1.0, heat);
light = tint * g + i.c1.rgb * hotc * intensity * 0.6;
alpha = min(g * occl, 1.0);
return finish(vec4f(light, alpha), px);
}
if (c.variant == 0) {
let out_g = bloom(c.d, radius, reach);
let in_g = inner * 0.7 * exp(min(c.d, 0.0) / (0.4 * radius));
let gl = mix(in_g, out_g, edge);
let corew = gauss(max(c.d, 0.0), 0.3 * radius) * hot * smoothstep(0.6, 1.0, heat);
let col = mix(tint, i.c1.rgb, corew * 0.8);
let e = knee(gl * intensity * 1.1);
light = col * e;
alpha = e * occl;
} else if (c.variant == 1) {
// Neon: a white-hot hairline core on the border, coloured bloom both sides.
let w = max(i.p2.y, c.aa * 0.75);
let core = gauss(c.d, w) ;
let out_g = bloom(c.d, radius, reach) * edge;
let in_g = inner * bloom(-c.d, radius * 0.6, reach) * (1.0 - edge);
let corec = mix(tint, i.c1.rgb, 0.7 * hot * smoothstep(0.5, 1.0, heat));
let e = knee((out_g + in_g) * intensity);
light = corec * core * 1.4 * intensity + tint * e * 0.9;
alpha = core * 0.6 * intensity + e * occl;
} else {
// Aura: spectrum flowing around the perimeter, inner rim light + outer bloom + hairline.
let pr = rrect_perim(c.q, c.half, c.r);
var u = pr.x / pr.y;
var flow = 0.0;
if (!c.reduced) { flow = c.t * i.p2.x; }
let col = aura_palette(u - flow, tint, i.c1.rgb, i.c2.rgb);
// Slow brightness variation along the loop (periodic noise), never below 70%.
let wob = 0.85 + 0.15 * pgnoise(vec2f(u * 6.0, flow * 1.7 + 3.0), 6, c.seed);
let out_g = bloom(c.d, radius, reach) * edge;
let in_g = inner * exp(min(c.d, 0.0) / (0.55 * radius)) * (1.0 - edge);
let hair = gauss(c.d + 0.6, max(i.p2.y, c.aa)) * 0.9;
let lit = knee((out_g + in_g) * wob * intensity * 1.1);
light = col * lit + mix(col, vec3f(1.0), 0.6) * hair * intensity * hot;
alpha = lit * occl;
}
return finish(vec4f(light, alpha), px);
}
+40
View File
@@ -0,0 +1,40 @@
// Mask pyramid downsample: Jimenez 13-tap (CoD:AW 2014) from the level above. Smooth, no box seams.
@group(0) @binding(0) var src: texture_2d<f32>;
@group(0) @binding(1) var smp: sampler;
struct V {
@builtin(position) pos: vec4f,
@location(0) uv: vec2f,
}
@vertex
fn vs(@builtin(vertex_index) vi: u32) -> V {
let p = vec2f(f32((vi << 1u) & 2u), f32(vi & 2u));
var o: V;
o.pos = vec4f(p * 2.0 - 1.0, 0.0, 1.0);
o.uv = vec2f(p.x, 1.0 - p.y);
return o;
}
fn s(uv: vec2f) -> vec4f { return textureSampleLevel(src, smp, uv, 0.0); }
@fragment
fn fs(in: V) -> @location(0) vec4f {
let t = 1.0 / vec2f(textureDimensions(src, 0));
let uv = in.uv;
let a = s(uv + t * vec2f(-2.0, -2.0));
let b = s(uv + t * vec2f(0.0, -2.0));
let c = s(uv + t * vec2f(2.0, -2.0));
let d = s(uv + t * vec2f(-1.0, -1.0));
let e = s(uv + t * vec2f(1.0, -1.0));
let f = s(uv + t * vec2f(-2.0, 0.0));
let g = s(uv);
let h = s(uv + t * vec2f(2.0, 0.0));
let i = s(uv + t * vec2f(-1.0, 1.0));
let j = s(uv + t * vec2f(1.0, 1.0));
let k = s(uv + t * vec2f(-2.0, 2.0));
let l = s(uv + t * vec2f(0.0, 2.0));
let m = s(uv + t * vec2f(2.0, 2.0));
return (d + e + i + j) * 0.125 + (a + b + g + f) * 0.03125 + (b + c + h + g) * 0.03125
+ (f + g + l + k) * 0.03125 + (g + h + m + l) * 0.03125;
}
+43
View File
@@ -0,0 +1,43 @@
// Motion blur of a node layer (`source` = the node rendered at rest, covering aux2 with a transparent margin).
// xf (first, count, mode, _). mode 0 = shutter: `count` exact sub-frame poses, each two vec4s:
// (ia, ib, ic, id) inverse linear part, (itx, ity, weight*opacity, _): local = M^-1 * screen.
// mode 1 = directional: pose 0 is the current pose; aux.xy is the blur vector (pt, whole shutter);
// `count` taps along it with a smooth window.
fn src_at(i: Inst, l: vec2f) -> vec4f {
let uv = (l - i.aux2.xy) / i.aux2.zw;
return textureSampleLevel(source, samp, uv, 0.0);
}
fn pose(base: u32, k: u32, p: vec2f) -> vec3f {
let m = data[base + k * 2u];
let tw = data[base + k * 2u + 1u];
return vec3f(m.x * p.x + m.z * p.y + tw.x, m.y * p.x + m.w * p.y + tw.y, tw.z);
}
fn shade(i: Inst, px: vec2f) -> vec4f {
let p = px / i.shape.y;
let first = u32(i.xf.x);
let n = u32(i.xf.y);
var acc = vec4f(0.0);
if (i.xf.z < 0.5) {
for (var k = 0u; k < n; k++) {
let l = pose(first, k, p);
acc += src_at(i, l.xy) * l.z;
}
} else {
// Taps are <= ~2 px apart at typical speeds; a fixed (un-jittered) set avoids the hatching
// that per-pixel jitter leaves on edges.
let j = 0.5;
let b = i.aux.xy;
var wsum = 0.0;
for (var k = 0u; k < n; k++) {
let o = (f32(k) + j) / f32(n) - 0.5;
let w = 1.0 - 4.0 * o * o * 0.85;
let l = pose(first, 0u, p - b * o);
acc += src_at(i, l.xy) * (w * l.z);
wsum += w;
}
acc /= max(wsum, 1e-4);
}
return finish(acc, px);
}
+157
View File
@@ -0,0 +1,157 @@
// Pulses. variant: 0 radar rings, 1 breathing halo, 2 heartbeat, 3 ping (travels A -> along dir), 4 tap ripple.
// c0 colour, c1 hot/core colour
// p0 (count, period, reach, width)
// p1 (intensity, t0, duration, repeat) t0/duration/repeat: one-shots (ping, ripple)
// p2 (travel, lag, head radius, occlusion)
// aux: origin xy, direction xy (ping) | origin xy (ripple)
// Ease with anticipation for the ping: cubic Bézier in value, P1 < 0 winds up against the travel,
// P2 = 1 lands with zero velocity (decelerates in, never stops dead).
fn shoot(u: f32) -> f32 {
let x = clamp(u, 0.0, 1.0);
let m = 1.0 - x;
return 3.0 * m * m * x * (-0.12) + 3.0 * m * x * x * 1.0 + x * x * x;
}
fn beat_env(x: f32) -> f32 {
// Fast attack, exponential release; continuous at the peak.
return select(exp(-x / 0.085), exp(-(x / 0.018) * (x / 0.018)), x < 0.0);
}
// One ping shot at `age` seconds: (energy, white-hot share).
fn ping(c: Ctx, i: Inst, age: f32, dur: f32) -> vec2f {
let o = i.aux.xy;
let dir = normalize(i.aux.zw);
let travel = i.p2.x;
let head_r = i.p2.z;
if (age < 0.0) { return vec2f(0.0); }
let u = age / dur;
if (c.reduced) {
// No travel: the destination glows up and cools in place.
let dest = o + dir * travel;
let env = smoothstep(0.0, 0.2, age) * exp(-max(age - 0.2, 0.0) * 3.0);
return vec2f(env * gauss(length(c.p - dest), head_r * 3.0), 0.0);
}
let s_head = shoot(u);
let s_tail = shoot(u - i.p2.y);
let hpos = o + dir * travel * s_head;
let tpos = o + dir * travel * s_tail;
let sd = segdist(c.p, tpos, hpos);
// After arrival the head blooms out and cools (continuous at u = 1).
let after = max(u - 1.0, 0.0);
let cool = exp(-after * 3.5);
let hr = head_r * (1.0 + 0.9 * (1.0 - cool));
let tailw = head_r * 0.55 * (0.35 + 0.65 * sd.y);
let tail = gauss(sd.x, tailw) * sd.y * sd.y * 0.8;
let dh = length(c.p - hpos);
let head = gauss(dh, hr) + 0.35 * bloom(dh - hr * 0.5, hr * 1.2, hr * 8.0);
var e = (head + tail) * cool;
let hot = gauss(dh, hr * 0.45) * cool * cool;
// Launch flash at the origin.
let fr = 26.0 * (1.0 - exp(-age * 7.0));
e += exp(-age * 10.0) * smoothstep(0.0, 0.03, age) * gauss(length(c.p - o) - fr, 2.0 + age * 6.0) * 0.5;
return vec2f(e, hot);
}
fn shade(i: Inst, px: vec2f) -> vec4f {
let c = ctx(i, px);
let n = i32(i.p0.x + 0.5);
let period = max(i.p0.y, 0.05);
let reach = i.p0.z;
let width = i.p0.w;
let inten = i.p1.x;
let occl = select(1.0, i.p2.w, effective_blend_mode(i) == 0u);
let outside = smoothstep(-c.aa, c.aa, c.d);
var e = 0.0; // emitted energy (tint)
var hotv = 0.0; // white-hot share
if (c.variant == 0) {
if (c.reduced) {
e = 0.35 * bloom(c.d, reach * 0.18, reach * 0.8);
} else {
for (var k = 0; k < n; k++) {
let ph = fract(c.t / period + f32(k) / f32(n));
let r = reach * (1.0 - pow(1.0 - ph, 2.2));
let w = width * (1.0 + 2.2 * ph);
let a = pow(1.0 - ph, 1.6) * smoothstep(0.0, 0.08, ph);
let ring = gauss(c.d - r, w);
// Faint wash trailing inside the ring front, like a radar sweep.
let wash = smoothstep(r + w, r - w, c.d) * exp(-(r - c.d) / max(reach * 0.22, 1.0));
e += a * (ring + 0.22 * wash);
}
e += 0.18 * bloom(c.d, reach * 0.1, reach * 0.6);
}
e *= outside;
} else if (c.variant == 1) {
var b = 0.5;
if (!c.reduced) { b = 0.5 - 0.5 * cos(TAU * c.t / period); b = b * b * (3.0 - 2.0 * b); }
let r = reach * (0.55 + 0.45 * b);
e = (0.45 + 0.55 * b) * bloom(c.d, r, r * 5.0) * outside;
hotv = 0.25 * b * gauss(max(c.d, 0.0), r * 0.25);
} else if (c.variant == 2) {
var beat = 0.3;
var ring = 0.0;
if (!c.reduced) {
// Every beat is its own instance: the rings of earlier beats keep expanding and fading
// under the new one instead of being cut when it starts.
let tp = c.t / period;
let kb = floor(tp);
beat = 0.0;
for (var k = -1; k < 3; k++) {
let x = tp - (kb - f32(k));
beat += beat_env(x) + 0.62 * beat_env(x - 0.17);
let age = x * period; // seconds since that beat's lub
if (age > 0.0) {
let rr = reach * (1.0 - exp(-age * 4.5));
// Finished rings fade out instead of piling up into a band at full reach.
ring += exp(-age * 3.2) * smoothstep(0.0, 0.03, age) * (1.0 - smoothstep(0.7, 1.3, age)) * gauss(c.d - rr, width * (1.0 + age * 3.0));
}
}
// Fade the faint tail of old rings out before the quad edge.
let edge = reach + width * 16.0;
ring *= 1.0 - smoothstep(edge * 0.8, edge, c.d);
}
let r = reach * 0.22 * (1.0 + 0.35 * beat);
e = ((0.25 + 0.75 * beat) * bloom(c.d, r, reach) + 0.55 * ring) * outside;
hotv = 0.35 * beat * gauss(max(c.d, 0.0), r * 0.25) * outside;
} else if (c.variant == 3) {
let dur = max(i.p1.z, 0.05);
let age0 = c.t - i.p1.y;
// A repeating ping lets the previous shot finish blooming while the next one flies.
var shots = 1;
var age = age0;
if (i.p1.w > 0.0 && age0 > 0.0) {
age = age0 - floor(age0 / i.p1.w) * i.p1.w;
shots = 3;
}
for (var k = 0; k < shots; k++) {
let a = age + f32(k) * i.p1.w;
// PING_LIFE in pack.rs: the frame loop ticks until the last shot ends here.
if (a > age0 + 1e-4 || a > dur * 2.2) { break; }
let pe = ping(c, i, a, dur);
e += pe.x;
hotv += pe.y;
}
} else {
// Ripple from a tap point, confined to the shape with a soft edge.
let dur = max(i.p1.z, 0.05);
let age = c.t - i.p1.y;
if (age >= 0.0 && age < dur) {
let u = age / dur;
let r = length(c.p - i.aux.xy);
let inside = smoothstep(c.aa, -c.aa, c.d);
if (c.reduced) {
e = 0.06 * (1.0 - u) * smoothstep(0.0, 0.08, u) * inside;
} else {
let rr = reach * (1.0 - pow(1.0 - u, 3.0));
let w = width * (1.0 + 3.0 * u);
let fade = pow(1.0 - u, 1.5);
let ring = gauss(r - rr, w) * fade * 0.55;
let fill = smoothstep(rr + w, rr - w * 3.0, r) * 0.05 * (1.0 - u) * (1.0 - u) * smoothstep(0.0, 0.05, u);
e = (ring * 0.7 + fill) * inside;
hotv = ring * 0.1 * inside;
}
}
}
let col = i.c0.rgb * e + i.c1.rgb * hotv;
return finish(vec4f(col * inten, (e + hotv) * occl * inten), px);
}
+425
View File
@@ -0,0 +1,425 @@
//! Fire and smoke simulation: one small stable-fluids grid per simulated fire layer (shaders/firesim.wgsl).
//!
//! `FxRenderer::prepare` plans each grid's steps for the frame (fixed 1/60 s steps, capped, so the
//! look doesn't depend on frame rate), `FxRenderer::simulate` records them as compute dispatches,
//! and the fire layer samples the resulting state texture.
use crate::*;
const DT: f32 = 1.0 / 60.0;
const JACOBI: usize = 14;
/// Steps per frame while playing; beyond it the sim skips time instead of stalling the frame.
const MAX_STEPS: usize = 4;
/// A grid that starts (or goes back in time) warms up this long, so its first frame is already burning.
const WARMUP: f32 = 1.2;
const SLOTS: usize = 80;
const SLOT: usize = 256;
#[repr(C)]
#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)]
pub(crate) struct SimUniform {
pub(crate) dims: [f32; 4],
pub(crate) origin: [f32; 4],
pub(crate) shape: [f32; 4],
pub(crate) shape2: [f32; 4],
pub(crate) fire: [f32; 4],
pub(crate) fire2: [f32; 4],
}
const _: () = {
assert!(std::mem::size_of::<SimUniform>() == 96);
assert!(std::mem::offset_of!(SimUniform, dims) == 0);
assert!(std::mem::offset_of!(SimUniform, origin) == 16);
assert!(std::mem::offset_of!(SimUniform, shape) == 32);
assert!(std::mem::offset_of!(SimUniform, shape2) == 48);
assert!(std::mem::offset_of!(SimUniform, fire) == 64);
assert!(std::mem::offset_of!(SimUniform, fire2) == 80);
};
/// Which fire a grid serves: grids are matched by (seed, style, size) and serve one fire per frame.
#[derive(Clone, Copy, Debug, PartialEq)]
struct Claim {
key: (u32, u32, u32, u32),
/// Where the fire's domain was when it last claimed the grid (pt).
origin: [f32; 2],
/// The frame it last claimed the grid.
used: u64,
}
impl Claim {
/// A grid whose fire wasn't drawn last frame is gone; its fire would start over anyway.
fn alive(&self, frame: u64) -> bool {
self.used + 1 >= frame
}
}
/// The grid a fire with `key` at `origin` takes this frame: an unclaimed one with the same key,
/// the nearest to where it was, so identical fires each keep their own state. None: make one.
fn pick(claims: impl Iterator<Item = Claim>, key: (u32, u32, u32, u32), origin: [f32; 2], frame: u64) -> Option<usize> {
let dist = |c: &Claim| (c.origin[0] - origin[0]).powi(2) + (c.origin[1] - origin[1]).powi(2);
claims.enumerate().filter(|(_, c)| c.key == key && c.used != frame).min_by(|a, b| dist(&a.1).total_cmp(&dist(&b.1))).map(|(i, _)| i)
}
/// Steps to run for a grid last stepped to `prev` (None: never), to reach `target`: how many, and
/// where they start. A hitch runs at most `MAX_STEPS` and skips the rest; only a new grid or a jump
/// back in time warms up.
fn schedule(prev: Option<f32>, target: f32, frozen: bool) -> (usize, Start) {
match prev {
Some(t) if frozen => (0, Start::Continue { t0: t }),
Some(t) if target >= t - 1e-4 => {
let due = ((target - t) / DT + 1e-3).floor() as usize;
let steps = due.min(MAX_STEPS);
(steps, Start::Continue { t0: target - steps as f32 * DT })
}
_ => {
let steps = ((WARMUP / DT).round() as usize).min(SLOTS);
(steps, Start::Reset { t0: target - steps as f32 * DT })
}
}
}
/// Where a planned run starts: continuing from the grid's last state, or starting the sim over.
#[derive(Clone, Copy)]
enum Start {
/// Picks up at `t0`, the time of the state it starts from.
Continue { t0: f32 },
/// Clears the state on its first step, starting at `t0`.
Reset { t0: f32 },
}
impl Start {
/// Sim time before the first step.
fn t0(self) -> f32 {
match self {
Start::Continue { t0 } | Start::Reset { t0 } => t0,
}
}
fn is_reset(self) -> bool {
matches!(self, Start::Reset { .. })
}
}
struct Grid {
claim: Claim,
n: [u32; 2],
views: [wgpu::TextureView; 2],
binds: [[wgpu::BindGroup; 7]; 2],
uniforms: wgpu::Buffer,
/// Which state texture holds the latest step.
cur: usize,
/// Sim time of `views[cur]`; None until the first step.
t: Option<f32>,
phase: Phase,
}
/// What a grid is doing this frame. `begin_frame` puts every grid back to `Idle`.
#[derive(Clone, Copy)]
enum Phase {
/// Nothing planned this frame: `views[cur]` is already what the layer samples.
Idle,
/// Steps are due but not yet recorded, so `views[cur]` is the state before them.
Planned(Plan),
/// Recorded this frame; `cur` already points at the newest state.
Stepped,
}
#[derive(Clone, Copy)]
struct Plan {
/// At least one step.
steps: usize,
start: Start,
u: SimUniform,
}
pub(crate) struct Sims {
pipes: [wgpu::ComputePipeline; 6],
bgl: wgpu::BindGroupLayout,
grids: Vec<Grid>,
frame: u64,
/// One grid's step uniforms, reused across frames.
bytes: Vec<u8>,
}
const CURL: usize = 0;
const FORCES: usize = 1;
const DIV: usize = 2;
const JAC: usize = 3;
const PROJECT: usize = 4;
const ADVECT: usize = 5;
impl Sims {
pub fn new(device: &wgpu::Device) -> Sims {
let cs = wgpu::ShaderStages::COMPUTE;
let e = |binding, ty| wgpu::BindGroupLayoutEntry { binding, visibility: cs, ty, count: None };
let tex = wgpu::BindingType::Texture {
sample_type: wgpu::TextureSampleType::Float { filterable: false },
view_dimension: wgpu::TextureViewDimension::D2,
multisampled: false,
};
let store = |format| wgpu::BindingType::StorageTexture {
access: wgpu::StorageTextureAccess::WriteOnly,
format,
view_dimension: wgpu::TextureViewDimension::D2,
};
let bgl = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
label: Some("fx firesim"),
entries: &[
e(0, wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: true, min_binding_size: None }),
e(1, tex),
e(3, store(wgpu::TextureFormat::Rgba16Float)),
e(4, tex),
e(5, tex),
e(6, store(wgpu::TextureFormat::R32Float)),
],
});
let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
label: Some("fx firesim"),
bind_group_layouts: &[Some(&bgl)],
immediate_size: 0,
});
let module = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("fx firesim"),
source: wgpu::ShaderSource::Wgsl(include_str!("shaders/firesim.wgsl").into()),
});
let pipe = |entry: &str| {
device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
label: Some(entry),
layout: Some(&layout),
module: &module,
entry_point: Some(entry),
compilation_options: Default::default(),
cache: None,
})
};
Sims {
pipes: [pipe("curl"), pipe("forces"), pipe("divergence"), pipe("jacobi"), pipe("project"), pipe("advect")],
bgl,
grids: Vec::new(),
frame: 0,
bytes: Vec::new(),
}
}
pub fn begin_frame(&mut self) {
self.frame += 1;
let f = self.frame;
self.grids.retain(|g| g.claim.alive(f));
for g in &mut self.grids {
g.phase = Phase::Idle;
}
}
/// Find or make the grid for a fire layer covering `domain` (pt) and plan this frame's steps.
/// Call once per fire per frame, after `begin_frame`.
/// Returns the grid index (see `final_view`) and the grid's extent in pt (whole cells, so a
/// little larger than `domain`).
pub fn plan(&mut self, device: &wgpu::Device, layer: &FxLayer, p: &FireParams, domain: Rect, frozen: bool) -> (usize, [f32; 2]) {
let area = (domain.w * domain.h).max(1.0);
let cell = (area / 16_000.0).sqrt().clamp(1.0, 3.0);
let n = [((domain.w / cell).ceil() as u32).max(8), ((domain.h / cell).ceil() as u32).max(8)];
let style = p.style as u32;
let key = (layer.seed, style, n[0], n[1]);
let origin = [domain.x, domain.y];
let claim = Claim { key, origin, used: self.frame };
let idx = match pick(self.grids.iter().map(|g| g.claim), key, origin, self.frame) {
Some(i) => i,
None => {
self.grids.push(self.grid(device, n, claim));
self.grids.len() - 1
}
};
let g = &mut self.grids[idx];
g.claim = claim;
let (steps, start) = schedule(g.t, layer.time, frozen);
let s = layer.shape;
let r = s.rect;
let speed = (p.speed / 1.5).max(0.05);
// Rise speed and buoyancy set how fast it climbs; cooling sets where the visible tips end
// (the flame is visible until T falls to ~0.15, after about 1.9 / cooling seconds).
let rise = (p.height * 2.2).clamp(20.0, 140.0) * speed.sqrt();
// Visible until T falls to ~0.35: ln(1 / 0.35) / (height / rise).
let cooling = 1.15 * rise / p.height.max(4.0);
let u = SimUniform {
dims: [n[0] as f32, n[1] as f32, cell, DT],
origin: [domain.x, domain.y, 0.0, 0.0],
shape: [r.x + r.w * 0.5, r.y + r.h * 0.5, r.w * 0.5, r.h * 0.5],
shape2: [s.radius, (layer.seed % 65_536) as f32, rise, p.scale.max(2.0)],
fire: [rise * 3.0, cooling, p.smoke.max(0.0) * 0.6, 0.25 + 0.6 * p.warp],
fire2: [rise * (0.3 + 1.5 * p.swirl), speed, 1.4, 2.0],
};
g.phase = if steps == 0 { Phase::Idle } else { Phase::Planned(Plan { steps, start, u }) };
(idx, [n[0] as f32 * cell, n[1] as f32 * cell])
}
/// The state view a grid's layer should sample this frame (after its planned steps).
pub fn final_view(&self, i: usize) -> &wgpu::TextureView {
let g = &self.grids[i];
let steps = match g.phase {
Phase::Planned(p) => p.steps,
Phase::Idle | Phase::Stepped => 0,
};
&g.views[g.cur ^ (steps & 1)]
}
pub fn pending(&self) -> bool {
self.grids.iter().any(|g| matches!(g.phase, Phase::Planned(_)))
}
pub fn record(&mut self, staging: Option<&rune_staging::Staging>, queue: &wgpu::Queue, encoder: &mut wgpu::CommandEncoder, timestamps: Option<wgpu::ComputePassTimestampWrites<'_>>) -> bool {
if !self.pending() {
return false;
}
for g in &self.grids {
let Phase::Planned(plan) = g.phase else { continue };
let bytes = &mut self.bytes;
bytes.clear();
bytes.resize(plan.steps * SLOT, 0);
for k in 0..plan.steps {
let mut u = plan.u;
u.origin[2] = plan.start.t0() + (k + 1) as f32 * DT;
u.origin[3] = if plan.start.is_reset() && k == 0 { 1.0 } else { 0.0 };
bytes[k * SLOT..k * SLOT + std::mem::size_of::<SimUniform>()].copy_from_slice(bytemuck::bytes_of(&u));
}
match staging {
Some(s) => s.write_buffer(&g.uniforms, 0, bytes),
None => queue.write_buffer(&g.uniforms, 0, bytes),
}
}
if let Some(s) = staging { s.flush(encoder); }
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("fx firesim"), timestamp_writes: timestamps });
for g in &mut self.grids {
let Phase::Planned(plan) = g.phase else { continue };
let wg = [g.n[0].div_ceil(8), g.n[1].div_ceil(8)];
for k in 0..plan.steps {
let off = (k * SLOT) as u32;
let b = &g.binds[g.cur];
let mut run = |pipe: usize, bind: &wgpu::BindGroup| {
pass.set_pipeline(&self.pipes[pipe]);
pass.set_bind_group(0, bind, &[off]);
pass.dispatch_workgroups(wg[0], wg[1], 1);
};
run(CURL, &b[0]);
run(FORCES, &b[1]);
run(DIV, &b[2]);
for j in 0..JACOBI {
run(JAC, &b[3 + (j & 1)]);
}
run(PROJECT, &b[5]);
run(ADVECT, &b[6]);
g.cur ^= 1;
}
g.t = Some(plan.start.t0() + plan.steps as f32 * DT);
g.phase = Phase::Stepped;
}
true
}
fn grid(&self, device: &wgpu::Device, n: [u32; 2], claim: Claim) -> Grid {
let tex = |label, format| {
device.create_texture(&wgpu::TextureDescriptor {
label: Some(label),
size: wgpu::Extent3d { width: n[0], height: n[1], depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::STORAGE_BINDING | wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
})
};
let views = [
tex("fx sim state a", wgpu::TextureFormat::Rgba16Float).create_view(&Default::default()),
tex("fx sim state b", wgpu::TextureFormat::Rgba16Float).create_view(&Default::default()),
];
// Scalars: curl, divergence, pressure ping-pong.
let r: Vec<wgpu::TextureView> = ["fx sim curl", "fx sim div", "fx sim p0", "fx sim p1"]
.iter()
.map(|l| tex(l, wgpu::TextureFormat::R32Float).create_view(&Default::default()))
.collect();
let (curl, div, p0, p1) = (&r[0], &r[1], &r[2], &r[3]);
let uniforms = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("fx sim params"),
size: (SLOTS * SLOT) as u64,
usage: wgpu::BufferUsages::UNIFORM | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
let bind = |s_in: &wgpu::TextureView, s_out: &wgpu::TextureView, a: &wgpu::TextureView, b: &wgpu::TextureView, out: &wgpu::TextureView| {
device.create_bind_group(&wgpu::BindGroupDescriptor {
label: Some("fx firesim"),
layout: &self.bgl,
entries: &[
wgpu::BindGroupEntry {
binding: 0,
resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { buffer: &uniforms, offset: 0, size: wgpu::BufferSize::new(std::mem::size_of::<SimUniform>() as u64) }),
},
wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(s_in) },
wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(s_out) },
wgpu::BindGroupEntry { binding: 4, resource: wgpu::BindingResource::TextureView(a) },
wgpu::BindGroupEntry { binding: 5, resource: wgpu::BindingResource::TextureView(b) },
wgpu::BindGroupEntry { binding: 6, resource: wgpu::BindingResource::TextureView(out) },
],
})
};
// Starting from state X (other one Y), a step ends in Y:
// curl X->c, forces X->Y, div Y->d, jacobi p0<->p1 (even count: ends in p0), project Y->X, advect X->Y.
let set = |x: &wgpu::TextureView, y: &wgpu::TextureView| {
[
bind(x, y, p1, div, curl),
bind(x, y, curl, div, p1),
bind(y, x, curl, p0, div),
bind(y, x, p0, div, p1),
bind(y, x, p1, div, p0),
bind(y, x, p0, div, curl),
bind(x, y, curl, div, p1),
]
};
let binds = [set(&views[0], &views[1]), set(&views[1], &views[0])];
Grid { claim, n, views, binds, uniforms, cur: 0, t: None, phase: Phase::Idle }
}
}
#[cfg(test)]
mod tests {
use super::*;
/// `Sims::plan`'s bookkeeping without the GPU.
fn claim(grids: &mut Vec<Claim>, key: (u32, u32, u32, u32), origin: [f32; 2], frame: u64) -> usize {
let i = pick(grids.iter().copied(), key, origin, frame).unwrap_or_else(|| {
grids.push(Claim { key, origin, used: frame });
grids.len() - 1
});
grids[i] = Claim { key, origin, used: frame };
i
}
#[test]
fn identical_fires_get_their_own_grids_and_free_them() {
let key = (1, 0, 40, 30);
let mut grids = Vec::new();
let (a, b) = (claim(&mut grids, key, [0.0, 0.0], 1), claim(&mut grids, key, [300.0, 0.0], 1));
assert_ne!(a, b, "same seed and size, two grids");
// Next frame, listed the other way round and moved a little: each keeps its grid.
assert_eq!(claim(&mut grids, key, [302.0, 1.0], 2), b);
assert_eq!(claim(&mut grids, key, [1.0, 0.0], 2), a);
assert_eq!(grids.len(), 2);
// The second fire goes away: its grid is dropped at the next frame, the first's stays.
claim(&mut grids, key, [1.0, 0.0], 3);
grids.retain(|c| c.alive(4));
assert_eq!(grids.len(), 1);
assert_eq!(grids[0].origin, [1.0, 0.0]);
}
#[test]
fn hitches_skip_time_and_only_new_or_rewound_grids_warm_up() {
let warm = (WARMUP / DT).round() as usize;
let (n, start) = schedule(None, 3.0, false);
assert!(start.is_reset() && n == warm);
let (n, start) = schedule(Some(1.0), 1.0 + 2.5 * DT, false);
assert!(!start.is_reset() && n == 2 && (start.t0() - (1.0 + 0.5 * DT)).abs() < 1e-5);
let (n, start) = schedule(Some(1.0), 3.0, false);
assert!(!start.is_reset() && n == MAX_STEPS && (start.t0() + MAX_STEPS as f32 * DT - 3.0).abs() < 1e-5, "a 2 s hitch: {n} steps");
assert!(schedule(Some(2.0), 1.0, false).1.is_reset(), "back in time starts over");
assert_eq!(schedule(Some(1.0), 3.0, true).0, 0, "frozen");
}
}
+330
View File
@@ -0,0 +1,330 @@
use super::*;
use crate::params::invert;
#[test]
fn sparkle_cap_and_tables_reach_64_without_regrowing() {
let p = SparkleParams { count: 100, burst: Some(0.0), life: 10.0, ..Default::default() };
let layer = Fx::sparkles(p).on(card()).at(1.0);
let (_, packed, _) = layer.pack().unwrap();
assert_eq!(packed.p0[0], 64.0);
assert_eq!(layer.fx.cost().samples, 128);
let mut table = Vec::with_capacity(128);
let capacity = table.capacity();
let (_, count) = cpu::sparkles(&p, card().rect, 1.0, 1, false, &mut table);
assert!(count > 32.0 && count <= 64.0);
assert_eq!(table.len(), count as usize * 2);
assert_eq!(table.capacity(), capacity);
}
fn card() -> Shape {
Shape::rounded(100.0, 100.0, 200.0, 120.0, 16.0)
}
#[test]
fn idle_layers_cost_nothing() {
let l = Fx::glow(GlowParams { intensity: 0.0, ..Default::default() }).on(card());
assert!(l.pack().is_none());
let l = Fx::glow(GlowParams { heat: 0.0, ..Default::default() }).on(card());
assert!(l.pack().is_none(), "a fully cooled light is culled");
let ripple = PulseParams { style: PulseStyle::Ripple { at: [150.0, 150.0] }, t0: 1.0, duration: 0.5, ..Default::default() };
assert!(Fx::pulse(ripple).on(card()).at(0.5).pack().is_none(), "before the tap");
assert!(Fx::pulse(ripple).on(card()).at(1.2).pack().is_some());
assert!(Fx::pulse(ripple).on(card()).at(1.6).pack().is_none(), "after the ripple");
assert!(!Fx::pulse(ripple).on(card()).at(1.6).is_animating());
let shock = DistortParams::shockwave([0.0, 0.0], 0.0);
assert!(Fx::distort(shock).on(card()).at(2.0).pack().is_none());
}
#[test]
fn layers_that_draw_nothing_never_keep_the_loop_awake() {
let glow = GlowParams { breathe: 0.3, ..Default::default() };
let pulse = PulseParams::default();
let electric = ElectricParams::default();
let fire = FireParams::default();
let haze = |amount| DistortParams::HeatHaze { height: 40.0, scale: 14.0, speed: 2.2, amount, whole_shape: false };
let chroma = |glitch| DistortParams::ChromaSplit { offset: [0.0, 0.0], glitch, feather: 0.0 };
let shimmer = ShimmerParams::default();
let sparkles = SparkleParams::default();
let aurora = AuroraParams::default();
let grain = GrainParams { fps: 24.0, ..Default::default() };
let pairs = [
(Fx::glow(glow), Fx::glow(GlowParams { intensity: 0.0, ..glow })),
(Fx::glow(glow), Fx::glow(GlowParams { heat: 0.0, ..glow })),
(Fx::pulse(pulse), Fx::pulse(PulseParams { intensity: 0.0, ..pulse })),
(Fx::electric(electric), Fx::electric(ElectricParams { intensity: 0.0, ..electric })),
(Fx::fire(fire), Fx::fire(FireParams { intensity: 0.0, ..fire })),
(Fx::distort(haze(1.6)), Fx::distort(haze(0.0))),
(Fx::distort(chroma(0.5)), Fx::distort(chroma(0.0))),
(Fx::shimmer(shimmer), Fx::shimmer(ShimmerParams { intensity: 0.0, base_alpha: 0.0, ..shimmer })),
(Fx::sparkles(sparkles), Fx::sparkles(SparkleParams { intensity: 0.0, ..sparkles })),
(Fx::sparkles(sparkles), Fx::sparkles(SparkleParams { count: 0, ..sparkles })),
(Fx::aurora(aurora), Fx::aurora(AuroraParams { intensity: 0.0, ..aurora })),
(Fx::grain(grain), Fx::grain(GrainParams { amount: 0.0, ..grain })),
];
for (live, silent) in pairs {
let live = live.on(card()).at(1.0);
assert!(live.is_animating() && live.pack().is_some(), "{live:?}");
assert!(!live.opacity(0.0).is_animating(), "zero opacity: {live:?}");
let silent = silent.on(card()).at(1.0);
assert!(!silent.is_animating() && silent.pack().is_none(), "{silent:?}");
}
}
#[test]
fn a_ping_ticks_until_its_shot_has_cooled() {
let ping = PulseParams { style: PulseStyle::Ping { from: [0.0, 0.0], dir: [1.0, 0.0], travel: 200.0 }, t0: 1.0, duration: 0.5, ..Default::default() };
let at = |t: f32| Fx::pulse(ping).on(card()).at(t);
let cooling = 1.0 + 0.5 * 2.1;
assert!(at(cooling).pack().is_some(), "still drawn while it cools");
assert!(at(cooling).is_animating(), "so the loop keeps ticking");
let done = 1.0 + 0.5 * 2.3;
assert!(at(done).pack().is_none() && !at(done).is_animating());
}
#[test]
fn one_shots_overlap_and_retire_by_fading() {
let mut p = OneShots::new(3);
for k in 0..3 {
p.trigger(k as f32 * 0.1, k);
}
let live: Vec<_> = p.live(0.25, 1.0).map(|(s, o)| (s.data, o)).collect();
assert_eq!(live, vec![(0, 1.0), (1, 1.0), (2, 1.0)], "a retrigger never restarts or cuts the running ones");
// Full: the oldest fades out over FADE instead of vanishing.
p.trigger(0.3, 3);
let o0 = |t: f32| p.live(t, 1.0).find(|(s, _)| s.data == 0).map_or(0.0, |(_, o)| o);
assert_eq!(o0(0.3), 1.0);
let mut prev = 1.0;
for i in 1..=20 {
let v = o0(0.3 + i as f32 * OneShots::<i32>::FADE / 20.0);
assert!(v <= prev && prev - v < 0.2, "fades smoothly: {prev} -> {v}");
prev = v;
}
assert_eq!(prev, 0.0);
assert_eq!(p.live(0.31, 1.0).filter(|(_, o)| *o == 1.0).count(), 3);
// A storm of triggers stays bounded.
for k in 0..100 {
p.trigger(0.4 + k as f32 * 0.001, k);
}
assert!(p.live(0.5, 1.0).count() <= 6);
let seeds: std::collections::HashSet<u32> = p.live(0.5, 1.0).map(|(s, _)| s.seed).collect();
assert!(seeds.len() > 1, "instances get distinct seeds");
}
#[test]
fn opacity_zero_is_culled() {
assert!(Fx::glow(GlowParams::default()).on(card()).opacity(0.0).pack().is_none());
let (_, i, _) = Fx::glow(GlowParams::default()).on(card()).opacity(0.4).pack().unwrap();
assert_eq!(i.shape[2], 0.4);
}
#[test]
fn zaps_and_bursts_live_out_their_window_then_cull() {
let zap = Fx::electric(ElectricParams { style: ElectricStyle::Arc { a: [0.0, 0.0], b: [200.0, 40.0] }, zap: Some(1.0), ..Default::default() }).on(card());
assert!(zap.at(0.9).pack().is_none());
assert!(zap.at(1.2).pack().is_some() && zap.at(1.2).is_animating());
assert!(zap.at(1.0 + ElectricParams::ZAP_LIFE + 0.01).pack().is_none());
let p = SparkleParams { burst: Some(2.0), ..Default::default() };
let burst = Fx::sparkles(p).on(card());
assert!(burst.at(2.3).pack().is_some());
assert!(!burst.at(2.0 + p.burst_life() + 0.01).is_animating());
let mut data = Vec::new();
let (_, n) = cpu::sparkles(&p, card().rect, 2.0 + p.burst_life() + 0.01, 1, false, &mut data);
assert_eq!(n, 0.0, "every burst star is gone by burst_life()");
let dense = SparkleParams { count: 64, burst: Some(0.0), life: 2.0, ..Default::default() };
let (_, inst, _) = Fx::sparkles(dense).on(card()).at(0.3).pack().unwrap();
assert_eq!(inst.p0[0], 64.0);
assert_eq!(Fx::sparkles(SparkleParams { count: 100, ..dense }).cost().samples, 128);
data.clear();
let (_, n64) = cpu::sparkles(&dense, card().rect, 0.3, 1, false, &mut data);
assert_eq!(n64, 64.0, "all 64 burst stars are emitted within the cap");
assert_eq!(data.len(), 128, "two vec4f entries per star");
}
#[test]
fn motion_blur_is_one_sample_at_rest_and_scales_with_speed() {
let rest = Rect::new(0.0, 0.0, 100.0, 60.0);
let p = MotionBlurParams::default();
let still = MotionSamples::from_track(&p, rest, 1.0, 2.0, |_| Pose::default());
assert_eq!(still.count, 1);
assert!(!still.is_moving());
let slow = MotionSamples::from_track(&p, rest, 1.0, 2.0, |t| Pose { x: t * 300.0, ..Default::default() });
let fast = MotionSamples::from_track(&p, rest, 1.0, 2.0, |t| Pose { x: t * 1500.0, ..Default::default() });
assert!(slow.count > 1 && fast.count > slow.count, "{} {}", slow.count, fast.count);
let w: f32 = fast.xforms[..fast.count as usize].iter().map(|x| x[6]).sum();
assert!((w - 1.0).abs() < 1e-4, "shutter weights sum to opacity: {w}");
// Bounds cover the swept rect.
assert!(fast.bounds.w > rest.w + 10.0);
}
#[test]
fn pose_inverse_round_trips() {
let rest = Rect::new(10.0, 20.0, 100.0, 60.0);
let pose = Pose { x: 33.0, y: -7.0, rotation: 0.4, scale: 1.3, opacity: 1.0 };
let inv = invert(pose.affine(rest));
let p = pose.apply(rest, [25.0, 40.0]);
let back = [inv[0] * p[0] + inv[2] * p[1] + inv[4], inv[1] * p[0] + inv[3] * p[1] + inv[5]];
assert!((back[0] - 25.0).abs() < 1e-3 && (back[1] - 40.0).abs() < 1e-3, "{back:?}");
}
#[test]
fn phase_never_jumps_when_speed_changes() {
let mut ph = Phase::new(1.0);
let before = ph.at(2.0);
ph.set_speed(2.0, 3.0);
assert!((ph.at(2.0) - before).abs() < 1e-6);
assert!((ph.at(2.1) - before - 0.3).abs() < 1e-5);
}
#[test]
fn heat_cools_continuously() {
let mut h = Heat::new(0.1, 0.3);
h.set(0.0, true);
let lit = h.at(0.5);
assert!((lit - 1.0).abs() < 1e-6);
h.set(0.5, false);
assert!((h.at(0.5) - lit).abs() < 1e-6, "no cut at switch-off");
let mut prev = h.at(0.5);
for i in 1..100 {
let v = h.at(0.5 + i as f32 * 0.01);
assert!(v < prev && prev - v < 0.05, "monotonic, no step");
prev = v;
}
// Switching back on mid-cool resumes from the current heat.
let mid = h.at(0.7);
h.set(0.7, true);
assert!((h.at(0.7) - mid).abs() < 1e-6);
}
#[test]
fn a_lit_heat_stops_asking_for_frames_once_warm() {
let mut h = Heat::new(0.1, 0.3);
assert!(!h.is_active(0.0), "cold and off");
h.set(1.0, true);
assert!(h.is_active(1.05), "warming");
assert_eq!(h.at(1.2), 1.0);
assert!(!h.is_active(1.2), "fully lit holds still");
h.set(1.2, true);
assert!(!h.is_active(1.3), "switching on again while on changes nothing");
h.set(2.0, false);
assert!(h.is_active(2.5), "cooling");
assert!(!h.is_active(10.0), "cooled");
}
#[test]
fn cpu_noise_is_bounded_periodic_and_deterministic() {
for i in 0..2000 {
let x = i as f32 * 0.173;
let v = cpu::gnoise(x, x * 0.37, 0, 9);
assert!(v.abs() <= 1.01, "{v}");
assert_eq!(v, cpu::gnoise(x, x * 0.37, 0, 9));
let a = cpu::gnoise(x, 0.4, 7, 3);
let b = cpu::gnoise(x + 7.0, 0.4, 7, 3);
assert!((a - b).abs() < 1e-4, "periodic in x");
}
}
#[test]
fn electric_tables_have_the_declared_layout() {
let mut data = Vec::new();
let p = ElectricParams { style: ElectricStyle::Arc { a: [0.0, 0.0], b: [300.0, 0.0] }, strands: 2, forks: 1.0, ..Default::default() };
let xf = cpu::electric(&p, card(), 1.7, 3, false, &mut data);
let (n, forks, strands) = (xf[1] as usize, xf[2] as usize, xf[3] as usize);
assert_eq!(data.len(), 2 + 2 * strands * n / 4 + forks * 6);
// Endpoints are pinned.
assert!(data[2][0].abs() < 1e-3);
let reduced = cpu::electric(&p, card(), 1.7, 3, true, &mut Vec::new());
assert_eq!(reduced[2], 0.0, "reduced motion: no forks");
}
#[test]
fn zero_amplitude_electricity_is_a_straight_finite_line() {
for style in [ElectricStyle::Arc { a: [0.0, 0.0], b: [300.0, 0.0] }, ElectricStyle::Border] {
let p = ElectricParams { style, amplitude: 0.0, forks: 1.0, ..Default::default() };
for t in [0.0, 0.4, 1.7] {
let mut data = Vec::new();
cpu::electric(&p, card(), t, 3, false, &mut data);
assert!(data.iter().flatten().all(|v| v.is_finite()), "{style:?} at {t}");
}
}
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn wgsl_uniform_and_storage_layouts_match_rust() {
use crate::pack::InstRaw;
use crate::renderer::Globals;
use crate::sim::SimUniform;
use wgpu::naga::{TypeInner, front::wgsl, proc::Layouter, valid::{Capabilities, ValidationFlags, Validator}};
let check = |label: &str, source: &str, structs: &[(&str, usize, &[(&str, usize)])]| {
let module = wgsl::parse_str(source).unwrap_or_else(|e| panic!("{label}: {}", e.emit_to_string(source)));
Validator::new(ValidationFlags::all(), Capabilities::default() | Capabilities::SHADER_FLOAT16_IN_FLOAT32)
.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}"));
for &(name, size, expected) in structs {
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 inst_fields: &[(&str, usize)] = &[
("rect", std::mem::offset_of!(InstRaw, rect)),
("shape", std::mem::offset_of!(InstRaw, shape)),
("bounds", std::mem::offset_of!(InstRaw, bounds)),
("c0", std::mem::offset_of!(InstRaw, c0)),
("c1", std::mem::offset_of!(InstRaw, c1)),
("c2", std::mem::offset_of!(InstRaw, c2)),
("p0", std::mem::offset_of!(InstRaw, p0)),
("p1", std::mem::offset_of!(InstRaw, p1)),
("p2", std::mem::offset_of!(InstRaw, p2)),
("p3", std::mem::offset_of!(InstRaw, p3)),
("t", std::mem::offset_of!(InstRaw, t)),
("aux", std::mem::offset_of!(InstRaw, aux)),
("aux2", std::mem::offset_of!(InstRaw, aux2)),
("xf", std::mem::offset_of!(InstRaw, xf)),
("clip", std::mem::offset_of!(InstRaw, clip)),
("fade", std::mem::offset_of!(InstRaw, fade)),
];
let globals_fields: &[(&str, usize)] = &[
("viewport", std::mem::offset_of!(Globals, viewport)),
("dither", std::mem::offset_of!(Globals, dither)),
("srgb", std::mem::offset_of!(Globals, srgb)),
];
let fx_src = format!("{}\n{}\n{}", crate::pipes::CLIP, crate::pipes::COMMON, crate::pipes::SOURCES[0].1);
check(
"common+glow.wgsl",
&fx_src,
&[
("Globals", std::mem::size_of::<Globals>(), globals_fields),
("Inst", std::mem::size_of::<InstRaw>(), inst_fields),
],
);
let sim_fields: &[(&str, usize)] = &[
("dims", std::mem::offset_of!(SimUniform, dims)),
("origin", std::mem::offset_of!(SimUniform, origin)),
("shape", std::mem::offset_of!(SimUniform, shape)),
("shape2", std::mem::offset_of!(SimUniform, shape2)),
("fire", std::mem::offset_of!(SimUniform, fire)),
("fire2", std::mem::offset_of!(SimUniform, fire2)),
];
check(
"firesim.wgsl",
include_str!("shaders/firesim.wgsl"),
&[("P", std::mem::size_of::<SimUniform>(), sim_fields)],
);
}
@@ -0,0 +1,59 @@
//! A steady frame reuses last frame's bind groups instead of making new ones.
use rune::render::Gpu;
use rune_fx::*;
const FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Rgba8UnormSrgb;
fn backdrop(gpu: &Gpu) -> wgpu::TextureView {
gpu.device
.create_texture(&wgpu::TextureDescriptor {
label: None,
size: wgpu::Extent3d { width: 96, height: 96, depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: FORMAT,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING,
view_formats: &[],
})
.create_view(&Default::default())
}
fn frame(gpu: &Gpu, fx: &mut FxRenderer, layers: &[FxLayer], backdrop: &wgpu::TextureView, slot_backdrop: Option<&wgpu::TextureView>) -> Vec<Option<wgpu::BindGroup>> {
fx.prepare(&gpu.device, &gpu.queue, &FxFrame { viewport: [96, 96], scale: 1.0, layers, backdrop: Some(backdrop), sources: &[] });
let mut enc = gpu.device.create_command_encoder(&Default::default());
if let Some(b) = slot_backdrop {
fx.blur_backdrop(&gpu.device, &gpu.queue, &mut enc, b, 1);
}
gpu.queue.submit([enc.finish()]);
gpu.device.poll(wgpu::PollType::wait_indefinitely()).expect("poll");
(0..layers.len()).map(|i| fx.layer_bind_group(i).cloned()).collect()
}
#[test]
fn a_steady_frame_reuses_its_bind_groups() {
let gpu = Gpu::headless();
let mut fx = FxRenderer::new(&gpu.device, FORMAT, FxOptions::default());
let bd = backdrop(&gpu);
let slot = backdrop(&gpu);
let layers = [
Fx::glow(GlowParams { radius: 10.0, intensity: 0.8, ..Default::default() }).on(Shape::rounded(16.0, 16.0, 32.0, 32.0, 8.0)).at(0.5),
Fx::lens(LensParams { frost: 0.6, ..Default::default() }).on(Shape::rounded(40.0, 40.0, 40.0, 40.0, 12.0)).at(0.5),
];
let first = frame(&gpu, &mut fx, &layers, &bd, None);
let second = frame(&gpu, &mut fx, &layers, &bd, None);
assert!(first.iter().all(Option::is_some));
assert_eq!(first, second, "the frame backdrop's groups were made again");
// A per-slot backdrop bound after `prepare` is reused too.
let first = frame(&gpu, &mut fx, &layers, &bd, Some(&slot));
let second = frame(&gpu, &mut fx, &layers, &bd, Some(&slot));
assert_eq!(first, second, "the slot backdrop's group was made again");
// A different backdrop gets its own group.
let other = backdrop(&gpu);
let third = frame(&gpu, &mut fx, &layers, &other, None);
assert_eq!(third[0], second[0]);
assert_ne!(third[1], second[1]);
}
@@ -0,0 +1,436 @@
use rune::render::Gpu;
use rune_fx::*;
#[test]
fn external_struct_update_and_emitted_rust_compile() {
let _literal = FxLayer {
fx: Fx::distort(DistortParams::chroma_split([0.0; 2])),
shape: Shape::rounded(0.0, 0.0, 16.0, 16.0, 0.0),
place: Place::Over, time: 0.0, seed: 1, reduced_motion: false,
source: None, opacity: 1.0,
};
let card = Shape::rounded(10.0, 10.0, 120.0, 80.0, 12.0);
let layers = [
Fx::fill(LiquidMetalParams { flow: 0.9, scale: 80.0, ..LiquidMetalParams::rose() }.border(4.0).intensity(0.8)),
Fx::fill(MeshGradientParams { colors: Stops::hex(&[0x1b1f3b, 0xff6f91, 0xffc75f, 0x845ec2]), drift: 0.15, ..MeshGradientParams::dusk() }),
Fx::fill(DitherParams { pattern: DitherPattern::BlueNoise, pixel: 2.0, ..DitherParams::backdrop() }),
Fx::fill(GrainGradientParams { kind: GradientKind::Conic, mono: false, amount: 0.3, ..GrainGradientParams::sweep() }),
Fx::fill(FlutedGlassParams { rib: 10.0, refraction: 7.0, frost: 0.4, ..FlutedGlassParams::reeded() }),
Fx::fill(MetaballParams { count: 4, gloss: 0.7, ..MetaballParams::mint() }),
Fx::fill(SwirlParams { twist: -0.8, warp: 1.2, ..SwirlParams::marble() }),
Fx::fill(VoronoiParams { scale: 24.0, edge: 2.0, ..VoronoiParams::stained() }),
Fx::fill(WaveParams { amplitude: 0.06, softness: 0.01, ..WaveParams::dunes() }),
Fx::fill(HalftoneParams { input: FillInput::Linear, cell: 5.0, ..HalftoneParams::print() }),
Fx::fill(PlasticParams { roughness: 0.6, dome: -0.4, ..PlasticParams::glossy() }.border(5.0)),
Fx::fill(LiquidMetalParams::chrome().anchor(FillAnchor::Element)),
Fx::fill(LiquidMetalParams { anchor: FillAnchor::Element, ..LiquidMetalParams::gold() }),
];
for fx in layers {
let Fx::Fill(p) = fx else { unreachable!() };
assert!(!p.to_rust().is_empty());
let layer = fx.on(card).at(1.0);
assert_eq!(layer.place, if p.needs_backdrop() { Place::Over } else { Place::Under });
}
}
#[test]
fn linear_backdrop_views_are_not_double_decoded_in_srgb_frames() {
use rune::render::Offscreen;
let Gpu { device, queue, .. } = Gpu::headless();
let mut fx = FxRenderer::new(&device, wgpu::TextureFormat::Rgba8Unorm, FxOptions::default());
fx.set_srgb_blend(true);
let layers = [Fx::distort(DistortParams::chroma_split([1e-6, 0.0]))
.on(Shape::rounded(0.0, 0.0, 32.0, 32.0, 0.0))];
for format in [wgpu::TextureFormat::Rgba8UnormSrgb, wgpu::TextureFormat::Rgba16Float] {
let texture = device.create_texture(&wgpu::TextureDescriptor {
label: None,
size: wgpu::Extent3d { width: 32, height: 32, 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: &[],
});
let view = texture.create_view(&Default::default());
// Direct frame input retains the old linear-samples contract; a hook can also
// override the pass-copy convention for its own linear or hardware-decoded view.
for per_slot in [false, true] {
let target = Offscreen::with_format(&device, 32, 32, wgpu::TextureFormat::Rgba8Unorm);
let frame = FxFrame { viewport: [32, 32], scale: 1.0, layers: &layers,
backdrop: (!per_slot).then_some(&view), sources: &[] };
let slots = if per_slot { vec![FxSlot::default().backdrop_srgb(false)] } else { vec![] };
assert_eq!(fx.prepare_with_slots(&device, &queue, &frame, &slots).drawn, 1);
let mut encoder = device.create_command_encoder(&Default::default());
{
let _pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view, depth_slice: None, resolve_target: None,
ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color { r: 0.25, g: 0.125, b: 0.0625, a: 1.0 }), store: wgpu::StoreOp::Store },
})], ..Default::default()
});
}
fx.blur_backdrop(&device, &queue, &mut encoder, &view, 0);
{
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &target.view, depth_slice: None, resolve_target: None,
ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), store: wgpu::StoreOp::Store },
})], ..Default::default()
});
fx.draw_layer(&mut pass, 0);
}
target.copy(&mut encoder);
queue.submit([encoder.finish()]);
let pixels = target.read(&device);
let at = (16 * 32 + 16) * 4;
let expected = [0.25, 0.125, 0.0625].map(|c| (rune::color::srgb_encode(c) * 255.0).round() as u8);
for (got, want) in pixels[at..at + 3].iter().zip(expected) {
assert!(got.abs_diff(want) <= 2, "{format:?} per_slot={per_slot}: {got} != {want}");
}
}
}
}
#[test]
fn gpu_fills_are_finite_at_extremes_degenerate_params_and_large_time() {
let Gpu { device, queue, .. } = Gpu::headless();
let fmt = wgpu::TextureFormat::Rgba16Float;
let mut fx = FxRenderer::new(&device, fmt, FxOptions { dither: true });
let (w, h) = (32u32, 32u32);
let row_bytes = w * 8; // 256 bytes: aligned to COPY_BYTES_PER_ROW_ALIGNMENT
let mk_tex = |usage: wgpu::TextureUsages| {
let t = 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: fmt,
usage,
view_formats: &[],
});
let v = t.create_view(&Default::default());
(t, v)
};
let (target, target_view) = mk_tex(wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC);
let (_bd, bd_view) = mk_tex(wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING);
let (_src, src_view) = mk_tex(wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING);
let readback = device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: (row_bytes * h) as u64,
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
});
let shape = Shape::rounded(2.0, 2.0, 28.0, 28.0, 6.0);
let mut draw = |layer: FxLayer| -> Vec<u16> {
let layers = [layer];
let sources = [&src_view];
let stats = fx.prepare(&device, &queue, &FxFrame {
viewport: [w, h],
scale: 1.0,
layers: &layers,
backdrop: Some(&bd_view),
sources: &sources,
});
assert_eq!(stats.drawn, 1);
let mut enc = device.create_command_encoder(&Default::default());
fx.blur_backdrop(&device, &queue, &mut enc, &bd_view, 0);
{
let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
label: None,
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &target_view,
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,
});
fx.draw_layer(&mut pass, 0);
}
enc.copy_texture_to_buffer(
target.as_image_copy(),
wgpu::TexelCopyBufferInfo {
buffer: &readback,
layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(row_bytes), rows_per_image: Some(h) },
},
wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
);
queue.submit([enc.finish()]);
let slice = readback.slice(..);
slice.map_async(wgpu::MapMode::Read, |_| {});
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
let words: Vec<u16> = bytemuck::cast_slice(&slice.get_mapped_range().unwrap()).to_vec();
readback.unmap();
for &word in &words {
assert_ne!(word & 0x7c00, 0x7c00, "non-finite f16 word {word:#06x}");
}
words
};
// Every style at catalog min, catalog max, and t = 1e5 s.
for style in fill_styles() {
let mut min_fill = style.default_fill();
let mut max_fill = style.default_fill();
for p in style.params {
match p.kind {
ParamKind::Number { min, max, .. } => {
min_fill.set(p.id, Value::Number(min));
max_fill.set(p.id, Value::Number(max));
}
ParamKind::Count { min, max } => {
min_fill.set(p.id, Value::Count(min));
max_fill.set(p.id, Value::Count(max));
}
ParamKind::Choice(c) => {
min_fill.set(p.id, Value::Choice(0));
max_fill.set(p.id, Value::Choice(c.len() - 1));
}
ParamKind::Colors { min, max } => {
let palette = [0x112233, 0x445566, 0x778899, 0xaabbcc, 0xddeeff, 0xff8800];
min_fill.set(p.id, Value::Colors(Stops::hex(&palette[..min])));
max_fill.set(p.id, Value::Colors(Stops::hex(&palette[..max])));
}
_ => {}
}
}
draw(Fx::fill(min_fill).on(shape).source(0, Rect::new(2.0, 2.0, 28.0, 28.0)).at(0.5));
draw(Fx::fill(max_fill).on(shape).source(0, Rect::new(2.0, 2.0, 28.0, 28.0)).at(0.5));
let preset = style.default_fill();
let f0 = draw(Fx::fill(preset).on(shape).at(1e5));
let f1 = draw(Fx::fill(preset).on(shape).at(1e5 + 0.25));
if Fx::fill(preset).on(shape).is_animating() {
assert_ne!(f0, f1, "{} still animates at t = 1e5", style.id);
}
}
// Degenerate cases: conic centre on an exact pixel centre, zero-radius metaballs, extreme mesh sharpness, zero-size source rect,
// slab extremes (roughness 0/1, dome ±1, bevel and border larger than half the shape, tiny shapes, non-finite fields).
let pixel_center = Shape::rounded(0.5, 0.5, 20.0, 20.0, 0.0);
draw(Fx::fill(GrainGradientParams { kind: GradientKind::Conic, center: [0.5, 0.5], ..GrainGradientParams::sweep() }).on(pixel_center).at(1.0));
draw(Fx::fill(MetaballParams { size: 0.0, ..MetaballParams::lava() }).on(shape).at(1.0));
draw(Fx::fill(MeshGradientParams { sharpness: 50.0, ..MeshGradientParams::dusk() }).on(shape).at(1.0));
draw(Fx::fill(DitherParams { input: FillInput::Image, ..DitherParams::bayer() }).on(shape).source(0, Rect::new(0.0, 0.0, 0.0, 0.0)).at(1.0));
for tiny in [Shape::rounded(2.0, 2.0, 4.0, 4.0, 2.0), Shape::rounded(2.5, 2.5, 1.0, 1.0, 0.5)] {
draw(Fx::fill(PlasticParams { roughness: 0.0, dome: 1.0, bevel: 48.0, ..PlasticParams::glossy() }).on(tiny));
draw(Fx::fill(PlasticParams { roughness: 1.0, dome: -1.0, bevel: 48.0, ..PlasticParams::dished() }.border(20.0)).on(tiny));
draw(Fx::fill(LiquidMetalParams { bevel: 48.0, dome: -1.0, anchor: FillAnchor::Element, ..LiquidMetalParams::chrome() }).on(tiny).at(1.0));
}
draw(Fx::fill(PlasticParams { roughness: f32::NAN, dome: f32::INFINITY, bevel: f32::NAN, angle: f32::NEG_INFINITY, ..PlasticParams::glossy() }).on(shape));
draw(Fx::fill(LiquidMetalParams { flow: f32::NAN, scale: f32::NAN, bevel: f32::INFINITY, dome: f32::NAN, contrast: f32::NAN, ..LiquidMetalParams::chrome() }).on(shape).at(1.0));
}
/// Draws `layers` at `scale` into a transparent `w`×`h` Rgba16Float target with no dither, and
/// reads it back as premultiplied linear RGBA (or sRGB-encoded with `srgb`).
fn render(w: u32, h: u32, scale: f32, srgb: bool, layers: &[FxLayer]) -> Vec<[f32; 4]> {
render_at(w, h, scale, srgb, [0.0, 0.0], layers)
}
fn render_at(w: u32, h: u32, scale: f32, srgb: bool, origin: [f32; 2], layers: &[FxLayer]) -> Vec<[f32; 4]> {
static CTX: std::sync::Mutex<Option<(Gpu, FxRenderer)>> = std::sync::Mutex::new(None);
let fmt = wgpu::TextureFormat::Rgba16Float;
let mut guard = CTX.lock().unwrap();
let (gpu, fx) = guard.get_or_insert_with(|| {
let gpu = Gpu::headless();
let fx = FxRenderer::new(&gpu.device, fmt, FxOptions { dither: false });
(gpu, fx)
});
let (device, queue) = (&gpu.device, &gpu.queue);
fx.set_srgb_blend(srgb);
assert_eq!(w * 8 % 256, 0, "row alignment");
let target = 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: fmt,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
});
let view = target.create_view(&Default::default());
let readback = device.create_buffer(&wgpu::BufferDescriptor { label: None, size: (w * 8 * h) as u64, usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ, mapped_at_creation: false });
let vw = w + origin[0].ceil() as u32;
let vh = h + origin[1].ceil() as u32;
let stats = fx.prepare(&device, &queue, &FxFrame { viewport: [vw, vh], scale, layers, backdrop: None, sources: &[] });
assert_eq!(stats.drawn as usize, layers.len());
let mut enc = device.create_command_encoder(&Default::default());
{
let mut 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(wgpu::Color::TRANSPARENT), store: wgpu::StoreOp::Store },
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
for k in 0..layers.len() {
fx.draw_layer_in(&mut pass, fmt, origin, k);
}
}
enc.copy_texture_to_buffer(
target.as_image_copy(),
wgpu::TexelCopyBufferInfo { buffer: &readback, layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(w * 8), rows_per_image: Some(h) } },
wgpu::Extent3d { width: w, height: h, depth_or_array_layers: 1 },
);
queue.submit([enc.finish()]);
let slice = readback.slice(..);
slice.map_async(wgpu::MapMode::Read, |_| {});
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
let words: Vec<u16> = bytemuck::cast_slice(&slice.get_mapped_range().unwrap()).to_vec();
words.chunks(4).map(|p| std::array::from_fn(|c| f16(p[c]))).collect()
}
fn f16(h: u16) -> f32 {
let (s, e, m) = ((h >> 15) as u32, ((h >> 10) & 0x1f) as i32, (h & 0x3ff) as f32);
let v = match e {
0 => m * 2f32.powi(-24),
31 => f32::INFINITY,
_ => (1.0 + m / 1024.0) * 2f32.powi(e - 15),
};
if s == 1 { -v } else { v }
}
fn lum(p: [f32; 4]) -> f32 {
0.2126 * p[0] + 0.7152 * p[1] + 0.0722 * p[2]
}
/// A 56 pt key at 2× in a 128×128 px target.
const KEY: (u32, u32, f32) = (128, 128, 2.0);
fn key() -> Shape {
Shape::rounded(4.0, 4.0, 56.0, 56.0, 8.0)
}
/// Plastic's colour is coverage: the highlight lightens toward white inside the shape's alpha and
/// never adds light past it, at any roughness, intensity or blend mode.
#[test]
fn plastic_never_paints_past_its_coverage() {
let (w, h, s) = KEY;
for srgb in [false, true] {
for roughness in [0.0, 0.05, 0.45, 1.0] {
for (color, intensity) in [(rgb(0xffffff), 1.0), (rgb(0xffd60a), 1.0), (rgb(0xd7263d), 0.5), (rgb(0x202226), 1.0)] {
let p = PlasticParams { color, roughness, ..PlasticParams::glossy() };
for layer in [Fx::fill(p.intensity(intensity)).on(key()), Fx::fill(p.border(6.0)).on(key())] {
let img = render(w, h, s, srgb, &[layer]);
let worst = img.iter().map(|p| p[0].max(p[1]).max(p[2]) - p[3]).fold(f32::MIN, f32::max);
assert!(worst <= 2e-3, "srgb {srgb} roughness {roughness} {color:?} x{intensity}: rgb exceeds alpha by {worst}");
let centre = img[(h / 2 * w + w / 2) as usize];
assert!(layer_is_border(&layer) || (centre[3] - intensity).abs() < 2e-3, "centre alpha {centre:?}");
}
}
}
// Extreme dome (±1), bevel wider than half the shape, and a tiny 4 pt shape.
for dome in [-1.0, 1.0] {
let p = PlasticParams { color: rgb(0xffd60a), roughness: 0.0, dome, bevel: 40.0, angle: 0.8 };
for sh in [key(), Shape::rounded(4.0, 4.0, 4.0, 4.0, 1.5)] {
let img = render(w, h, s, srgb, &[Fx::fill(p).on(sh)]);
let worst = img.iter().map(|p| p[0].max(p[1]).max(p[2]) - p[3]).fold(f32::MIN, f32::max);
assert!(worst <= 2e-3, "srgb {srgb} dome {dome}: rgb exceeds alpha by {worst}");
}
}
}
}
fn layer_is_border(l: &FxLayer) -> bool {
matches!(l.fx, Fx::Fill(p) if p.border > 0.0)
}
/// The flat centre shows the chosen colour (a satin or matte highlight lays a faint sheen over it); glossy plastic has a brighter, tighter highlight than
/// matte; the rim facing the light is lighter than the rim facing away.
#[test]
fn plastic_highlight_follows_roughness_and_light() {
let (w, h, s) = KEY;
let base = rgb(0x3d6fd6);
let mut peaks = Vec::new();
for roughness in [0.05, 0.45, 1.0] {
let img = render(w, h, s, false, &[Fx::fill(PlasticParams { color: base, roughness, ..PlasticParams::glossy() }).on(key())]);
let at = |x: u32, y: u32| img[(y * w + x) as usize];
let centre = at(w / 2, h / 2);
// The colour, under at most a faint sheen from a broad highlight.
for c in 0..3 {
let lift = centre[c] - base.0[c];
assert!((-0.01..0.07).contains(&lift), "roughness {roughness}: centre {centre:?} vs {base:?}");
}
let face: Vec<f32> = img.iter().filter(|p| p[3] > 0.999).map(|p| lum(*p) - lum(centre)).collect();
let peak = face.iter().copied().fold(0.0f32, f32::max);
let spread = face.iter().filter(|v| **v > 0.5 * peak).count();
// Light from above and a little left: the top rim is lit, the bottom rim is in shade.
let (lit, shade) = (lum(at(64, 14)), lum(at(64, 114)));
eprintln!("roughness {roughness}: peak +{peak:.3}, {spread} px above half peak, rims {lit:.3} / {shade:.3}");
assert!(lit > shade * 1.3, "roughness {roughness}: lit rim {lit} vs shaded rim {shade}");
peaks.push((peak, spread));
}
assert!(peaks[0].0 > peaks[1].0 && peaks[1].0 > peaks[2].0, "gloss is brighter: {peaks:?}");
assert!(peaks[0].1 < peaks[2].1, "gloss is tighter: {peaks:?}");
}
/// Eight 24 pt keys in a row at 2×: element-anchored liquid metal paints every key the same,
/// pixel for pixel, at any time (including folded large times); window-anchored does not.
#[test]
fn element_anchored_metal_keys_are_identical() {
let keys_at = |anchor: FillAnchor, t: f32, ox: f32, oy: f32| -> Vec<FxLayer> {
(0..8).map(|k| Fx::fill(LiquidMetalParams::chrome().anchor(anchor)).on(Shape::rounded(ox + k as f32 * 28.0, oy, 24.0, 24.0, 5.0)).at(t)).collect()
};
let (w, h) = (512u32, 64u32);
// Each key's quad is its rect plus 1 pt: 26 pt = 52 px from (3 + 28k) pt.
let tile = |img: &[[f32; 4]], k: u32| -> Vec<[u32; 4]> {
let x0 = 6 + 56 * k;
(6..58).flat_map(|y| (x0..x0 + 52).map(move |x| (x, y))).map(|(x, y)| img[(y * w + x) as usize].map(f32::to_bits)).collect()
};
for t in [1.3, 1e5 + 0.37] {
let img = render(w, h, 2.0, false, &keys_at(FillAnchor::Element, t, 4.0, 4.0));
let first = tile(&img, 0);
assert!(first.iter().any(|p| f32::from_bits(p[3]) > 0.99), "the key is drawn");
for k in 1..8 {
assert!(tile(&img, k) == first, "t = {t}: key {k} differs from key 0");
}
let world = render(w, h, 2.0, false, &keys_at(FillAnchor::World, t, 4.0, 4.0));
assert!((1..8).any(|k| tile(&world, k) != tile(&world, 0)), "t = {t}: window-anchored keys should differ");
}
// Sub-pixel / live_offset positions, isolated-layer viewport shift, and non-power-of-two scale (1.5×).
let subpx = render(w, h, 2.0, false, &keys_at(FillAnchor::Element, 1.3, 4.25, 4.375));
let subpx_tile = |img: &[[f32; 4]], k: u32| -> Vec<[u32; 4]> {
let x0 = 6 + 56 * k;
(6..59).flat_map(|y| (x0..x0 + 53).map(move |x| (x, y))).map(|(x, y)| img[(y * w + x) as usize].map(f32::to_bits)).collect()
};
let sub0 = subpx_tile(&subpx, 0);
for k in 1..8 {
assert!(subpx_tile(&subpx, k) == sub0, "fractional offset: key {k} differs from key 0");
}
let in_layer = render_at(w, h, 2.0, false, [16.0, 12.0], &keys_at(FillAnchor::Element, 1.3, 12.25, 10.375));
for k in 0..8 {
assert!(subpx_tile(&in_layer, k) == sub0, "in-layer origin shift: key {k} differs from direct draw");
}
let scale15 = render(w, h, 1.5, false, &keys_at(FillAnchor::Element, 1.3, 4.0, 4.0));
let tile15 = |img: &[[f32; 4]], k: u32| -> Vec<[u32; 4]> {
let x0 = 4 + 42 * k;
(4..44).flat_map(|y| (x0..x0 + 40).map(move |x| (x, y))).map(|(x, y)| img[(y * w + x) as usize].map(f32::to_bits)).collect()
};
let s15_0 = tile15(&scale15, 0);
for k in 1..8 {
assert!(tile15(&scale15, k) == s15_0, "scale 1.5: key {k} differs from key 0");
}
// Time folding at 512 s and 1024 s turns smoothly without a frame jump.
for fold in [512.0f32, 1024.0] {
let dt = 1.0 / 64.0;
let before = render(128, 64, 2.0, false, &[Fx::fill(LiquidMetalParams::chrome()).on(Shape::rounded(4.0, 4.0, 24.0, 24.0, 5.0)).at(fold - dt)]);
let at_fold = render(128, 64, 2.0, false, &[Fx::fill(LiquidMetalParams::chrome()).on(Shape::rounded(4.0, 4.0, 24.0, 24.0, 5.0)).at(fold)]);
let after = render(128, 64, 2.0, false, &[Fx::fill(LiquidMetalParams::chrome()).on(Shape::rounded(4.0, 4.0, 24.0, 24.0, 5.0)).at(fold + dt)]);
assert_eq!(before, after, "triangle wave is symmetric across {fold}");
let step = before.iter().zip(&at_fold).flat_map(|(a, b)| (0..4).map(move |c| (a[c] - b[c]).abs())).fold(0.0f32, f32::max);
assert!(step < 0.2, "no frame jump at {fold}: max step {step}");
}
}
@@ -0,0 +1,678 @@
//! An effect drawn by a Rune compositor at an effect slot: inside a faded, rounded layer, in
//! either blend mode, through one renderer serving the frame target and the layer's target.
use std::sync::{Arc, Mutex};
use rune::color::{hex, srgb_decode, srgb_encode};
use rune::compose::{Compositor, Frame};
use rune::render::{EffectPhase, EffectSite, KIND_EFFECT};
use rune::{App, AppSpec, Cx, El, effect, el};
use rune_fx::*;
struct Dusk {
fx: Option<FxRenderer>,
formats: Arc<Mutex<Vec<wgpu::TextureFormat>>>,
effect: fn(u32) -> Fx,
}
fn dusk() -> Fx {
Fx::fill(MeshGradientParams::dusk())
}
fn glow(occlusion: f32) -> Fx {
Fx::glow(GlowParams { radius: 12.0, occlusion, ..Default::default() })
}
impl Compositor<()> for Dusk {
fn render(&mut self, f: &mut Frame<'_, ()>) {
let (device, queue, size) = (f.device, f.queue, f.size);
let marks = &f.rt.marks;
let slots: Vec<(u32, rune::render::Instance, u32)> = f.rt.instances.iter().enumerate()
.filter(|(_, i)| i.params[1] == KIND_EFFECT)
.map(|(n, i)| (n as u32, *i, marks.get(n).copied().unwrap_or(1)))
.collect();
let layers: Vec<FxLayer> = slots.iter()
.map(|(_, i, m)| {
let k = i.params[3];
let [x, y, w, h] = i.rect.map(|v| v / k);
let r = i.radii.iter().fold(0.0f32, |a, v| a.max(v.abs())) / k;
(self.effect)(*m).on(Shape::rounded(x, y, w, h, r)).at(1.0)
}).collect();
let fx = self.fx.get_or_insert_with(|| FxRenderer::new(device, f.format, FxOptions::default()));
fx.set_srgb_blend(f.srgb_blend());
fx.add_format(device, wgpu::TextureFormat::Rgba16Float);
let placements: Vec<_> = slots.iter().map(|(_, i, _)| FxSlot::default().scale(i.params[3]).clip(i.clip, i.fade)).collect();
fx.prepare_with_slots(device, queue, &FxFrame { viewport: [size.0, size.1], scale: 1.0, layers: &layers, backdrop: None, sources: &[] }, &placements);
let clear = f.rt.clear_color();
f.ui.prepare(device, queue, &mut f.rt.text.atlas, &f.rt.instances, size);
let formats = &self.formats;
f.ui.draw_with_backdrop(f.encoder, f.target, clear, &mut |phase, s: &EffectSite<'_>| match phase {
EffectPhase::Backdrop(enc) => {
if let (Some(bd), Some(k)) = (s.backdrop, slots.iter().position(|(at, _, _)| *at == s.index)) {
fx.blur_backdrop(device, queue, enc, bd, k);
}
}
EffectPhase::Draw(pass) => {
let mut seen = formats.lock().unwrap();
if !seen.contains(&s.format) { seen.push(s.format); }
if let Some(k) = slots.iter().position(|(at, _, _)| *at == s.index) {
assert_eq!(s.scale, slots[k].1.params[3]);
fx.draw_layer_in(pass, s.format, s.origin, k);
}
}
});
}
}
fn snap(name: &'static str, view: fn(&(), &mut Cx<()>) -> El, srgb: bool, formats: Arc<Mutex<Vec<wgpu::TextureFormat>>>) -> (u32, Vec<u8>) {
snap_with(name, view, srgb, formats, 1, dusk)
}
fn snap_at(name: &'static str, view: fn(&(), &mut Cx<()>) -> El, srgb: bool, formats: Arc<Mutex<Vec<wgpu::TextureFormat>>>, scale: u32) -> (u32, Vec<u8>) {
snap_with(name, view, srgb, formats, scale, dusk)
}
fn snap_with(name: &'static str, view: fn(&(), &mut Cx<()>) -> El, srgb: bool, formats: Arc<Mutex<Vec<wgpu::TextureFormat>>>, scale: u32, effect: fn() -> Fx) -> (u32, Vec<u8>) {
let dir = std::env::temp_dir().join(format!("rune-fx-layer-{name}-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("snap.png");
thread_local! { static EFFECT: std::cell::Cell<fn() -> Fx> = const { std::cell::Cell::new(dusk) }; }
EFFECT.set(effect);
App::new(AppSpec::new(name, (96.0, 96.0), || (), view))
.compositor(Dusk { fx: None, formats, effect: |_| EFFECT.get()() })
.srgb_blend(srgb)
.args(["--snap".to_string(), path.to_str().unwrap().to_string(), "--scale".to_string(), scale.to_string()])
.run();
let mut reader = png::Decoder::new(std::io::BufReader::new(std::fs::File::open(&path).unwrap())).read_info().unwrap();
let mut buf = vec![0u8; reader.output_buffer_size().unwrap()];
let info = reader.next_frame(&mut buf).unwrap();
buf.truncate(info.buffer_size());
std::fs::remove_dir_all(&dir).unwrap();
(info.width, buf)
}
fn px(rgba: &[u8], width: u32, x: u32, y: u32) -> [u8; 3] {
let at = ((y * width + x) * 4) as usize;
[rgba[at], rgba[at + 1], rgba[at + 2]]
}
fn background() -> El {
el().size(96.0, 96.0).fill(hex("#202020").unwrap())
}
fn plain(_: &(), _: &mut Cx<()>) -> El {
background().child(effect(1).absolute(16.0, 16.0).size(64.0, 64.0))
}
fn faded_rounded(_: &(), _: &mut Cx<()>) -> El {
background().child(
el().size(64.0, 64.0).absolute(16.0, 16.0).opacity(0.5).clip_rounded(24.0)
.child(effect(1).absolute(0.0, 0.0).size(64.0, 64.0))
.child(el().absolute(48.0, 48.0).size(8.0, 8.0).fill(hex("#0000ff").unwrap())),
)
}
#[test]
fn fill_in_a_faded_rounded_layer_matches_the_plain_fill_faded() {
for srgb in [false, true] {
let (w, plain) = snap("plain", plain, srgb, Arc::default());
let formats = Arc::default();
let (_, layered) = snap("layer", faded_rounded, srgb, Arc::clone(&formats));
let bg = 32.0 / 255.0;
for (x, y) in [(40, 40), (60, 30)] {
let fill = px(&plain, w, x, y);
let want: [u8; 3] = std::array::from_fn(|c| {
let f = fill[c] as f32 / 255.0;
let v = if srgb { 0.5 * f + 0.5 * bg } else { srgb_encode(0.5 * srgb_decode(f) + 0.5 * srgb_decode(bg)) };
(v * 255.0).round() as u8
});
let got = px(&layered, w, x, y);
assert!(got.iter().zip(want).all(|(a, b)| a.abs_diff(b) <= 4), "srgb {srgb} at ({x}, {y}): got {got:?}, want {want:?}");
}
let corner = px(&layered, w, 17, 17);
assert!(corner.iter().all(|c| c.abs_diff(32) <= 2), "corner is clipped away: {corner:?}");
assert_eq!(formats.lock().unwrap().as_slice(), [wgpu::TextureFormat::Rgba16Float]);
}
}
#[test]
fn fills_match_across_blend_modes_when_opaque() {
let (_, linear) = snap("lin", plain, false, Arc::default());
let (_, gamma) = snap("gam", plain, true, Arc::default());
let worst = linear.iter().zip(&gamma).map(|(a, b)| a.abs_diff(*b)).max().unwrap();
assert!(worst <= 3, "modes differ by {worst}");
}
fn glow_on_black(_: &(), _: &mut Cx<()>) -> El {
el().size(96.0, 96.0).fill(hex("#000000").unwrap()).child(effect(1).absolute(32.0, 32.0).size(32.0, 32.0))
}
/// A glow's light is premultiplied colour past its occlusion alpha. In a gamma-blended frame a
/// faint occlusion must barely change it, not encode the light as a straight colour many times
/// full scale and all but black it out.
#[test]
fn faint_occlusion_keeps_the_glow_lit_in_gamma_blend() {
let (w, clear) = snap_with("glow-clear", glow_on_black, true, Arc::default(), 1, || glow(0.0));
let (_, faint) = snap_with("glow-faint", glow_on_black, true, Arc::default(), 1, || glow(0.002));
let mut lit = 0;
for (x, y) in [(28, 48), (24, 48), (48, 27), (48, 22), (68, 48), (28, 28)] {
let (a, b) = (px(&clear, w, x, y), px(&faint, w, x, y));
lit += a.iter().any(|c| *c > 24) as u32;
assert!(a.iter().zip(b).all(|(a, b)| a.abs_diff(b) <= 6), "({x}, {y}): clear {a:?}, faint {b:?}");
}
assert!(lit >= 3, "the glow should light the samples");
}
fn grain_on_grey(_: &(), _: &mut Cx<()>) -> El {
el().size(96.0, 96.0).fill(hex("#808080").unwrap()).child(effect(1).absolute(0.0, 0.0).size(96.0, 96.0))
}
/// Grain is texture: over mid-grey it must lighten and darken by the same amount, and leave the
/// mean where it was, in either blend mode.
#[test]
fn grain_is_symmetric_in_both_blend_modes() {
for srgb in [false, true] {
let (w, img) = snap_with("grain", grain_on_grey, srgb, Arc::default(), 1, || {
Fx::grain(GrainParams { amount: 0.06, ..Default::default() })
});
let (_, base) = snap_with("grain-base", grain_on_grey, srgb, Arc::default(), 1, || {
Fx::grain(GrainParams { amount: 0.0, ..Default::default() })
});
// Blending happens in linear light when `srgb` is off, so compare in the space the
// frame blends in; the grain moves each pixel toward white or black by the same fraction.
let space = |v: u8| if srgb { v as f64 / 255.0 } else { srgb_decode(v as f32 / 255.0) as f64 };
let (mut up, mut down, mut raw, mut n) = (0.0f64, 0.0f64, 0.0f64, 0.0f64);
for y in 0..96 {
for x in 0..w.min(96) {
let (v, b) = (px(&img, w, x, y)[0], px(&base, w, x, y)[0]);
let (vs, bs) = (space(v), space(b));
if vs > bs { up += (vs - bs) / (1.0 - bs) } else { down += (bs - vs) / bs }
raw += v as f64 - b as f64;
n += 1.0;
}
}
let (up, down, raw) = (up / n, down / n, raw / n);
eprintln!("srgb {srgb}: mean fraction toward white {up:.4}, toward black {down:.4}, mean shift {raw:.3}/255");
assert!(up > 0.005 && down > 0.005, "srgb {srgb}: grain should show, up {up} down {down}");
// Within 20%: NVIDIA quantizes the 8-bit source before the blend, which pulls odd grain steps half a
// level down and leaves the two sides about 17% apart (a float blend leaves under 2%). The mean
// shift below still holds the picture where it was.
assert!((up - down).abs() <= 0.2 * (up + down) / 2.0, "srgb {srgb}: toward white {up}, toward black {down}");
if srgb {
assert!(raw.abs() <= 1.0, "srgb {srgb}: mean shifts by {raw:.2}/255");
}
}
}
fn zoomed_slot(_: &(), _: &mut Cx<()>) -> El {
background().child(
el().absolute(32.0, 32.0).size(32.0, 32.0).live_scale(&rune::Live::new(2.0))
.child(effect(1).size(32.0, 32.0).radius(8.0)),
)
}
fn unzoomed_double(_: &(), _: &mut Cx<()>) -> El {
background().child(effect(1).absolute(16.0, 16.0).size(64.0, 64.0).radius(16.0))
}
#[test]
fn slot_scale_scales_effect_lengths_and_radii_without_bleed() {
let ring6 = || Fx::fill(FillParams::from(MeshGradientParams::dusk()).border(6.0));
let ring12 = || Fx::fill(FillParams::from(MeshGradientParams::dusk()).border(12.0));
let (w, zoomed) = snap_with("zoomed-ring", zoomed_slot, false, Arc::default(), 1, ring6);
let (_, direct) = snap_with("direct-ring", unzoomed_double, false, Arc::default(), 1, ring12);
// The 6pt border at 2x live_scale is 12px wide (x = 16..28); x = 22 is inside the ring,
// x = 48 is the hollow centre.
assert!(px(&zoomed, w, 22, 48).iter().any(|&c| c > 45), "ring is lit at 12px width");
assert!(px(&zoomed, w, 48, 48).iter().all(|&c| c.abs_diff(32) <= 2), "centre is hollow");
let worst = zoomed.iter().zip(&direct).map(|(a, b)| a.abs_diff(*b)).max().unwrap();
assert!(worst <= 3, "zoomed slot and 2x direct ring differ by {worst}");
}
fn rounded_scroll(_: &(), _: &mut Cx<()>) -> El {
background().child(
el().scroll(rune::ScrollSpec { stick_bottom: false }).size(64.0, 64.0).absolute(16.0, 16.0)
.clip_rounded(24.0).clip_fade(0.0, 0.0, 0.0, 16.0)
.child(el().size(64.0, 96.0).child(effect(1).size(64.0, 64.0))),
)
}
#[test]
fn fill_under_a_rounded_scroll_container_clips_without_a_layer() {
for srgb in [false, true] {
let formats = Arc::default();
let (w, plain_img) = snap("scroll-plain", plain, srgb, Arc::default());
let (_, clipped) = snap("scroll-clipped", rounded_scroll, srgb, Arc::clone(&formats));
let seen = formats.lock().unwrap().clone();
assert!(!seen.contains(&wgpu::TextureFormat::Rgba16Float), "must not allocate an isolated layer: {seen:?}");
// Rounded top-left corner at (17, 17) is outside the 24px radius and cut to the #202020 background.
let corner = px(&clipped, w, 17, 17);
assert!(corner.iter().all(|c| c.abs_diff(32) <= 2), "srgb {srgb} corner is clipped away: {corner:?}");
// Straight top edge (48, 17) and centre (48, 48) match the unclipped fill.
for (x, y) in [(48, 17), (48, 48)] {
let got = px(&clipped, w, x, y);
let want = px(&plain_img, w, x, y);
assert!(got.iter().zip(want).all(|(a, b)| a.abs_diff(b) <= 2), "srgb {srgb} at ({x}, {y}): got {got:?}, want {want:?}");
}
// Soft bottom edge (y = 64..80, 16px fade): at y = 72 coverage is ~0.5, between background and fill.
let mid_fade = px(&clipped, w, 48, 72);
let full = px(&plain_img, w, 48, 72);
assert!(mid_fade.iter().zip(full).any(|(m, f)| *m < f.saturating_sub(15)), "srgb {srgb} soft edge fades toward background: {mid_fade:?} vs {full:?}");
assert!(mid_fade.iter().any(|&c| c > 40), "srgb {srgb} soft edge is not hard-cut at y = 72: {mid_fade:?}");
}
}
fn snap_by_mark(name: &'static str, view: fn(&(), &mut Cx<()>) -> El, srgb: bool, formats: Arc<Mutex<Vec<wgpu::TextureFormat>>>, effect: fn(u32) -> Fx) -> (u32, Vec<u8>) {
let dir = std::env::temp_dir().join(format!("rune-fx-layer-{name}-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("snap.png");
App::new(AppSpec::new(name, (96.0, 96.0), || (), view))
.compositor(Dusk { fx: None, formats, effect })
.srgb_blend(srgb)
.args(["--snap".to_string(), path.to_str().unwrap().to_string(), "--scale".to_string(), "1".to_string()])
.run();
let mut reader = png::Decoder::new(std::io::BufReader::new(std::fs::File::open(&path).unwrap())).read_info().unwrap();
let mut buf = vec![0u8; reader.output_buffer_size().unwrap()];
let info = reader.next_frame(&mut buf).unwrap();
buf.truncate(info.buffer_size());
std::fs::remove_dir_all(&dir).unwrap();
(info.width, buf)
}
fn single_glass_scene(_: &(), _: &mut Cx<()>) -> El {
background()
.child(el().absolute(0.0, 0.0).size(48.0, 96.0).fill(hex("#00e5ff").unwrap()))
.child(effect(1).effect_backdrop(true).absolute(16.0, 16.0).size(64.0, 64.0))
}
fn stacked_glass_scene(_: &(), _: &mut Cx<()>) -> El {
background()
.child(el().absolute(0.0, 0.0).size(48.0, 96.0).fill(hex("#00e5ff").unwrap()))
.child(effect(1).effect_backdrop(true).absolute(16.0, 16.0).size(64.0, 64.0))
.child(el().absolute(40.0, 32.0).size(16.0, 32.0).fill(hex("#ff2040").unwrap()))
.child(effect(2).effect_backdrop(true).absolute(24.0, 24.0).size(56.0, 48.0))
.child(el().absolute(68.0, 60.0).size(10.0, 10.0).fill(hex("#00ff00").unwrap()))
}
fn frosted_glass_fx(mark: u32) -> Fx {
match mark {
1 => Fx::lens(LensParams { frost: 0.85, depth: 0.0, magnification: 1.0, shadow: 0.0, rim: 0.0, ..Default::default() }),
_ => Fx::fill(FlutedGlassParams { frost: 0.85, refraction: 0.0, dispersion: 0.0, highlight: 0.0, ..FlutedGlassParams::frosted() }),
}
}
#[test]
fn backdrop_slots_blur_background_and_stack_glass_over_glass_in_painter_order() {
let (w, one) = snap_by_mark("one-glass", single_glass_scene, false, Arc::default(), frosted_glass_fx);
// At (54, 48), just to the right of the x=48 cyan stripe, frosted glass 1 blurs cyan into the dark half.
let p_one = px(&one, w, 54, 48);
assert!(p_one[1] > 60 && p_one[2] > 70, "glass 1 blurs cyan across the x=48 edge: {p_one:?}");
let (_, stacked) = snap_by_mark("stacked-glass", stacked_glass_scene, false, Arc::default(), frosted_glass_fx);
// At (60, 48), to the right of the red bar (x=40..56) drawn between glass 1 and glass 2,
// glass 2 blurs both glass 1's cyan and the intermediate red bar, raising the red channel over `one`.
let p_two = px(&stacked, w, 60, 48);
let p_one_60 = px(&one, w, 60, 48);
assert!(p_two[0] > p_one_60[0] + 15, "glass 2 sees the intermediate red bar and glass 1: {p_two:?} vs {p_one_60:?}");
// The green badge at (72, 64) is drawn after glass 2, so it stays sharp green on top.
let badge = px(&stacked, w, 72, 64);
assert!(badge[0] < 10 && badge[1] > 245 && badge[2] < 10, "later content stays sharp on top of glass 2: {badge:?}");
}
fn layered_glass_scene(_: &(), _: &mut Cx<()>) -> El {
background().child(
el().absolute(16.0, 16.0).size(64.0, 64.0).opacity(0.5)
.child(el().absolute(0.0, 0.0).size(32.0, 64.0).fill(hex("#00e5ff").unwrap()))
.child(effect(1).effect_backdrop(true).absolute(0.0, 0.0).size(64.0, 64.0)),
)
}
fn moved_nested_scene(slot: bool) -> El {
let mut card = el().size(72.0, 72.0).opacity(0.6)
.live_offset(&rune::Live::new([-4.25, -3.75]))
.fill(hex("#804020").unwrap())
.child(el().absolute(24.0, 0.0).size(8.0, 72.0).fill(hex("#00e5ff").unwrap()));
if slot { card = card.child(effect(1).effect_backdrop(true).absolute(0.0, 0.0).size(72.0, 72.0)); }
background().child(el().absolute(8.25, 8.75).size(72.0, 72.0).scale(1.125).opacity(0.8)
.scroll(rune::ScrollSpec { stick_bottom: true })
.child(el().size(72.0, 140.0).child(card.absolute(0.0, 68.0))))
}
#[test]
fn backdrop_origin_tracks_fractional_scale_scroll_live_offset_and_nested_layers() {
for srgb in [false, true] {
let (w, base) = snap_with("moved-base", |_, _| moved_nested_scene(false), srgb, Arc::default(), 2,
|| Fx::distort(DistortParams::chroma_split([1e-6, 0.0])));
let (_, slot) = snap_with("moved-slot", |_, _| moved_nested_scene(true), srgb, Arc::default(), 2,
|| Fx::distort(DistortParams::chroma_split([1e-6, 0.0])));
// An effectively zero offset (nonzero to avoid idle culling) reproduces the contents before the
// two layer opacities composite, including the stripe's window-space position.
for y in [40, 72, 104] {
for x in [24, 48, 56, 64, 88, 120] {
let got = px(&slot, w, x, y);
let want = px(&base, w, x, y);
assert!(got.iter().zip(want).all(|(a, b)| a.abs_diff(b) <= 3),
"srgb={srgb} ({x},{y}): {got:?} != {want:?}");
}
}
}
}
fn edge_scene(slot: bool) -> El {
let mut card = el().absolute(-8.25, -9.75).size(112.0, 112.0).opacity(0.6).blur(3.0).scale(1.125)
.fill(hex("#804020").unwrap())
.child(el().absolute(40.0, 0.0).size(8.0, 112.0).fill(hex("#00e5ff").unwrap()));
if slot { card = card.child(effect(1).effect_backdrop(true).absolute(0.0, 0.0).size(112.0, 112.0)); }
background().child(card)
}
#[test]
fn negative_layer_origins_copy_the_visible_region_at_all_window_edges() {
for srgb in [false, true] {
let (w, base) = snap_with("edge-base", |_, _| edge_scene(false), srgb, Arc::default(), 2,
|| Fx::distort(DistortParams::chroma_split([1e-6, 0.0])));
let (_, slot) = snap_with("edge-slot", |_, _| edge_scene(true), srgb, Arc::default(), 2,
|| Fx::distort(DistortParams::chroma_split([1e-6, 0.0])));
for y in [0, 1, 4, 64, 187, 190, 191] {
for x in [0, 1, 4, 64, 187, 190, 191] {
let got = px(&slot, w, x, y);
let want = px(&base, w, x, y);
assert!(got.iter().zip(want).all(|(a, b)| a.abs_diff(b) <= 3),
"srgb={srgb} ({x},{y}): {got:?} != {want:?}");
}
}
}
}
#[test]
fn backdrop_slot_in_an_isolated_layer_reads_and_blurs_that_layers_target() {
let formats = Arc::default();
let (w, img) = snap_by_mark("layer-glass", layered_glass_scene, false, Arc::clone(&formats), frosted_glass_fx);
let seen = formats.lock().unwrap().clone();
assert!(seen.contains(&wgpu::TextureFormat::Rgba16Float), "isolated layer uses Rgba16Float: {seen:?}");
// Inside the isolated layer, the cyan stripe covers x = 16..48. At (52, 48) (right half of the
// layer, where nothing was drawn before the slot), the frosted lens blurs the layer's cyan stripe
// into the right half, and the layer composites at 0.5 opacity over #202020.
let blurred_right = px(&img, w, 52, 48);
assert!(blurred_right[1] > 45 && blurred_right[2] > 50, "layer backdrop slot blurs the layer's stripe: {blurred_right:?}");
// Inside the cyan stripe at (24, 48), the 0.5-opacity layer is dimmer than full #00e5ff.
let faded_left = px(&img, w, 24, 48);
assert!(faded_left[2] > 100 && faded_left[2] < 220, "isolated layer composites at 0.5 opacity: {faded_left:?}");
}
fn midtone_glass_scene(_: &(), _: &mut Cx<()>) -> El {
background()
.child(el().absolute(8.0, 8.0).size(80.0, 80.0).fill(hex("#804020").unwrap()))
.child(effect(1).effect_backdrop(true).absolute(16.0, 16.0).size(20.0, 64.0))
.child(effect(2).effect_backdrop(true).absolute(36.0, 16.0).size(20.0, 64.0))
.child(effect(3).effect_backdrop(true).absolute(56.0, 16.0).size(24.0, 64.0))
}
fn midtone_layered_glass_scene(_: &(), _: &mut Cx<()>) -> El {
background().child(
el().absolute(8.0, 8.0).size(80.0, 80.0).opacity(0.85)
.child(el().absolute(0.0, 0.0).size(80.0, 80.0).fill(hex("#804020").unwrap()))
.child(effect(1).effect_backdrop(true).absolute(8.0, 8.0).size(20.0, 64.0))
.child(effect(2).effect_backdrop(true).absolute(28.0, 8.0).size(20.0, 64.0))
.child(effect(3).effect_backdrop(true).absolute(48.0, 8.0).size(24.0, 64.0)),
)
}
fn identity_glass_and_dither_fx(mark: u32) -> Fx {
match mark {
1 => Fx::fill(FlutedGlassParams { refraction: 0.0, frost: 0.0, dispersion: 0.0, highlight: 0.0, tint_amount: 0.0, ..FlutedGlassParams::reeded() }),
2 => Fx::fill(FlutedGlassParams { refraction: 0.0, frost: 0.6, dispersion: 0.0, highlight: 0.0, tint_amount: 0.0, ..FlutedGlassParams::reeded() }),
_ => Fx::fill(DitherParams::backdrop()),
}
}
#[test]
fn srgb_blend_decodes_backdrop_without_double_encoding_on_frame_and_layer_targets() {
let (w, lin) = snap_by_mark("srgb-bd-lin", midtone_glass_scene, false, Arc::default(), identity_glass_and_dither_fx);
let (_, gam) = snap_by_mark("srgb-bd-gam", midtone_glass_scene, true, Arc::default(), identity_glass_and_dither_fx);
// At (24, 48), inside clear glass over #804020 (128, 64, 32), neither mode washes out to
// double-encoded sRGB (~188, 137, 99): both stay at the #804020 midtone.
let p_clear_lin = px(&lin, w, 24, 48);
let p_clear_gam = px(&gam, w, 24, 48);
assert!(p_clear_lin[0].abs_diff(128) <= 3 && p_clear_lin[1].abs_diff(64) <= 3 && p_clear_lin[2].abs_diff(32) <= 3, "linear clear glass preserves #804020: {p_clear_lin:?}");
assert!(p_clear_gam[0].abs_diff(128) <= 3 && p_clear_gam[1].abs_diff(64) <= 3 && p_clear_gam[2].abs_diff(32) <= 3, "srgb_blend clear glass is not double-encoded: {p_clear_gam:?}");
// At (46, 48), inside frosted glass (which samples the blur pyramid `bdb`), `srgb_blend`
// matches linear within 3 LSB instead of washing out by ~60 LSB.
let p_frost_lin = px(&lin, w, 46, 48);
let p_frost_gam = px(&gam, w, 46, 48);
for c in 0..3 {
assert!(p_frost_lin[c].abs_diff(p_frost_gam[c]) <= 3, "frosted glass matches across blend modes: lin {p_frost_lin:?} vs gam {p_frost_gam:?}");
}
// Across the backdrop-dithered strip (x = 60..76, y = 24..72), perceptual tone input matches
// between linear and srgb_blend frames.
let dither_diff: u32 = (24..72)
.flat_map(|y| (60..76).map(move |x| (x, y)))
.map(|(x, y)| {
let (a, b) = (px(&lin, w, x, y), px(&gam, w, x, y));
a[0].abs_diff(b[0]) as u32 + a[1].abs_diff(b[1]) as u32 + a[2].abs_diff(b[2]) as u32
})
.max()
.unwrap();
assert!(dither_diff <= 6, "backdrop dither tone matches between linear and srgb_blend (max channel sum diff {dither_diff})");
// Inside an Rgba16Float isolated layer in srgb_blend mode, the backdrop is also sRGB-encoded
// premultiplied and must not be double-encoded before the layer composites.
let (w, layer_gam) = snap_by_mark("srgb-bd-layer", midtone_layered_glass_scene, true, Arc::default(), identity_glass_and_dither_fx);
let outside_slot = px(&layer_gam, w, 12, 12);
let inside_clear_glass = px(&layer_gam, w, 24, 48);
let inside_frost_glass = px(&layer_gam, w, 46, 48);
for c in 0..3 {
assert!(
inside_clear_glass[c].abs_diff(outside_slot[c]) <= 3,
"Rgba16Float layer clear glass in srgb_blend matches surrounding layer fill ({inside_clear_glass:?} vs {outside_slot:?})"
);
}
assert!(inside_frost_glass[0] < 135 && inside_frost_glass[1] < 70, "Rgba16Float layer frosted glass is not washed out: {inside_frost_glass:?}");
}
fn plastic(roughness: f32) -> Fx {
Fx::fill(PlasticParams { color: rgb(0xffd60a), roughness, ..PlasticParams::glossy() })
}
/// Plastic is opaque coverage with its highlight inside it, so it looks the same in either blend
/// mode, and faded it blends like any other fill, at every roughness.
#[test]
fn plastic_matches_across_blend_modes() {
let looks: [(f32, fn() -> Fx); 3] = [(0.05, || plastic(0.05)), (0.45, || plastic(0.45)), (1.0, || plastic(1.0))];
for (roughness, look) in looks {
let (w, linear) = snap_with("plastic-lin", plain, false, Arc::default(), 1, look);
let (_, gamma) = snap_with("plastic-gam", plain, true, Arc::default(), 1, look);
let worst = linear.iter().zip(&gamma).map(|(a, b)| a.abs_diff(*b)).max().unwrap();
assert!(worst <= 3, "roughness {roughness}: modes differ by {worst}");
for srgb in [false, true] {
let opaque = if srgb { &gamma } else { &linear };
let (_, faded) = snap_with("plastic-faded", faded_rounded, srgb, Arc::default(), 1, look);
let bg = 32.0 / 255.0;
for (x, y) in [(40, 40), (30, 22), (60, 30), (48, 66)] {
let fill = px(opaque, w, x, y);
let want: [u8; 3] = std::array::from_fn(|c| {
let f = fill[c] as f32 / 255.0;
let v = if srgb { 0.5 * f + 0.5 * bg } else { srgb_encode(0.5 * srgb_decode(f) + 0.5 * srgb_decode(bg)) };
(v * 255.0).round() as u8
});
let got = px(&faded, w, x, y);
assert!(got.iter().zip(want).all(|(a, b)| a.abs_diff(b) <= 4), "roughness {roughness} srgb {srgb} at ({x}, {y}): got {got:?}, want {want:?}");
}
}
}
}
#[test]
fn fx_blend_modes_over_cream_paper_and_fallback_without_backdrop() {
use rune::render::{Gpu, Offscreen};
let gpu = Gpu::headless();
let (w, h) = (96u32, 96u32);
let warm_glow = || {
Fx::glow(GlowParams {
color: rgb(0xc85a14),
core: rgb(0xe88c28),
radius: 10.0,
reach: 2.5,
intensity: 1.15,
inner: 0.8,
hot: 0.35,
..Default::default()
})
.on(Shape::rounded(32.0, 32.0, 32.0, 32.0, 10.0))
.at(0.5)
};
for srgb in [false, true] {
let format = if srgb {
wgpu::TextureFormat::Rgba8Unorm
} else {
wgpu::TextureFormat::Rgba8UnormSrgb
};
let mut fx = FxRenderer::new(&gpu.device, format, FxOptions::default());
fx.set_srgb_blend(srgb);
// Cream paper (#FAF7F2) in the target's clear encoding.
let cream_srgb = [0xfa as f32 / 255.0, 0xf7 as f32 / 255.0, 0xf2 as f32 / 255.0];
let cream_lin = cream_srgb.map(srgb_decode);
let clear = if srgb {
wgpu::Color { r: cream_srgb[0] as f64, g: cream_srgb[1] as f64, b: cream_srgb[2] as f64, a: 1.0 }
} else {
wgpu::Color { r: cream_lin[0] as f64, g: cream_lin[1] as f64, b: cream_lin[2] as f64, a: 1.0 }
};
let backdrop_tex = gpu.device.create_texture(&wgpu::TextureDescriptor {
label: Some("cream backdrop"),
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_DST,
view_formats: &[],
});
let backdrop_view = backdrop_tex.create_view(&Default::default());
{
let mut enc = gpu.device.create_command_encoder(&Default::default());
let _ = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
label: None,
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &backdrop_view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations { load: wgpu::LoadOp::Clear(clear), store: wgpu::StoreOp::Store },
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
gpu.queue.submit([enc.finish()]);
}
let render_mode = |fx: &mut FxRenderer, mode: FxBlend, with_backdrop: bool| -> Vec<u8> {
let target = Offscreen::with_format(&gpu.device, w, h, format);
let layers = [warm_glow()];
let slots = [FxSlot::default().blend(mode).backdrop_srgb(srgb)];
let stats = fx.prepare_with_slots(
&gpu.device,
&gpu.queue,
&FxFrame {
viewport: [w, h],
scale: 1.0,
layers: &layers,
backdrop: with_backdrop.then_some(&backdrop_view),
sources: &[],
},
&slots,
);
assert_eq!(stats.needs_backdrop, mode.needs_backdrop());
let mut enc = gpu.device.create_command_encoder(&Default::default());
{
let mut pass = enc.begin_render_pass(&wgpu::RenderPassDescriptor {
label: None,
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &target.view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations { load: wgpu::LoadOp::Clear(clear), store: wgpu::StoreOp::Store },
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
fx.draw_layer(&mut pass, 0);
}
target.copy(&mut enc);
gpu.queue.submit([enc.finish()]);
target.read(&gpu.device)
};
let normal = render_mode(&mut fx, FxBlend::Normal, true);
let multiply = render_mode(&mut fx, FxBlend::Multiply, true);
let screen = render_mode(&mut fx, FxBlend::Screen, true);
let overlay = render_mode(&mut fx, FxBlend::Overlay, true);
let soft_light = render_mode(&mut fx, FxBlend::SoftLight, true);
// Outside the glow, all modes leave #FAF7F2 cream paper untouched.
for out in [&normal, &multiply, &screen, &overlay, &soft_light] {
let corner = px(out, w, 2, 2);
assert!(
corner[0].abs_diff(0xfa) <= 1 && corner[1].abs_diff(0xf7) <= 1 && corner[2].abs_diff(0xf2) <= 1,
"srgb={srgb} untouched cream paper at (2,2): {corner:?}"
);
}
// At the warm glow rim (32, 48): Normal washes out toward white on cream paper, whereas
// Multiply and SoftLight deepen the blue/green channels to a warm amber tone.
let rim_norm = px(&normal, w, 32, 48);
let rim_mul = px(&multiply, w, 32, 48);
let rim_scr = px(&screen, w, 32, 48);
let rim_ovl = px(&overlay, w, 32, 48);
let rim_soft = px(&soft_light, w, 32, 48);
assert!(
rim_mul[2] + 40 < rim_norm[2] && rim_mul[1] + 20 < rim_norm[1] && rim_mul[0] > rim_mul[1] && rim_mul[1] > rim_mul[2],
"srgb={srgb} Multiply deepens cream paper into warm amber ({rim_mul:?}) vs Normal ({rim_norm:?})"
);
assert!(
rim_scr[0] >= 0xfa && rim_scr[1] >= rim_mul[1] && rim_scr[2] >= rim_mul[2],
"srgb={srgb} Screen lifts above Multiply: screen={rim_scr:?}, mul={rim_mul:?}"
);
assert_ne!(rim_ovl, rim_norm, "srgb={srgb} Overlay differs from Normal on cream paper");
assert_ne!(rim_soft, rim_norm, "srgb={srgb} SoftLight differs from Normal on cream paper");
assert_ne!(rim_ovl, rim_soft, "srgb={srgb} Overlay and SoftLight are distinct");
// Without a bound backdrop (e.g. a target lacking COPY_SRC), sampled modes
// degrade cleanly to Normal.
let overlay_no_bd = render_mode(&mut fx, FxBlend::Overlay, false);
let soft_no_bd = render_mode(&mut fx, FxBlend::SoftLight, false);
let multiply_no_bd = render_mode(&mut fx, FxBlend::Multiply, false);
assert_eq!(multiply_no_bd, normal, "srgb={srgb} Multiply without backdrop falls back to Normal");
assert_eq!(overlay_no_bd, normal, "srgb={srgb} Overlay without backdrop falls back to Normal");
assert_eq!(soft_no_bd, normal, "srgb={srgb} SoftLight without backdrop falls back to Normal");
}
}
/// Writes `demo/fx/in-layer.png`: a fill in a faded, rounded, clipped card, linear blend on the
/// left and gamma blend on the right. `cargo test -p rune-fx --test integration in_layer:: -- --ignored`.
#[test]
#[ignore]
fn write_demo_still() {
let (w, linear) = snap_at("demo-lin", faded_rounded, false, Arc::default(), 3);
let (_, gamma) = snap_at("demo-gam", faded_rounded, true, Arc::default(), 3);
let h = linear.len() as u32 / 4 / w;
let mut out = Vec::with_capacity(linear.len() * 2);
for y in 0..h as usize {
let row = y * w as usize * 4..(y + 1) * w as usize * 4;
out.extend_from_slice(&linear[row.clone()]);
out.extend_from_slice(&gamma[row]);
}
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../demo/fx/in-layer.png");
let mut enc = png::Encoder::new(std::io::BufWriter::new(std::fs::File::create(path).unwrap()), w * 2, h);
enc.set_color(png::ColorType::Rgba);
enc.set_depth(png::BitDepth::Eight);
enc.write_header().unwrap().write_image_data(&out).unwrap();
}
@@ -0,0 +1,53 @@
//! A renderer builds an effect's pipeline only when a frame draws that effect, in that blend,
//! into that format, so one that only glows never pays for the other families.
use rune::render::{Gpu, Offscreen};
use rune_fx::*;
fn draw(gpu: &Gpu, fx: &mut FxRenderer, format: wgpu::TextureFormat, layers: &[FxLayer], slots: &[FxSlot]) {
let target = Offscreen::with_format(&gpu.device, 64, 64, format);
fx.prepare_with_slots(&gpu.device, &gpu.queue, &FxFrame { viewport: [64, 64], scale: 1.0, layers, backdrop: None, sources: &[] }, slots);
let mut encoder = gpu.device.create_command_encoder(&Default::default());
{
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &target.view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), store: wgpu::StoreOp::Store },
})],
..Default::default()
});
for i in 0..layers.len() {
fx.draw_layer_in(&mut pass, format, [0.0; 2], i);
}
}
gpu.queue.submit([encoder.finish()]);
}
#[test]
fn pipelines_are_built_for_what_frames_draw() {
let gpu = Gpu::headless();
let window = wgpu::TextureFormat::Rgba8UnormSrgb;
let layer = wgpu::TextureFormat::Rgba16Float;
let mut fx = FxRenderer::new(&gpu.device, window, FxOptions::default());
fx.add_format(&gpu.device, layer);
assert_eq!(fx.built_pipelines(), 0, "nothing is built before a frame draws");
let shape = Shape::rounded(16.0, 16.0, 32.0, 32.0, 6.0);
let glow = Fx::glow(GlowParams::default()).on(shape);
draw(&gpu, &mut fx, window, &[glow], &[]);
assert_eq!(fx.built_pipelines(), 1, "a glow builds the glow");
draw(&gpu, &mut fx, window, &[glow], &[]);
assert_eq!(fx.built_pipelines(), 1, "and keeps it");
let fire = Fx::fire(FireParams::default()).on(shape);
draw(&gpu, &mut fx, window, &[glow, fire, glow], &[FxSlot::default(), FxSlot::default(), FxSlot::default().blend(FxBlend::Screen)]);
assert_eq!(fx.built_pipelines(), 3, "a fire and a screen-blended glow build one each");
draw(&gpu, &mut fx, layer, &[glow], &[]);
assert_eq!(fx.built_pipelines(), 4, "another format builds its own when drawn into");
fx.build_every_pipeline();
assert_eq!(fx.built_pipelines(), 32, "eight families, two blends, two formats");
}
@@ -0,0 +1,5 @@
mod bind_groups;
mod fills;
mod in_layer;
mod lazy_pipelines;
mod sim;
+89
View File
@@ -0,0 +1,89 @@
//! The simulated fire's compute steps, on Rune's GPU (`RUNE_GPU_BACKEND` picks its backend) and
//! on wgpu's own, frame for frame.
use rune::render::Gpu;
use rune_fx::*;
const W: u32 = 64;
const H: u32 = 96;
/// Three frames of a simulated fire, each one's f16 pixels.
fn frames(device: &wgpu::Device, queue: &wgpu::Queue) -> Vec<Vec<u16>> {
let fmt = wgpu::TextureFormat::Rgba16Float;
let mut fx = FxRenderer::new(device, fmt, FxOptions { dither: false });
fx.set_fire_sim(device, true);
let target = 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: fmt,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
});
let view = target.create_view(&Default::default());
let readback = device.create_buffer(&wgpu::BufferDescriptor {
label: None,
size: u64::from(W * 8 * H),
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
});
(1..=3)
.map(|n| {
let layers = [Fx::fire(FireParams::default()).on(Shape::rounded(8.0, 60.0, 48.0, 24.0, 6.0)).at(n as f32 * 0.05)];
fx.prepare(device, queue, &FxFrame { viewport: [W, H], scale: 1.0, layers: &layers, backdrop: None, sources: &[] });
let mut encoder = device.create_command_encoder(&Default::default());
assert!(fx.simulate(queue, &mut encoder, None), "frame {n} stepped the simulation");
{
let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), store: wgpu::StoreOp::Store },
})],
..Default::default()
});
fx.draw_layer(&mut pass, 0);
}
encoder.copy_texture_to_buffer(
target.as_image_copy(),
wgpu::TexelCopyBufferInfo {
buffer: &readback,
layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(W * 8), rows_per_image: Some(H) },
},
target.size(),
);
queue.submit([encoder.finish()]);
let slice = readback.slice(..);
slice.map_async(wgpu::MapMode::Read, |_| {});
device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
let words = bytemuck::cast_slice(&slice.get_mapped_range().unwrap()).to_vec();
readback.unmap();
words
})
.collect()
}
#[test]
fn simulated_fire_matches_wgpus_frame_for_frame() {
let gpu = Gpu::headless();
let got = frames(&gpu.device, &gpu.queue);
let mut desc = wgpu::InstanceDescriptor::new_without_display_handle();
if cfg!(target_os = "windows") {
// Match Gpu::headless()'s DX12 + FXC configuration; FXC and DXC round differently across
// the 72-step warmup, and wgpu's default descriptor also loads Vulkan/dxcompiler.dll.
desc.backends = wgpu::Backends::DX12;
desc.backend_options.dx12.shader_compiler = wgpu::Dx12Compiler::Fxc;
}
let wgpu = Gpu::new(wgpu::Instance::new(desc), None);
let want = frames(&wgpu.device, &wgpu.queue);
for (n, (got, want)) in got.iter().zip(&want).enumerate() {
assert!(got.iter().all(|w| w & 0x7c00 != 0x7c00), "frame {n} is finite");
let lit = got.chunks(4).filter(|p| p[3] != 0).count();
assert!(lit > (W * H / 20) as usize, "frame {n} drew a fire ({lit} pixels lit)");
assert!(got == want, "frame {n} differs from wgpu's at {:?}", got.iter().zip(want).position(|(a, b)| a != b));
}
assert!(got[0] != got[2], "the simulation moved the flame");
}