Compare commits
11
Commits
5f4207b6fd
...
webgl
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0884944137 | ||
|
|
553a486d79 | ||
|
|
437a7249f4 | ||
|
|
fccf6ea50f | ||
|
|
ca9f172758 | ||
|
|
4a14f80b76 | ||
|
|
833859b974 | ||
|
|
289cfb2976 | ||
|
|
825bf6474a | ||
|
|
52e1814266 | ||
|
|
91360a1e1c |
@@ -15,14 +15,14 @@ once a pixel is ~2^-124 wide (~10³⁴× at 1080p), so from 2^-122 per pixel
|
||||
rescaled deltas (f32 mantissa × 2^i32). There's no practical depth limit:
|
||||
`half_height` is a `view::Scale` (f64 mantissa × 2^i32), floored only at
|
||||
`Scale::MIN` = 2^-(2^20) to keep shader exponent sums in i32. Runs
|
||||
natively (Vulkan/Metal/DX12) and in the browser (WebGPU only — WebGL2 can't do
|
||||
storage buffers, which the fragment shader needs for the reference orbit).
|
||||
natively (Vulkan/Metal/DX12) and in the browser: WebGPU, plus a WebGL2
|
||||
fallback with the `webgl` feature (see "WebGL2 fallback" below).
|
||||
|
||||
## Commands
|
||||
|
||||
```sh
|
||||
cargo run --release # native, run (release matters: fractal math is hot)
|
||||
cargo test # reference-orbit math, share-link round-trip, WGSL validation
|
||||
cargo test # reference-orbit math, share-link round-trip, WGSL validation (+ GLSL ES 3.00 via glslangValidator if installed)
|
||||
cargo test --features wasm # same, on the web build's malachite big-float backend
|
||||
cargo test --test shader_valid # just the WGSL parse/validate tests (naga, no GPU needed)
|
||||
cargo clippy
|
||||
@@ -31,12 +31,12 @@ cargo build --release --no-default-features # headless-only binary: no eframe/
|
||||
tools/bench/bench.sh --rev HEAD # perf of uncommitted edits vs HEAD (hyperfine; see tools/bench/README.md)
|
||||
```
|
||||
|
||||
Web build (WebGPU):
|
||||
Web build (WebGPU, with WebGL2 fallback):
|
||||
|
||||
```sh
|
||||
rustup target add wasm32-unknown-unknown
|
||||
cargo install wasm-bindgen-cli --version 0.2.128 # must match the wasm-bindgen crate version
|
||||
./build-web.sh # -> ./dist (builds with --features wasm)
|
||||
./build-web.sh # -> ./dist (builds with --features wasm,webgl)
|
||||
python3 -m http.server -d dist 8080
|
||||
```
|
||||
|
||||
@@ -54,7 +54,16 @@ window/event loop. Not yet supported with `--buddhabrot`. With
|
||||
`--auto-color-scale`, a downscaled 1-spp `fs_data` prepass
|
||||
(`ExportRender::ci_range_blocking`, ≤ 1024 px) is histogrammed like the
|
||||
interactive `CiStats`. The fit is then written into the export's uniforms,
|
||||
and animations refit every frame from the same start. Run
|
||||
and animations refit every frame from the same start. With auto-iterations,
|
||||
a still whose full orbit would be costly (`orbit_secs` > `PROBE_MIN_SECS`)
|
||||
computes only a prefix (8192 steps, then ×4) and probes it with the same
|
||||
prepass (`max_escape_blocking`): the shader treats an exhausted reference
|
||||
as an escape, so once the last probe escape is under half the prefix the
|
||||
image is unchanged (c = -1.5 at 1e-1000 needs ~10k of the 900k auto steps).
|
||||
Device setup runs on a thread meanwhile. Stills and animation frames share
|
||||
this loop (`Exporter::build`). In animations, probed frames' prefixes start
|
||||
at 4× the last probe's escape (`len_hint`) and are computed just in time,
|
||||
at most `PROBE_LAG` frames ahead of the GPU, so the hint is recent. Run
|
||||
`mandelbrot --help` for the full list.
|
||||
|
||||
`--headless` also has an animation mode, for feeding into `ffmpeg`: give any
|
||||
@@ -95,7 +104,9 @@ state is a pure function of `t` (`apply_frame`), so all frames'
|
||||
`FractalApp::reference_job`s are snapshotted up front and `RefJob::compute`d
|
||||
by a worker pool. The main thread renders them on the GPU as they arrive
|
||||
(out of order), and another pool PNG-encodes and writes them
|
||||
(`encode_png`, `Compression::Fast`). Channels are bounded. Once orbits and
|
||||
(`encode_png`). PNGs (stills too) default to `Compression::Fast`
|
||||
(`--png-compression`): the default zlib level took longer than a deep
|
||||
render itself, for ~7% smaller files. Channels are bounded. Once orbits and
|
||||
encoding are off the main thread, the GPU is usually the bottleneck.
|
||||
|
||||
There's no GPU in most sandboxes: `cargo check`/`cargo test --test shader_valid`
|
||||
@@ -113,7 +124,12 @@ For a pixel at parameter `c = C_ref + dc`, its orbit is written as
|
||||
and `e_n` is a small `f32` delta. Whenever `|y_n| < |e_n|` (or the reference
|
||||
runs out), rebase: `e ← y_n − X_0`, restart the reference index at 0. This is
|
||||
what makes deep zoom cheap — one expensive high-precision orbit, then every
|
||||
pixel is a handful of `f32` complex multiplies.
|
||||
pixel is a handful of `f32` complex multiplies. A rebase whose real part cancels to
|
||||
exactly 0 keeps a rounding-sized one instead (`ROUNDING_X`). On a real
|
||||
reference orbit (views centered on the real axis) the pixel's imaginary part
|
||||
lives only in `e.y`, and the next step scales it by 2·Re z. At exactly 0 the
|
||||
pixel was stuck on the bounded real line, drawn black after `max_iter` steps.
|
||||
That was a few pixels per frame and ~40% of a −1.5 zoom's time.
|
||||
|
||||
- `src/bignum/` — `Big`, the arbitrary-precision binary float, with one
|
||||
backend per library behind the same inherent API + operators: `rug`
|
||||
@@ -176,6 +192,8 @@ pixel is a handful of `f32` complex multiplies.
|
||||
constants) is prepended to every shader. `iterate_uniforms.wgsl` (the
|
||||
perturbation-pipeline `Uniforms` struct + `palette()`) is additionally
|
||||
prepended to `mandelbrot.wgsl` and `colorize.wgsl`, which share that layout.
|
||||
`mandelbrot.wgsl` is followed by a data fragment, picked at runtime
|
||||
(`GpuPath::mandelbrot_source`): `data_storage.wgsl` or `data_texture.wgsl`.
|
||||
Because there's no namespacing, a definition must live in exactly one file
|
||||
among those concatenated together for a given shader — don't redefine a
|
||||
`common.wgsl`/`iterate_uniforms.wgsl` symbol locally.
|
||||
@@ -197,7 +215,11 @@ pixel is a handful of `f32` complex multiplies.
|
||||
window saves its iterate closest to the critical point, not the one at the
|
||||
checkpoint. At an arbitrary phase the relative tolerance is far coarser
|
||||
than a deep minibrot's scale, and a black disk surrounded the minibrot
|
||||
(seen at ~1e-13 zoom). Phoenix is excluded (two-term map).
|
||||
(seen at ~1e-13 zoom). Phoenix is excluded (two-term map). Both
|
||||
tests only run on steps where |z|² is at most the saved iterate's (with
|
||||
slack) or below the window's closest so far. Anything else can't pass
|
||||
them, so the result is unchanged. Before that gate, the per-step checks
|
||||
took ~18% of a seahorse zoom.
|
||||
`advance_delta(z, e)` is the per-kind delta step (`z` = reference point,
|
||||
`e` = current delta); the caller adds `step_add` (= `dc`) afterward — this
|
||||
relies on `c` being additive in every current kind's formula (a kind where
|
||||
@@ -242,7 +264,17 @@ pixel is a handful of `f32` complex multiplies.
|
||||
The deep path is exact at any depth: forcing it everywhere (raise
|
||||
`DEEP_PIXEL_SIZE`, raise `DEEP_EXIT_LOG2` to about -8) must reproduce the
|
||||
plain f32 renders on non-chaotic views. That's the check to rerun after
|
||||
changing it. Known gaps: Lambda's critical point is 1/2, so its step keeps
|
||||
changing it. At minibrot depths (seahorse 1e-200) this prologue is most
|
||||
of the render. The reference passes near 0 once per period, which the
|
||||
aligned BLA levels cut into ~10 jumps plus up to 8 plain steps; BLA
|
||||
segments (below) make that one jump and a plain step. It's ALU-bound,
|
||||
so `ldexp_sat` adds to the exponent bits for normal inputs. Measured no
|
||||
help: reading `frexp`'s exponent from the bits, a branchless
|
||||
`ldexp_sat`, uploading BLA levels 1–2. Shallower deep frames (seahorse
|
||||
1e-100) are instead ~500 genuinely nonlinear f32 steps per pixel (the
|
||||
valley's slow spiral), where only per-step instructions matter: that
|
||||
loop tests the level alignment before `log2_mag` and the lookup, and
|
||||
doesn't track segments (tracking them there cost 11%). 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
|
||||
@@ -261,8 +293,14 @@ pixel is a handful of `f32` complex multiplies.
|
||||
what makes deep zoom fast: every pixel follows the reference for tens of
|
||||
thousands of steps before diverging (Mandelbrot 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, 48 B nodes, `bla_meta` =
|
||||
`[min_level, levels, offsets…]`). Coefficients are floatexp (f32
|
||||
levels ≥ 3 are uploaded (built across cores, `par_map`; bindings 4/5, 48 B nodes, `bla_meta` =
|
||||
`[min_level, levels, offsets…, seg_count, seg_starts…]`). **Segments**
|
||||
add one node per run between "bad" steps (own radius < 2^-40, i.e.
|
||||
`|X| < 2^-12` for Mandelbrot: near-zero passes, fold lines), from step 1
|
||||
and from just after each bad step, where pixels land after stepping over
|
||||
one or rebasing. Only the deep prologue uses them (`bla_jump`, with a
|
||||
per-pixel cursor `seg_i`/`seg_at` reset on rebase), falling back to the
|
||||
levels. Coefficients are floatexp (f32
|
||||
mantissas + 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 or kind
|
||||
@@ -341,6 +379,45 @@ histogram buffer, tone-mapped by a fragment pass every frame. Its own
|
||||
`KIND_*` iteration formulas in `advance()` must be kept in sync with
|
||||
`reference.rs` by hand (there's no shared code path).
|
||||
|
||||
### WebGL2 fallback (`GpuPath` in `renderer.rs`)
|
||||
|
||||
WebGL2 has no storage buffers and no compute shaders, and naga's GLSL ES 3.00
|
||||
output can't use `ldexp`/`findLSB` (ES 3.10) or a correct `frexp` (its
|
||||
polyfill goes through log2). So `mandelbrot.wgsl` never touches bindings
|
||||
1/3/4/5 or those builtins directly. It calls accessors (`ref_point`,
|
||||
`ref_exp_at`, `bla_node`, `bla_r_log2`, `bla_steps`, `bla_meta_at`) and
|
||||
`frexp_f32`/`ldexp_f32`/`ctz_u32`, defined by one of two data fragments,
|
||||
which must stay in sync:
|
||||
- `data_storage.wgsl` (`GpuPath::Storage`): the storage buffers and native
|
||||
builtins. Every device with ≥ 4 fragment storage buffers uses it. The
|
||||
benchmarks showed no change from before the split.
|
||||
- `data_texture.wgsl` (`GpuPath::Texture`): each array as a
|
||||
`DATA_TEX_WIDTH` (2048)-wide texture, BLA nodes as 3 `Rgba32Uint` texels
|
||||
with floats as raw bits, plus bit-exact builtin replacements. It is about
|
||||
6–16% slower on a GTX 1650, so it's only used when the device has no
|
||||
storage buffers. `RefData`/`DataArray` own either form. Orbit length is
|
||||
capped at 2048 × the max texture height (`ref_len` is clamped on upload),
|
||||
and a BLA table that doesn't fit is replaced by the empty one.
|
||||
- Natively, `MANDELBROT_GPU_PATH=texture|storage` forces a path. Renders
|
||||
must be pixel-identical between the two (headless, any view,
|
||||
`WGPU_BACKEND=gl` too). That's the check to rerun after touching either
|
||||
fragment.
|
||||
|
||||
The texture path also replaces the compute `ci` histogram with
|
||||
`CiHistogram::Readback`: `ci_sample.wgsl` point-samples a 256² grid, which
|
||||
is read back and binned on the CPU. Buddhabrot (compute + atomics) is
|
||||
disabled on such devices (`FractalApp::buddhabrot_supported`). The `webgl`
|
||||
cargo feature only adds `Backends::GL` on wasm32. egui-wgpu still tries
|
||||
WebGPU first, and eframe's defaults already compile wgpu's WebGL backend.
|
||||
`?backend=webgl` (`web_forced_webgl` in `main.rs`) forces WebGL2. The
|
||||
Advanced section's "Use WebGPU" checkbox (`FractalApp::backend_ui`) sets or
|
||||
clears it by reloading the page, with the view in the fragment: the backend
|
||||
can't change in place, because a canvas with a WebGPU context can't get a
|
||||
WebGL2 one.
|
||||
`tests/shader_valid.rs` translates every texture-path specialization to
|
||||
GLSL ES 3.00 and compiles it with `glslangValidator` when that's on the
|
||||
PATH.
|
||||
|
||||
### Two-pass render + caching (`renderer.rs`)
|
||||
|
||||
The interactive path splits iteration (expensive, perturbation) from
|
||||
|
||||
+7
-1
@@ -10,6 +10,12 @@ gui = ["dep:eframe", "dep:egui"]
|
||||
# Pure-Rust big floats for the web build (`rug` needs GMP/MPFR, which can't
|
||||
# target wasm32). Required for wasm32, optional natively (to test that backend).
|
||||
wasm = ["dep:malachite-float", "dep:malachite-base"]
|
||||
# Web build: fall back to WebGL2 when the browser has no WebGPU (WebGPU is
|
||||
# still preferred). WebGL2 has no storage buffers or compute shaders, so the
|
||||
# fractal shader then reads its data from textures (`GpuPath::Texture`, a bit
|
||||
# slower) and Buddhabrot mode is unavailable. No effect natively, where the
|
||||
# path is picked from the device's limits anyway.
|
||||
webgl = []
|
||||
|
||||
[dependencies]
|
||||
bytemuck = { version = "1.25.2", features = ["derive"] }
|
||||
@@ -53,4 +59,4 @@ opt-level = 1
|
||||
opt-level = 3
|
||||
|
||||
[dev-dependencies]
|
||||
naga = { version = "30", features = ["wgsl-in", "spv-out"] }
|
||||
naga = { version = "30", features = ["wgsl-in", "spv-out", "glsl-out"] }
|
||||
|
||||
+3
-2
@@ -1,14 +1,15 @@
|
||||
#!/usr/bin/env bash
|
||||
# Build the WebAssembly bundle into ./dist using wasm-bindgen.
|
||||
# Serve it over HTTP (e.g. `python3 -m http.server -d dist 8080`) and open in a
|
||||
# WebGPU-capable browser (recent Chrome/Edge, Firefox, or Safari 26+).
|
||||
# WebGPU-capable browser (recent Chrome/Edge, Firefox, or Safari 26+); the
|
||||
# `webgl` feature falls back to WebGL2 elsewhere (no Buddhabrot there).
|
||||
set -euo pipefail
|
||||
|
||||
export PATH="$HOME/.cargo/bin:$PATH"
|
||||
OUT="${1:-dist}"
|
||||
|
||||
echo "==> cargo build (wasm32, release)"
|
||||
cargo build --release --target wasm32-unknown-unknown --features wasm
|
||||
cargo build --release --target wasm32-unknown-unknown --features wasm,webgl
|
||||
|
||||
echo "==> wasm-bindgen -> $OUT"
|
||||
mkdir -p "$OUT"
|
||||
|
||||
+3
-2
@@ -46,8 +46,9 @@
|
||||
const msg = (err && err.message) || String(err);
|
||||
if (!msg.includes("Using exceptions for control flow")) {
|
||||
document.getElementById("loading_text").innerHTML =
|
||||
"<p>Failed to start. This app needs a WebGPU-capable browser " +
|
||||
"(recent Chrome/Edge, Firefox, or Safari 26+).</p>";
|
||||
"<p>Failed to start. This app needs WebGPU (recent Chrome/Edge, " +
|
||||
"Firefox, or Safari 26+) or, in builds with the <code>webgl</code> " +
|
||||
"feature, WebGL2 with float render targets.</p>";
|
||||
console.error(err);
|
||||
}
|
||||
});
|
||||
|
||||
+195
-36
@@ -197,6 +197,32 @@ pub(crate) struct RefJob {
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
impl RefJob {
|
||||
/// Orbit steps this job computes.
|
||||
pub(crate) fn steps(&self) -> u32 {
|
||||
self.key.iter
|
||||
}
|
||||
|
||||
/// Working precision, in bits.
|
||||
pub(crate) fn precision(&self) -> usize {
|
||||
self.precision
|
||||
}
|
||||
|
||||
/// This job with the orbit cut after `len` steps. `max_iterations` is
|
||||
/// unchanged: the shader treats the exhausted reference as an escape, so
|
||||
/// the render only differs if some pixel gets that far (headless probes
|
||||
/// for that before paying for the whole orbit).
|
||||
pub(crate) fn prefix(&self, len: u32) -> RefJob {
|
||||
let mut job = self.clone();
|
||||
job.key.iter = job.key.iter.min(len);
|
||||
job
|
||||
}
|
||||
|
||||
/// Whether `points`, computed for this job, is the whole orbit `full`
|
||||
/// steps would give: not cut, or the reference escaped before the cut.
|
||||
pub(crate) fn is_whole(&self, full: u32, points: &RefOrbit) -> bool {
|
||||
self.key.iter >= full || points.len() <= self.key.iter as usize
|
||||
}
|
||||
|
||||
/// Iterate the reference orbit at full precision (the expensive part).
|
||||
pub(crate) fn compute(&self) -> RefOrbit {
|
||||
let key = &self.key;
|
||||
@@ -571,6 +597,10 @@ pub struct FractalApp {
|
||||
/// Keep dispatching new sample batches every frame (progressive
|
||||
/// accumulation). Turning it off freezes the current histogram.
|
||||
buddha_accumulate: bool,
|
||||
/// The device can run Buddhabrot mode's compute pass (not on WebGL2).
|
||||
buddhabrot_supported: bool,
|
||||
/// Backend the renderer runs on (`None` without a GPU, i.e. headless).
|
||||
gpu_backend: Option<wgpu::Backend>,
|
||||
/// Whether the controls side panel is expanded. Collapsible so the fractal
|
||||
/// can take (nearly) the whole screen — important on a phone.
|
||||
controls_open: bool,
|
||||
@@ -691,16 +721,54 @@ impl FractalApp {
|
||||
.as_ref()
|
||||
.expect("eframe must run with the wgpu backend");
|
||||
|
||||
let adapter_info = render_state.adapter.get_info();
|
||||
// The iteration data textures are `Rgba32Float` render targets
|
||||
// (`EXT_color_buffer_float` on WebGL2, which nearly every browser has).
|
||||
if !render_state
|
||||
.adapter
|
||||
.get_texture_format_features(wgpu::TextureFormat::Rgba32Float)
|
||||
.allowed_usages
|
||||
.contains(wgpu::TextureUsages::RENDER_ATTACHMENT)
|
||||
{
|
||||
panic!(
|
||||
"this GPU / browser can't render to 32-bit float textures \
|
||||
({:?} on {})",
|
||||
adapter_info.backend, adapter_info.name
|
||||
);
|
||||
}
|
||||
let renderer = FractalRenderer::new(&render_state.device, render_state.target_format);
|
||||
let buddhabrot_renderer =
|
||||
BuddhabrotRenderer::new(&render_state.device, render_state.target_format);
|
||||
log::info!(
|
||||
"GPU: {} ({:?}), data path {:?}",
|
||||
adapter_info.name,
|
||||
adapter_info.backend,
|
||||
renderer.gpu_path()
|
||||
);
|
||||
// Buddhabrot accumulates with a compute pass and reads its histogram
|
||||
// from a storage buffer in the fragment stage.
|
||||
let buddhabrot_supported = render_state
|
||||
.adapter
|
||||
.get_downlevel_capabilities()
|
||||
.flags
|
||||
.contains(wgpu::DownlevelFlags::COMPUTE_SHADERS)
|
||||
&& render_state
|
||||
.device
|
||||
.limits()
|
||||
.max_storage_buffers_per_shader_stage
|
||||
>= 1;
|
||||
{
|
||||
let mut guard = render_state.renderer.write();
|
||||
guard.callback_resources.insert(renderer);
|
||||
guard.callback_resources.insert(buddhabrot_renderer);
|
||||
if buddhabrot_supported {
|
||||
guard.callback_resources.insert(BuddhabrotRenderer::new(
|
||||
&render_state.device,
|
||||
render_state.target_format,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
let mut app = Self::default_state();
|
||||
app.buddhabrot_supported = buddhabrot_supported;
|
||||
app.gpu_backend = Some(adapter_info.backend);
|
||||
|
||||
// On the web, restore a shared view from the URL fragment (#...).
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
@@ -760,6 +828,8 @@ impl FractalApp {
|
||||
buddha_exposure: 1.0,
|
||||
buddha_palette: 0,
|
||||
buddha_accumulate: true,
|
||||
buddhabrot_supported: true,
|
||||
gpu_backend: None,
|
||||
controls_open: true,
|
||||
fullscreen: false,
|
||||
info_open: false,
|
||||
@@ -964,7 +1034,7 @@ impl FractalApp {
|
||||
}
|
||||
|
||||
/// Force `max_iterations` to auto-scale with zoom depth on every
|
||||
/// subsequent `compute_reference_blocking` call. Used by headless
|
||||
/// subsequent `reference_job` call. Used by headless
|
||||
/// animation so iteration count keeps pace with the camera zooming in,
|
||||
/// the same way it does while dragging/zooming interactively.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -1138,6 +1208,32 @@ impl FractalApp {
|
||||
}
|
||||
}
|
||||
|
||||
/// Web "Use WebGPU" toggle. The backend is fixed when the page starts (a
|
||||
/// canvas with a WebGPU context can't get a WebGL2 one), so switching
|
||||
/// reloads the page with or without `?backend=webgl`, keeping the view
|
||||
/// in the URL fragment.
|
||||
#[cfg(all(target_arch = "wasm32", feature = "webgl"))]
|
||||
fn backend_ui(&mut self, ui: &mut egui::Ui) {
|
||||
let on_webgpu = self.gpu_backend == Some(wgpu::Backend::BrowserWebGpu);
|
||||
// On WebGL2 without the override, WebGPU was tried and failed.
|
||||
let available = on_webgpu || (crate::web_forced_webgl() && web_has_webgpu());
|
||||
let mut use_webgpu = on_webgpu;
|
||||
let toggled = ui
|
||||
.add_enabled(
|
||||
available,
|
||||
egui::Checkbox::new(&mut use_webgpu, "Use WebGPU"),
|
||||
)
|
||||
.on_hover_text(
|
||||
"WebGPU is faster and supports Buddhabrot mode; WebGL2 is the \
|
||||
fallback. Switching reloads the page (the view is kept).",
|
||||
)
|
||||
.on_disabled_hover_text("This browser can't run WebGPU here: using WebGL2.")
|
||||
.changed();
|
||||
if toggled {
|
||||
web_reload_with_backend(use_webgpu, &self.share_state().encode());
|
||||
}
|
||||
}
|
||||
|
||||
/// A full shareable URL. On web this is the page URL with a `#fragment`; on
|
||||
/// native (no page) it is just the fragment for pasting onto a deployment.
|
||||
fn share_url(&self) -> String {
|
||||
@@ -1427,22 +1523,15 @@ impl FractalApp {
|
||||
}
|
||||
}
|
||||
|
||||
/// Compute the reference orbit for the current view synchronously, on the
|
||||
/// calling thread — unlike `ensure_reference`, which dispatches to the
|
||||
/// native worker (or, on wasm, computes inline but still runs once per
|
||||
/// frame poll). Used by headless rendering, which has no frame loop to
|
||||
/// poll a background result on and only ever needs one reference.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn compute_reference_blocking(&mut self) {
|
||||
let job = self.reference_job();
|
||||
let points = job.compute();
|
||||
self.finish_reference(job, points);
|
||||
pub(crate) fn auto_iterations(&self) -> bool {
|
||||
self.auto_iterations
|
||||
}
|
||||
|
||||
/// Snapshot everything the reference orbit for the current view depends
|
||||
/// on, as a self-contained job that can be computed on another thread
|
||||
/// (headless animation computes many frames' orbits in parallel). Also
|
||||
/// applies auto-iterations, like `compute_reference_blocking`.
|
||||
/// applies auto-iterations.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
pub(crate) fn reference_job(&mut self) -> RefJob {
|
||||
if self.auto_iterations {
|
||||
@@ -1719,10 +1808,13 @@ impl FractalApp {
|
||||
&device, &queue, &handles, w, h, uniforms, &reference, &bla, &lights,
|
||||
);
|
||||
let sh = Arc::clone(&shared);
|
||||
let png =
|
||||
crate::fractal::export_to_png_blocking(&device, &queue, &er, |phase, f| {
|
||||
set_progress(&sh, phase, f)
|
||||
});
|
||||
let png = crate::fractal::export_to_png_blocking(
|
||||
&device,
|
||||
&queue,
|
||||
&er,
|
||||
png::Compression::Fast,
|
||||
|phase, f| set_progress(&sh, phase, f),
|
||||
);
|
||||
|
||||
set_progress(&shared, "Saving", 0.98);
|
||||
let result = std::fs::write(&name, &png)
|
||||
@@ -1741,16 +1833,18 @@ impl FractalApp {
|
||||
&device, &queue, &handles, w, h, uniforms, &reference, &bla, &lights,
|
||||
);
|
||||
|
||||
// Render tile by tile, awaiting each submission so the browser
|
||||
// executes it and the UI can repaint between tiles.
|
||||
for t in 0..er.tiles {
|
||||
er.render_tile(&device, &queue, t);
|
||||
// Render band by band, awaiting each submission so the browser
|
||||
// executes it and the UI can repaint between bands. (No
|
||||
// `Instant` here to time them, so bands keep the safe height.)
|
||||
let rows = er.band_sizer().rows();
|
||||
for y0 in (0..er.height).step_by(rows as usize) {
|
||||
er.render_band(&device, &queue, y0, y0 + rows);
|
||||
let (tx, rx) = futures_channel::oneshot::channel();
|
||||
queue.on_submitted_work_done(move || {
|
||||
let _ = tx.send(());
|
||||
});
|
||||
let _ = rx.await;
|
||||
let done = (t + 1) as f32 / er.tiles as f32;
|
||||
let done = (y0 + rows).min(er.height) as f32 / er.height as f32;
|
||||
set_progress(&shared, "Rendering", RENDER_END * done);
|
||||
}
|
||||
er.copy_to_readback(&device, &queue);
|
||||
@@ -1777,6 +1871,7 @@ impl FractalApp {
|
||||
er.height,
|
||||
er.padded_bpr,
|
||||
er.swap_rb,
|
||||
png::Compression::Fast,
|
||||
|f| set_progress(&sh, "Encoding", RENDER_END + (0.97 - RENDER_END) * f),
|
||||
)
|
||||
};
|
||||
@@ -2266,7 +2361,9 @@ impl FractalApp {
|
||||
}
|
||||
});
|
||||
if self.kind == FractalKind::Multibrot {
|
||||
ui.add(egui::Slider::new(&mut self.power, 2..=20).text("power"));
|
||||
deferred_slider(ui, &mut self.power, "power", |v| {
|
||||
egui::Slider::new(v, 2..=20).text("power")
|
||||
});
|
||||
}
|
||||
if self.kind == FractalKind::Phoenix {
|
||||
ui.horizontal(|ui| {
|
||||
@@ -2324,12 +2421,18 @@ impl FractalApp {
|
||||
ui.horizontal(|ui| {
|
||||
ui.radio_value(&mut self.mode, FractalMode::Mandelbrot, "Set");
|
||||
ui.radio_value(&mut self.mode, FractalMode::Julia, "Julia");
|
||||
ui.radio_value(&mut self.mode, FractalMode::Buddhabrot, "Buddhabrot")
|
||||
.on_hover_text(
|
||||
"Monte-Carlo density of escaping orbits instead of the ordinary \
|
||||
ui.add_enabled(
|
||||
self.buddhabrot_supported,
|
||||
egui::RadioButton::new(self.mode == FractalMode::Buddhabrot, "Buddhabrot"),
|
||||
)
|
||||
.on_hover_text(
|
||||
"Monte-Carlo density of escaping orbits instead of the ordinary \
|
||||
escape-time set. Plain f32 view (no deep zoom); the image \
|
||||
progressively sharpens while the view stays still.",
|
||||
);
|
||||
)
|
||||
.on_disabled_hover_text("Needs compute shaders (WebGPU); not available on WebGL2.")
|
||||
.clicked()
|
||||
.then(|| self.mode = FractalMode::Buddhabrot);
|
||||
});
|
||||
if self.mode != prev_mode {
|
||||
self.morph = None;
|
||||
@@ -2405,11 +2508,13 @@ impl FractalApp {
|
||||
});
|
||||
if self.rendering_mode == 2 {
|
||||
let old_scale = self.render_scale_3d;
|
||||
ui.add(egui::Slider::new(&mut self.render_scale_3d, 1.0..=4.0).text("3D render scale"))
|
||||
.on_hover_text(
|
||||
"Resolution multiplier of the 3D height field. Higher shows more \
|
||||
deferred_slider(ui, &mut self.render_scale_3d, "render_scale_3d", |v| {
|
||||
egui::Slider::new(v, 1.0..=4.0).text("3D render scale")
|
||||
})
|
||||
.on_hover_text(
|
||||
"Resolution multiplier of the 3D height field. Higher shows more \
|
||||
distant detail but costs GPU time and memory.",
|
||||
);
|
||||
);
|
||||
// The 3D camera zooms in by the render scale (`Camera::orthographic`):
|
||||
// zoom the view out by the same ratio so the fractal keeps its
|
||||
// on-screen size and the extra texels become surrounding terrain.
|
||||
@@ -2430,12 +2535,12 @@ impl FractalApp {
|
||||
} else {
|
||||
// Dragging stays within the slider's range, but a typed value
|
||||
// isn't clamped to it: only to what the reference buffer can hold.
|
||||
ui.add(
|
||||
egui::Slider::new(&mut self.max_iterations, 32..=100_000)
|
||||
deferred_slider(ui, &mut self.max_iterations, "max_iterations", |v| {
|
||||
egui::Slider::new(v, 32..=100_000)
|
||||
.text("iterations")
|
||||
.logarithmic(true)
|
||||
.clamping(egui::SliderClamping::Never),
|
||||
);
|
||||
.clamping(egui::SliderClamping::Never)
|
||||
});
|
||||
self.max_iterations = self.max_iterations.clamp(32, MAX_ITERATIONS);
|
||||
}
|
||||
ui.checkbox(&mut self.antialias, "Antialiasing (2×2)")
|
||||
@@ -2538,6 +2643,8 @@ impl FractalApp {
|
||||
more FPS at deep zoom but a blurrier image in motion; full \
|
||||
resolution returns once input settles.",
|
||||
);
|
||||
#[cfg(all(target_arch = "wasm32", feature = "webgl"))]
|
||||
self.backend_ui(ui);
|
||||
});
|
||||
|
||||
ui.collapsing("Animation", |ui| {
|
||||
@@ -3150,6 +3257,11 @@ impl FractalApp {
|
||||
#[cfg(feature = "gui")]
|
||||
impl eframe::App for FractalApp {
|
||||
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
|
||||
// A CLI flag can ask for Buddhabrot on a device that can't run it.
|
||||
if !self.buddhabrot_supported && self.mode == FractalMode::Buddhabrot {
|
||||
self.mode = FractalMode::Mandelbrot;
|
||||
self.status = Some("Buddhabrot mode needs WebGPU compute shaders".into());
|
||||
}
|
||||
self.poll_export(ui.ctx());
|
||||
self.poll_ci_stats(ui.ctx(), frame);
|
||||
self.update_fps(ui);
|
||||
@@ -3194,6 +3306,32 @@ impl eframe::App for FractalApp {
|
||||
}
|
||||
}
|
||||
|
||||
/// A slider whose value is expensive to apply (a new reference orbit, a full
|
||||
/// re-iteration or a resized 3D height field): while it's dragged, it moves a
|
||||
/// preview copy kept in egui's temp memory, and `value` only takes it on
|
||||
/// release (or on a click / typed value, which aren't drags). Applying it live
|
||||
/// froze the UI for the whole render each step, and the mouse moves and
|
||||
/// release queued meanwhile all landed in one later frame: the slider then
|
||||
/// jumped to wherever the pointer had gone since, so a second render ran.
|
||||
#[cfg(feature = "gui")]
|
||||
fn deferred_slider<N: egui::emath::Numeric + Send + Sync>(
|
||||
ui: &mut egui::Ui,
|
||||
value: &mut N,
|
||||
id_salt: &str,
|
||||
slider: impl for<'a> FnOnce(&'a mut N) -> egui::Slider<'a>,
|
||||
) -> egui::Response {
|
||||
let id = ui.make_persistent_id(id_salt);
|
||||
let mut shown = ui.data(|d| d.get_temp::<N>(id)).unwrap_or(*value);
|
||||
let response = ui.add(slider(&mut shown));
|
||||
if response.dragged() && !response.drag_stopped() {
|
||||
ui.data_mut(|d| d.insert_temp(id, shown));
|
||||
} else {
|
||||
ui.data_mut(|d| d.remove::<N>(id));
|
||||
*value = shown;
|
||||
}
|
||||
response
|
||||
}
|
||||
|
||||
/// Reference-orbit length to request for `max_iterations`: 1.5× headroom
|
||||
/// (capped at the GPU buffer size). Auto-iterations grows with every zoom
|
||||
/// frame, and without headroom each tiny increase re-ran the whole
|
||||
@@ -3258,6 +3396,27 @@ fn web_location_hash() -> Option<String> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The browser exposes WebGPU (`navigator.gpu`); an adapter may still fail.
|
||||
#[cfg(all(target_arch = "wasm32", feature = "webgl"))]
|
||||
fn web_has_webgpu() -> bool {
|
||||
web_sys::window()
|
||||
.and_then(|w| js_sys::Reflect::get(&w.navigator(), &"gpu".into()).ok())
|
||||
.is_some_and(|gpu| !gpu.is_undefined() && !gpu.is_null())
|
||||
}
|
||||
|
||||
/// Reload the page on WebGPU (preferred) or forced WebGL2, at the view
|
||||
/// `fragment`.
|
||||
#[cfg(all(target_arch = "wasm32", feature = "webgl"))]
|
||||
fn web_reload_with_backend(webgpu: bool, fragment: &str) {
|
||||
let Some(loc) = web_sys::window().map(|w| w.location()) else {
|
||||
return;
|
||||
};
|
||||
let origin = loc.origin().unwrap_or_default();
|
||||
let path = loc.pathname().unwrap_or_default();
|
||||
let query = if webgpu { "" } else { "?backend=webgl" };
|
||||
let _ = loc.replace(&format!("{origin}{path}{query}#{fragment}"));
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
fn web_download_png(bytes: &[u8], filename: &str) {
|
||||
use wasm_bindgen::JsCast as _;
|
||||
|
||||
+24
@@ -107,6 +107,12 @@ pub struct Cli {
|
||||
#[arg(long, value_name = "PATH")]
|
||||
pub export_path: Option<String>,
|
||||
|
||||
/// PNG compression for --headless output. "fast" encodes several times
|
||||
/// quicker (at 1080p it otherwise takes longer than a deep render
|
||||
/// itself) for somewhat larger files; "balanced"/"high" for smaller ones.
|
||||
#[arg(long, value_enum, default_value_t = PngCompressionArg::Fast)]
|
||||
pub png_compression: PngCompressionArg,
|
||||
|
||||
/// End view for an animation: "re,im,half_height[,iterations]", the same
|
||||
/// syntax as --view. Combine with --view (or --share, --kind, --julia...)
|
||||
/// for the start view; headless then renders a sequence of frames
|
||||
@@ -244,6 +250,24 @@ pub enum KindArg {
|
||||
ComplexMultibrot,
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, Default, ValueEnum)]
|
||||
pub enum PngCompressionArg {
|
||||
#[default]
|
||||
Fast,
|
||||
Balanced,
|
||||
High,
|
||||
}
|
||||
|
||||
impl From<PngCompressionArg> for png::Compression {
|
||||
fn from(c: PngCompressionArg) -> Self {
|
||||
match c {
|
||||
PngCompressionArg::Fast => png::Compression::Fast,
|
||||
PngCompressionArg::Balanced => png::Compression::Balanced,
|
||||
PngCompressionArg::High => png::Compression::High,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Copy, Clone, Debug, ValueEnum)]
|
||||
pub enum RenderingKindArg {
|
||||
Classic,
|
||||
|
||||
+157
-25
@@ -48,12 +48,25 @@ const EPSILON_LOG2: i32 = -28;
|
||||
/// table at 12 bytes per orbit point.
|
||||
const MIN_LEVEL: u32 = 3;
|
||||
|
||||
/// A step whose own radius is below `2^SEG_BAD_LOG2` (`|X| < 2^-12` for
|
||||
/// Mandelbrot: a near-zero pass of the reference, or a fold line for the abs
|
||||
/// kinds) ends a segment (see [`build`]).
|
||||
const SEG_BAD_LOG2: f64 = EPSILON_LOG2 as f64 - 12.0;
|
||||
|
||||
/// Shortest segment worth a node (the levels cover shorter runs in a
|
||||
/// lookup or two). Also bounds the segment count to `steps / SEG_MIN_STEPS`.
|
||||
const SEG_MIN_STEPS: usize = 64;
|
||||
|
||||
/// Steps folded per parallel task when building segments.
|
||||
const SEG_CHUNK: usize = 1024;
|
||||
|
||||
/// 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: `M = m·2^m_exp`,
|
||||
/// `N = n·2^n_exp` (row-major 2×2: `[m00, m01, m10, m11]`), valid while
|
||||
/// `log2|e| < r_log2`.
|
||||
/// `log2|e| < r_log2`. `steps` is the run length of a segment node (0 in
|
||||
/// the levels, where it follows from the level).
|
||||
#[repr(C)]
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, bytemuck::Pod, bytemuck::Zeroable)]
|
||||
pub struct GpuBla {
|
||||
@@ -62,7 +75,7 @@ pub struct GpuBla {
|
||||
pub m_exp: i32,
|
||||
pub n_exp: i32,
|
||||
pub r_log2: f32,
|
||||
pub _pad: u32,
|
||||
pub steps: u32,
|
||||
}
|
||||
|
||||
/// `r_log2` of a node that's never valid (f32 `-inf` is fine in WGSL, but a
|
||||
@@ -71,9 +84,11 @@ 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`.
|
||||
/// `meta` is `[min_level, level_count, off_0, …, off_{level_count},
|
||||
/// seg_count, seg_start_0, …]`: 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`. Segment `i` is `nodes[off_{level_count} + i]`
|
||||
/// and covers `steps` steps from `seg_start_i` (ascending); see [`build`].
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct BlaTable {
|
||||
pub nodes: Vec<GpuBla>,
|
||||
@@ -85,7 +100,7 @@ impl BlaTable {
|
||||
pub fn empty() -> Self {
|
||||
Self {
|
||||
nodes: vec![GpuBla::default()],
|
||||
meta: vec![MIN_LEVEL, 0, 0],
|
||||
meta: vec![MIN_LEVEL, 0, 0, 0],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -532,7 +547,7 @@ impl Node {
|
||||
} else {
|
||||
NEVER
|
||||
},
|
||||
_pad: 0,
|
||||
steps: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -567,7 +582,8 @@ pub fn build(
|
||||
};
|
||||
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 {
|
||||
while ((steps >> min_level) * 2 + steps / SEG_MIN_STEPS) * size_of::<GpuBla>() > MAX_TABLE_BYTES
|
||||
{
|
||||
min_level += 1;
|
||||
}
|
||||
if steps >> min_level == 0 {
|
||||
@@ -583,34 +599,131 @@ pub fn build(
|
||||
Fx::new(re as f64, im as f64, orbit.exps[m])
|
||||
};
|
||||
|
||||
// First stored level, folded straight from single steps.
|
||||
// First stored level, folded straight from single steps. The same pass
|
||||
// notes the "bad" steps (tiny radius) that end segments (below).
|
||||
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(map, point(start)), |acc, k| {
|
||||
acc.then(Node::step(map, point(start + k)), dc_max)
|
||||
})
|
||||
})
|
||||
let is_bad = |nd: &Node| nd.r.log2() < SEG_BAD_LOG2;
|
||||
let first: Vec<(Node, Vec<usize>)> = par_map(steps >> min_level, 4096, |i| {
|
||||
let start = 1 + i * run;
|
||||
let mut bad = Vec::new();
|
||||
let mut acc = Node::step(map, point(start));
|
||||
if is_bad(&acc) {
|
||||
bad.push(start);
|
||||
}
|
||||
for m in start + 1..start + run {
|
||||
let nd = Node::step(map, point(m));
|
||||
if is_bad(&nd) {
|
||||
bad.push(m);
|
||||
}
|
||||
acc = acc.then(nd, dc_max);
|
||||
}
|
||||
(acc, bad)
|
||||
});
|
||||
let base: Vec<Node> = first.iter().map(|f| f.0).collect();
|
||||
let tail = 1 + base.len() * run..steps + 1; // past the last whole run
|
||||
let bad: Vec<usize> = first
|
||||
.into_iter()
|
||||
.flat_map(|f| f.1)
|
||||
.chain(tail.filter(|&m| is_bad(&Node::step(map, point(m)))))
|
||||
.collect();
|
||||
|
||||
let mut nodes = Vec::new();
|
||||
let mut meta = vec![min_level, 0];
|
||||
let mut level = base.clone();
|
||||
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();
|
||||
level = par_map(level.len() / 2, 4096, |i| {
|
||||
level[2 * i].then(level[2 * i + 1], dc_max)
|
||||
});
|
||||
}
|
||||
meta[1] = (meta.len() - 2) as u32;
|
||||
meta.push(nodes.len() as u32);
|
||||
|
||||
// Segments: one node per run between bad steps, from step 1 and from
|
||||
// just after each bad step, where a pixel lands after stepping over it
|
||||
// or rebasing. Deep minibrot views pass near 0 once per period, so the
|
||||
// aligned levels cut every period into ~10 jumps plus up to 2^min_level
|
||||
// single steps; a segment crosses it in one.
|
||||
let mut segs = Vec::new();
|
||||
let mut start = 1;
|
||||
for b in bad.into_iter().chain([steps + 1]) {
|
||||
if b >= start + SEG_MIN_STEPS {
|
||||
segs.push((start, b));
|
||||
}
|
||||
start = b + 1;
|
||||
}
|
||||
// Folded in parallel pieces cut at multiples of `chunk` (aligned to the
|
||||
// first level), each from first-level nodes plus single steps at its
|
||||
// ragged ends, then merged in order.
|
||||
let chunk = SEG_CHUNK.max(run);
|
||||
let pieces: Vec<(usize, usize)> = segs
|
||||
.iter()
|
||||
.flat_map(|&(a, b)| {
|
||||
let cuts = (a - 1) / chunk + 1..(b - 2) / chunk + 1;
|
||||
std::iter::once(a)
|
||||
.chain(cuts.map(move |k| 1 + k * chunk))
|
||||
.chain([b])
|
||||
.collect::<Vec<_>>()
|
||||
.windows(2)
|
||||
.map(|w| (w[0], w[1]))
|
||||
.collect::<Vec<_>>()
|
||||
})
|
||||
.collect();
|
||||
let folded = par_map(pieces.len(), 4, |i| {
|
||||
let (a, b) = pieces[i];
|
||||
let mut acc: Option<Node> = None;
|
||||
let mut m = a;
|
||||
while m < b {
|
||||
let aligned = (m - 1) % run == 0 && m + run <= b && (m - 1) / run < base.len();
|
||||
let (nd, k) = if aligned {
|
||||
(base[(m - 1) / run], run)
|
||||
} else {
|
||||
(Node::step(map, point(m)), 1)
|
||||
};
|
||||
acc = Some(acc.map_or(nd, |x| x.then(nd, dc_max)));
|
||||
m += k;
|
||||
}
|
||||
acc.unwrap()
|
||||
});
|
||||
let mut k = 0;
|
||||
for &(a, b) in &segs {
|
||||
let mut seg = folded[k];
|
||||
k += 1;
|
||||
while k < pieces.len() && pieces[k].0 < b && pieces[k].0 > a {
|
||||
seg = seg.then(folded[k], dc_max);
|
||||
k += 1;
|
||||
}
|
||||
nodes.push(GpuBla {
|
||||
steps: (b - a) as u32,
|
||||
..seg.gpu()
|
||||
});
|
||||
}
|
||||
meta.push(segs.len() as u32);
|
||||
meta.extend(segs.iter().map(|&(a, _)| a as u32));
|
||||
BlaTable { nodes, meta }
|
||||
}
|
||||
|
||||
/// `(0..n).map(f).collect()`, split across cores when there are at least
|
||||
/// `min` items, enough work to pay for the threads (a 900k-step table took
|
||||
/// ~60 ms on one core).
|
||||
fn par_map<T: Send>(n: usize, min: usize, f: impl Fn(usize) -> T + Sync) -> Vec<T> {
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if n >= min {
|
||||
let threads = std::thread::available_parallelism().map_or(1, |t| t.get());
|
||||
let chunk = n.div_ceil(threads);
|
||||
let f = &f;
|
||||
return std::thread::scope(|scope| {
|
||||
let parts: Vec<_> = (0..n)
|
||||
.step_by(chunk)
|
||||
.map(|a| scope.spawn(move || (a..(a + chunk).min(n)).map(f).collect::<Vec<T>>()))
|
||||
.collect();
|
||||
parts.into_iter().flat_map(|p| p.join().unwrap()).collect()
|
||||
});
|
||||
}
|
||||
(0..n).map(f).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
@@ -778,13 +891,23 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// Replay the shader's lookup: the longest valid aligned node at `m`,
|
||||
/// of at most `budget` steps.
|
||||
/// Replay the shader's lookup: the segment starting at `m` if it's
|
||||
/// valid, else the longest valid aligned node at `m`, of at most
|
||||
/// `budget` steps.
|
||||
fn lookup(t: &BlaTable, m: usize, e_log2: f64, budget: usize) -> Option<(usize, usize)> {
|
||||
let (lmin, levels) = (t.meta[0], t.meta[1]);
|
||||
if m == 0 || levels == 0 {
|
||||
return None;
|
||||
}
|
||||
let sc = 3 + levels as usize; // seg_count
|
||||
let starts = &t.meta[sc + 1..sc + 1 + t.meta[sc] as usize];
|
||||
if let Ok(i) = starts.binary_search(&(m as u32)) {
|
||||
let idx = t.meta[sc - 1] as usize + i;
|
||||
let nd = &t.nodes[idx];
|
||||
if e_log2 < nd.r_log2 as f64 && nd.steps as usize <= budget {
|
||||
return Some((idx, nd.steps as usize));
|
||||
}
|
||||
}
|
||||
let j = m - 1;
|
||||
let tz = if j == 0 { 32 } else { j.trailing_zeros() };
|
||||
if tz < lmin {
|
||||
@@ -1083,7 +1206,16 @@ mod tests {
|
||||
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 (levels, sc) = (t.levels() as usize, 3 + t.levels() as usize);
|
||||
let seg_count = t.meta[sc] as usize;
|
||||
assert_eq!(t.meta.len(), sc + 1 + seg_count);
|
||||
assert_eq!(t.meta[2 + levels] as usize + seg_count, t.nodes.len());
|
||||
// No bad step in the cardioid: one segment over every step.
|
||||
assert_eq!(seg_count, 1);
|
||||
assert_eq!(
|
||||
(t.meta[sc + 1], t.nodes.last().unwrap().steps),
|
||||
(1, steps as u32)
|
||||
);
|
||||
let tiny = mandel_orbit(-3.0, 0.0, 1000); // escapes at once
|
||||
assert_eq!(build(&tiny, tiny.len(), -30, 1e6, &m).levels(), 0);
|
||||
}
|
||||
|
||||
+994
-405
File diff suppressed because it is too large
Load Diff
+176
-52
@@ -9,14 +9,15 @@
|
||||
|
||||
use std::collections::{BTreeMap, HashMap};
|
||||
use std::io::{IsTerminal, Write};
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering};
|
||||
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::renderer::ExportHandles;
|
||||
use crate::fractal::{
|
||||
ExportRender, FractalKind, FractalRenderer, PipelineKey, ShareState, encode_png,
|
||||
ExportRender, FractalKind, FractalRenderer, PipelineKey, RefOrbit, ShareState, encode_png,
|
||||
export_to_png_blocking, render_readback_blocking, unpad_rgba,
|
||||
};
|
||||
use crate::view::{
|
||||
@@ -30,6 +31,34 @@ const MAX_DIM: u32 = 8192 * 16;
|
||||
/// `--export-path` value meaning "write to stdout".
|
||||
const STDOUT_PATH: &str = "-";
|
||||
|
||||
/// First orbit length tried with auto-iterations (see [`Exporter::build`]);
|
||||
/// grown 4× per probe until no pixel gets near its end.
|
||||
const PROBE_FIRST_LEN: u32 = 8192;
|
||||
|
||||
/// How many frames past the last rendered one an animation computes probed
|
||||
/// (prefix) orbits, so they get a recent length hint.
|
||||
const PROBE_LAG: usize = 2;
|
||||
|
||||
/// Probe only when the whole orbit (+ its BLA table) would take longer than
|
||||
/// this: each probe is a GPU pass plus a BLA rebuild, and minibrot dives
|
||||
/// climb all the way to the full length anyway (seahorse 1e-200: 80 ms of
|
||||
/// orbit, +0.4 s of probes).
|
||||
const PROBE_MIN_SECS: f64 = 0.25;
|
||||
|
||||
/// Whether to compute only a prefix of `full`'s orbit and probe it (see
|
||||
/// [`Exporter::build`]): with auto-iterations, when the whole orbit is costly.
|
||||
fn probes(app: &FractalApp, full: &RefJob) -> bool {
|
||||
app.auto_iterations() && orbit_secs(full.steps(), full.precision()) > PROBE_MIN_SECS
|
||||
}
|
||||
|
||||
/// Rough CPU time of `steps` reference steps at `precision` bits plus their
|
||||
/// BLA nodes, fitted on a Ryzen with GMP: ~0.4 µs/step (allocation, f32
|
||||
/// conversion, BLA) + 3e-4 µs × limbs² for the multiplies.
|
||||
fn orbit_secs(steps: u32, precision: usize) -> f64 {
|
||||
let limbs = precision.div_ceil(64) as f64;
|
||||
steps as f64 * (0.4 + 3e-4 * limbs * limbs) * 1e-6
|
||||
}
|
||||
|
||||
/// Refuse to dump binary image data onto a terminal.
|
||||
fn check_stdout_piped() -> Result<(), String> {
|
||||
if std::io::stdout().is_terminal() {
|
||||
@@ -54,6 +83,7 @@ pub fn run(cli: Cli) -> Result<(), String> {
|
||||
// consumes `cli` to build the start state.
|
||||
let targets = AnimTargets::from_cli(&cli)?;
|
||||
let export_path = cli.export_path.clone();
|
||||
let compression = png::Compression::from(cli.png_compression);
|
||||
if export_path.as_deref() == Some(STDOUT_PATH) {
|
||||
check_stdout_piped()?;
|
||||
}
|
||||
@@ -67,32 +97,28 @@ pub fn run(cli: Cli) -> Result<(), String> {
|
||||
app.set_output_size(width, height);
|
||||
|
||||
if targets.any() {
|
||||
return run_animation(app, targets, width, height, export_path);
|
||||
return run_animation(app, targets, width, height, export_path, compression);
|
||||
}
|
||||
|
||||
let export_path = export_path.unwrap_or_else(|| format!("fractal-{}.png", unix_timestamp()));
|
||||
|
||||
// A costly orbit starts as a prefix, probed and grown by `Exporter::build`.
|
||||
let full = app.reference_job();
|
||||
let job = if probes(&app, &full) {
|
||||
full.prefix(PROBE_FIRST_LEN)
|
||||
} else {
|
||||
full.clone()
|
||||
};
|
||||
let device_thread = std::thread::spawn(|| pollster::block_on(request_device()));
|
||||
eprintln!("computing reference orbit…");
|
||||
app.compute_reference_blocking();
|
||||
let points = job.compute();
|
||||
|
||||
let (device, queue) = pollster::block_on(request_device())?;
|
||||
let format = wgpu::TextureFormat::Bgra8Unorm;
|
||||
let renderer = FractalRenderer::new(&device, format);
|
||||
let uniforms = app.make_uniforms(width as f64 / height as f64, height as f64);
|
||||
let (device, queue) = device_thread
|
||||
.join()
|
||||
.map_err(|_| "GPU setup panicked".to_string())??;
|
||||
let auto_color = app.auto_color_active();
|
||||
let handles = renderer.export_handles(&device, &uniforms, auto_color);
|
||||
|
||||
let mut er = ExportRender::new(
|
||||
&device,
|
||||
&queue,
|
||||
&handles,
|
||||
width,
|
||||
height,
|
||||
uniforms,
|
||||
app.reference_points(),
|
||||
&bla::for_uniforms(app.reference_points(), &uniforms, app.use_bla()),
|
||||
app.lights(),
|
||||
);
|
||||
let mut exporter = Exporter::new(&device, &queue, width, height, auto_color);
|
||||
let (mut er, _) = exporter.build(&mut app, &full, job, points);
|
||||
if auto_color {
|
||||
match fit_auto_color(&mut app, &mut er, &device, &queue) {
|
||||
Some((lo, hi)) => eprintln!("auto color scale: ci {lo:.1}–{hi:.1}"),
|
||||
@@ -101,7 +127,7 @@ pub fn run(cli: Cli) -> Result<(), String> {
|
||||
}
|
||||
|
||||
eprintln!("rendering {width}×{height}…");
|
||||
let png = export_to_png_blocking(&device, &queue, &er, |phase, fraction| {
|
||||
let png = export_to_png_blocking(&device, &queue, &er, compression, |phase, fraction| {
|
||||
eprint!("\r{phase} {:>3.0}%", fraction * 100.0);
|
||||
});
|
||||
eprintln!();
|
||||
@@ -240,6 +266,7 @@ fn run_animation(
|
||||
width: u32,
|
||||
height: u32,
|
||||
export_path: Option<String>,
|
||||
compression: png::Compression,
|
||||
) -> Result<(), String> {
|
||||
let fps = targets.fps;
|
||||
let frames = match targets.frames {
|
||||
@@ -365,13 +392,19 @@ fn run_animation(
|
||||
.collect();
|
||||
|
||||
let (device, queue) = pollster::block_on(request_device())?;
|
||||
let format = wgpu::TextureFormat::Bgra8Unorm;
|
||||
let renderer = FractalRenderer::new(&device, format);
|
||||
let aspect = width as f64 / height as f64;
|
||||
// Refit per frame from the same start, so each frame's colours depend only
|
||||
// on that frame (frames render out of order, and shards must join up).
|
||||
let auto_color = app.auto_color_active();
|
||||
let color_fit0 = app.color_fit();
|
||||
// Frames whose whole orbit is costly get a prefix (see `Exporter::build`)
|
||||
// this long: 4× the latest escape the last probed frame saw, so frames
|
||||
// zooming a little deeper than it mostly pass their first probe. Those
|
||||
// prefixes take milliseconds, so they're computed just in time (at most
|
||||
// `PROBE_LAG` frames past the last rendered one) to see a recent hint; a
|
||||
// failed probe recomputes on the GPU thread.
|
||||
let probe: Vec<bool> = jobs.iter().map(|job| probes(&app, job)).collect();
|
||||
let len_hint = AtomicU32::new(PROBE_FIRST_LEN);
|
||||
let rendered = AtomicUsize::new(0);
|
||||
|
||||
// Three-stage pipeline, connected by bounded channels (which also cap
|
||||
// memory): `threads` workers compute reference orbits (CPU, the expensive
|
||||
@@ -408,10 +441,12 @@ fn run_animation(
|
||||
let png_rx = Mutex::new(png_rx);
|
||||
let (raw_tx, raw_rx) = mpsc::sync_channel::<(usize, Vec<u8>)>(threads * 2);
|
||||
std::thread::scope(|scope| {
|
||||
let (ref_tx, ref_rx) = mpsc::sync_channel::<(usize, crate::fractal::RefOrbit)>(threads * 2);
|
||||
let (ref_tx, ref_rx) = mpsc::sync_channel::<(usize, RefJob, RefOrbit)>(threads * 2);
|
||||
for _ in 0..threads {
|
||||
let ref_tx = ref_tx.clone();
|
||||
let (jobs, next_job, saved, failed) = (&jobs, &next_job, &saved, &failed);
|
||||
let (jobs, probe, len_hint, rendered, next_job, saved, failed) = (
|
||||
&jobs, &probe, &len_hint, &rendered, &next_job, &saved, &failed,
|
||||
);
|
||||
scope.spawn(move || {
|
||||
loop {
|
||||
let i = next_job.fetch_add(1, Ordering::Relaxed);
|
||||
@@ -424,7 +459,20 @@ fn run_animation(
|
||||
{
|
||||
std::thread::sleep(std::time::Duration::from_millis(2));
|
||||
}
|
||||
if ref_tx.send((i, jobs[i].compute())).is_err() {
|
||||
let job = if probe[i] {
|
||||
// Can't deadlock: every frame before `i` was claimed
|
||||
// earlier, and the lowest unrendered one never waits.
|
||||
while i > rendered.load(Ordering::Relaxed) + PROBE_LAG
|
||||
&& !failed.load(Ordering::Relaxed)
|
||||
{
|
||||
std::thread::sleep(std::time::Duration::from_millis(1));
|
||||
}
|
||||
jobs[i].prefix(len_hint.load(Ordering::Relaxed))
|
||||
} else {
|
||||
jobs[i].clone()
|
||||
};
|
||||
let points = job.compute();
|
||||
if ref_tx.send((i, job, points)).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -479,8 +527,7 @@ fn run_animation(
|
||||
let _ = raw_tx.send((i, raw));
|
||||
continue;
|
||||
}
|
||||
let png =
|
||||
encode_png(&padded, width, height, bpr, swap_rb, png::Compression::Fast);
|
||||
let png = encode_png(&padded, width, height, bpr, swap_rb, compression);
|
||||
let path = format!("{out_dir}/frame-{:05}.png", first as usize + i + 1);
|
||||
if let Err(e) = std::fs::write(&path, &png) {
|
||||
fail(format!("save failed: {e}"));
|
||||
@@ -494,32 +541,19 @@ fn run_animation(
|
||||
|
||||
// GPU stage, on this thread (it owns the app and the device). The
|
||||
// shader specialization (kind, Julia, DE, morph) can change between
|
||||
// frames during a kind morph; build each pipeline once.
|
||||
let mut pipelines = HashMap::new();
|
||||
for (i, points) in ref_rx.iter() {
|
||||
// frames during a kind morph; `exporter` builds each pipeline once.
|
||||
let mut exporter = Exporter::new(&device, &queue, width, height, auto_color);
|
||||
for (i, job, points) in ref_rx.iter() {
|
||||
if failed.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
apply_frame(&mut app, first + i as u32);
|
||||
app.finish_reference(jobs[i].clone(), points);
|
||||
|
||||
let uniforms = app.make_uniforms(aspect, height as f64);
|
||||
let handles = pipelines
|
||||
.entry(PipelineKey::from_uniforms(&uniforms))
|
||||
.or_insert_with(|| renderer.export_handles(&device, &uniforms, auto_color));
|
||||
let mut er = ExportRender::new(
|
||||
&device,
|
||||
&queue,
|
||||
handles,
|
||||
width,
|
||||
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(),
|
||||
);
|
||||
let (mut er, escape) = exporter.build(&mut app, &jobs[i], job, points);
|
||||
if let Some(n) = escape {
|
||||
// `as` saturates.
|
||||
len_hint.store(((4.0 * n) as u32).max(PROBE_FIRST_LEN), Ordering::Relaxed);
|
||||
}
|
||||
rendered.fetch_add(1, Ordering::Relaxed);
|
||||
if auto_color {
|
||||
app.set_color_fit(color_fit0);
|
||||
fit_auto_color(&mut app, &mut er, &device, &queue);
|
||||
@@ -564,6 +598,96 @@ fn run_animation(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Builds each frame's [`ExportRender`] on one device, caching the export
|
||||
/// pipelines per shader specialization.
|
||||
struct Exporter<'a> {
|
||||
device: &'a wgpu::Device,
|
||||
queue: &'a wgpu::Queue,
|
||||
renderer: FractalRenderer,
|
||||
/// Keyed by specialization and whether the `ci` probe pass is built.
|
||||
handles: HashMap<(PipelineKey, bool), ExportHandles>,
|
||||
width: u32,
|
||||
height: u32,
|
||||
auto_color: bool,
|
||||
}
|
||||
|
||||
impl<'a> Exporter<'a> {
|
||||
fn new(
|
||||
device: &'a wgpu::Device,
|
||||
queue: &'a wgpu::Queue,
|
||||
width: u32,
|
||||
height: u32,
|
||||
auto_color: bool,
|
||||
) -> Self {
|
||||
Self {
|
||||
device,
|
||||
queue,
|
||||
renderer: FractalRenderer::new(device, wgpu::TextureFormat::Bgra8Unorm),
|
||||
handles: HashMap::new(),
|
||||
width,
|
||||
height,
|
||||
auto_color,
|
||||
}
|
||||
}
|
||||
|
||||
/// Install `points`, the orbit computed for `job` (`full` or a
|
||||
/// [`prefix`](RefJob::prefix) of it), and build the frame's render.
|
||||
///
|
||||
/// Auto-iterations ask for 400 + 900·decades steps, all computed when the
|
||||
/// reference never escapes (e.g. c = -1.5 at 1e-1000: 900k steps of
|
||||
/// 3000-bit arithmetic, plus the BLA table over them), even when every
|
||||
/// pixel has escaped by step 10k. So callers may compute a prefix, which
|
||||
/// is probed here (downscaled prepass) for how far pixels follow it: the
|
||||
/// shader treats an exhausted reference as an escape, so while no pixel
|
||||
/// gets near the end, the image is the same as with the whole orbit.
|
||||
/// Otherwise the prefix grows 4× and is probed again.
|
||||
///
|
||||
/// Also returns the latest escape the accepted probe saw, if it probed.
|
||||
fn build(
|
||||
&mut self,
|
||||
app: &mut FractalApp,
|
||||
full: &RefJob,
|
||||
mut job: RefJob,
|
||||
mut points: RefOrbit,
|
||||
) -> (ExportRender, Option<f64>) {
|
||||
loop {
|
||||
let len = job.steps();
|
||||
let whole = job.is_whole(full.steps(), &points);
|
||||
app.finish_reference(job, points);
|
||||
let uniforms =
|
||||
app.make_uniforms(self.width as f64 / self.height as f64, self.height as f64);
|
||||
let probe = self.auto_color || !whole;
|
||||
let handles = self
|
||||
.handles
|
||||
.entry((PipelineKey::from_uniforms(&uniforms), probe))
|
||||
.or_insert_with(|| self.renderer.export_handles(self.device, &uniforms, probe));
|
||||
let er = ExportRender::new(
|
||||
self.device,
|
||||
self.queue,
|
||||
handles,
|
||||
self.width,
|
||||
self.height,
|
||||
uniforms,
|
||||
app.reference_points(),
|
||||
// Needs this frame's uniforms; ~15 ms per 100k points on one core.
|
||||
&bla::for_uniforms(app.reference_points(), &uniforms, app.use_bla()),
|
||||
app.lights(),
|
||||
);
|
||||
if whole {
|
||||
return (er, None);
|
||||
}
|
||||
match er.max_escape_blocking(self.device, self.queue) {
|
||||
// 2× margin: the full image samples finer than the probe.
|
||||
Some(n) if n < len as f64 / 2.0 => return (er, Some(n)),
|
||||
_ => {
|
||||
job = full.prefix(len.saturating_mul(4));
|
||||
points = job.compute();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Auto colour scale: fit `app`'s colour scale to `er`'s image (a prepass)
|
||||
/// and upload the result. Returns the fitted `ci` range, or `None` (colours
|
||||
/// untouched) if nothing escaped.
|
||||
|
||||
+27
-6
@@ -36,12 +36,14 @@ type MainResult = eframe::Result;
|
||||
type MainResult = Result<(), String>;
|
||||
|
||||
/// wgpu configuration for eframe. The fractal fragment shader reads the
|
||||
/// reference orbit from a **storage buffer**, so the device must allow storage
|
||||
/// buffers in the fragment stage. eframe's default requests WebGL2-downlevel
|
||||
/// limits when a GL adapter is picked (storage buffers = 0), so we:
|
||||
/// reference orbit from **storage buffers** where the device allows them in
|
||||
/// the fragment stage (`GpuPath` in renderer.rs). eframe's default requests
|
||||
/// WebGL2-downlevel limits when a GL adapter is picked (storage buffers = 0),
|
||||
/// so we:
|
||||
/// * request the adapter's real limits (which include storage buffers), and
|
||||
/// * force the WebGPU backend on the web (WebGL2 can't do storage buffers at
|
||||
/// all) — failing cleanly on browsers without WebGPU, per the design.
|
||||
/// * on the web, use WebGPU only, failing cleanly on browsers without it,
|
||||
/// unless the `webgl` feature adds WebGL2 as a fallback (egui-wgpu
|
||||
/// tries WebGPU first).
|
||||
#[cfg(feature = "gui")]
|
||||
fn wgpu_options() -> eframe::egui_wgpu::WgpuConfiguration {
|
||||
use eframe::egui_wgpu::{WgpuSetup, wgpu};
|
||||
@@ -55,14 +57,33 @@ fn wgpu_options() -> eframe::egui_wgpu::WgpuConfiguration {
|
||||
required_limits: adapter.limits(),
|
||||
..Default::default()
|
||||
});
|
||||
#[cfg(target_arch = "wasm32")]
|
||||
#[cfg(all(target_arch = "wasm32", not(feature = "webgl")))]
|
||||
{
|
||||
setup.instance_descriptor.backends = wgpu::Backends::BROWSER_WEBGPU;
|
||||
}
|
||||
#[cfg(all(target_arch = "wasm32", feature = "webgl"))]
|
||||
{
|
||||
setup.instance_descriptor.backends = if web_forced_webgl() {
|
||||
wgpu::Backends::GL
|
||||
} else {
|
||||
wgpu::Backends::BROWSER_WEBGPU | wgpu::Backends::GL
|
||||
};
|
||||
}
|
||||
}
|
||||
options
|
||||
}
|
||||
|
||||
/// The page asks for WebGL2 even where WebGPU works (`?backend=webgl`, set
|
||||
/// by the "Use WebGPU" toggle in the app's Advanced section).
|
||||
#[cfg(all(target_arch = "wasm32", feature = "webgl"))]
|
||||
fn web_forced_webgl() -> bool {
|
||||
web_sys::window()
|
||||
.and_then(|w| w.location().search().ok())
|
||||
.and_then(|q| web_sys::UrlSearchParams::new_with_str(&q).ok())
|
||||
.and_then(|p| p.get("backend"))
|
||||
.is_some_and(|b| b == "webgl")
|
||||
}
|
||||
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
fn main() -> MainResult {
|
||||
use clap::Parser as _;
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
// Auto colour scale without compute shaders (WebGL2): point-samples the data
|
||||
// texture onto a small CI_SAMPLE_DIM² grid, read back and binned on the CPU
|
||||
// like `ci_stats.wgsl` (`CiHistogram::Readback` in renderer.rs). The grid
|
||||
// stretches to the source's aspect; percentiles don't care.
|
||||
|
||||
@group(0) @binding(0) var data_tex: texture_2d<f32>;
|
||||
|
||||
@vertex
|
||||
fn vs_main(@builtin(vertex_index) idx: u32) -> @builtin(position) vec4<f32> {
|
||||
return vec4<f32>(fullscreen_triangle_pos(idx), 0.0, 1.0);
|
||||
}
|
||||
|
||||
// Must match `CI_SAMPLE_DIM` in renderer.rs.
|
||||
const CI_SAMPLE_DIM: f32 = 256.0;
|
||||
|
||||
@fragment
|
||||
fn fs_main(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
|
||||
let size = vec2<f32>(textureDimensions(data_tex));
|
||||
let p = min(vec2<i32>(floor(pos.xy * size / CI_SAMPLE_DIM)), vec2<i32>(size) - 1);
|
||||
let d = textureLoad(data_tex, p, 0);
|
||||
return vec4<f32>(d.r, d.b, 0.0, 0.0);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
// Reference orbit + BLA table as storage buffers, and the native float
|
||||
// builtins: the data fragment of `mandelbrot.wgsl` on every device with
|
||||
// fragment-stage storage buffers (WebGPU, Vulkan, Metal, DX12). Each
|
||||
// accessor is a plain index that the shader compiler inlines. Must define
|
||||
// the same functions as `data_texture.wgsl` (the WebGL2 fallback).
|
||||
|
||||
@group(0) @binding(1) var<storage, read> ref_orbit: array<vec2<f32>>;
|
||||
@group(0) @binding(3) var<storage, read> ref_exp: array<i32>;
|
||||
@group(0) @binding(4) var<storage, read> bla_nodes: array<Bla>;
|
||||
@group(0) @binding(5) var<storage, read> bla_meta: array<u32>;
|
||||
|
||||
fn ref_point(m: u32) -> vec2<f32> {
|
||||
return ref_orbit[m];
|
||||
}
|
||||
|
||||
fn ref_exp_at(m: u32) -> i32 {
|
||||
return ref_exp[m];
|
||||
}
|
||||
|
||||
fn bla_node(i: u32) -> Bla {
|
||||
return bla_nodes[i];
|
||||
}
|
||||
|
||||
fn bla_r_log2(i: u32) -> f32 {
|
||||
return bla_nodes[i].r_log2;
|
||||
}
|
||||
|
||||
fn bla_steps(i: u32) -> u32 {
|
||||
return bla_nodes[i].steps;
|
||||
}
|
||||
|
||||
fn bla_meta_at(i: u32) -> u32 {
|
||||
return bla_meta[i];
|
||||
}
|
||||
|
||||
fn frexp_f32(x: f32) -> Frexp {
|
||||
let f = frexp(x);
|
||||
return Frexp(f.fract, f.exp);
|
||||
}
|
||||
|
||||
fn ldexp_f32(x: f32, k: i32) -> f32 {
|
||||
return ldexp(x, k);
|
||||
}
|
||||
|
||||
fn ctz_u32(x: u32) -> u32 {
|
||||
return countTrailingZeros(x);
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
// Reference orbit + BLA table as textures, and bit-exact replacements for
|
||||
// float builtins: the data fragment of `mandelbrot.wgsl` on devices without
|
||||
// fragment-stage storage buffers (WebGL2, `GpuPath::Texture` in
|
||||
// renderer.rs). Must define the same functions as `data_storage.wgsl`.
|
||||
//
|
||||
// Every array is laid out row-major in a texture DATA_TEX_WIDTH texels wide
|
||||
// (element i at (i % W, i / W); `RefData` in renderer.rs). BLA nodes are 3
|
||||
// `Rgba32Uint` texels each (m, n, then m_exp/n_exp/r_log2/steps), floats as
|
||||
// raw bits: a float texture could flush the small i32 exponents, whose bit
|
||||
// patterns are subnormal floats.
|
||||
|
||||
@group(0) @binding(1) var ref_orbit_tex: texture_2d<f32>;
|
||||
@group(0) @binding(3) var ref_exp_tex: texture_2d<i32>;
|
||||
@group(0) @binding(4) var bla_nodes_tex: texture_2d<u32>;
|
||||
@group(0) @binding(5) var bla_meta_tex: texture_2d<u32>;
|
||||
|
||||
// Must match `DATA_TEX_WIDTH` in renderer.rs (2048, WebGL2's guaranteed
|
||||
// minimum texture size).
|
||||
const DATA_TEX_LOG2_W: u32 = 11u;
|
||||
|
||||
fn data_texel(i: u32) -> vec2<i32> {
|
||||
return vec2<i32>(i32(i & ((1u << DATA_TEX_LOG2_W) - 1u)), i32(i >> DATA_TEX_LOG2_W));
|
||||
}
|
||||
|
||||
fn ref_point(m: u32) -> vec2<f32> {
|
||||
return textureLoad(ref_orbit_tex, data_texel(m), 0).xy;
|
||||
}
|
||||
|
||||
fn ref_exp_at(m: u32) -> i32 {
|
||||
return textureLoad(ref_exp_tex, data_texel(m), 0).x;
|
||||
}
|
||||
|
||||
fn bla_node(i: u32) -> Bla {
|
||||
let a = textureLoad(bla_nodes_tex, data_texel(3u * i), 0);
|
||||
let b = textureLoad(bla_nodes_tex, data_texel(3u * i + 1u), 0);
|
||||
let c = textureLoad(bla_nodes_tex, data_texel(3u * i + 2u), 0);
|
||||
return Bla(
|
||||
bitcast<vec4<f32>>(a),
|
||||
bitcast<vec4<f32>>(b),
|
||||
bitcast<i32>(c.x),
|
||||
bitcast<i32>(c.y),
|
||||
bitcast<f32>(c.z),
|
||||
c.w,
|
||||
);
|
||||
}
|
||||
|
||||
fn bla_r_log2(i: u32) -> f32 {
|
||||
return bitcast<f32>(textureLoad(bla_nodes_tex, data_texel(3u * i + 2u), 0).z);
|
||||
}
|
||||
|
||||
fn bla_steps(i: u32) -> u32 {
|
||||
return textureLoad(bla_nodes_tex, data_texel(3u * i + 2u), 0).w;
|
||||
}
|
||||
|
||||
fn bla_meta_at(i: u32) -> u32 {
|
||||
return textureLoad(bla_meta_tex, data_texel(i), 0).x;
|
||||
}
|
||||
|
||||
// 2^e for e in [-126, 127], built from its bits.
|
||||
fn pow2_f32(e: i32) -> f32 {
|
||||
return bitcast<f32>(u32(e + 127) << 23u);
|
||||
}
|
||||
|
||||
// WGSL `frexp` from the exponent bits. naga's GLSL ES 3.00 polyfill goes
|
||||
// through log2, which is wrong for negative x and off by one near powers of
|
||||
// two. Subnormals are scaled up by 2^64 first (0 if the GPU flushes them).
|
||||
fn frexp_f32(x: f32) -> Frexp {
|
||||
var bits = bitcast<u32>(x);
|
||||
var bias = 0;
|
||||
if ((bits >> 23u) & 0xffu) == 0u {
|
||||
if (bits & 0x7fffffffu) == 0u {
|
||||
return Frexp(x, 0);
|
||||
}
|
||||
bits = bitcast<u32>(x * 18446744073709551616.0); // 2^64
|
||||
bias = -64;
|
||||
if ((bits >> 23u) & 0xffu) == 0u {
|
||||
return Frexp(0.0, 0);
|
||||
}
|
||||
}
|
||||
let biased = i32((bits >> 23u) & 0xffu);
|
||||
if biased == 255 {
|
||||
return Frexp(x, 0); // inf / NaN
|
||||
}
|
||||
return Frexp(bitcast<f32>((bits & 0x807fffffu) | 0x3f000000u), biased - 126 + bias);
|
||||
}
|
||||
|
||||
// WGSL `ldexp` (GLSL ES 3.10+) as two exact power-of-two multiplies, valid
|
||||
// for |k| <= 252; with both halves the same sign, the intermediate is
|
||||
// normal whenever the result is.
|
||||
fn ldexp_f32(x: f32, k: i32) -> f32 {
|
||||
let k1 = clamp(k / 2, -126, 127);
|
||||
let k2 = clamp(k - k1, -126, 127);
|
||||
return x * pow2_f32(k1) * pow2_f32(k2);
|
||||
}
|
||||
|
||||
// WGSL `countTrailingZeros` (`findLSB` is GLSL ES 3.10+): the exponent of
|
||||
// the lowest set bit, which converts to f32 exactly.
|
||||
fn ctz_u32(x: u32) -> u32 {
|
||||
if x == 0u {
|
||||
return 32u;
|
||||
}
|
||||
let low = x & (~x + 1u);
|
||||
return (bitcast<u32>(f32(low)) >> 23u) - 127u;
|
||||
}
|
||||
+172
-45
@@ -18,35 +18,45 @@
|
||||
// to the plain f32 loop once the delta is big enough (see `iterate_sample`).
|
||||
|
||||
@group(0) @binding(0) var<uniform> u: Uniforms;
|
||||
@group(0) @binding(1) var<storage, read> ref_orbit: array<vec2<f32>>;
|
||||
// Bindings 1 and 3-5 (reference orbit, its exponents, the BLA table) are
|
||||
// declared by the data fragment concatenated after this file: storage
|
||||
// buffers (`data_storage.wgsl`) or, where the device has none (WebGL2),
|
||||
// textures (`data_texture.wgsl`). Both provide `ref_point`, `ref_exp_at`,
|
||||
// `bla_node`, `bla_r_log2`, `bla_steps`, `bla_meta_at`, plus `frexp_f32`,
|
||||
// `ldexp_f32` and `ctz_u32` (GLSL ES 3.00 lacks the builtins).
|
||||
// Only read by `fs_color`'s shadow branch (custom-lights palette); the
|
||||
// iteration pass (`fs_data`) never touches it.
|
||||
@group(0) @binding(2) var<uniform> lights: array<Light, 16>;
|
||||
// Only read by the adaptive-AA refine pass (`fs_refine`): the 1-sample-per-
|
||||
// pixel data texture written by `fs_data`, which decides where to supersample.
|
||||
@group(1) @binding(0) var coarse_tex: texture_2d<f32>;
|
||||
// Per-point binary exponents of the reference orbit (`RefOrbit::exps`): the
|
||||
// true X[m] is ref_orbit[m] * 2^ref_exp[m]. Non-zero only for points below
|
||||
// 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>;
|
||||
// Reference orbit: point m is `ref_point(m)`, and the true X[m] is
|
||||
// ref_point(m) * 2^ref_exp_at(m). The exponent is non-zero only for points
|
||||
// below f32's range, which only deep references contain; only `DEEP`
|
||||
// pipelines read it (see `ref_at`).
|
||||
// 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' = M·e + N·dc, valid while log2|e| < r_log2. M = m·2^m_exp and
|
||||
// N = n·2^n_exp are real 2x2 matrices, row-major (the Jacobian of the map,
|
||||
// so the abs/conjugate kinds are covered too). `bla_meta` is
|
||||
// [min_level, level_count, off_0, ..., off_{level_count}]; only `BLA`
|
||||
// pipelines read either.
|
||||
// so the abs/conjugate kinds are covered too). `bla_meta_at` reads
|
||||
// [min_level, level_count, off_0, ..., off_{level_count}, seg_count,
|
||||
// seg_start_0, ...]: segment i is node off_{level_count} + i and covers its
|
||||
// `steps` steps from seg_start_i (see `bla_seg_find`). Only `BLA` pipelines
|
||||
// read either.
|
||||
struct Bla {
|
||||
m: vec4<f32>,
|
||||
n: vec4<f32>,
|
||||
m_exp: i32,
|
||||
n_exp: i32,
|
||||
r_log2: f32,
|
||||
_pad: u32,
|
||||
steps: u32,
|
||||
};
|
||||
|
||||
// `frexp` result (see `frexp_f32`).
|
||||
struct Frexp {
|
||||
fract: f32,
|
||||
exp: i32,
|
||||
};
|
||||
@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
|
||||
@@ -298,7 +308,23 @@ fn ldexp_sat(x: f32, k: i32) -> f32 {
|
||||
if x == 0.0 {
|
||||
return 0.0;
|
||||
}
|
||||
let f = frexp(x);
|
||||
// Normal x (the usual case): the same result by adding k to the
|
||||
// exponent field, much cheaper than frexp + ldexp in this hot path.
|
||||
// frexp's exponent is the biased field - 126; the checks keep the
|
||||
// result's field in [1, 226], so the add can't carry into the sign.
|
||||
let bits = bitcast<u32>(x);
|
||||
let biased = i32((bits >> 23u) & 0xffu);
|
||||
if biased != 0 && biased != 255 {
|
||||
let ex = biased - 126 + k;
|
||||
if ex > 100 {
|
||||
return select(-LDEXP_SAT, LDEXP_SAT, x > 0.0);
|
||||
}
|
||||
if ex < -125 {
|
||||
return 0.0;
|
||||
}
|
||||
return bitcast<f32>(bitcast<i32>(bits) + (k << 23u));
|
||||
}
|
||||
let f = frexp_f32(x);
|
||||
let ex = f.exp + k;
|
||||
if ex > 100 {
|
||||
return select(-LDEXP_SAT, LDEXP_SAT, x > 0.0);
|
||||
@@ -306,7 +332,7 @@ fn ldexp_sat(x: f32, k: i32) -> f32 {
|
||||
if ex < -125 {
|
||||
return 0.0;
|
||||
}
|
||||
return ldexp(f.fract, ex);
|
||||
return ldexp_f32(f.fract, ex);
|
||||
}
|
||||
|
||||
fn ldexp2_sat(v: vec2<f32>, k: i32) -> vec2<f32> {
|
||||
@@ -325,16 +351,16 @@ fn fe_make(v: vec2<f32>, e: i32) -> Fe {
|
||||
if a == 0.0 {
|
||||
return Fe(vec2<f32>(0.0, 0.0), 0);
|
||||
}
|
||||
let k = frexp(a).exp;
|
||||
let k = frexp_f32(a).exp;
|
||||
return Fe(ldexp2_sat(v, -k), e + k);
|
||||
}
|
||||
|
||||
// Reference point X[m] as f32 (points stored normalized flush to 0 here;
|
||||
// only deep references have any, see `ref_exp`).
|
||||
fn ref_at(m: u32) -> vec2<f32> {
|
||||
let x = ref_orbit[m];
|
||||
let x = ref_point(m);
|
||||
if DEEP {
|
||||
let k = ref_exp[m];
|
||||
let k = ref_exp_at(m);
|
||||
if k != 0 {
|
||||
return ldexp2_sat(x, k);
|
||||
}
|
||||
@@ -344,7 +370,7 @@ fn ref_at(m: u32) -> vec2<f32> {
|
||||
|
||||
// X[m] with its full exponent range (deep phase only).
|
||||
fn ref_fe(m: u32) -> Fe {
|
||||
return fe_make(ref_orbit[m], ref_exp[m]);
|
||||
return fe_make(ref_point(m), ref_exp_at(m));
|
||||
}
|
||||
|
||||
// Complex log of m * 2^e (m != 0).
|
||||
@@ -549,7 +575,7 @@ fn deep_log2(a: vec2<f32>, b: vec2<f32>) -> i32 {
|
||||
if m == 0.0 {
|
||||
return DEEP_ZERO;
|
||||
}
|
||||
return frexp(m).exp;
|
||||
return frexp_f32(m).exp;
|
||||
}
|
||||
|
||||
// f'(y) at the full value y = X + w * 2^s, as an `Fe`. Plain `fprime` in f32
|
||||
@@ -597,6 +623,9 @@ const DEEP_RENORM_LOG2: i32 = 16;
|
||||
// A reference point can only matter for rebasing when it's within this many
|
||||
// binades above the delta's scale (|w| < 2^DEEP_RENORM_LOG2).
|
||||
const DEEP_NEAR_LOG2: i32 = 24;
|
||||
// A rebase's full value when its real part cancels to exactly 0, relative
|
||||
// to the addends (see the f32 loop's rebase).
|
||||
const ROUNDING_X: f32 = 5.9604645e-8; // 2^-24
|
||||
|
||||
// Row-major 2x2 matrix times vector (a BLA node's M or N).
|
||||
fn mat2v(m: vec4<f32>, v: vec2<f32>) -> vec2<f32> {
|
||||
@@ -618,34 +647,85 @@ fn log2_mag(v: vec2<f32>) -> f32 {
|
||||
// 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];
|
||||
let levels = bla_meta_at(1u);
|
||||
if levels == 0u || m == 0u {
|
||||
return best;
|
||||
}
|
||||
let lmin = bla_meta[0];
|
||||
let lmin = bla_meta_at(0u);
|
||||
let j = m - 1u;
|
||||
let tz = countTrailingZeros(j); // 32 when j == 0
|
||||
let tz = ctz_u32(j); // 32 when j == 0
|
||||
if tz < lmin {
|
||||
return best;
|
||||
}
|
||||
let top = min(tz - lmin, levels - 1u);
|
||||
// Level offsets without loading them from `bla_meta` per level (one more
|
||||
// dependent load each): level 0 starts at 0 and each level has half the
|
||||
// previous one's nodes, rounded down (`bla::build`).
|
||||
var base = 0u;
|
||||
var count = bla_meta_at(3u);
|
||||
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 {
|
||||
if steps > budget || local >= count {
|
||||
break;
|
||||
}
|
||||
let idx = base + local;
|
||||
if !(e_log2 < bla_nodes[idx].r_log2) {
|
||||
if !(e_log2 < bla_r_log2(idx)) {
|
||||
break;
|
||||
}
|
||||
best = vec2<u32>(idx, steps);
|
||||
base = base + count;
|
||||
count = count >> 1u;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
// Segment jumps (`bla::build`): one node per run of the reference between
|
||||
// two steps where it passes near 0 (or a fold line), starting right after
|
||||
// one. Each pixel tracks the first segment starting at or after its `m`
|
||||
// (`seg_i`, starting at `seg_at`); m only grows between rebases, so that
|
||||
// only moves forward.
|
||||
fn bla_seg_count() -> u32 {
|
||||
return bla_meta_at(bla_meta_at(1u) + 3u);
|
||||
}
|
||||
|
||||
fn bla_seg_start(i: u32) -> u32 {
|
||||
if i >= bla_seg_count() {
|
||||
return 0xffffffffu;
|
||||
}
|
||||
return bla_meta_at(bla_meta_at(1u) + 4u + i);
|
||||
}
|
||||
|
||||
// First segment from `lo` on that starts at or after `m` (binary search: a
|
||||
// long level jump can pass many segments).
|
||||
fn bla_seg_find(lo: u32, m: u32) -> u32 {
|
||||
var a = lo;
|
||||
var b = bla_seg_count();
|
||||
while a < b {
|
||||
let mid = (a + b) / 2u;
|
||||
if bla_meta_at(bla_meta_at(1u) + 4u + mid) < m {
|
||||
a = mid + 1u;
|
||||
} else {
|
||||
b = mid;
|
||||
}
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
// The segment jump at `m` if segment `seg_i` starts there and is valid,
|
||||
// else `bla_lookup`'s: (node index, steps), steps = 0 when there's none.
|
||||
fn bla_jump(m: u32, seg_i: u32, seg_at: u32, e_log2: f32, budget: u32) -> vec2<u32> {
|
||||
if seg_at == m {
|
||||
let idx = bla_meta_at(bla_meta_at(1u) + 2u) + seg_i;
|
||||
let steps = bla_steps(idx);
|
||||
if e_log2 < bla_r_log2(idx) && steps <= budget {
|
||||
return vec2<u32>(idx, steps);
|
||||
}
|
||||
}
|
||||
return bla_lookup(m, e_log2, budget);
|
||||
}
|
||||
|
||||
// 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 {
|
||||
@@ -699,6 +779,9 @@ const PERIOD_FIRST_CHECK: u32 = 16u;
|
||||
const PERIOD_EPS2: f32 = 1e-12;
|
||||
const PERIOD_MAX_MULT2: f32 = 0.25;
|
||||
const PERIOD_CONFIRMATIONS: u32 = 2u;
|
||||
// A return within PERIOD_EPS2 has |z|^2 <= |z_saved|^2 / (1 - 1e-6)^2; the
|
||||
// rest is room for f32 rounding.
|
||||
const PERIOD_SAVE_SLACK: f32 = 1.001;
|
||||
|
||||
// Whether `iterate_sample` runs periodicity detection for this kind (folds to
|
||||
// a constant per pipeline).
|
||||
@@ -751,7 +834,7 @@ fn iterate_sample(offset: vec2<f32>, px: f32) -> Sample {
|
||||
// so skip the test once a pixel is smaller than that error (deep zoom),
|
||||
// where it could misclassify pixels right at the boundary.
|
||||
if KIND == KIND_MANDELBROT && !MORPH && !IS_JULIA && !DEEP && ref_len > 1u && px > 1e-6 {
|
||||
let c = ref_orbit[1] + offset;
|
||||
let c = ref_point(1u) + offset;
|
||||
let xq = c.x - 0.25;
|
||||
let q = xq * xq + c.y * c.y;
|
||||
let in_cardioid = q * (q + xq) <= 0.25 * c.y * c.y;
|
||||
@@ -799,6 +882,8 @@ fn iterate_sample(offset: vec2<f32>, px: f32) -> Sample {
|
||||
// Plus whether this window already had a contracting return, and how many
|
||||
// consecutive windows have.
|
||||
var z_saved = z;
|
||||
// |z_saved|^2 with slack for rounding: returns can't be farther out.
|
||||
var save_d2 = z2 * PERIOD_SAVE_SLACK;
|
||||
var mult2 = 1.0;
|
||||
var check_at = PERIOD_FIRST_CHECK;
|
||||
var period_hit = false;
|
||||
@@ -845,6 +930,14 @@ fn iterate_sample(offset: vec2<f32>, px: f32) -> Sample {
|
||||
var w_old = w;
|
||||
var rebase_exit = false;
|
||||
var cut_exit = false;
|
||||
// Next BLA segment (see `bla_jump`; the f32 loop below only uses
|
||||
// the levels: its steps are too cheap to pay for tracking this).
|
||||
var seg_first = 0xffffffffu;
|
||||
if BLA {
|
||||
seg_first = bla_seg_start(0u);
|
||||
}
|
||||
var seg_i = 0u;
|
||||
var seg_at = seg_first;
|
||||
loop {
|
||||
// Full value y = X + e as f32 (e flushes to 0 when negligible).
|
||||
let yt = xt + ldexp2_sat(w, sx);
|
||||
@@ -865,9 +958,13 @@ fn iterate_sample(offset: vec2<f32>, px: f32) -> Sample {
|
||||
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 seg_at < m {
|
||||
seg_i = bla_seg_find(seg_i + 1u, m);
|
||||
seg_at = bla_seg_start(seg_i);
|
||||
}
|
||||
let hit = bla_jump(m, seg_i, seg_at, e_log2, min(max_iter - n, ref_len - 1u - m));
|
||||
if hit.y != 0u {
|
||||
let nd = bla_nodes[hit.x];
|
||||
let nd = bla_node(hit.x);
|
||||
if DE {
|
||||
var accv = fe_make(mat2v(nd.m, v), nd.m_exp + sv);
|
||||
if !IS_JULIA {
|
||||
@@ -996,8 +1093,10 @@ fn iterate_sample(offset: vec2<f32>, px: f32) -> Sample {
|
||||
// Rebase test |X + e| < |e|, in units of 2^sx. Only possible when
|
||||
// |X| is within a few binades of |e| (|w| < 2^DEEP_RENORM_LOG2).
|
||||
if xf.e - sx < DEEP_NEAR_LOG2 {
|
||||
let q = ldexp2_sat(xf.m, xf.e - sx) + w;
|
||||
var q = ldexp2_sat(xf.m, xf.e - sx) + w;
|
||||
if dot(q, q) < dot(w, w) {
|
||||
// (Exact cancellation: see the f32 loop's rebase.)
|
||||
q.x = select(q.x, abs(w.x) * ROUNDING_X, q.x == 0.0);
|
||||
// The new delta y - X[0] stays tiny only if X[0] is
|
||||
// (always, for the set plane), and for Phoenix only if the
|
||||
// previous full value y_{n-1} (its new previous delta) is.
|
||||
@@ -1015,6 +1114,8 @@ fn iterate_sample(offset: vec2<f32>, px: f32) -> Sample {
|
||||
xf = z0f;
|
||||
xt = z0;
|
||||
m = 0u;
|
||||
seg_i = 0u;
|
||||
seg_at = seg_first;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1084,12 +1185,19 @@ fn iterate_sample(offset: vec2<f32>, px: f32) -> Sample {
|
||||
// pixels as interior (see PERIOD_FIRST_CHECK). The sentinel is far
|
||||
// outside the bailout radius, so no return can match it.
|
||||
z_saved = vec2<f32>(1e18, 1e18);
|
||||
save_d2 = -1.0;
|
||||
z_cand = z;
|
||||
while check_at <= n {
|
||||
check_at = check_at * 2u;
|
||||
}
|
||||
}
|
||||
|
||||
// Level nodes start at 1 + i·2^min_level, so only those steps can jump
|
||||
// (tested before `log2_mag` and the lookup: most steps here are plain).
|
||||
var bla_align = 0xffffffffu;
|
||||
if BLA && bla_meta_at(1u) != 0u {
|
||||
bla_align = (1u << bla_meta_at(0u)) - 1u;
|
||||
}
|
||||
loop {
|
||||
// (`escaped` may already be set by the deep phase.)
|
||||
if escaped || z2 > bailout_sq {
|
||||
@@ -1117,10 +1225,10 @@ fn iterate_sample(offset: vec2<f32>, px: f32) -> Sample {
|
||||
let e_old = e;
|
||||
let z_old = z;
|
||||
var jumped = false;
|
||||
if BLA && m != 0u {
|
||||
if BLA && m != 0u && ((m - 1u) & bla_align) == 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 nd = bla_node(hit.x);
|
||||
let se = select(0, u.scale_exp, DEEP);
|
||||
if periodic {
|
||||
let det = abs(nd.m.x * nd.m.w - nd.m.y * nd.m.z);
|
||||
@@ -1199,27 +1307,45 @@ fn iterate_sample(offset: vec2<f32>, px: f32) -> Sample {
|
||||
if phoenix_w > 0.0 {
|
||||
e_prev = z_old;
|
||||
}
|
||||
// X + e can cancel to exactly 0 in x though the true value is
|
||||
// only below f32 rounding; keep a rounding-sized one. On a real
|
||||
// reference orbit (a view centered on the real axis) the pixel's
|
||||
// imaginary part lives only in e.y, and the next step scales it
|
||||
// by 2·z.x: at 0 it's lost for good, and the pixel is stuck on
|
||||
// the real line, which is bounded (z² - 1.5 maps [-1.82, 1.82]
|
||||
// into itself). It was drawn black after max_iter steps.
|
||||
z.x = select(z.x, abs(e.x) * ROUNDING_X, z.x == 0.0);
|
||||
e = z - z0;
|
||||
xm = z0;
|
||||
m = 0u;
|
||||
}
|
||||
|
||||
if periodic {
|
||||
// Closed an attracting cycle in enough consecutive windows:
|
||||
// interior (see PERIOD_FIRST_CHECK).
|
||||
let d = z - z_saved;
|
||||
if !period_hit && mult2 < PERIOD_MAX_MULT2 && dot(d, d) <= PERIOD_EPS2 * z2 {
|
||||
period_hit = true;
|
||||
period_streak = period_streak + 1u;
|
||||
if period_streak >= PERIOD_CONFIRMATIONS {
|
||||
break;
|
||||
// A return (below) and a new save candidate both need z next to
|
||||
// the critical point: |z|^2 at most the saved iterate's (a return
|
||||
// within PERIOD_EPS2 can't be farther out), or below this
|
||||
// window's closest so far. Most steps are neither and skip both
|
||||
// tests (Lambda's critical point isn't 0, so it always tests).
|
||||
if KIND == KIND_LAMBDA || z2 <= max(save_d2, cand_d2) {
|
||||
// Closed an attracting cycle in enough consecutive windows:
|
||||
// interior (see PERIOD_FIRST_CHECK).
|
||||
let d = z - z_saved;
|
||||
if !period_hit && mult2 < PERIOD_MAX_MULT2 && dot(d, d) <= PERIOD_EPS2 * z2 {
|
||||
period_hit = true;
|
||||
period_streak = period_streak + 1u;
|
||||
if period_streak >= PERIOD_CONFIRMATIONS {
|
||||
break;
|
||||
}
|
||||
}
|
||||
var dc2 = z2;
|
||||
if KIND == KIND_LAMBDA {
|
||||
dc2 = dot(z - crit, z - crit);
|
||||
}
|
||||
if dc2 < cand_d2 {
|
||||
cand_d2 = dc2;
|
||||
z_cand = z;
|
||||
mult2_cand = 1.0;
|
||||
}
|
||||
}
|
||||
let dc2 = dot(z - crit, z - crit);
|
||||
if dc2 < cand_d2 {
|
||||
cand_d2 = dc2;
|
||||
z_cand = z;
|
||||
mult2_cand = 1.0;
|
||||
}
|
||||
if n >= check_at {
|
||||
if !period_hit {
|
||||
@@ -1227,6 +1353,7 @@ fn iterate_sample(offset: vec2<f32>, px: f32) -> Sample {
|
||||
}
|
||||
period_hit = false;
|
||||
z_saved = z_cand;
|
||||
save_d2 = cand_d2 * PERIOD_SAVE_SLACK;
|
||||
mult2 = mult2_cand;
|
||||
cand_d2 = 3.0e38;
|
||||
// (A BLA jump can pass several window ends at once.)
|
||||
|
||||
+251
-17
@@ -65,22 +65,33 @@ fn specialize(
|
||||
.unwrap_or_else(|e| panic!("{name} {entry_point} {constants:?}: SPIR-V error: {e:?}"));
|
||||
}
|
||||
|
||||
/// `mandelbrot.wgsl` as `GpuPath::Storage` builds it (renderer.rs's
|
||||
/// `GpuPath::mandelbrot_source`).
|
||||
const MANDELBROT_SRC: &str = concat!(
|
||||
include_str!("../src/shaders/common.wgsl"),
|
||||
include_str!("../src/shaders/iterate_uniforms.wgsl"),
|
||||
include_str!("../src/shaders/mandelbrot.wgsl"),
|
||||
include_str!("../src/shaders/data_storage.wgsl"),
|
||||
);
|
||||
|
||||
/// `mandelbrot.wgsl` as `GpuPath::Texture` (WebGL2) builds it.
|
||||
const MANDELBROT_TEXTURE_SRC: &str = concat!(
|
||||
include_str!("../src/shaders/common.wgsl"),
|
||||
include_str!("../src/shaders/iterate_uniforms.wgsl"),
|
||||
include_str!("../src/shaders/mandelbrot.wgsl"),
|
||||
include_str!("../src/shaders/data_texture.wgsl"),
|
||||
);
|
||||
|
||||
#[test]
|
||||
fn mandelbrot_shader_is_valid() {
|
||||
validate("mandelbrot.wgsl", MANDELBROT_SRC);
|
||||
validate("mandelbrot.wgsl (texture)", MANDELBROT_TEXTURE_SRC);
|
||||
}
|
||||
|
||||
/// Every specialization renderer.rs can build (`PipelineKey`: kind × Julia ×
|
||||
/// DE × morph × deep × BLA), for every fragment entry point.
|
||||
#[test]
|
||||
fn mandelbrot_shader_specializations_compile() {
|
||||
let (module, info) = validate("mandelbrot.wgsl", MANDELBROT_SRC);
|
||||
/// Every `PipelineKey` renderer.rs can build: kind × Julia × DE × morph ×
|
||||
/// deep × BLA, as override constants.
|
||||
fn pipeline_keys() -> Vec<[(&'static str, f64); 6]> {
|
||||
let mut keys = Vec::new();
|
||||
for kind in 0..kind_count() {
|
||||
for julia in [0.0, 1.0] {
|
||||
for de in [0.0, 1.0] {
|
||||
@@ -93,30 +104,243 @@ fn mandelbrot_shader_specializations_compile() {
|
||||
&[0.0]
|
||||
};
|
||||
for &bla in blas {
|
||||
let constants = [
|
||||
keys.push([
|
||||
("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(
|
||||
"mandelbrot.wgsl",
|
||||
&module,
|
||||
&info,
|
||||
naga::ShaderStage::Fragment,
|
||||
entry,
|
||||
&constants,
|
||||
);
|
||||
}
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
keys
|
||||
}
|
||||
|
||||
/// Every specialization renderer.rs can build, for every fragment entry
|
||||
/// point, on both data paths.
|
||||
#[test]
|
||||
fn mandelbrot_shader_specializations_compile() {
|
||||
for (name, src) in [
|
||||
("mandelbrot.wgsl", MANDELBROT_SRC),
|
||||
("mandelbrot.wgsl (texture)", MANDELBROT_TEXTURE_SRC),
|
||||
] {
|
||||
let (module, info) = validate(name, src);
|
||||
for constants in pipeline_keys() {
|
||||
for entry in ["fs_data", "fs_refine", "fs_color"] {
|
||||
specialize(
|
||||
name,
|
||||
&module,
|
||||
&info,
|
||||
naga::ShaderStage::Fragment,
|
||||
entry,
|
||||
&constants,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Translate `entry_point` to GLSL ES 3.00 as wgpu's GL backend does on
|
||||
/// WebGL2 (`wgpu-hal`'s gles `create_pipeline`), and, when
|
||||
/// `glslangValidator` is on the PATH, compile the result. naga's ES 3.00
|
||||
/// output can call builtins ES 3.00 lacks (`ldexp`, `findLSB`), which only
|
||||
/// a real GLSL compiler (or the browser) rejects.
|
||||
fn to_gles300(
|
||||
name: &str,
|
||||
module: &naga::Module,
|
||||
info: &naga::valid::ModuleInfo,
|
||||
stage: naga::ShaderStage,
|
||||
entry_point: &str,
|
||||
constants: &[(&str, f64)],
|
||||
) -> String {
|
||||
let mut pc = naga::back::PipelineConstants::default();
|
||||
for (k, v) in constants {
|
||||
pc.insert((*k).to_string(), *v);
|
||||
}
|
||||
let what = format!("{name} {entry_point} {constants:?}");
|
||||
let (module, info) = naga::back::pipeline_constants::process_overrides(
|
||||
module,
|
||||
info,
|
||||
Some((stage, entry_point)),
|
||||
&pc,
|
||||
)
|
||||
.unwrap_or_else(|e| panic!("{what}: override error: {e:?}"));
|
||||
let options = naga::back::glsl::Options {
|
||||
version: naga::back::glsl::Version::Embedded {
|
||||
version: 300,
|
||||
is_webgl: true,
|
||||
},
|
||||
..Default::default()
|
||||
};
|
||||
let pipeline = naga::back::glsl::PipelineOptions {
|
||||
shader_stage: stage,
|
||||
entry_point: entry_point.to_string(),
|
||||
multiview: None,
|
||||
};
|
||||
let mut out = String::new();
|
||||
naga::back::glsl::Writer::new(
|
||||
&mut out,
|
||||
&module,
|
||||
&info,
|
||||
&options,
|
||||
&pipeline,
|
||||
naga::proc::BoundsCheckPolicies::default(),
|
||||
)
|
||||
.and_then(|mut w| w.write())
|
||||
.unwrap_or_else(|e| panic!("{what}: GLSL error: {e:?}"));
|
||||
glslang_check(&what, stage, &out);
|
||||
out
|
||||
}
|
||||
|
||||
/// Compile GLSL `src` with `glslangValidator`, if installed.
|
||||
fn glslang_check(what: &str, stage: naga::ShaderStage, src: &str) {
|
||||
use std::io::Write as _;
|
||||
let stage = match stage {
|
||||
naga::ShaderStage::Vertex => "vert",
|
||||
naga::ShaderStage::Fragment => "frag",
|
||||
_ => unreachable!("WebGL2 has no other stages"),
|
||||
};
|
||||
let child = std::process::Command::new("glslangValidator")
|
||||
.args(["--stdin", "-S", stage])
|
||||
.stdin(std::process::Stdio::piped())
|
||||
.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::piped())
|
||||
.spawn();
|
||||
let Ok(mut child) = child else {
|
||||
return; // not installed: naga's translation is all we can check
|
||||
};
|
||||
child
|
||||
.stdin
|
||||
.take()
|
||||
.unwrap()
|
||||
.write_all(src.as_bytes())
|
||||
.unwrap();
|
||||
let out = child.wait_with_output().unwrap();
|
||||
assert!(
|
||||
out.status.success(),
|
||||
"{what}: GLSL ES 3.00 doesn't compile:\n{}\n{src}",
|
||||
String::from_utf8_lossy(&out.stdout)
|
||||
);
|
||||
}
|
||||
|
||||
/// The WebGL2 build's shaders (`GpuPath::Texture`, plus the passes shared
|
||||
/// with WebGPU) translate to GLSL ES 3.00 that compiles, for every
|
||||
/// specialization.
|
||||
#[test]
|
||||
fn webgl_shaders_compile_to_gles300() {
|
||||
let (module, info) = validate("mandelbrot.wgsl (texture)", MANDELBROT_TEXTURE_SRC);
|
||||
let keys = pipeline_keys();
|
||||
// One thread per chunk of keys: glslangValidator runs once per shader.
|
||||
let threads = std::thread::available_parallelism().map_or(4, |n| n.get());
|
||||
std::thread::scope(|scope| {
|
||||
for chunk in keys.chunks(keys.len().div_ceil(threads)) {
|
||||
let (module, info) = (&module, &info);
|
||||
scope.spawn(move || {
|
||||
for constants in chunk {
|
||||
for entry in ["fs_data", "fs_refine", "fs_color"] {
|
||||
to_gles300(
|
||||
"mandelbrot.wgsl (texture)",
|
||||
module,
|
||||
info,
|
||||
naga::ShaderStage::Fragment,
|
||||
entry,
|
||||
constants,
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
to_gles300(
|
||||
"mandelbrot.wgsl (texture)",
|
||||
&module,
|
||||
&info,
|
||||
naga::ShaderStage::Vertex,
|
||||
"vs_main",
|
||||
&[],
|
||||
);
|
||||
|
||||
let others: [(&str, &str, &[&str]); 4] = [
|
||||
(
|
||||
"colorize.wgsl",
|
||||
concat!(
|
||||
include_str!("../src/shaders/common.wgsl"),
|
||||
include_str!("../src/shaders/iterate_uniforms.wgsl"),
|
||||
include_str!("../src/shaders/colorize.wgsl"),
|
||||
),
|
||||
&["fs_main"],
|
||||
),
|
||||
(
|
||||
"lipschitz.wgsl",
|
||||
concat!(
|
||||
include_str!("../src/shaders/common.wgsl"),
|
||||
include_str!("../src/shaders/lipschitz.wgsl"),
|
||||
),
|
||||
&["fs_seed", "fs_jump", "fs_compose"],
|
||||
),
|
||||
(
|
||||
"blit.wgsl",
|
||||
concat!(
|
||||
include_str!("../src/shaders/common.wgsl"),
|
||||
include_str!("../src/shaders/blit.wgsl"),
|
||||
),
|
||||
&["fs_main"],
|
||||
),
|
||||
("ci_sample.wgsl", CI_SAMPLE_SRC, &["fs_main"]),
|
||||
];
|
||||
for (name, src, entries) in others {
|
||||
let (module, info) = validate(name, src);
|
||||
to_gles300(
|
||||
name,
|
||||
&module,
|
||||
&info,
|
||||
naga::ShaderStage::Vertex,
|
||||
"vs_main",
|
||||
&[],
|
||||
);
|
||||
for entry in entries {
|
||||
to_gles300(
|
||||
name,
|
||||
&module,
|
||||
&info,
|
||||
naga::ShaderStage::Fragment,
|
||||
entry,
|
||||
&[],
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The texture path's bit-level `frexp`/`ldexp`/`ctz` replacements must not
|
||||
/// fall back on the builtins GLSL ES 3.00 lacks or polyfills badly (naga's
|
||||
/// `frexp` polyfill goes through log2).
|
||||
#[test]
|
||||
fn texture_path_avoids_es31_builtins() {
|
||||
let (module, info) = validate("mandelbrot.wgsl (texture)", MANDELBROT_TEXTURE_SRC);
|
||||
let constants = [
|
||||
("KIND", 0.0),
|
||||
("IS_JULIA", 0.0),
|
||||
("DE", 1.0),
|
||||
("MORPH", 0.0),
|
||||
("DEEP", 1.0),
|
||||
("BLA", 1.0),
|
||||
];
|
||||
let glsl = to_gles300(
|
||||
"mandelbrot.wgsl (texture)",
|
||||
&module,
|
||||
&info,
|
||||
naga::ShaderStage::Fragment,
|
||||
"fs_data",
|
||||
&constants,
|
||||
);
|
||||
for builtin in ["ldexp(", "frexp(", "findLSB("] {
|
||||
assert!(!glsl.contains(builtin), "texture path GLSL calls {builtin}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -179,6 +403,16 @@ fn buddhabrot_shader_specializations_compile() {
|
||||
}
|
||||
}
|
||||
|
||||
const CI_SAMPLE_SRC: &str = concat!(
|
||||
include_str!("../src/shaders/common.wgsl"),
|
||||
include_str!("../src/shaders/ci_sample.wgsl"),
|
||||
);
|
||||
|
||||
#[test]
|
||||
fn ci_sample_shader_is_valid() {
|
||||
validate("ci_sample.wgsl", CI_SAMPLE_SRC);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ci_stats_shader_is_valid() {
|
||||
validate(
|
||||
|
||||
Reference in New Issue
Block a user