perf: Add BLA rendering
This commit is contained in:
@@ -45,7 +45,7 @@ Native CLI flags (`src/cli.rs`, applied in `FractalApp::apply_cli`): `--kind`,
|
||||
`--palette`, `--share <fragment>`,
|
||||
`--view re,im,half_height[,iterations]`, `--rendering-kind`,
|
||||
`--yaw`/`--pitch` (3D camera, degrees), `--de`, `--antialias` (2×2),
|
||||
`--auto-color-scale`, `--color-scale`, `--buddhabrot`,
|
||||
`--auto-color-scale`, `--color-scale`, `--no-bla`, `--buddhabrot`,
|
||||
`--buddha-palette`. `--headless` (`src/headless.rs`) skips the window
|
||||
entirely: it builds the same view from the other flags, creates its own
|
||||
offscreen wgpu device, and renders straight to a PNG (`--width`/`--height`,
|
||||
@@ -245,6 +245,25 @@ pixel is a handful of `f32` complex multiplies.
|
||||
changing it. Known gaps: Lambda's critical point is 1/2, so its step keeps
|
||||
the input scale. Lambda set mode's reference sits at the origin, so it
|
||||
never reaches deep zooms anyway.
|
||||
- `src/fractal/bla.rs` — **bivariate linear approximation**: a table of
|
||||
merged linear steps `e' = A·e + B·dc` (valid while `|e| < R`) built on
|
||||
the CPU from the reference orbit, so the shader's `bla_lookup` jumps each
|
||||
pixel over whole runs of steps. Plain Mandelbrot only (set + Julia, no
|
||||
morph; `bla::applies`, the `BLA` override). This is what makes deep zoom
|
||||
fast: every pixel follows the reference for tens of thousands of steps
|
||||
before diverging (1e-200: 12.7 s → 0.7 s at 960×540). Level `l` node `i`
|
||||
covers steps `1 + i·2^l ..`, and only levels ≥ 3 are uploaded (bindings 4/5,
|
||||
`bla_meta` = `[min_level, levels, offsets…]`). Coefficients are
|
||||
floatexp (f32 mantissa + i32 exponent), so a jump in the deep prologue
|
||||
lands straight at its output scale. `R` depends on the view's largest
|
||||
`|dc|` (`dc_max_log2`), so `FractalApp::bla_table` rebuilds on reference
|
||||
change or when the dc range grows (or shrinks by `BLA_DC_SLACK` binades);
|
||||
exports/headless build per frame via `bla::for_uniforms`. The table stops
|
||||
before the reference crosses the pixel bailout, so a jump never skips an
|
||||
escape. Measure `|e|` with `log2_mag`, never `log2(dot(e, e))`: a
|
||||
2^-100 delta squares to 0 in f32 and passed every radius test.
|
||||
`--no-bla` / the "Skip iterations (BLA)" checkbox upload an empty table
|
||||
for A/B checks (it must render like `--no-bla` up to f32 noise).
|
||||
- `src/fractal/renderer.rs` — `FractalRenderer` (wgpu pipelines, uniform +
|
||||
storage buffers, bind groups), `Uniforms` (repr(C) layout that must match
|
||||
the WGSL `Uniforms` struct field-for-field, including padding; it includes
|
||||
|
||||
+74
-2
@@ -10,6 +10,7 @@ use glam::Vec4Swizzles;
|
||||
use crate::camera::Camera;
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
use crate::cli::Cli;
|
||||
use crate::fractal::bla::{self, BlaTable};
|
||||
use crate::fractal::{
|
||||
BuddhabrotCallback, BuddhabrotRenderer, BuddhabrotUniforms, ExportRender, FractalCallback,
|
||||
FractalKind, FractalRenderer, MAX_REF_POINTS, RefOrbit, ShareState, Uniforms,
|
||||
@@ -47,6 +48,19 @@ const MAX_EXPORT_DIM: u32 = 8192 * 16;
|
||||
/// buffer holds (past it, the shader would read pixels as escaped).
|
||||
const MAX_ITERATIONS: u32 = MAX_REF_POINTS as u32 - 1;
|
||||
|
||||
/// Binades of dc range a BLA table may overcover before it's rebuilt for a
|
||||
/// zoomed-in view (it stays valid, but its radii shrink with dc_max).
|
||||
const BLA_DC_SLACK: i32 = 2;
|
||||
|
||||
/// What the current BLA table was built for (see `FractalApp::bla_table`).
|
||||
#[derive(Clone, Copy, PartialEq)]
|
||||
struct BlaKey {
|
||||
generation: u64,
|
||||
on: bool,
|
||||
julia: bool,
|
||||
dc_log2: i32,
|
||||
}
|
||||
|
||||
/// While the user is actively panning/zooming, the fractal is rendered into a
|
||||
/// cache texture downscaled by this factor per axis (and with AA forced off), so
|
||||
/// each interacting frame is cheap; the linear blit upsamples it to the widget.
|
||||
@@ -528,6 +542,8 @@ pub struct FractalApp {
|
||||
shadow_palette: u32,
|
||||
/// Supersample each pixel 2×2 for smoother edges (costs ~4× fragment work).
|
||||
antialias: bool,
|
||||
/// Skip perturbation steps with the BLA table (`fractal::bla`).
|
||||
use_bla: bool,
|
||||
/// Distance-estimation shading: darkens toward the set boundary using the
|
||||
/// orbit derivative, giving crisp filaments at deep zoom instead of speckle.
|
||||
de_coloring: bool,
|
||||
@@ -582,6 +598,11 @@ pub struct FractalApp {
|
||||
reference: Arc<RefOrbit>,
|
||||
/// Bumped whenever `reference` is replaced, so the GPU re-uploads it.
|
||||
generation: u64,
|
||||
/// BLA table for `reference` (see `bla_table`), what it was built for,
|
||||
/// and its own generation for the GPU upload.
|
||||
bla: Arc<BlaTable>,
|
||||
bla_key: Option<BlaKey>,
|
||||
bla_generation: u64,
|
||||
/// Center + zoom the current `reference` was computed at (may differ
|
||||
/// slightly from the live view; the shader compensates via `dc_offset`).
|
||||
ref_center_re: Big,
|
||||
@@ -728,6 +749,7 @@ impl FractalApp {
|
||||
palette: 0,
|
||||
shadow_palette: 0,
|
||||
antialias: false,
|
||||
use_bla: true,
|
||||
de_coloring: false,
|
||||
rendering_mode: 0,
|
||||
lights: vec![Light::default()],
|
||||
@@ -748,6 +770,9 @@ impl FractalApp {
|
||||
fps_window_start: 0.0,
|
||||
reference: Arc::new(RefOrbit::default()),
|
||||
generation: 0,
|
||||
bla: Arc::new(BlaTable::empty()),
|
||||
bla_key: None,
|
||||
bla_generation: 0,
|
||||
ref_center_re,
|
||||
ref_center_im,
|
||||
ref_half_height,
|
||||
@@ -866,6 +891,9 @@ impl FractalApp {
|
||||
if cli.antialias {
|
||||
self.antialias = true;
|
||||
}
|
||||
if cli.no_bla {
|
||||
self.use_bla = false;
|
||||
}
|
||||
if cli.buddhabrot {
|
||||
self.mode = FractalMode::Buddhabrot;
|
||||
}
|
||||
@@ -1263,6 +1291,39 @@ impl FractalApp {
|
||||
&self.reference
|
||||
}
|
||||
|
||||
/// Whether BLA is on (headless builds its own tables per frame).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn use_bla(&self) -> bool {
|
||||
self.use_bla
|
||||
}
|
||||
|
||||
/// The BLA table for rendering `u` from the current reference, rebuilt
|
||||
/// when the reference changed or the view's dc range left what the table
|
||||
/// covers. A table built for a larger dc range is still valid, just
|
||||
/// jumps less, so zooming in only rebuilds every `BLA_DC_SLACK` binades.
|
||||
fn bla_table(&mut self, u: &Uniforms) -> Arc<BlaTable> {
|
||||
let want = BlaKey {
|
||||
generation: self.generation,
|
||||
on: self.use_bla && bla::applies(u),
|
||||
julia: u.is_julia != 0,
|
||||
dc_log2: bla::dc_max_log2(u),
|
||||
};
|
||||
let fresh = self.bla_key.as_ref().is_some_and(|k| {
|
||||
k.generation == want.generation
|
||||
&& k.on == want.on
|
||||
&& k.julia == want.julia
|
||||
&& (!want.on
|
||||
|| want.julia
|
||||
|| (want.dc_log2 <= k.dc_log2 && want.dc_log2 + BLA_DC_SLACK >= k.dc_log2))
|
||||
});
|
||||
if !fresh {
|
||||
self.bla = Arc::new(bla::for_uniforms(&self.reference, u, self.use_bla));
|
||||
self.bla_key = Some(want);
|
||||
self.bla_generation = self.bla_generation.wrapping_add(1);
|
||||
}
|
||||
Arc::clone(&self.bla)
|
||||
}
|
||||
|
||||
/// The configured shadow-style lights, for headless export's `ExportRender`
|
||||
/// (which has no `FractalCallback` to source them from).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -1632,6 +1693,7 @@ impl FractalApp {
|
||||
renderer.export_handles(&device, &uniforms, false)
|
||||
};
|
||||
let reference = Arc::clone(&self.reference);
|
||||
let use_bla = self.use_bla;
|
||||
let lights = self.lights.clone();
|
||||
|
||||
let shared = Arc::new(Mutex::new(ExportShared {
|
||||
@@ -1649,8 +1711,9 @@ impl FractalApp {
|
||||
.clone()
|
||||
.unwrap_or_else(|| format!("fractal-{}.png", unix_timestamp()));
|
||||
std::thread::spawn(move || {
|
||||
let bla = bla::for_uniforms(&reference, &uniforms, use_bla);
|
||||
let er = ExportRender::new(
|
||||
&device, &queue, &handles, w, h, uniforms, &reference, &lights,
|
||||
&device, &queue, &handles, w, h, uniforms, &reference, &bla, &lights,
|
||||
);
|
||||
let sh = Arc::clone(&shared);
|
||||
let png =
|
||||
@@ -1670,8 +1733,9 @@ impl FractalApp {
|
||||
// Progress budget: rendering fills [0, RENDER_END], encoding the rest.
|
||||
const RENDER_END: f32 = 0.6;
|
||||
wasm_bindgen_futures::spawn_local(async move {
|
||||
let bla = bla::for_uniforms(&reference, &uniforms, use_bla);
|
||||
let er = ExportRender::new(
|
||||
&device, &queue, &handles, w, h, uniforms, &reference, &lights,
|
||||
&device, &queue, &handles, w, h, uniforms, &reference, &bla, &lights,
|
||||
);
|
||||
|
||||
// Render tile by tile, awaiting each submission so the browser
|
||||
@@ -2373,6 +2437,11 @@ impl FractalApp {
|
||||
}
|
||||
ui.checkbox(&mut self.antialias, "Antialiasing (2×2)")
|
||||
.on_hover_text("Supersample each pixel for smoother edges (~4× slower).");
|
||||
ui.checkbox(&mut self.use_bla, "Skip iterations (BLA)")
|
||||
.on_hover_text(
|
||||
"Bivariate linear approximation: jump over runs of iterations where \
|
||||
every pixel follows the reference linearly. Much faster at deep zoom.",
|
||||
);
|
||||
if self.rendering_mode == 0 {
|
||||
ui.checkbox(&mut self.de_coloring, "Distance shading")
|
||||
.on_hover_text(
|
||||
@@ -3058,6 +3127,7 @@ impl FractalApp {
|
||||
if interacting || self.morph.is_some() || self.ref_morph.is_some() {
|
||||
uniforms.aa_level = 1;
|
||||
}
|
||||
let bla = self.bla_table(&uniforms);
|
||||
ui.painter().add(egui_wgpu::Callback::new_paint_callback(
|
||||
rect,
|
||||
FractalCallback {
|
||||
@@ -3065,6 +3135,8 @@ impl FractalApp {
|
||||
lights: gpu_lights(&self.lights).0,
|
||||
reference: Arc::clone(&self.reference),
|
||||
generation: self.generation,
|
||||
bla,
|
||||
bla_generation: self.bla_generation,
|
||||
size_px,
|
||||
auto_color: self.auto_color_active(),
|
||||
},
|
||||
|
||||
@@ -78,6 +78,11 @@ pub struct Cli {
|
||||
#[arg(long)]
|
||||
pub antialias: bool,
|
||||
|
||||
/// Disable bivariate linear approximation (BLA), i.e. iterate every
|
||||
/// perturbation step (for A/B comparisons; much slower at deep zoom).
|
||||
#[arg(long)]
|
||||
pub no_bla: bool,
|
||||
|
||||
/// Coloring palette index.
|
||||
#[arg(long, value_name = "INDEX")]
|
||||
pub palette: Option<u32>,
|
||||
|
||||
@@ -0,0 +1,586 @@
|
||||
//! Bivariate linear approximation (BLA): skipping many perturbation steps at
|
||||
//! once.
|
||||
//!
|
||||
//! Near the reference, a Mandelbrot delta step `e ← 2·X_m·e + e² + dc` is
|
||||
//! linear in `(e, dc)` as long as `e²` is negligible next to `2·X_m·e`, i.e.
|
||||
//! `|e| < R = ε·|X_m|`. Composing such steps gives `e_{m+k} = A·e_m + B·dc`
|
||||
//! for whole runs of steps. This module builds a binary table of those
|
||||
//! compositions from the reference orbit (level `l` merges `2^l` steps). The
|
||||
//! shader (`bla_lookup` in `mandelbrot.wgsl`) then jumps each pixel over the
|
||||
//! longest run whose validity radius its delta is inside. At deep zoom every
|
||||
//! pixel follows the reference for tens of thousands of iterations before
|
||||
//! its orbit diverges, so most of that turns into a few table lookups.
|
||||
//!
|
||||
//! Merging steps `x` then `y`:
|
||||
//! `A = A_y·A_x`, `B = A_y·B_x + B_y`,
|
||||
//! `R = min(R_x, max(0, (R_y − |B_x|·dc_max) / |A_x|))`.
|
||||
//! `R` depends on the largest pixel offset `dc_max`, so a table is only valid
|
||||
//! for views whose `|dc|` stays below the one it was built with (see
|
||||
//! [`dc_max_log2`]). Coefficients span far more than f64's exponent range at
|
||||
//! deep zoom (`|A|` ~ 1/pixel size), so they're built as [`Fx`] (f64 mantissa
|
||||
//! with its own exponent) and uploaded as f32 mantissa + i32 exponent.
|
||||
//!
|
||||
//! Only the plain Mandelbrot map (set plane and Julia) uses it for now.
|
||||
|
||||
use super::FractalKind;
|
||||
use super::reference::RefOrbit;
|
||||
use super::renderer::Uniforms;
|
||||
|
||||
/// Relative size of the dropped `e²` term that a step may have. f32's own
|
||||
/// precision (2^-24) already renders indistinguishably from plain stepping,
|
||||
/// but a chaotic seahorse pixel then escaped 7 iterations late against an
|
||||
/// f64 emulation (`escape_counts_match`). 2^-28 fixes that at the same
|
||||
/// render speed on deep views.
|
||||
const EPSILON_LOG2: i32 = -28;
|
||||
|
||||
/// Lowest level uploaded. Lower levels are still merged, just not stored:
|
||||
/// a 1..4-step jump doesn't pay for its lookup, and skipping them keeps the
|
||||
/// table at 8 bytes per orbit point.
|
||||
const MIN_LEVEL: u32 = 3;
|
||||
|
||||
/// Upload budget (bytes): the WebGPU default storage binding size limit.
|
||||
const MAX_TABLE_BYTES: usize = 128 << 20;
|
||||
|
||||
/// One table node, as the shader's `Bla` struct: `A = a·2^a_exp`,
|
||||
/// `B = b·2^b_exp`, valid while `log2|e| < r_log2`.
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
|
||||
pub struct GpuBla {
|
||||
pub a: [f32; 2],
|
||||
pub b: [f32; 2],
|
||||
pub a_exp: i32,
|
||||
pub b_exp: i32,
|
||||
pub r_log2: f32,
|
||||
pub _pad: u32,
|
||||
}
|
||||
|
||||
/// `r_log2` of a node that's never valid (f32 `-inf` is fine in WGSL, but a
|
||||
/// finite sentinel keeps comparisons obvious).
|
||||
const NEVER: f32 = -3.0e38;
|
||||
|
||||
/// A BLA table ready for upload.
|
||||
///
|
||||
/// `meta` is `[min_level, level_count, off_0, …, off_{level_count}]`: level
|
||||
/// `min_level + k` occupies `nodes[off_k..off_{k+1}]`, and its node `i`
|
||||
/// covers reference steps `1 + i·2^l .. 1 + (i+1)·2^l`.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct BlaTable {
|
||||
pub nodes: Vec<GpuBla>,
|
||||
pub meta: Vec<u32>,
|
||||
}
|
||||
|
||||
impl BlaTable {
|
||||
/// A table with no levels: the shader never jumps.
|
||||
pub fn empty() -> Self {
|
||||
Self {
|
||||
nodes: vec![GpuBla::default()],
|
||||
meta: vec![MIN_LEVEL, 0, 0],
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn levels(&self) -> u32 {
|
||||
self.meta[1]
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for BlaTable {
|
||||
fn default() -> Self {
|
||||
Self::empty()
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the shader's BLA path applies to these uniforms' kind / morph
|
||||
/// (the `BLA` pipeline override, see `PipelineKey`).
|
||||
pub fn applies(u: &Uniforms) -> bool {
|
||||
u.kind == FractalKind::Mandelbrot as u32 && u.morph_w <= 0.0
|
||||
}
|
||||
|
||||
/// The table for rendering `u` from `orbit` (empty when BLA doesn't apply
|
||||
/// or is switched off).
|
||||
pub fn for_uniforms(orbit: &RefOrbit, u: &Uniforms, enabled: bool) -> BlaTable {
|
||||
if !enabled || !applies(u) {
|
||||
return BlaTable::empty();
|
||||
}
|
||||
build(
|
||||
orbit,
|
||||
u.ref_len as usize,
|
||||
dc_max_log2(u),
|
||||
u.is_julia != 0,
|
||||
u.bailout_sq as f64,
|
||||
)
|
||||
}
|
||||
|
||||
/// Largest `log2|dc|` a pixel sample of this view can have, rounded up with
|
||||
/// one binade of headroom so the table survives small pans and zoom-outs.
|
||||
/// `span` / `dc_offset` are in units of `2^scale_exp` (see `make_uniforms`);
|
||||
/// AA jitter and `fs_color`'s shadow neighbours stay within `span` plus a
|
||||
/// pixel, which the headroom covers.
|
||||
pub fn dc_max_log2(u: &Uniforms) -> i32 {
|
||||
let dc = (u.dc_offset[0] as f64).hypot(u.dc_offset[1] as f64);
|
||||
let span = (u.span[0] as f64).hypot(u.span[1] as f64);
|
||||
let m = dc + span;
|
||||
if m <= 0.0 {
|
||||
return i32::MIN / 2;
|
||||
}
|
||||
m.log2().ceil() as i32 + 1 + u.scale_exp
|
||||
}
|
||||
|
||||
/// Extended-range complex number `(re + i·im)·2^e`, the larger component
|
||||
/// normalized to `[0.5, 1)` (or exactly zero, with `e = 0`). Scalars use
|
||||
/// `im = 0`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
struct Fx {
|
||||
re: f64,
|
||||
im: f64,
|
||||
e: i32,
|
||||
}
|
||||
|
||||
/// `frexp`-style exponent of a finite non-zero f64 (`|x| = f·2^k`, `f` in
|
||||
/// `[0.5, 1)`).
|
||||
fn exponent(x: f64) -> i32 {
|
||||
let bits = x.abs().to_bits();
|
||||
let raw = ((bits >> 52) & 0x7ff) as i32;
|
||||
if raw == 0 {
|
||||
// Subnormal: normalize through a multiply (exact).
|
||||
return exponent(x * 2f64.powi(64)) - 64;
|
||||
}
|
||||
raw - 1022
|
||||
}
|
||||
|
||||
/// `x·2^k` for `|k|` well inside f64's exponent range (mantissas only).
|
||||
fn scale(x: f64, k: i32) -> f64 {
|
||||
x * 2f64.powi(k)
|
||||
}
|
||||
|
||||
impl Fx {
|
||||
const ZERO: Fx = Fx {
|
||||
re: 0.0,
|
||||
im: 0.0,
|
||||
e: 0,
|
||||
};
|
||||
|
||||
fn new(re: f64, im: f64, e: i32) -> Fx {
|
||||
let a = re.abs().max(im.abs());
|
||||
if a == 0.0 || !a.is_finite() {
|
||||
return Fx::ZERO;
|
||||
}
|
||||
let k = exponent(a);
|
||||
Fx {
|
||||
re: scale(re, -k),
|
||||
im: scale(im, -k),
|
||||
e: e + k,
|
||||
}
|
||||
}
|
||||
|
||||
fn scalar(x: f64, e: i32) -> Fx {
|
||||
Fx::new(x, 0.0, e)
|
||||
}
|
||||
|
||||
fn is_zero(self) -> bool {
|
||||
self.re == 0.0 && self.im == 0.0
|
||||
}
|
||||
|
||||
fn mul(self, o: Fx) -> Fx {
|
||||
if self.is_zero() || o.is_zero() {
|
||||
return Fx::ZERO;
|
||||
}
|
||||
Fx::new(
|
||||
self.re * o.re - self.im * o.im,
|
||||
self.re * o.im + self.im * o.re,
|
||||
self.e + o.e,
|
||||
)
|
||||
}
|
||||
|
||||
fn add(self, o: Fx) -> Fx {
|
||||
if self.is_zero() {
|
||||
return o;
|
||||
}
|
||||
if o.is_zero() {
|
||||
return self;
|
||||
}
|
||||
let e = self.e.max(o.e);
|
||||
let (da, db) = (self.e - e, o.e - e);
|
||||
if da < -80 {
|
||||
return o;
|
||||
}
|
||||
if db < -80 {
|
||||
return self;
|
||||
}
|
||||
Fx::new(
|
||||
scale(self.re, da) + scale(o.re, db),
|
||||
scale(self.im, da) + scale(o.im, db),
|
||||
e,
|
||||
)
|
||||
}
|
||||
|
||||
fn neg(self) -> Fx {
|
||||
Fx {
|
||||
re: -self.re,
|
||||
im: -self.im,
|
||||
e: self.e,
|
||||
}
|
||||
}
|
||||
|
||||
/// `|self|` as a scalar.
|
||||
fn abs(self) -> Fx {
|
||||
Fx::scalar(self.re.hypot(self.im), self.e)
|
||||
}
|
||||
|
||||
/// Scalar division (both scalars, `o` non-zero).
|
||||
fn div(self, o: Fx) -> Fx {
|
||||
Fx::scalar(self.re / o.re, self.e - o.e)
|
||||
}
|
||||
|
||||
/// Scalar comparison (both scalars).
|
||||
fn lt(self, o: Fx) -> bool {
|
||||
self.log2() < o.log2()
|
||||
}
|
||||
|
||||
/// `log2|self|` (`-inf` for zero).
|
||||
fn log2(self) -> f64 {
|
||||
if self.is_zero() {
|
||||
return f64::NEG_INFINITY;
|
||||
}
|
||||
self.re.hypot(self.im).log2() + self.e as f64
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Node {
|
||||
a: Fx,
|
||||
b: Fx,
|
||||
r: Fx,
|
||||
}
|
||||
|
||||
impl Node {
|
||||
/// Step at reference point `x`: `A = 2x`, `B = 1` (0 for Julia, where no
|
||||
/// dc is added), `R = ε·|x|`.
|
||||
fn step(x: Fx, julia: bool) -> Node {
|
||||
Node {
|
||||
a: Fx { e: x.e + 1, ..x },
|
||||
b: if julia { Fx::ZERO } else { Fx::scalar(1.0, 0) },
|
||||
r: Fx {
|
||||
e: x.e + EPSILON_LOG2,
|
||||
..x.abs()
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// `self` then `y`.
|
||||
fn then(self, y: Node, dc_max: Fx) -> Node {
|
||||
let a = y.a.mul(self.a);
|
||||
let b = y.a.mul(self.b).add(y.b);
|
||||
let r = if self.r.is_zero() || self.a.is_zero() {
|
||||
Fx::ZERO
|
||||
} else {
|
||||
let rem = y.r.add(self.b.abs().mul(dc_max).neg());
|
||||
if rem.re <= 0.0 {
|
||||
Fx::ZERO
|
||||
} else {
|
||||
let ry = rem.div(self.a.abs());
|
||||
if ry.lt(self.r) { ry } else { self.r }
|
||||
}
|
||||
};
|
||||
Node { a, b, r }
|
||||
}
|
||||
|
||||
fn gpu(self) -> GpuBla {
|
||||
let r_log2 = self.r.log2();
|
||||
GpuBla {
|
||||
a: [self.a.re as f32, self.a.im as f32],
|
||||
b: [self.b.re as f32, self.b.im as f32],
|
||||
a_exp: self.a.e,
|
||||
b_exp: self.b.e,
|
||||
r_log2: if r_log2.is_finite() {
|
||||
r_log2 as f32
|
||||
} else {
|
||||
NEVER
|
||||
},
|
||||
_pad: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Build the table for the first `len` points of `orbit`. `dc_max_log2` is
|
||||
/// [`dc_max_log2`] of the view (ignored for Julia, where dc is 0).
|
||||
///
|
||||
/// A jump must not skip a pixel's escape: the shader only tests the bailout
|
||||
/// between jumps, and inside a run a pixel's value is the reference's to
|
||||
/// within ε. The reference itself is iterated past the pixel bailout
|
||||
/// (`REFERENCE_ESCAPE_SQ`), so the table stops at its first point beyond
|
||||
/// `bailout_sq`: runs may land there, never pass it.
|
||||
pub fn build(
|
||||
orbit: &RefOrbit,
|
||||
len: usize,
|
||||
dc_max_log2: i32,
|
||||
julia: bool,
|
||||
bailout_sq: f64,
|
||||
) -> BlaTable {
|
||||
let len = len.min(orbit.len());
|
||||
// Steps 1..=len-2 (step m reads X_m and lands on X_{m+1}, which must
|
||||
// exist). Step 0 (X_0 = 0, e ← e² + dc) is never linear.
|
||||
let limit = bailout_sq * (1.0 - 1e-3);
|
||||
let escape = (1..len).find(|&m| {
|
||||
let [re, im] = orbit.points[m];
|
||||
orbit.exps[m] == 0 && (re as f64).powi(2) + (im as f64).powi(2) >= limit
|
||||
});
|
||||
let steps = match escape {
|
||||
Some(m) => m - 1,
|
||||
None => len.saturating_sub(2),
|
||||
};
|
||||
let mut min_level = MIN_LEVEL;
|
||||
// Level l has steps >> l nodes, so levels >= min hold < 2·(steps >> min).
|
||||
while (steps >> min_level) * 2 * size_of::<GpuBla>() > MAX_TABLE_BYTES {
|
||||
min_level += 1;
|
||||
}
|
||||
if steps >> min_level == 0 {
|
||||
return BlaTable::empty();
|
||||
}
|
||||
let dc_max = if julia {
|
||||
Fx::ZERO
|
||||
} else {
|
||||
Fx::scalar(1.0, dc_max_log2)
|
||||
};
|
||||
let point = |m: usize| {
|
||||
let [re, im] = orbit.points[m];
|
||||
Fx::new(re as f64, im as f64, orbit.exps[m])
|
||||
};
|
||||
|
||||
// First stored level, folded straight from single steps.
|
||||
let run = 1usize << min_level;
|
||||
let mut level: Vec<Node> = (0..steps >> min_level)
|
||||
.map(|i| {
|
||||
let start = 1 + i * run;
|
||||
(1..run).fold(Node::step(point(start), julia), |acc, k| {
|
||||
acc.then(Node::step(point(start + k), julia), dc_max)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
|
||||
let mut nodes = Vec::new();
|
||||
let mut meta = vec![min_level, 0];
|
||||
while !level.is_empty() {
|
||||
meta.push(nodes.len() as u32);
|
||||
nodes.extend(level.iter().map(|n| n.gpu()));
|
||||
level = level
|
||||
.as_chunks::<2>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|[x, y]| x.then(*y, dc_max))
|
||||
.collect();
|
||||
}
|
||||
meta[1] = (meta.len() - 2) as u32;
|
||||
meta.push(nodes.len() as u32);
|
||||
BlaTable { nodes, meta }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::fractal::compute_set_reference;
|
||||
use crate::view::Big;
|
||||
|
||||
fn orbit(cr: f64, ci: f64, iters: u32) -> RefOrbit {
|
||||
compute_set_reference(
|
||||
&Big::from_f64(cr, 128),
|
||||
&Big::from_f64(ci, 128),
|
||||
iters,
|
||||
128,
|
||||
FractalKind::Mandelbrot,
|
||||
2,
|
||||
(0.0, 0.0),
|
||||
(0.0, 0.0),
|
||||
(0.0, 0.0),
|
||||
None,
|
||||
)
|
||||
}
|
||||
|
||||
fn fx_to_f64(v: [f32; 2], e: i32) -> (f64, f64) {
|
||||
let s = 2f64.powi(e);
|
||||
(v[0] as f64 * s, v[1] as f64 * s)
|
||||
}
|
||||
|
||||
/// Replay the shader's lookup: the longest valid aligned node at `m`.
|
||||
fn lookup(t: &BlaTable, m: usize, e_log2: f64) -> Option<(usize, usize)> {
|
||||
let (lmin, levels) = (t.meta[0], t.meta[1]);
|
||||
if m == 0 || levels == 0 {
|
||||
return None;
|
||||
}
|
||||
let j = m - 1;
|
||||
let tz = if j == 0 { 32 } else { j.trailing_zeros() };
|
||||
if tz < lmin {
|
||||
return None;
|
||||
}
|
||||
let mut best = None;
|
||||
for k in 0..=(tz - lmin).min(levels - 1) {
|
||||
let l = lmin + k;
|
||||
let base = t.meta[2 + k as usize] as usize;
|
||||
let count = t.meta[3 + k as usize] as usize - base;
|
||||
let local = j >> l;
|
||||
if local >= count {
|
||||
break;
|
||||
}
|
||||
let node = &t.nodes[base + local];
|
||||
if e_log2 >= node.r_log2 as f64 {
|
||||
break;
|
||||
}
|
||||
best = Some((base + local, 1usize << l));
|
||||
}
|
||||
best
|
||||
}
|
||||
|
||||
/// Jumping with the table must track the plain perturbation iteration.
|
||||
#[test]
|
||||
fn jumps_match_stepping() {
|
||||
// A point inside the main cardioid: the orbit never escapes, so the
|
||||
// reference is long and smooth, and the deltas stay small.
|
||||
let orb = orbit(-0.1, 0.2, 5000);
|
||||
assert_eq!(orb.len(), 5001);
|
||||
let dc_max_log2 = -40;
|
||||
let t = build(&orb, orb.len(), dc_max_log2, false, 1e6);
|
||||
assert!(t.levels() > 3);
|
||||
let x = |m: usize| (orb.points[m][0] as f64, orb.points[m][1] as f64);
|
||||
let mut jumped = 0;
|
||||
for &(dr, di) in &[(0.7, 0.1), (-0.3, 0.9), (0.0, -1.0)] {
|
||||
let dc = (dr * 2f64.powi(dc_max_log2), di * 2f64.powi(dc_max_log2));
|
||||
// Reference: plain perturbation steps.
|
||||
let mut e_ref = (0.0, 0.0);
|
||||
let mut plain = vec![e_ref];
|
||||
for m in 0..orb.len() - 1 {
|
||||
let (xr, xi) = x(m);
|
||||
let (er, ei) = e_ref;
|
||||
e_ref = (
|
||||
2.0 * (xr * er - xi * ei) + er * er - ei * ei + dc.0,
|
||||
2.0 * (xr * ei + xi * er) + 2.0 * er * ei + dc.1,
|
||||
);
|
||||
plain.push(e_ref);
|
||||
}
|
||||
// With jumps.
|
||||
let (mut m, mut e) = (0usize, (0.0f64, 0.0f64));
|
||||
while m < orb.len() - 1 {
|
||||
let e_log2 = e.0.hypot(e.1).log2();
|
||||
if let Some((idx, n)) = lookup(&t, m, e_log2) {
|
||||
let nd = &t.nodes[idx];
|
||||
let (ar, ai) = fx_to_f64(nd.a, nd.a_exp);
|
||||
let (br, bi) = fx_to_f64(nd.b, nd.b_exp);
|
||||
e = (
|
||||
ar * e.0 - ai * e.1 + br * dc.0 - bi * dc.1,
|
||||
ar * e.1 + ai * e.0 + br * dc.1 + bi * dc.0,
|
||||
);
|
||||
m += n;
|
||||
jumped += n;
|
||||
} else {
|
||||
let (xr, xi) = x(m);
|
||||
let (er, ei) = e;
|
||||
e = (
|
||||
2.0 * (xr * er - xi * ei) + er * er - ei * ei + dc.0,
|
||||
2.0 * (xr * ei + xi * er) + 2.0 * er * ei + dc.1,
|
||||
);
|
||||
m += 1;
|
||||
}
|
||||
let want = plain[m];
|
||||
let err = (e.0 - want.0).hypot(e.1 - want.1);
|
||||
let mag = want.0.hypot(want.1);
|
||||
assert!(err <= 1e-4 * mag + 1e-300, "m={m}: {e:?} vs {want:?}");
|
||||
}
|
||||
}
|
||||
assert!(jumped > (orb.len() - 1) / 2, "only {jumped} steps jumped");
|
||||
}
|
||||
|
||||
/// The shader's f32 loop (rebasing, escape, smooth count) with and
|
||||
/// without jumps, on a chaotic seahorse view: escape iteration counts and
|
||||
/// smooth values must agree.
|
||||
#[test]
|
||||
fn escape_counts_match() {
|
||||
let (cr, ci) = (-0.743_643_887_037_151, 0.131_825_904_205_330);
|
||||
let orb = orbit(cr, ci, 20_000);
|
||||
let half = 1e-9f64;
|
||||
let dc_max_log2 = (2.0 * half).log2().ceil() as i32 + 1;
|
||||
let t = build(&orb, orb.len(), dc_max_log2, false, 1e6);
|
||||
let x = |m: usize| (orb.points[m][0] as f64, orb.points[m][1] as f64);
|
||||
let run = |dc: (f64, f64), bla: bool| -> (u32, f64) {
|
||||
let (mut m, mut n, mut e) = (0usize, 0u32, (0.0f64, 0.0f64));
|
||||
loop {
|
||||
let xm = x(m);
|
||||
let z = (xm.0 + e.0, xm.1 + e.1);
|
||||
let z2 = z.0 * z.0 + z.1 * z.1;
|
||||
if z2 > 1e6 || n >= 20_000 {
|
||||
return (n, z2);
|
||||
}
|
||||
let hit = if bla && m != 0 {
|
||||
lookup(&t, m, e.0.hypot(e.1).log2())
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some((idx, k)) = hit {
|
||||
let nd = &t.nodes[idx];
|
||||
let (ar, ai) = fx_to_f64(nd.a, nd.a_exp);
|
||||
let (br, bi) = fx_to_f64(nd.b, nd.b_exp);
|
||||
e = (
|
||||
ar * e.0 - ai * e.1 + br * dc.0 - bi * dc.1,
|
||||
ar * e.1 + ai * e.0 + br * dc.1 + bi * dc.0,
|
||||
);
|
||||
m += k;
|
||||
n += k as u32;
|
||||
} else {
|
||||
let (er, ei) = e;
|
||||
e = (
|
||||
2.0 * (xm.0 * er - xm.1 * ei) + er * er - ei * ei + dc.0,
|
||||
2.0 * (xm.0 * ei + xm.1 * er) + 2.0 * er * ei + dc.1,
|
||||
);
|
||||
m += 1;
|
||||
n += 1;
|
||||
}
|
||||
if m >= orb.len() {
|
||||
return (u32::MAX, 0.0);
|
||||
}
|
||||
let xm = x(m);
|
||||
let z = (xm.0 + e.0, xm.1 + e.1);
|
||||
if z.0 * z.0 + z.1 * z.1 < e.0 * e.0 + e.1 * e.1 {
|
||||
e = z;
|
||||
m = 0;
|
||||
}
|
||||
}
|
||||
};
|
||||
let mut jumped_any = false;
|
||||
for i in 0..40 {
|
||||
let a = i as f64 * 0.37;
|
||||
let dc = (half * a.cos(), half * (1.3 * a).sin());
|
||||
let (n0, z0) = run(dc, false);
|
||||
let (n1, z1) = run(dc, true);
|
||||
jumped_any |= n0 > 1000;
|
||||
let smooth = |n: u32, z2: f64| n as f64 - (0.5 * z2.ln()).log2();
|
||||
assert!(
|
||||
(smooth(n0, z0) - smooth(n1, z1)).abs() < 0.05,
|
||||
"dc {dc:?}: plain {n0} ({z0}), bla {n1} ({z1})"
|
||||
);
|
||||
}
|
||||
assert!(jumped_any);
|
||||
}
|
||||
|
||||
/// A table built for a small dc_max must reject deltas it can't cover.
|
||||
#[test]
|
||||
fn radius_shrinks_with_dc_max() {
|
||||
let orb = orbit(-0.1, 0.2, 2000);
|
||||
let small = build(&orb, orb.len(), -40, false, 1e6);
|
||||
let big = build(&orb, orb.len(), -4, false, 1e6);
|
||||
let top = |t: &BlaTable| t.nodes[t.meta[2 + t.levels() as usize - 1] as usize].r_log2;
|
||||
assert!(top(&big) < top(&small));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn layout() {
|
||||
let orb = orbit(-0.1, 0.2, 1000);
|
||||
let t = build(&orb, orb.len(), -30, false, 1e6);
|
||||
let steps = orb.len() - 2;
|
||||
assert_eq!(t.meta[0], MIN_LEVEL);
|
||||
for k in 0..t.levels() as usize {
|
||||
let count = t.meta[3 + k] - t.meta[2 + k];
|
||||
assert_eq!(count as usize, steps >> (MIN_LEVEL as usize + k));
|
||||
}
|
||||
assert_eq!(*t.meta.last().unwrap() as usize, t.nodes.len());
|
||||
let tiny = orbit(-3.0, 0.0, 1000); // escapes at once
|
||||
assert_eq!(build(&tiny, tiny.len(), -30, false, 1e6).levels(), 0);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//! GPU fractal rendering: wgpu pipeline, uniforms, reference orbit, and the
|
||||
//! egui paint callback.
|
||||
|
||||
pub mod bla;
|
||||
pub mod buddhabrot;
|
||||
pub mod kind;
|
||||
pub mod reference;
|
||||
|
||||
+124
-2
@@ -16,6 +16,7 @@ use std::sync::Arc;
|
||||
use eframe::egui_wgpu;
|
||||
use wgpu::util::DeviceExt as _;
|
||||
|
||||
use super::bla::BlaTable;
|
||||
use super::kind::FractalKind;
|
||||
use super::reference::RefOrbit;
|
||||
use crate::lights::{GpuLight, Light, MAX_LIGHT_COUNT, gpu_lights};
|
||||
@@ -101,6 +102,9 @@ pub struct PipelineKey {
|
||||
/// Deep view: the delta starts out in rescaled (mantissa + exponent)
|
||||
/// form (`scale_exp != 0`).
|
||||
deep: bool,
|
||||
/// BLA jumps (`bla::applies`; disabling BLA uploads an empty table
|
||||
/// instead, see `BlaTable::empty`).
|
||||
bla: bool,
|
||||
}
|
||||
|
||||
impl PipelineKey {
|
||||
@@ -111,16 +115,18 @@ impl PipelineKey {
|
||||
de: u.de_coloring != 0,
|
||||
morph: u.morph_w > 0.0,
|
||||
deep: u.scale_exp != 0,
|
||||
bla: super::bla::applies(u),
|
||||
}
|
||||
}
|
||||
|
||||
fn constants(&self) -> [(&'static str, f64); 5] {
|
||||
fn constants(&self) -> [(&'static str, f64); 6] {
|
||||
[
|
||||
("KIND", self.kind as f64),
|
||||
("IS_JULIA", self.julia as u32 as f64),
|
||||
("DE", self.de as u32 as f64),
|
||||
("MORPH", self.morph as u32 as f64),
|
||||
("DEEP", self.deep as u32 as f64),
|
||||
("BLA", self.bla as u32 as f64),
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -769,6 +775,7 @@ struct CacheTarget {
|
||||
struct IterState {
|
||||
uniforms: Uniforms,
|
||||
generation: u64,
|
||||
bla_generation: u64,
|
||||
width: u32,
|
||||
height: u32,
|
||||
}
|
||||
@@ -782,6 +789,48 @@ struct ColorState {
|
||||
height: u32,
|
||||
}
|
||||
|
||||
/// GPU copy of a [`BlaTable`] (bindings 4 and 5 of the iterate group).
|
||||
struct BlaBuffers {
|
||||
nodes: wgpu::Buffer,
|
||||
meta: wgpu::Buffer,
|
||||
}
|
||||
|
||||
impl BlaBuffers {
|
||||
/// Buffers holding exactly `table` (plus room to grow into, `min_*`).
|
||||
fn new(device: &wgpu::Device, table: &BlaTable, min_nodes: usize, min_meta: usize) -> Self {
|
||||
// Padded with zeros up to the requested capacity.
|
||||
let init = |label, data: &[u8], size: usize| {
|
||||
let mut bytes = data.to_vec();
|
||||
bytes.resize(size.max(data.len()), 0);
|
||||
device.create_buffer_init(&wgpu::util::BufferInitDescriptor {
|
||||
label: Some(label),
|
||||
contents: &bytes,
|
||||
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
|
||||
})
|
||||
};
|
||||
let node_size = std::mem::size_of::<super::bla::GpuBla>();
|
||||
Self {
|
||||
nodes: init(
|
||||
"bla nodes",
|
||||
bytemuck::cast_slice(&table.nodes),
|
||||
min_nodes * node_size,
|
||||
),
|
||||
meta: init("bla meta", bytemuck::cast_slice(&table.meta), min_meta * 4),
|
||||
}
|
||||
}
|
||||
|
||||
fn write(&self, queue: &wgpu::Queue, table: &BlaTable) {
|
||||
queue.write_buffer(&self.nodes, 0, bytemuck::cast_slice(&table.nodes));
|
||||
queue.write_buffer(&self.meta, 0, bytemuck::cast_slice(&table.meta));
|
||||
}
|
||||
|
||||
fn fits(&self, table: &BlaTable) -> bool {
|
||||
let node_size = std::mem::size_of::<super::bla::GpuBla>() as u64;
|
||||
table.nodes.len() as u64 * node_size <= self.nodes.size()
|
||||
&& table.meta.len() as u64 * 4 <= self.meta.size()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct FractalRenderer {
|
||||
/// `mandelbrot.wgsl`, specialized per [`PipelineKey`] at pipeline creation.
|
||||
shader: wgpu::ShaderModule,
|
||||
@@ -798,6 +847,9 @@ pub struct FractalRenderer {
|
||||
ref_exp_buffer: wgpu::Buffer,
|
||||
/// Points `ref_buffer` / `ref_exp_buffer` can hold (see `ensure_ref_capacity`).
|
||||
ref_capacity: usize,
|
||||
bla: BlaBuffers,
|
||||
/// Generation of the BLA table currently in `bla`.
|
||||
uploaded_bla_generation: u64,
|
||||
lights_buffer: wgpu::Buffer,
|
||||
bind_group: wgpu::BindGroup,
|
||||
target_format: wgpu::TextureFormat,
|
||||
@@ -851,6 +903,11 @@ impl FractalRenderer {
|
||||
usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
self.rebuild_bind_group(device);
|
||||
self.ref_capacity = capacity;
|
||||
}
|
||||
|
||||
fn rebuild_bind_group(&mut self, device: &wgpu::Device) {
|
||||
self.bind_group = iterate_bind_group(
|
||||
device,
|
||||
&self.bind_group_layout,
|
||||
@@ -858,8 +915,18 @@ impl FractalRenderer {
|
||||
&self.ref_buffer,
|
||||
&self.lights_buffer,
|
||||
&self.ref_exp_buffer,
|
||||
&self.bla,
|
||||
);
|
||||
self.ref_capacity = capacity;
|
||||
}
|
||||
|
||||
/// Upload `table`, growing the BLA buffers (by powers of two) if needed.
|
||||
fn upload_bla(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, table: &BlaTable) {
|
||||
if self.bla.fits(table) {
|
||||
self.bla.write(queue, table);
|
||||
return;
|
||||
}
|
||||
self.bla = BlaBuffers::new(device, table, table.nodes.len().next_power_of_two(), 64);
|
||||
self.rebuild_bind_group(device);
|
||||
}
|
||||
|
||||
pub fn new(device: &wgpu::Device, target_format: wgpu::TextureFormat) -> Self {
|
||||
@@ -956,9 +1023,31 @@ impl FractalRenderer {
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 4,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: true },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
// BLA table nodes / meta (`fractal::bla`).
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 5,
|
||||
visibility: wgpu::ShaderStages::FRAGMENT,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: true },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
let bla = BlaBuffers::new(device, &BlaTable::empty(), 1 << 14, 64);
|
||||
let bind_group = iterate_bind_group(
|
||||
device,
|
||||
&bind_group_layout,
|
||||
@@ -966,6 +1055,7 @@ impl FractalRenderer {
|
||||
&ref_buffer,
|
||||
&lights_buffer,
|
||||
&ref_exp_buffer,
|
||||
&bla,
|
||||
);
|
||||
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
@@ -1174,6 +1264,8 @@ impl FractalRenderer {
|
||||
ref_buffer,
|
||||
ref_exp_buffer,
|
||||
ref_capacity: INITIAL_REF_POINTS,
|
||||
bla,
|
||||
uploaded_bla_generation: u64::MAX,
|
||||
lights_buffer,
|
||||
bind_group,
|
||||
target_format,
|
||||
@@ -1539,6 +1631,7 @@ impl ExportRender {
|
||||
height: u32,
|
||||
uniforms: Uniforms,
|
||||
reference: &RefOrbit,
|
||||
bla: &BlaTable,
|
||||
lights: &[Light],
|
||||
) -> Self {
|
||||
let uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
@@ -1582,6 +1675,8 @@ impl ExportRender {
|
||||
let (gpu_lights, _) = gpu_lights(lights);
|
||||
queue.write_buffer(&lights_buffer, 0, bytemuck::cast_slice(&gpu_lights));
|
||||
|
||||
let bla_buffers = BlaBuffers::new(device, bla, 0, 0);
|
||||
|
||||
let target_format = handles.format;
|
||||
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("export bind group"),
|
||||
@@ -1603,6 +1698,14 @@ impl ExportRender {
|
||||
binding: 3,
|
||||
resource: ref_exp_buffer.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 4,
|
||||
resource: bla_buffers.nodes.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 5,
|
||||
resource: bla_buffers.meta.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
@@ -2129,6 +2232,7 @@ fn iterate_bind_group(
|
||||
ref_buffer: &wgpu::Buffer,
|
||||
lights_buffer: &wgpu::Buffer,
|
||||
ref_exp_buffer: &wgpu::Buffer,
|
||||
bla: &BlaBuffers,
|
||||
) -> wgpu::BindGroup {
|
||||
device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("fractal bind group"),
|
||||
@@ -2150,6 +2254,14 @@ fn iterate_bind_group(
|
||||
binding: 3,
|
||||
resource: ref_exp_buffer.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 4,
|
||||
resource: bla.nodes.as_entire_binding(),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 5,
|
||||
resource: bla.meta.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
})
|
||||
}
|
||||
@@ -2304,6 +2416,10 @@ pub struct FractalCallback {
|
||||
pub lights: [GpuLight; MAX_LIGHT_COUNT],
|
||||
pub reference: Arc<RefOrbit>,
|
||||
pub generation: u64,
|
||||
/// BLA table for `reference` and this view's `dc` range, and its
|
||||
/// generation (bumped on every rebuild).
|
||||
pub bla: Arc<BlaTable>,
|
||||
pub bla_generation: u64,
|
||||
/// Widget size in physical pixels — the cache texture resolution.
|
||||
pub size_px: [u32; 2],
|
||||
/// Histogram each new iteration for the auto colour scale
|
||||
@@ -2346,6 +2462,7 @@ impl egui_wgpu::CallbackTrait for FractalCallback {
|
||||
// camera moves skip the perturbation entirely.
|
||||
let iter_dirty = renderer.iterated.as_ref().is_none_or(|r| {
|
||||
r.generation != self.generation
|
||||
|| r.bla_generation != self.bla_generation
|
||||
|| r.width != width
|
||||
|| r.height != height
|
||||
|| geom_differs(&r.uniforms, &self.uniforms)
|
||||
@@ -2402,6 +2519,10 @@ impl egui_wgpu::CallbackTrait for FractalCallback {
|
||||
);
|
||||
renderer.uploaded_generation = self.generation;
|
||||
}
|
||||
if iter_dirty && renderer.uploaded_bla_generation != self.bla_generation {
|
||||
renderer.upload_bla(device, queue, &self.bla);
|
||||
renderer.uploaded_bla_generation = self.bla_generation;
|
||||
}
|
||||
|
||||
// Every pass reads the uniform buffer; refresh it once.
|
||||
queue.write_buffer(
|
||||
@@ -2510,6 +2631,7 @@ impl egui_wgpu::CallbackTrait for FractalCallback {
|
||||
renderer.iterated = Some(IterState {
|
||||
uniforms: self.uniforms,
|
||||
generation: self.generation,
|
||||
bla_generation: self.bla_generation,
|
||||
width,
|
||||
height,
|
||||
});
|
||||
|
||||
@@ -14,6 +14,7 @@ use std::sync::{Mutex, mpsc};
|
||||
|
||||
use crate::app::{FractalApp, RefJob, parse_complex_pair, unix_timestamp};
|
||||
use crate::cli::Cli;
|
||||
use crate::fractal::bla;
|
||||
use crate::fractal::{
|
||||
ExportRender, FractalKind, FractalRenderer, PipelineKey, ShareState, encode_png,
|
||||
export_to_png_blocking, render_readback_blocking, unpad_rgba,
|
||||
@@ -89,6 +90,7 @@ pub fn run(cli: Cli) -> Result<(), String> {
|
||||
height,
|
||||
uniforms,
|
||||
app.reference_points(),
|
||||
&bla::for_uniforms(app.reference_points(), &uniforms, app.use_bla()),
|
||||
app.lights(),
|
||||
);
|
||||
if auto_color {
|
||||
@@ -513,6 +515,9 @@ fn run_animation(
|
||||
height,
|
||||
uniforms,
|
||||
app.reference_points(),
|
||||
// Built here rather than in the orbit pool: it needs this
|
||||
// frame's uniforms, and costs ~1 ms per 100k points.
|
||||
&bla::for_uniforms(app.reference_points(), &uniforms, app.use_bla()),
|
||||
app.lights(),
|
||||
);
|
||||
if auto_color {
|
||||
|
||||
+145
-3
@@ -30,6 +30,21 @@
|
||||
// f32's range, which only deep references contain; only `DEEP` pipelines read
|
||||
// it (see `ref_at`).
|
||||
@group(0) @binding(3) var<storage, read> ref_exp: array<i32>;
|
||||
// Bivariate linear approximation table (`fractal::bla`): node i of level l
|
||||
// maps the delta at reference step 1 + i·2^l to the one 2^l steps later as
|
||||
// e' = A·e + B·dc, valid while log2|e| < r_log2. `bla_meta` is
|
||||
// [min_level, level_count, off_0, ..., off_{level_count}]; only `BLA`
|
||||
// pipelines read either.
|
||||
struct Bla {
|
||||
a: vec2<f32>,
|
||||
b: vec2<f32>,
|
||||
a_exp: i32,
|
||||
b_exp: i32,
|
||||
r_log2: f32,
|
||||
_pad: u32,
|
||||
};
|
||||
@group(0) @binding(4) var<storage, read> bla_nodes: array<Bla>;
|
||||
@group(0) @binding(5) var<storage, read> bla_meta: array<u32>;
|
||||
|
||||
// Pipeline-overridable specialization constants, set per pipeline from the
|
||||
// uniforms' `kind` / `is_julia` / `de_coloring` (see `PipelineKey` in
|
||||
@@ -49,6 +64,9 @@ override MORPH: bool = false;
|
||||
// and `u.span` / `u.dc_offset` are all in units of 2^scale_exp, and each pixel
|
||||
// starts in the rescaled deep phase (see `iterate_sample`).
|
||||
override DEEP: bool = false;
|
||||
// Jump over runs of reference steps with the BLA table (plain Mandelbrot,
|
||||
// no morph; see `bla_lookup`).
|
||||
override BLA: bool = false;
|
||||
|
||||
struct VsOut {
|
||||
@builtin(position) pos: vec4<f32>,
|
||||
@@ -578,6 +596,49 @@ const DEEP_RENORM_LOG2: i32 = 16;
|
||||
// binades above the delta's scale (|w| < 2^DEEP_RENORM_LOG2).
|
||||
const DEEP_NEAR_LOG2: i32 = 24;
|
||||
|
||||
// log2|v|, from above (|v| <= sqrt(2)·max component). Not via dot(v, v):
|
||||
// a delta ~2^-100 (a pixel offset at 1e-30 zoom) squares below f32's range,
|
||||
// and log2(0) = -inf passed every radius test, jumping pixels far too early.
|
||||
fn log2_mag(v: vec2<f32>) -> f32 {
|
||||
return log2(max(abs(v.x), abs(v.y))) + 0.5;
|
||||
}
|
||||
|
||||
// Longest BLA jump available at reference index `m` for a delta of
|
||||
// log2 magnitude `e_log2`, of at most `budget` steps: (node index, steps),
|
||||
// steps = 0 when there's none. Nodes start at 1 + i·2^l, so level l needs
|
||||
// m - 1 aligned to 2^l. A longer run's radius is never larger than its first
|
||||
// half's, so the search goes up from the shortest and stops at the first
|
||||
// invalid level (usually right away: one load per failed attempt).
|
||||
fn bla_lookup(m: u32, e_log2: f32, budget: u32) -> vec2<u32> {
|
||||
var best = vec2<u32>(0u, 0u);
|
||||
let levels = bla_meta[1];
|
||||
if levels == 0u || m == 0u {
|
||||
return best;
|
||||
}
|
||||
let lmin = bla_meta[0];
|
||||
let j = m - 1u;
|
||||
let tz = countTrailingZeros(j); // 32 when j == 0
|
||||
if tz < lmin {
|
||||
return best;
|
||||
}
|
||||
let top = min(tz - lmin, levels - 1u);
|
||||
for (var k: u32 = 0u; k <= top; k = k + 1u) {
|
||||
let l = lmin + k;
|
||||
let steps = 1u << l;
|
||||
let base = bla_meta[2u + k];
|
||||
let local = j >> l;
|
||||
if steps > budget || local >= bla_meta[3u + k] - base {
|
||||
break;
|
||||
}
|
||||
let idx = base + local;
|
||||
if !(e_log2 < bla_nodes[idx].r_log2) {
|
||||
break;
|
||||
}
|
||||
best = vec2<u32>(idx, steps);
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
// Weight of the Phoenix kind's p*z_{n-1} term in the current map: 1 for plain
|
||||
// Phoenix, its morph share while switching to/from Phoenix, else 0.
|
||||
fn phoenix_weight() -> f32 {
|
||||
@@ -792,6 +853,47 @@ fn iterate_sample(offset: vec2<f32>, px: f32) -> Sample {
|
||||
break;
|
||||
}
|
||||
|
||||
// BLA: jump the whole run the table covers, straight to its
|
||||
// output scale (usually many binades up, towards the f32 hand-off).
|
||||
var jumped = false;
|
||||
if BLA {
|
||||
let e_log2 = f32(sx) + log2_mag(w);
|
||||
let hit = bla_lookup(m, e_log2, min(max_iter - n, ref_len - 1u - m));
|
||||
if hit.y != 0u {
|
||||
let nd = bla_nodes[hit.x];
|
||||
if DE {
|
||||
var accv = fe_make(cmul(nd.a, v), nd.a_exp + sv);
|
||||
if !IS_JULIA {
|
||||
accv = fe_add(accv, fe_make(nd.b * px, nd.b_exp + scale_e));
|
||||
}
|
||||
v = accv.m;
|
||||
if accv.m.x != 0.0 || accv.m.y != 0.0 {
|
||||
sv = accv.e;
|
||||
if !IS_JULIA {
|
||||
pd = ldexp_sat(px, scale_e - sv);
|
||||
}
|
||||
}
|
||||
}
|
||||
var acc = fe_make(cmul(nd.a, w), nd.a_exp + sx);
|
||||
if !IS_JULIA {
|
||||
acc = fe_add(acc, fe_make(cmul(nd.b, offset), nd.b_exp + scale_e));
|
||||
}
|
||||
w = acc.m;
|
||||
if acc.m.x != 0.0 || acc.m.y != 0.0 {
|
||||
sx = acc.e;
|
||||
sc = ldexp_sat(1.0, sx);
|
||||
if !IS_JULIA {
|
||||
d = ldexp2_sat(offset, scale_e - sx);
|
||||
}
|
||||
}
|
||||
w_old = w;
|
||||
m = m + hit.y;
|
||||
n = n + hit.y;
|
||||
jumped = true;
|
||||
}
|
||||
}
|
||||
|
||||
if !jumped {
|
||||
if DE {
|
||||
let fp = deep_fprime(xf, w, sx, yt);
|
||||
if fp.e == 0 {
|
||||
@@ -873,6 +975,7 @@ fn iterate_sample(offset: vec2<f32>, px: f32) -> Sample {
|
||||
}
|
||||
m = m + 1u;
|
||||
n = n + 1u;
|
||||
}
|
||||
|
||||
if m >= ref_len {
|
||||
escaped = true; // see the f32 loop's reference-exhausted case
|
||||
@@ -994,6 +1097,43 @@ fn iterate_sample(offset: vec2<f32>, px: f32) -> Sample {
|
||||
// which only re-expresses the same value). Only when DE is enabled.
|
||||
// Phoenix's two-term map adds p·dz_{n-1} and carries the previous dz.
|
||||
// f'(z) of this step, shared by DE and the periodicity multiplier.
|
||||
// BLA jump (see the deep phase). dc and px are taken unscaled from
|
||||
// `offset`/`px`: at depth `step_add`/`px_t` have flushed to 0, but
|
||||
// B·dc hasn't. The skipped steps' |f'|^2 product is |A|^2. No
|
||||
// skipped iterate can be the window's closest to the critical point:
|
||||
// a run's radius is below ε·|X| for every X in it.
|
||||
let e_old = e;
|
||||
let z_old = z;
|
||||
var jumped = false;
|
||||
if BLA && m != 0u {
|
||||
let hit = bla_lookup(m, log2_mag(e), min(max_iter - n, ref_len - 1u - m));
|
||||
if hit.y != 0u {
|
||||
let nd = bla_nodes[hit.x];
|
||||
let se = select(0, u.scale_exp, DEEP);
|
||||
if periodic {
|
||||
let a2 = ldexp_sat(dot(nd.a, nd.a), 2 * nd.a_exp);
|
||||
mult2 = mult2 * a2;
|
||||
mult2_cand = mult2_cand * a2;
|
||||
}
|
||||
if DE {
|
||||
var dn = ldexp2_sat(cmul(nd.a, dzs), nd.a_exp);
|
||||
if !IS_JULIA {
|
||||
dn = dn + ldexp2_sat(nd.b * px, nd.b_exp + se);
|
||||
}
|
||||
dzs = dn;
|
||||
}
|
||||
var en = ldexp2_sat(cmul(nd.a, e), nd.a_exp);
|
||||
if !IS_JULIA {
|
||||
en = en + ldexp2_sat(cmul(nd.b, offset), nd.b_exp + se);
|
||||
}
|
||||
e = en;
|
||||
m = m + hit.y;
|
||||
n = n + hit.y;
|
||||
jumped = true;
|
||||
}
|
||||
}
|
||||
|
||||
if !jumped {
|
||||
var fp = vec2<f32>(0.0, 0.0);
|
||||
if DE || periodic {
|
||||
fp = fprime(z);
|
||||
@@ -1017,8 +1157,6 @@ fn iterate_sample(offset: vec2<f32>, px: f32) -> Sample {
|
||||
|
||||
// Advance the delta by this fractal's formula (+ dc for the set plane).
|
||||
// Phoenix additionally adds p·e_{n-1} and carries the previous delta.
|
||||
let e_old = e;
|
||||
let z_old = z;
|
||||
e = advance_delta(xm, e) + step_add;
|
||||
if phoenix_w > 0.0 {
|
||||
e = e + phoenix_w * cmul(u.phoenix_p, e_prev);
|
||||
@@ -1026,6 +1164,7 @@ fn iterate_sample(offset: vec2<f32>, px: f32) -> Sample {
|
||||
}
|
||||
m = m + 1u;
|
||||
n = n + 1u;
|
||||
}
|
||||
|
||||
// Keep the reference index valid and the delta small.
|
||||
if m >= ref_len {
|
||||
@@ -1069,7 +1208,7 @@ fn iterate_sample(offset: vec2<f32>, px: f32) -> Sample {
|
||||
z_cand = z;
|
||||
mult2_cand = 1.0;
|
||||
}
|
||||
if n == check_at {
|
||||
if n >= check_at {
|
||||
if !period_hit {
|
||||
period_streak = 0u;
|
||||
}
|
||||
@@ -1077,10 +1216,13 @@ fn iterate_sample(offset: vec2<f32>, px: f32) -> Sample {
|
||||
z_saved = z_cand;
|
||||
mult2 = mult2_cand;
|
||||
cand_d2 = 3.0e38;
|
||||
// (A BLA jump can pass several window ends at once.)
|
||||
while check_at <= n {
|
||||
check_at = check_at * 2u;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if !escaped {
|
||||
return Sample(0.0, 1.0, false); // interior of the set
|
||||
|
||||
+10
-1
@@ -77,7 +77,7 @@ fn mandelbrot_shader_is_valid() {
|
||||
}
|
||||
|
||||
/// Every specialization renderer.rs can build (`PipelineKey`: kind × Julia ×
|
||||
/// DE × morph × deep), for every fragment entry point.
|
||||
/// DE × morph × deep × BLA), for every fragment entry point.
|
||||
#[test]
|
||||
fn mandelbrot_shader_specializations_compile() {
|
||||
let (module, info) = validate("mandelbrot.wgsl", MANDELBROT_SRC);
|
||||
@@ -86,12 +86,20 @@ fn mandelbrot_shader_specializations_compile() {
|
||||
for de in [0.0, 1.0] {
|
||||
for morph in [0.0, 1.0] {
|
||||
for deep in [0.0, 1.0] {
|
||||
// BLA only exists for plain Mandelbrot (`bla::supported`).
|
||||
let blas: &[f64] = if kind == 0 && morph == 0.0 {
|
||||
&[0.0, 1.0]
|
||||
} else {
|
||||
&[0.0]
|
||||
};
|
||||
for &bla in blas {
|
||||
let constants = [
|
||||
("KIND", kind as f64),
|
||||
("IS_JULIA", julia),
|
||||
("DE", de),
|
||||
("MORPH", morph),
|
||||
("DEEP", deep),
|
||||
("BLA", bla),
|
||||
];
|
||||
for entry in ["fs_data", "fs_refine", "fs_color"] {
|
||||
specialize(
|
||||
@@ -109,6 +117,7 @@ fn mandelbrot_shader_specializations_compile() {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn colorize_shader_is_valid() {
|
||||
|
||||
Reference in New Issue
Block a user