Compare commits

74 Commits
Author SHA1 Message Date
surv 8750bb1590 fix: Smooth 2d shadow view of complex multibrot 2026-09-27 13:20:48 +02:00
surv f30921f7a5 fix: Smooth 3d view of complex multibrot 2026-09-27 13:17:35 +02:00
surv b6467fc18c fix: DE of multibrot fractal 2026-09-27 12:31:30 +02:00
surv 28ff2471b3 feat: multibrot exponent up to 20 2026-09-27 12:23:11 +02:00
surv 1bb3113581 fix: remove zoom limits 2026-09-27 12:17:08 +02:00
surv bfd3d18f3d feat: Add arbitrary precision numbers at deep zooms 2026-09-25 15:30:05 +02:00
surv fbf0ef64af fix: add c parameter again for lambda fractal in julia mode 2026-09-25 10:06:01 +02:00
surv 0d86e7b0e0 fix: periodicity checking stop flagging false positives 2026-09-25 10:02:14 +02:00
surv 583a535806 feat: allow bigger render distance in 3d view 2026-09-25 09:46:36 +02:00
surv ba385be18d fix: remove red band above small slope in 3d 2026-09-25 09:32:11 +02:00
surv 120e73fb10 fix: small zoom in 3d mode no longer create visual artefacts 2026-09-25 09:20:55 +02:00
surv 8889a09bf8 fix: remove weird gray circle around fractals 2026-09-25 09:13:59 +02:00
surv 94f9c488bd fix: complex multibrot rendering 2026-09-25 08:43:59 +02:00
surv a092be84b0 chore: remove warnings on web version 2026-09-25 08:12:02 +02:00
surv 73570fdab8 perf: Use multithreading for headless animation export 2026-09-25 08:09:34 +02:00
surv 9b0dec25e2 perf: reduce memory usage\nAllocate textures only when needed 2026-09-24 22:18:44 +02:00
surv 38cbb1f132 feat: add more animations and 3d export 2026-09-24 22:12:56 +02:00
surv 61d4766088 perf: disable AA when switching fractals 2026-09-24 21:56:39 +02:00
surv 51fa5ffa02 feat: add interpolation between fractals 2026-09-24 21:43:36 +02:00
surv 9cc5a80650 feat: add classic colors in 3d 2026-09-24 21:39:00 +02:00
surv 6a6796f528 fix: reduce memory usage on web 2026-09-24 21:06:34 +02:00
surv b4ca187ba2 fix: shadow and 3d rendering at deep zoom and on weird fractals 2026-09-24 20:38:37 +02:00
surv 2bdb2356c6 perf: improve 3d ray marching performance 2026-09-24 19:45:17 +02:00
surv 5206a22bdd fix: UX issues solved 2026-09-24 19:16:56 +02:00
surv 42dde04945 perf: add periodicity checking 2026-09-24 18:53:17 +02:00
surv a3fd152dff perf: improve overall performance 2026-09-24 18:23:19 +02:00
surv 7dd99cc1af feat: update gitignore 2026-09-24 16:48:06 +02:00
surv 63cee5d8b2 fix: correct 3d rendering 2026-09-23 18:34:00 +02:00
surv 694f63ab9d feat: improve CLI arguments 2026-09-22 11:39:11 +02:00
surv 7274f19b33 feat: improve UI/UX 2026-09-22 09:59:58 +02:00
surv 66669cd801 feat: add 3d support 2026-09-22 09:36:30 +02:00
surv c2de1bc4bb fix: disable auto-iterations when passing an iterations parameter in CLI through --view 2026-09-21 22:42:55 +02:00
surv 07319874bf fixup: add animation export 2026-09-20 15:23:15 +02:00
surv 449b1b289b feat: add animation export 2026-09-20 14:12:54 +02:00
surv 993185795f feat: improve CLI 2026-09-20 13:37:33 +02:00
surv 456d744ac6 feat: Better default values 2026-09-20 13:37:33 +02:00
surv 90d917ede0 refactor: cleanup code 2026-09-20 13:37:33 +02:00
surv 5a81247d76 refactor: add common shaders helpers + fix shadow export 2026-09-20 13:37:33 +02:00
surv d84e752e15 feat: improve colors when using distance estimate 2026-09-20 13:37:33 +02:00
surv eb041c22c5 feat: improve UI/UX 2026-09-20 13:37:33 +02:00
surv 06b52fe954 feat: Add complex multibrot fractal 2026-09-20 13:37:33 +02:00
surv c7d687c107 feat: minor visual fix for PNG export 2026-09-20 13:37:33 +02:00
survandClaude Sonnet 5 c2b38ea21b feat: add keyboard shortcuts for pan/zoom/iterations/AA
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-20 13:37:33 +02:00
survandClaude Sonnet 5 16a916d35a feat: add fractal info and help overlays
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-20 13:37:33 +02:00
survandClaude Sonnet 5 45654c0846 feat: add a headless mode, driven by clap CLI args
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-20 13:37:33 +02:00
survandClaude Sonnet 5 cc0609ffbb feat: add clap CLI arg parser, replacing MANDEL_* debug env vars
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-19 20:50:17 +02:00
surv 0f25c89a7b feat: Add a CLAUDE.md file 2026-09-19 20:50:17 +02:00
surv 908c13bfb0 feat: add shadow coloring 2026-09-19 20:50:17 +02:00
surv 7c347a5abf feat: add buddhabrot fractal 2026-09-16 22:04:21 +02:00
surv afcd3c74da feat: add lambda fractal 2026-09-16 20:32:48 +02:00
surv 0b90b72a00 feat: remove warning and increase performance 2026-09-16 20:14:39 +02:00
surv ad63a1da09 feat: add more presets 2026-09-16 15:32:13 +02:00
surv f373db91e6 chore: Refactor files and fix warnings 2026-09-16 15:31:40 +02:00
surv f039d38bfa feat: Add FPS counter 2026-09-15 21:22:39 +02:00
surv fbe7f4da13 perf: editing theme doesn't require a complete reredenring 2026-09-15 21:14:14 +02:00
surv a5b26ce738 feat: Add animations 2026-09-15 21:00:29 +02:00
surv 311b797724 feat: Add fullscreen button 2026-09-15 20:28:51 +02:00
surv 7f4f31a09f feat: Add more fractals 2026-09-15 19:28:49 +02:00
surv d77baf5e15 feat: add favicon 2026-09-15 18:29:38 +02:00
surv 9e9641891e feat: distance-estimation shading for crisp deep-zoom filaments 2026-09-15 15:50:57 +02:00
surv acbf25d64e feat: lossless share links + auto iteration count 2026-09-15 15:50:57 +02:00
surv c92c685ade perf: reduce resolution and disable AA when moving/zooming 2026-09-15 15:50:57 +02:00
surv c36c8b9829 feat: add other fractals 2026-09-15 15:50:57 +02:00
surv 72c3ea2ee8 feat: add rendering export progress bar 2026-09-15 11:01:30 +02:00
surv f9a51fd2d7 feat: add PNG encoding progress bar 2026-09-15 10:42:39 +02:00
surv a7a34adff2 feat: add presets for mandelbrot 2026-09-15 10:18:19 +02:00
surv 9069d23b21 feat: coordinates and magnification can be set to specific values 2026-09-15 09:48:53 +02:00
surv 96c5d6344e feat: make amber the default theme 2026-09-15 09:38:57 +02:00
surv 8bed728585 feat: add multi touch zoom on phones 2026-09-15 09:27:39 +02:00
surv b2c29504bc feat: don't draw the fractal each frames 2026-09-15 09:22:38 +02:00
surv 343ddfc4b7 feat: add SSAA 2026-09-15 09:07:21 +02:00
surv 10fc122e9c feat: allow bigger exports 2026-09-15 09:06:58 +02:00
surv c197a03a51 feat: force webgpu in WASM 2026-09-15 08:55:18 +02:00
surv 09d7976ebd First commit 2026-09-15 08:55:18 +02:00
51 changed files with 668 additions and 7783 deletions
+1 -1
View File
@@ -3,4 +3,4 @@ Cargo.lock
dist
frames*
out.mp4
__pycache__
+23 -179
View File
@@ -6,8 +6,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
A deep-zoom fractal explorer (Rust + wgpu + egui + WGSL). It zooms past the
~10¹³× limit of plain `f64` using **perturbation theory**: one high-precision
reference orbit is computed on the CPU (arbitrary precision via `bignum::Big`:
`rug` natively, `malachite-float` on the web),
reference orbit is computed on the CPU (arbitrary precision via `dashu-float`),
and every pixel is rendered on the GPU as a cheap `f32` delta from it, with
rebasing to avoid glitches. Plain `f32` deltas run out of exponent range
once a pixel is ~2^-124 wide (~10³⁴× at 1080p), so from 2^-122 per pixel
@@ -15,28 +14,25 @@ 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, plus a WebGL2
fallback with the `webgl` feature (see "WebGL2 fallback" below).
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).
## Commands
```sh
cargo run --release # native, run (release matters: fractal math is hot)
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 # reference-orbit math, share-link round-trip, WGSL validation
cargo test --test shader_valid # just the WGSL parse/validate tests (naga, no GPU needed)
cargo clippy
cargo fmt # rustfmt.toml just pins edition = "2024"
cargo build --release --no-default-features # headless-only binary: no eframe/egui (the default `gui` feature)
tools/bench/bench.sh --rev HEAD # perf of uncommitted edits vs HEAD (hyperfine; see tools/bench/README.md)
```
Web build (WebGPU, with WebGL2 fallback):
Web build (WebGPU):
```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,webgl)
./build-web.sh # -> ./dist
python3 -m http.server -d dist 8080
```
@@ -44,26 +40,12 @@ Native CLI flags (`src/cli.rs`, applied in `FractalApp::apply_cli`): `--kind`,
`--power`, `--julia re,im`, `--phoenix-p re,im`, `--lambda-l re,im`,
`--palette`, `--share <fragment>`,
`--view re,im,half_height[,iterations]`, `--rendering-kind`,
`--yaw`/`--pitch` (3D camera, degrees), `--de`, `--antialias` (2×2),
`--auto-color-scale`, `--color-scale`, `--no-bla`, `--buddhabrot`,
`--yaw`/`--pitch` (3D camera, degrees), `--de`, `--buddhabrot`,
`--buddha-palette`. `--headless` (`src/headless.rs`) skips the window
entirely: it builds the same view from the other flags, creates its own
offscreen wgpu device, and renders straight to a PNG (`--width`/`--height`,
default 1920×1080, `--export-path out.png`) without needing a GPU-backed
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. 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
window/event loop. Not yet supported with `--buddhabrot`. Run
`mandelbrot --help` for the full list.
`--headless` also has an animation mode, for feeding into `ffmpeg`: give any
@@ -73,28 +55,16 @@ end-state flag alongside the start flags (`--view`/`--share`/`--kind`/
position/zoom/iterations are pulled out of the link), `--to-iterations`,
`--to-julia`, `--to-phoenix-p`, `--to-lambda-l`, `--to-complex-power`
(or `--to-complex-power-re`/`--to-complex-power-im` to move one component),
`--to-kind` (per-step formula blend via `KindMorph`, camera untouched), and
`--to-color-scale` (log-linear from `--color-scale`; refused with
`--auto-color-scale`; `--to-color-scale-at HALF_HEIGHT` pins its completion
to a zoom depth instead of the end). Anything without a target stays at its start value;
other colors (palette, offset) stay fixed.
and `--to-kind` (per-step formula blend via `KindMorph`, camera untouched).
Anything without a target stays at its start value; colors stay fixed.
`--export-path` then names an output *directory* of `frame-00001.png`,
`frame-00002.png`, ... instead of a single file. `--export-path -` writes
to stdout instead (refused on a terminal): the PNG for a still, or for an
animation raw RGBA8 frames in order (`unpad_rgba`, no PNG encode) for
`ffmpeg -f rawvideo -pix_fmt rgba -s WxH -r FPS -i -`. A single writer
thread reorders the frames. Its buffer is bounded by the orbit workers not
starting a frame more than `window` past the last one written, not by
blocking the writer, which could deadlock. `headless.rs::AnimTargets`
`frame-00002.png`, ... instead of a single file. `headless.rs::AnimTargets`
collects the targets; the export pipeline is rebuilt only when the
`PipelineKey` changes between frames (kind morph). `view::interpolate_view`
does the camera: half-height geometrically (log-linear, since zoom spans many
decades), center linearly through the complex plane at full `Big` precision;
constants interpolate linearly. `--linear` swaps the default smoothstep
easing for constant pacing. `--shards N --shard K` (1-based) renders only
the K-th of N contiguous parts (`shard_range`), still timed against the whole
animation (global `t`, global `frame-NNNNN.png` numbers; stdout streams just
that part), so separately rendered clips join seamlessly. Without `--to-iterations` (or a share link's),
easing for constant pacing. Without `--to-iterations` (or a share link's),
iteration count auto-scales with zoom depth per frame (same
`auto_iteration_count` the interactive app uses while zooming).
`--to-yaw`/`--to-pitch` (degrees, from `--yaw`/`--pitch`, yaw unwrapped so
@@ -104,9 +74,7 @@ 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`). 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
(`encode_png`, `Compression::Fast`). 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`
@@ -124,26 +92,10 @@ 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. 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.
pixel is a handful of `f32` complex multiplies.
- `src/bignum/` — `Big`, the arbitrary-precision binary float, with one
backend per library behind the same inherent API + operators: `rug`
(GMP/MPFR, default, fastest, can't target wasm32) and `malachite-float`
(pure Rust, the `wasm` feature, required for the web build; a
`compile_error!` enforces it). Cargo features are additive, so rug is a
non-wasm32 target dependency and the backend is picked by
`cfg(feature = "wasm")`. Both follow the precision rule: a result has the
larger operand precision, rounded to nearest; shifts are exact. Malachite's
zero has no precision, so its wrapper stores `prec` alongside. Any new
`Big` operation must be added to both backends (`cargo test` and
`cargo test --features wasm` run the same tests on each).
- `src/view.rs` — `ViewState`; center is arbitrary-precision `Big`
(re-exported as `view::Big`). The pixel scale (`half_height`) is a `Scale`, an f64
- `src/view.rs` — `ViewState`; center is arbitrary-precision `FBig` (`Big`
type alias). The pixel scale (`half_height`) is a `Scale`, an f64
mantissa with its own i32 exponent, so it goes past f64's ~1e-308. Never
collapse it (or a center difference) to a plain `f64` on a path used at
depth. Rescale first: `Scale::scaled_f64(k)`, or shift the `Big` by
@@ -168,21 +120,15 @@ That was a few pixels per frame and ~40% of a −1.5 zoom's time.
`f32` pairs — that's the reference orbit the GPU perturbs from. At
precision ≤ `F64_MAX_PRECISION` (80 bits, i.e. shallow views) it takes a
plain-`f64` fast path (`compute_reference_f64`), so each kind's formula
exists twice in this file (f64 + `Big`) and both must stay in sync;
exists twice in this file (f64 + `FBig`) and both must stay in sync;
`f64_fast_path_matches_big` checks they agree. The result is a `RefOrbit`:
`points` plus a parallel `exps`. A point below 2^-100 (only possible on the
`Big` path) is stored as a normalized mantissa with its exponent in `exps`
`FBig` path) is stored as a normalized mantissa with its exponent in `exps`
(the true value is `points[n]·2^exps[n]`). That happens when the orbit
passes near 0 at a deep minibrot. `has_scaled()` then forces the deep
pipeline, the only one that reads `exps`. Requests are made with 1.5×
iteration headroom (`reference_iterations` in `app.rs`), so auto-iterations
creeping up during a zoom doesn't recompute the orbit every frame. The
interactive reference buffers start at 2^17 points and grow on demand
(`FractalRenderer::ensure_ref_capacity`) up to `MAX_REF_POINTS` (2^24, the
128 MiB WebGPU default binding size). That is also the hard iteration
ceiling (`app.rs::MAX_ITERATIONS`), because the shader treats an exhausted
reference as escaped. The UI slider only goes to 100k when dragged; typed
values can go higher.
creeping up during a zoom doesn't recompute the orbit every frame.
- `src/shaders/*.wgsl` — none of these are standalone WGSL modules; WGSL has
no `#include`, so each is compiled by concatenating plain-text fragments
with `concat!`/`include_str!` at the `create_shader_module` call site (see
@@ -192,8 +138,6 @@ That was a few pixels per frame and ~40% of a −1.5 zoom's time.
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.
@@ -215,11 +159,7 @@ That was a few pixels per frame and ~40% of a −1.5 zoom's time.
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). 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.
(seen at ~1e-13 zoom). Phoenix is excluded (two-term map).
`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
@@ -233,7 +173,7 @@ That was a few pixels per frame and ~40% of a −1.5 zoom's time.
are `advance_delta_kind`/`fprime_kind`; `advance_delta`/`fprime` wrap them
to blend two kinds during the kind-switch morph (`u.morph_from`,
`u.morph_w`: each step is `(1-w)·f_kind + w·f_from`, mirrored on the CPU by
the `morph` argument of `compute_reference`, in both its f64 and `Big`
the `morph` argument of `compute_reference`, in both its f64 and `FBig`
paths). The blend only exists in pipelines built with the `MORPH` override
(part of `PipelineKey`, on while `morph_w > 0`); those also skip periodicity
detection and the cardioid bypass. App side: `KindMorph` in
@@ -264,56 +204,9 @@ That was a few pixels per frame and ~40% of a −1.5 zoom's time.
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. 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
changing it. Known gaps: Lambda's critical point is 1/2, so its step keeps
the input scale. Lambda set mode's reference sits at the origin, so it
never reaches deep zooms anyway.
- `src/fractal/bla.rs` — **bivariate linear approximation**: a table of
merged linear steps `e' = M·e + N·dc` (real 2×2 matrices; valid while
`|e| < R`) built on the CPU from the reference orbit, so the shader's
`bla_lookup` jumps each pixel over whole runs of steps. Every kind but
Phoenix (two-term map), no morph (`bla::applies`, the `BLA` override).
`M` is the map's Jacobian at `X`: `C(f'(X))` for the holomorphic kinds, a
sign fold of `C(2X)` for the abs/conjugate ones. Each kind's `M` and
radius live in `Node::step`, which must match `advance_delta_kind`. The
abs kinds' radius also keeps the delta off their fold lines (where
`diffabs` switches branch), and Complex Multibrot's keeps it off the
branch cut. So Burning Ship / Perpendicular / Buffalo can't jump along the
real axis (their fold), where their orbits often sit. Merges use the exact
2×2 spectral norm (Frobenius would lose √2 of radius per level). This is
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 (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
change or when the dc range grows (or shrinks by `BLA_DC_SLACK` binades).
Exports/headless build per frame via `bla::for_uniforms`. The table stops
before the reference crosses the pixel bailout, so a jump never skips an
escape. Measure `|e|` with `log2_mag`, never `log2(dot(e, e))`: a
2^-100 delta squares to 0 in f32 and passed every radius test.
`--no-bla` / the "Skip iterations (BLA)" checkbox upload an empty table
for A/B checks. BLA must render like `--no-bla` up to f32 noise; on
chaotic views, compare against a `--no-bla` render nudged by ~0.01 px,
which differs by more. `escape_counts_match_all_kinds` checks every
kind on the CPU against the plain loop with f32 rounding.
- `src/fractal/renderer.rs` — `FractalRenderer` (wgpu pipelines, uniform +
storage buffers, bind groups), `Uniforms` (repr(C) layout that must match
the WGSL `Uniforms` struct field-for-field, including padding; it includes
@@ -355,9 +248,7 @@ arms), `reference.rs` (CPU iteration formula arm, and a test comparing
against a naive `f64` iteration), `common.wgsl` (matching `KIND_*` const),
`mandelbrot.wgsl` (matching `advance_delta`/`fprime` arms, plus the deep
path's `advance_delta_scaled_kind` arm, its degree in `deep_step_kind` and,
if not z²-like, a `deep_fprime` arm), `bla.rs` (a `Node::step` arm: the
step's Jacobian and linearity radius, plus a case in
`escape_counts_match_all_kinds`; or exclude the kind in `applies`), `buddhabrot.wgsl`
if not z²-like, a `deep_fprime` arm), `buddhabrot.wgsl`
(matching arm in `advance()`, if the kind makes sense as a Buddhabrot),
`renderer.rs` `Uniforms` (only if the kind needs a new per-kind constant,
e.g. Phoenix's `phoenix_p`), `app.rs` (`JULIA_PRESETS`/`SET_PRESETS` slot,
@@ -379,45 +270,6 @@ 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
@@ -445,14 +297,6 @@ mip pyramid (quadtree height-field tracing) was tried and measured about 3×
slower, because it needs about 12 costlier steps per ray. Don't reintroduce it.
Orbiting the camera only re-runs the colourise pass, never iteration.
**Auto color scale** (`CiStats` in `renderer.rs`, `ci_stats.wgsl`): after
each iteration, a compute pass bins the data texture's `ci` into a log-scale
histogram. It's read back asynchronously: copied in frame N, mapped in N+1
(the copy has to be submitted first), and picked up by
`FractalApp::poll_ci_stats`. The app then fits one palette cycle across the
0.5–99.5th percentile. `ci_lo` shifts the offset (`effective_color_offset`),
which is what exports and share links get.
While the user is actively panning/zooming, the app renders downscaled with
AA off (`INTERACT_DOWNSCALE`) and snaps back to full resolution once input
settles (`INTERACT_SETTLE`).
+5 -23
View File
@@ -3,37 +3,19 @@ name = "mandelbrot"
version = "0.1.0"
edition = "2024"
[features]
default = ["gui"]
# Windowed egui app. Without it only `--headless` rendering is built.
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"] }
eframe = { version = "0.36.2", default-features = false, features = ["wgpu", "default_fonts", "x11", "wayland", "accesskit"], optional = true }
egui = { version = "0.36.2", optional = true }
ecolor = { version = "0.36.2", features = ["bytemuck"] }
wgpu = "30.0.1"
dashu-float = "0.6.0"
eframe = { version = "0.36.2", default-features = false, features = ["wgpu", "default_fonts", "x11", "wayland", "accesskit"] }
egui = "0.36.2"
glam = "0.33.8"
log = "0.4.34"
png = "0.18.1"
malachite-float = { version = "0.12", optional = true }
malachite-base = { version = "0.12", optional = true }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
env_logger = "0.11.11"
clap = { version = "4.5.51", features = ["derive"] }
pollster = "1.0.1"
rug = { version = "1.30.0", default-features = false, features = ["float", "std"] }
[target.'cfg(target_arch = "wasm32")'.dependencies]
futures-channel = { version = "0.3.34", default-features = false, features = ["alloc", "std"] }
@@ -50,7 +32,7 @@ opt-level = 3
# codegen-units = 1
debug = true
# Dev: keep our own crate debuggable, but optimize dependencies (big floats, wgpu,
# Dev: keep our own crate debuggable, but optimize dependencies (dashu, wgpu,
# egui) so the explorer is actually interactive during development.
[profile.dev]
opt-level = 1
@@ -59,4 +41,4 @@ opt-level = 1
opt-level = 3
[dev-dependencies]
naga = { version = "30", features = ["wgsl-in", "spv-out", "glsl-out"] }
naga = { version = "30", features = ["wgsl-in", "spv-out"] }
-674
View File
@@ -1,674 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
-114
View File
@@ -1,114 +0,0 @@
.PHONY: hevc-nvenc x265 x265-master x265-small av1 av1-master av1-small
FFMPEG=ffmpeg
IN_FMT=rgba
RESOLUTION=1920x1080
FPS=60
OUT=out.mp4
# 10 s GOP: fractal zooms have no scene cuts, so keyframes only cost bits.
KEYINT=$(shell awk 'BEGIN { print int($(FPS) * 10 + 0.5) }')
FFMPEG_IN=$(FFMPEG) -f rawvideo -pix_fmt $(IN_FMT) -s $(RESOLUTION) -framerate $(FPS) -i -
SCALE=scale=out_color_matrix=bt709:out_range=tv:flags=accurate_rnd+full_chroma_int+bitexact
# setparams tags the frames themselves: encoders read colour info from the
# filter output, so the -color_* options alone left primaries/transfer unset.
TAG=setparams=colorspace=bt709:color_primaries=bt709:color_trc=bt709:range=tv
COLOR_TAGS=-colorspace bt709 -color_primaries bt709 -color_trc bt709 -color_range tv
# Settings and CRFs come from tools/encode/ (see its README for the numbers).
# Tiers: `x265`/`av1` = delivery (VMAF ~95 mean, >= 90 worst frame, smallest
# file); `*-master` = upload master (>= 97 worst frame, size secondary);
# `*-small` = about half the delivery size, visibly softer on faint texture
# (CRF extrapolated from the sweeps, not measured).
# The binding test clip is a faint, low-contrast Julia texture: at a CRF where
# dense filaments already score 99, both encoders smear it, so it sets the CRF.
# preset medium: slow scores better at equal bitrate but runs ~2.4x slower,
# far outside the speed budget.
# aq-mode=3 (vs 4): 4 loses at matched bitrate on gradients and faint texture.
# no-sao: SAO lowers VMAF at the same bitrate (smooths fine filaments).
# merange=92: 4K zoom motion is large; ~2% smaller at no speed cost.
# rect=1: ~7% smaller at equal or better VMAF (about 20% slower).
# rdoq-level=2 + psy-rdoq=1: keeps the faint texture; the binding clip then
# needs CRF ~17 instead of ~15, a smaller file overall.
X265_PARAMS=keyint=$(KEYINT):min-keyint=$(FPS):aq-mode=3:no-sao=1:merange=92:rect=1:rdoq-level=2:psy-rdoq=1.0
# preset 6: fits the speed budget (p5 is ~20% slower).
# tune=0 (VQ; ffmpeg defaults to PSNR): much better worst frames on faint texture.
# enable-variance-boost=1: more bits to flat/low-contrast blocks; faint Julia
# texture goes from p1 ~85 to ~93 at CRF 32.
# enable-qm=1 (default qm-min): 3-11% smaller at equal VMAF; qm-min=0 caps
# quality on faint texture and hurts filaments.
# film-grain=0: synthetic grain would add noise the renders don't have.
# tf and overlays stay default: disabling tf costs +50% bits and adds banding.
# scd=1: untested on its own; SVT-AV1 4.2 says it won't insert keyframes at
# scene changes anyway, so it's likely a no-op here.
SVT_PARAMS=film-grain=0:keyint=$(KEYINT):scd=1:tune=0:enable-variance-boost=1:enable-qm=1
hevc-nvenc:
$(FFMPEG_IN) -vf "$(SCALE),format=p010le" \
-c:v hevc_nvenc -preset p7 -tune hq -rc vbr -cq 14 -b:v 0 -maxrate 200M -bufsize 400M \
-profile:v main10 -pix_fmt p010le \
-spatial-aq 1 -aq-strength 6 -temporal-aq 1 \
-rc-lookahead 32 -bf 4 -b_ref_mode middle -multipass fullres \
$(COLOR_TAGS) \
-tag:v hvc1 -movflags +faststart \
$(OUT)
# Delivery: CRF 17 (binding clip: VMAF 94.8 mean, 92.8 worst frame).
x265:
$(FFMPEG_IN) -vf "$(SCALE),format=yuv420p10le,$(TAG)" \
-c:v libx265 -profile:v main10 -preset medium -crf 17 \
-x265-params "$(X265_PARAMS)" \
$(COLOR_TAGS) \
-tag:v hvc1 -movflags +faststart \
$(OUT)
# Master: CRF 12 (binding clip: 97.6 worst frame).
x265-master:
$(FFMPEG_IN) -vf "$(SCALE),format=yuv420p10le,$(TAG)" \
-c:v libx265 -profile:v main10 -preset medium -crf 12 \
-x265-params "$(X265_PARAMS)" \
$(COLOR_TAGS) \
-tag:v hvc1 -movflags +faststart \
$(OUT)
# Small: CRF 23, ~half the size of `x265` (bitrate fell ~40% from CRF 16 to 20).
# Untested: expect faint texture around VMAF 89 mean; dense detail stays ~97+.
x265-small:
$(FFMPEG_IN) -vf "$(SCALE),format=yuv420p10le,$(TAG)" \
-c:v libx265 -profile:v main10 -preset medium -crf 23 \
-x265-params "$(X265_PARAMS)" \
$(COLOR_TAGS) \
-tag:v hvc1 -movflags +faststart \
$(OUT)
# Delivery: CRF 32 (binding clip: VMAF 95.0 mean, 93.4 worst frame).
av1:
$(FFMPEG_IN) -vf "$(SCALE),format=yuv420p10le,$(TAG)" \
-c:v libsvtav1 -preset 6 -crf 32 \
-svtav1-params "$(SVT_PARAMS)" \
$(COLOR_TAGS) \
-movflags +faststart \
$(OUT)
# Master: CRF 17 (binding clip: ~97.1 worst frame, interpolated from CRF 14/20).
av1-master:
$(FFMPEG_IN) -vf "$(SCALE),format=yuv420p10le,$(TAG)" \
-c:v libsvtav1 -preset 6 -crf 17 \
-svtav1-params "$(SVT_PARAMS)" \
$(COLOR_TAGS) \
-movflags +faststart \
$(OUT)
# Small: CRF 40, ~half the size of `av1` (bitrate fell ~35% from CRF 26 to 32).
# Untested: expect faint texture around VMAF 92 mean; dense detail stays ~97+.
av1-small:
$(FFMPEG_IN) -vf "$(SCALE),format=yuv420p10le,$(TAG)" \
-c:v libsvtav1 -preset 6 -crf 40 \
-svtav1-params "$(SVT_PARAMS)" \
$(COLOR_TAGS) \
-movflags +faststart \
$(OUT)
+2 -9
View File
@@ -3,8 +3,7 @@
A fast, interactive deep-zoom fractal explorer — Mandelbrot and Julia sets —
built with **Rust + wgpu + egui + WGSL**. It zooms far past the ~10¹³× limit of
plain `f64` using **perturbation theory**: one high-precision reference orbit is
computed on the CPU (arbitrary precision via `rug` natively, `malachite-float`
on the web), and every pixel is
computed on the CPU (arbitrary precision via `dashu-float`), and every pixel is
rendered on the GPU as a cheap `f32` delta from it, with **rebasing** to avoid
glitches. Runs natively (Vulkan/Metal/DX12) and in the browser (WebGPU).
@@ -28,9 +27,6 @@ The `f32` GPU tier reaches roughly **10³⁰× magnification** with sharp detail
cargo run --release
```
Native builds use `rug` (GMP/MPFR) for the reference orbit, which needs a C
toolchain and `m4` (on Windows, MSYS2).
## Build & run — web (WebGPU)
Requires the `wasm32-unknown-unknown` target and `wasm-bindgen-cli` (matching the
@@ -41,7 +37,6 @@ rustup target add wasm32-unknown-unknown
cargo install wasm-bindgen-cli --version 0.2.128 # once
./build-web.sh # outputs ./dist (index.html, .js, .wasm)
# (builds with --features wasm: pure-Rust big floats)
python3 -m http.server -d dist 8080 # serve over http
```
@@ -65,8 +60,7 @@ qualifies. Deploy by serving the `dist/` directory as static files.
## How it works
- `src/view.rs` — view state. Center is arbitrary precision (`Big`, from
`src/bignum/`); the pixel
- `src/view.rs` — view state. Center is arbitrary precision (`FBig`); the pixel
scale stays `f64` (even at 10³⁰× it is ~10⁻³³, within `f64` range).
- `src/fractal/reference.rs` — high-precision reference orbit `Z_{n+1}=Z_n²+C`.
- `src/shaders/mandelbrot.wgsl` — per-pixel perturbation `e_{n+1}=2·Z_n·e_n+e_n²+δc`
@@ -90,7 +84,6 @@ reference computation to a Web Worker.
```sh
cargo test
cargo test --features wasm # same suite on the web build's big-float backend
```
Covers the reference orbit (vs. a naive `f64` iteration, Mandelbrot and Julia)
+2 -3
View File
@@ -1,15 +1,14 @@
#!/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+); the
# `webgl` feature falls back to WebGL2 elsewhere (no Buddhabrot there).
# WebGPU-capable browser (recent Chrome/Edge, Firefox, or Safari 26+).
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,webgl
cargo build --release --target wasm32-unknown-unknown
echo "==> wasm-bindgen -> $OUT"
mkdir -p "$OUT"
+2 -3
View File
@@ -46,9 +46,8 @@
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 WebGPU (recent Chrome/Edge, " +
"Firefox, or Safari 26+) or, in builds with the <code>webgl</code> " +
"feature, WebGL2 with float render targets.</p>";
"<p>Failed to start. This app needs a WebGPU-capable browser " +
"(recent Chrome/Edge, Firefox, or Safari 26+).</p>";
console.error(err);
}
});
+79 -456
View File
File diff suppressed because it is too large Load Diff
-225
View File
@@ -1,225 +0,0 @@
//! Arbitrary-precision binary float [`Big`] (one coordinate of a deep-zoom
//! center, or of a reference orbit point), over one of two backends:
//!
//! - native (default): `rug` (GMP/MPFR), the fastest, but C code that can't
//! target `wasm32-unknown-unknown`;
//! - `wasm` feature: a pure-Rust library, required for the web build.
//!
//! Both expose the same inherent API plus the operators below, and follow
//! the same precision rule: an operation's result has the larger of its
//! operands' precisions (in bits), rounded to nearest. Shifts (`<<`/`>>` by
//! an `isize`) are exact multiplications by powers of two.
#[cfg(not(feature = "wasm"))]
mod rug_backend;
#[cfg(not(feature = "wasm"))]
pub use rug_backend::Big;
#[cfg(feature = "wasm")]
mod web_backend;
#[cfg(feature = "wasm")]
pub use web_backend::Big;
// Native `--features wasm` builds (to test the web backend) still link rug.
#[cfg(all(feature = "wasm", not(target_arch = "wasm32")))]
use rug as _;
#[cfg(all(target_arch = "wasm32", not(feature = "wasm")))]
compile_error!("the web build needs `--features wasm` (rug can't target wasm32)");
use core::ops::{Add, Mul, Neg, Shl, Shr, Sub};
/// Implements `$Trait` for every owned/borrowed combination of `Big`
/// operands, through the backend's by-reference `$imp`.
macro_rules! forward_binop {
($Trait:ident, $method:ident, $imp:ident) => {
impl $Trait<&Big> for &Big {
type Output = Big;
fn $method(self, rhs: &Big) -> Big {
self.$imp(rhs)
}
}
impl $Trait<Big> for &Big {
type Output = Big;
fn $method(self, rhs: Big) -> Big {
self.$imp(&rhs)
}
}
impl $Trait<&Big> for Big {
type Output = Big;
fn $method(self, rhs: &Big) -> Big {
(&self).$imp(rhs)
}
}
impl $Trait<Big> for Big {
type Output = Big;
fn $method(self, rhs: Big) -> Big {
(&self).$imp(&rhs)
}
}
};
}
forward_binop!(Add, add, add_ref);
forward_binop!(Sub, sub, sub_ref);
forward_binop!(Mul, mul, mul_ref);
impl Neg for Big {
type Output = Big;
fn neg(self) -> Big {
self.negated()
}
}
impl Neg for &Big {
type Output = Big;
fn neg(self) -> Big {
self.clone().negated()
}
}
impl Shl<isize> for Big {
type Output = Big;
fn shl(self, k: isize) -> Big {
self.mul_pow2(k)
}
}
impl Shl<isize> for &Big {
type Output = Big;
fn shl(self, k: isize) -> Big {
self.clone().mul_pow2(k)
}
}
impl Shr<isize> for Big {
type Output = Big;
fn shr(self, k: isize) -> Big {
self.mul_pow2(-k)
}
}
impl Shr<isize> for &Big {
type Output = Big;
fn shr(self, k: isize) -> Big {
self.clone().mul_pow2(-k)
}
}
/// Significant decimal digits of a value, as a backend's
/// `to_decimal_parts` returns them: the value is `±0.digits × 10^exp10`,
/// `digits` has no trailing zeros, and it is empty for zero.
pub struct DecimalParts {
pub negative: bool,
pub digits: String,
pub exp10: isize,
}
impl DecimalParts {
/// Build from a significand digit string (maybe with trailing zeros)
/// whose value is `0.digits × 10^exp10`.
fn new(negative: bool, digits: &str, exp10: isize) -> Self {
let digits = digits.trim_end_matches('0').to_string();
Self {
negative: negative && !digits.is_empty(),
digits,
exp10,
}
}
}
impl Big {
/// Decimal string with `sig_digits` significant digits, in plain
/// positional notation (`-0.000123`, `4500`), trailing zeros trimmed.
pub fn to_decimal_string(&self, sig_digits: usize) -> String {
let DecimalParts {
negative,
digits,
exp10,
} = self.to_decimal_parts(sig_digits.max(1));
if digits.is_empty() {
return "0".to_string();
}
let sign = if negative { "-" } else { "" };
let len = digits.len() as isize;
if exp10 <= 0 {
let zeros = "0".repeat((-exp10) as usize);
format!("{sign}0.{zeros}{digits}")
} else if exp10 >= len {
let zeros = "0".repeat((exp10 - len) as usize);
format!("{sign}{digits}{zeros}")
} else {
let (int, frac) = digits.split_at(exp10 as usize);
format!("{sign}{int}.{frac}")
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn big(x: f64) -> Big {
Big::from_f64(x, 200)
}
#[test]
fn decimal_string_is_positional() {
assert_eq!(
big(-0.7515).to_decimal_string(20),
"-0.75149999999999994582"
);
assert_eq!(big(-0.7515).to_decimal_string(5), "-0.7515");
assert_eq!(big(0.0).to_decimal_string(5), "0");
assert_eq!(big(1.0).to_decimal_string(5), "1");
assert_eq!(big(123.456).to_decimal_string(5), "123.46");
assert_eq!(big(1e20).to_decimal_string(5), "100000000000000000000");
assert_eq!(big(0.1).to_decimal_string(5), "0.1");
let tiny = big(1.0) >> 200;
let s = tiny.to_decimal_string(5);
assert_eq!(s, format!("0.{}6223", "0".repeat(60)));
}
#[test]
fn decimal_round_trip() {
let s = "-0.743643887037158704752191506114774";
let x = Big::from_decimal_str(s, 200).unwrap();
assert_eq!(x.to_decimal_string(33), s);
assert_eq!(
Big::from_decimal_str("1.5e-20", 64).unwrap().to_f64(),
1.5e-20
);
assert!(Big::from_decimal_str("abc", 64).is_none());
}
#[test]
fn precision_is_max_of_operands() {
let a = Big::from_f64(1.0, 100);
let b = Big::from_f64(3.0, 200);
assert_eq!((&a + &b).precision(), 200);
assert_eq!((&a * &b).precision(), 200);
assert_eq!((&b - &a).precision(), 200);
assert_eq!(a.clone().with_precision(300).precision(), 300);
}
#[test]
fn exact_shifts_and_log2() {
let x = Big::from_f64(0.75, 64) >> 5000;
assert_eq!(x.log2_floor(), Some(-5001));
assert_eq!((x << 5000).to_f64(), 0.75);
assert_eq!(Big::zero(64).log2_floor(), None);
assert!(Big::from_f64(-1.0, 64).is_negative());
assert!(!Big::zero(64).is_negative());
}
#[test]
fn transcendentals() {
let x = Big::from_f64(0.5, 128);
assert!((x.ln().to_f64() - 0.5f64.ln()).abs() < 1e-15);
assert!((x.exp().to_f64() - 0.5f64.exp()).abs() < 1e-15);
let (s, c) = x.sin_cos();
assert!((s.to_f64() - 0.5f64.sin()).abs() < 1e-15);
assert!((c.to_f64() - 0.5f64.cos()).abs() < 1e-15);
let y = Big::from_f64(-0.3, 128);
assert!((y.atan2(&x).to_f64() - (-0.3f64).atan2(0.5)).abs() < 1e-15);
}
}
-128
View File
@@ -1,128 +0,0 @@
//! [`Big`] over `rug::Float` (MPFR), for native builds.
use core::cmp::Ordering;
use rug::{Assign, Float};
use super::DecimalParts;
/// Arbitrary-precision binary float. See the module docs.
#[derive(Clone, Debug, PartialEq)]
pub struct Big(Float);
/// MPFR precision for `bits`, clamped to what it accepts.
fn prec(bits: usize) -> u32 {
(bits as u32).clamp(rug::float::prec_min(), rug::float::prec_max())
}
impl Big {
/// `x` at `bits` of precision (exact when `bits >= 53`). Non-finite `x`
/// reads as 0.
pub fn from_f64(x: f64, bits: usize) -> Self {
let x = if x.is_finite() { x } else { 0.0 };
Self(Float::with_val(prec(bits), x))
}
pub fn zero(bits: usize) -> Self {
Self(Float::new(prec(bits)))
}
/// Parse a decimal (`-0.75`, `1.5e-20`, any number of digits) at `bits`
/// (at least 53) of precision.
pub fn from_decimal_str(s: &str, bits: usize) -> Option<Self> {
let parsed = Float::parse(s.trim()).ok()?;
let x = Float::with_val(prec(bits.max(53)), parsed);
x.is_finite().then_some(Self(x))
}
pub fn precision(&self) -> usize {
self.0.prec() as usize
}
/// Change the precision, rounding to nearest if it shrinks.
pub fn with_precision(mut self, bits: usize) -> Self {
self.0.set_prec(prec(bits));
self
}
pub fn to_f64(&self) -> f64 {
self.0.to_f64()
}
pub fn is_zero(&self) -> bool {
self.0.is_zero()
}
pub fn is_negative(&self) -> bool {
self.0.cmp0() == Some(Ordering::Less)
}
pub fn abs(self) -> Self {
Self(self.0.abs())
}
pub fn sqr(&self) -> Self {
Self(Float::with_val(self.0.prec(), self.0.square_ref()))
}
/// `floor(log2|x|)`, or `None` for zero. Exact, at any exponent.
pub fn log2_floor(&self) -> Option<isize> {
// MPFR normalizes the significand to [0.5, 1).
self.0.get_exp().map(|e| e as isize - 1)
}
pub fn ln(&self) -> Self {
Self(Float::with_val(self.0.prec(), self.0.ln_ref()))
}
pub fn exp(&self) -> Self {
Self(Float::with_val(self.0.prec(), self.0.exp_ref()))
}
/// `atan2(self, x)`: the angle of `(x, self)`.
pub fn atan2(&self, x: &Big) -> Self {
let p = self.0.prec().max(x.0.prec());
Self(Float::with_val(p, self.0.atan2_ref(&x.0)))
}
pub fn sin_cos(&self) -> (Self, Self) {
let p = self.0.prec();
let (mut s, mut c) = (Float::new(p), Float::new(p));
(&mut s, &mut c).assign(self.0.sin_cos_ref());
(Self(s), Self(c))
}
/// `sig` significant decimal digits (rounded to nearest).
pub fn to_decimal_parts(&self, sig: usize) -> DecimalParts {
if self.0.is_zero() {
return DecimalParts::new(false, "", 0);
}
let (negative, digits, exp) = self.0.to_sign_string_exp(10, Some(sig));
DecimalParts::new(negative, &digits, exp.unwrap_or(0) as isize)
}
pub(super) fn add_ref(&self, rhs: &Big) -> Big {
let p = self.0.prec().max(rhs.0.prec());
Big(Float::with_val(p, &self.0 + &rhs.0))
}
pub(super) fn sub_ref(&self, rhs: &Big) -> Big {
let p = self.0.prec().max(rhs.0.prec());
Big(Float::with_val(p, &self.0 - &rhs.0))
}
pub(super) fn mul_ref(&self, rhs: &Big) -> Big {
let p = self.0.prec().max(rhs.0.prec());
Big(Float::with_val(p, &self.0 * &rhs.0))
}
pub(super) fn negated(self) -> Big {
Big(-self.0)
}
/// `self · 2^k`, exact. `|k|` stays far below `i32::MAX` (precision and
/// zoom depth are capped around 2^20 bits).
pub(super) fn mul_pow2(self, k: isize) -> Big {
Big(self.0 << k as i32)
}
}
-173
View File
@@ -1,173 +0,0 @@
//! [`Big`] over `malachite-float`, pure Rust, for the web build.
use malachite_base::num::basic::traits::Zero;
use malachite_base::num::conversion::string::options::ToSciOptions;
use malachite_base::num::conversion::traits::{RoundingFrom, ToSci};
use malachite_base::rounding_modes::RoundingMode::Nearest;
use malachite_float::Float;
use super::DecimalParts;
/// Arbitrary-precision binary float. See the module docs.
///
/// The precision is stored next to the value: malachite's zero has none,
/// but "zero at `p` bits" must still lift a sum with it to `p` bits.
#[derive(Clone, Debug)]
pub struct Big {
f: Float,
prec: u64,
}
impl PartialEq for Big {
fn eq(&self, other: &Self) -> bool {
self.f == other.f
}
}
fn prec(bits: usize) -> u64 {
(bits as u64).max(1)
}
impl Big {
fn new(f: Float, prec: u64) -> Self {
// Only finite values reach here; anything else (overflow) is a bug.
debug_assert!(f.is_finite(), "non-finite Big: {f}");
Self { f, prec }
}
/// `x` at `bits` of precision (exact when `bits >= 53`). Non-finite `x`
/// reads as 0.
pub fn from_f64(x: f64, bits: usize) -> Self {
let p = prec(bits);
if !x.is_finite() {
return Self::zero(bits);
}
Self::new(Float::from_primitive_float_prec(x, p).0, p)
}
pub fn zero(bits: usize) -> Self {
Self::new(Float::ZERO, prec(bits))
}
/// Parse a decimal (`-0.75`, `1.5e-20`, any number of digits) at `bits`
/// (at least 53) of precision.
pub fn from_decimal_str(s: &str, bits: usize) -> Option<Self> {
let p = prec(bits.max(53));
let (f, _) = Float::from_sci_string_prec(s.trim(), p)?;
f.is_finite().then(|| Self::new(f, p))
}
pub fn precision(&self) -> usize {
self.prec as usize
}
/// Change the precision, rounding to nearest if it shrinks.
pub fn with_precision(mut self, bits: usize) -> Self {
let p = prec(bits);
if self.f.get_prec().is_some() {
self.f.set_prec(p);
}
self.prec = p;
self
}
pub fn to_f64(&self) -> f64 {
f64::rounding_from(&self.f, Nearest).0
}
pub fn is_zero(&self) -> bool {
self.f.is_zero()
}
pub fn is_negative(&self) -> bool {
self.f.is_sign_negative() && !self.f.is_zero()
}
pub fn abs(self) -> Self {
if self.f.is_sign_negative() {
self.negated()
} else {
self
}
}
pub fn sqr(&self) -> Self {
Self::new(self.f.square_prec_ref(self.prec).0, self.prec)
}
/// `floor(log2|x|)`, or `None` for zero. Exact, at any exponent.
pub fn log2_floor(&self) -> Option<isize> {
// The significand is normalized to [0.5, 1).
self.f.get_exponent().map(|e| e as isize - 1)
}
pub fn ln(&self) -> Self {
Self::new(self.f.ln_prec_ref(self.prec).0, self.prec)
}
pub fn exp(&self) -> Self {
Self::new(self.f.exp_prec_ref(self.prec).0, self.prec)
}
/// `atan2(self, x)`: the angle of `(x, self)`.
pub fn atan2(&self, x: &Big) -> Self {
let p = self.prec.max(x.prec);
Self::new(self.f.atan2_prec_ref_ref(&x.f, p).0, p)
}
pub fn sin_cos(&self) -> (Self, Self) {
let (s, c, _, _) = self.f.sin_cos_prec_ref(self.prec);
(Self::new(s, self.prec), Self::new(c, self.prec))
}
/// `sig` significant decimal digits (rounded to nearest).
pub fn to_decimal_parts(&self, sig: usize) -> DecimalParts {
if self.f.is_zero() {
return DecimalParts::new(false, "", 0);
}
let mut options = ToSciOptions::default();
options.set_precision(sig as u64);
let s = self.f.to_sci_with_options(options).to_string();
// `[-]int[.frac][e±N]`, positional or scientific depending on size.
let (negative, s) = match s.strip_prefix('-') {
Some(rest) => (true, rest),
None => (false, s.as_str()),
};
let (mantissa, exp) = match s.split_once(['e', 'E']) {
Some((m, e)) => (m, e.trim_start_matches('+').parse::<isize>().unwrap_or(0)),
None => (s, 0),
};
let (int, frac) = mantissa.split_once('.').unwrap_or((mantissa, ""));
let all = format!("{int}{frac}");
let digits = all.trim_start_matches('0');
let leading_zeros = (all.len() - digits.len()) as isize;
// 0.digits · 10^exp10 = int.frac · 10^exp.
let exp10 = int.len() as isize - leading_zeros + exp;
DecimalParts::new(negative, digits, exp10)
}
pub(super) fn add_ref(&self, rhs: &Big) -> Big {
let p = self.prec.max(rhs.prec);
Big::new(self.f.add_prec_ref_ref(&rhs.f, p).0, p)
}
pub(super) fn sub_ref(&self, rhs: &Big) -> Big {
let p = self.prec.max(rhs.prec);
Big::new(self.f.sub_prec_ref_ref(&rhs.f, p).0, p)
}
pub(super) fn mul_ref(&self, rhs: &Big) -> Big {
let p = self.prec.max(rhs.prec);
Big::new(self.f.mul_prec_ref_ref(&rhs.f, p).0, p)
}
pub(super) fn negated(self) -> Big {
Big::new(-self.f, self.prec)
}
/// `self · 2^k`, exact (malachite's exponent range is ±2^30, far past
/// what zoom depth needs).
pub(super) fn mul_pow2(self, k: isize) -> Big {
Big::new(self.f << k as i64, self.prec)
}
}
+1 -69
View File
@@ -74,45 +74,17 @@ pub struct Cli {
#[arg(long)]
pub de: bool,
/// Enable 2×2 antialiasing (supersampling; ~4× slower).
#[arg(long)]
pub antialias: bool,
/// Disable bivariate linear approximation (BLA), i.e. iterate every
/// perturbation step (for A/B comparisons; much slower at deep zoom).
#[arg(long)]
pub no_bla: bool,
/// Coloring palette index.
#[arg(long, value_name = "INDEX")]
pub palette: Option<u32>,
/// Fit the colour scale to the image: one palette cycle across its
/// escape-time range (classic palette only). Animations refit it on
/// every frame.
#[arg(long)]
pub auto_color_scale: bool,
/// Colour scale: palette cycles per escape-time unit, clamped to
/// [0.0001, 1] (overrides a --share link's value).
#[arg(long, value_name = "SCALE")]
pub color_scale: Option<f32>,
/// Output path for --headless (default: fractal-<timestamp>.png). When
/// animating (--to-view/--to-share), this is a directory of
/// frame-00001.png, frame-00002.png, ... instead (default:
/// frames-<timestamp>/). "-" writes to stdout: the PNG for a single
/// image, or raw RGBA8 frames in order for an animation, to pipe into
/// `ffmpeg -f rawvideo -pix_fmt rgba -s WxH -r FPS -i - ...`.
/// frames-<timestamp>/).
#[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
@@ -130,17 +102,6 @@ pub struct Cli {
#[arg(long)]
pub to_iterations: Option<u32>,
/// End colour scale for an animation (from --color-scale), interpolated
/// geometrically. Can't be combined with --auto-color-scale.
#[arg(long, value_name = "SCALE")]
pub to_color_scale: Option<f32>,
/// Zoom depth (half-height, e.g. 1e-60) at which --to-color-scale is
/// reached: the scale then follows the zoom depth from the start view to
/// there, and holds. Requires --to-color-scale.
#[arg(long, value_name = "HALF_HEIGHT")]
pub to_color_scale_at: Option<String>,
/// End Julia constant for an animation: c is interpolated from --julia
/// to this over the frames.
#[arg(long, value_name = "RE,IM", allow_hyphen_values = true)]
@@ -204,17 +165,6 @@ pub struct Cli {
#[arg(long)]
pub linear: bool,
/// Split the animation into N equal parts (use with --shard) to render
/// it across several runs. Each part keeps the whole animation's timing
/// and easing, so the clips join seamlessly.
#[arg(long, value_name = "N")]
pub shards: Option<u32>,
/// Which part of --shards to render, 1-based. PNG frames keep their
/// global numbering, so all shards can share one --export-path directory.
#[arg(long, value_name = "K")]
pub shard: Option<u32>,
/// Run without opening a window: render the current view to a PNG and
/// exit. Combine with --kind/--julia/--share/--view etc. to pick what to
/// render, or any --to-* flag (--to-view, --to-julia, --to-kind, ...) to
@@ -250,24 +200,6 @@ 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,
-1222
View File
File diff suppressed because it is too large Load Diff
+11 -18
View File
@@ -5,8 +5,7 @@
use std::collections::HashMap;
#[cfg(feature = "gui")]
use eframe::egui_wgpu;
use eframe::egui_wgpu::{self, wgpu};
/// Random samples dispatched per accumulating frame. Chosen so a frame stays
/// interactive on a modest GPU even when most samples run the full `b_cap`
@@ -126,21 +125,16 @@ pub struct BuddhabrotRenderer {
impl BuddhabrotRenderer {
pub fn new(device: &wgpu::Device, target_format: wgpu::TextureFormat) -> Self {
let shader = unsafe {
device.create_shader_module_trusted(
wgpu::ShaderModuleDescriptor {
label: Some("buddhabrot"),
source: wgpu::ShaderSource::Wgsl(
concat!(
include_str!("../shaders/common.wgsl"),
include_str!("../shaders/buddhabrot.wgsl"),
)
.into(),
),
},
wgpu::ShaderRuntimeChecks::unchecked(),
)
};
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("buddhabrot"),
source: wgpu::ShaderSource::Wgsl(
concat!(
include_str!("../shaders/common.wgsl"),
include_str!("../shaders/buddhabrot.wgsl"),
)
.into(),
),
});
let uniform_buffer = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("buddhabrot uniforms"),
@@ -342,7 +336,6 @@ pub struct BuddhabrotCallback {
pub size_px: [u32; 2],
}
#[cfg(feature = "gui")]
impl egui_wgpu::CallbackTrait for BuddhabrotCallback {
fn prepare(
&self,
+1 -2
View File
@@ -1,7 +1,6 @@
//! GPU fractal rendering: wgpu pipeline, uniforms, reference orbit, and the
//! egui paint callback.
pub mod bla;
pub mod buddhabrot;
pub mod kind;
pub mod reference;
@@ -17,5 +16,5 @@ pub use renderer::PipelineKey;
pub use renderer::encode_png_with_progress;
pub use renderer::{ExportRender, FractalCallback, FractalRenderer, MAX_REF_POINTS, Uniforms};
#[cfg(not(target_arch = "wasm32"))]
pub use renderer::{encode_png, export_to_png_blocking, render_readback_blocking, unpad_rgba};
pub use renderer::{encode_png, export_to_png_blocking, render_readback_blocking};
pub use share::ShareState;
+95 -68
View File
@@ -1,7 +1,7 @@
//! High-precision reference-orbit computation for perturbation rendering.
//!
//! We iterate the fractal's formula `Z_{n+1} = f(Z_n, C)` at high precision
//! ([`Big`]: `rug` natively, pure Rust on the web), storing each `Z_n` as an `f32` pair. Every pixel is then
//! (`dashu-float`), storing each `Z_n` as an `f32` pair. Every pixel is then
//! rendered on the GPU as a small `f32` delta from this orbit — that is what
//! makes deep zoom cheap. See `shaders/mandelbrot.wgsl` for the delta side; the
//! delta formula there must match the orbit formula here.
@@ -24,7 +24,7 @@ use crate::view::{Big, big_from_f64};
const REFERENCE_ESCAPE_SQ: f64 = 1.0e10;
/// Up to this working precision (bits) the orbit is iterated in plain `f64`
/// instead of `Big` — orders of magnitude faster, which matters most on the
/// instead of `FBig` — orders of magnitude faster, which matters most on the
/// web (where the reference is computed inline on the UI thread).
///
/// `precision_for` asks for `zoom_bits + 48` guard bits, but the GPU only
@@ -60,9 +60,6 @@ pub struct RefOrbit {
impl RefOrbit {
fn with_capacity(n: usize) -> Self {
// Most orbits escape long before `max_iter`; don't reserve hundreds of
// MB up front for a multi-million iteration request.
let n = n.min(1 << 17);
Self {
points: Vec::with_capacity(n),
exps: Vec::with_capacity(n),
@@ -96,21 +93,29 @@ impl<'a> IntoIterator for &'a RefOrbit {
}
}
/// `floor(log2|x|)`, or `None` for zero. Exact (from the binary
/// representation), and works far below f64's range.
fn big_log2_floor(x: &Big) -> Option<isize> {
let repr = x.repr();
let digits = repr.digits();
(digits > 0).then(|| repr.exponent() + digits as isize - 1)
}
/// Store `(zr, zi)` into `orbit`, as plain f32 unless its magnitude is below
/// `2^TINY_LOG2`, in which case both components share an exponent `k` and
/// the stored mantissa `Z * 2^-k` has its larger component in `[0.5, 1)`.
fn push_big_point(orbit: &mut RefOrbit, zr: &Big, zi: &Big) {
let (lr, li) = (zr.log2_floor(), zi.log2_floor());
let (lr, li) = (big_log2_floor(zr), big_log2_floor(zi));
let top = lr.max(li);
match top {
Some(top) if top < TINY_LOG2 as isize => {
let k = top + 1;
let mr = (zr.clone() << -k).to_f64() as f32;
let mi = (zi.clone() << -k).to_f64() as f32;
let mr = (zr.clone() << -k).to_f64().value() as f32;
let mi = (zi.clone() << -k).to_f64().value() as f32;
orbit.points.push([mr, mi]);
orbit.exps.push(k as i32);
}
_ => orbit.push([zr.to_f64() as f32, zi.to_f64() as f32]),
_ => orbit.push([zr.to_f64().value() as f32, zi.to_f64().value() as f32]),
}
}
@@ -139,17 +144,23 @@ pub fn compute_reference(
let morph = morph.filter(|&(_, w)| w != 0.0);
if precision <= F64_MAX_PRECISION {
let k = StepConstsF64 {
c: (c_re.to_f64(), c_im.to_f64()),
c: (c_re.to_f64().value(), c_im.to_f64().value()),
p: phoenix_p,
l: lambda_l,
cpow: complex_power,
power,
};
return compute_reference_f64((z0_re.to_f64(), z0_im.to_f64()), max_iter, kind, &k, morph);
return compute_reference_f64(
(z0_re.to_f64().value(), z0_im.to_f64().value()),
max_iter,
kind,
&k,
morph,
);
}
let k = StepConsts {
cr: c_re.clone().with_precision(precision),
ci: c_im.clone().with_precision(precision),
cr: c_re.clone().with_precision(precision).value(),
ci: c_im.clone().with_precision(precision).value(),
pr: big_from_f64(phoenix_p.0, precision),
pi: big_from_f64(phoenix_p.1, precision),
lr: big_from_f64(lambda_l.0, precision),
@@ -278,7 +289,7 @@ struct StepConsts {
precision: usize,
}
/// [`compute_reference`] at arbitrary precision ([`Big`]), for deep views.
/// [`compute_reference`] at arbitrary precision (`FBig`), for deep views.
fn compute_reference_big(
z0_re: &Big,
z0_im: &Big,
@@ -290,11 +301,11 @@ fn compute_reference_big(
let precision = k.precision;
let morph = morph.map(|(from, w)| (from, big_from_f64(w, precision)));
let mut zr = z0_re.clone().with_precision(precision);
let mut zi = z0_im.clone().with_precision(precision);
let mut zr = z0_re.clone().with_precision(precision).value();
let mut zi = z0_im.clone().with_precision(precision).value();
// Previous iterate, for the Phoenix two-term recurrence (Y_{-1} = 0).
let mut zr_prev = Big::zero(precision);
let mut zi_prev = Big::zero(precision);
let mut zr_prev = big_zero(precision);
let mut zi_prev = big_zero(precision);
let mut points = RefOrbit::with_capacity(max_iter as usize + 1);
@@ -318,8 +329,8 @@ fn compute_reference_big(
// Shift the previous iterate (only the Phoenix arm reads it).
zr_prev = zr;
zi_prev = zi;
zr = new_zr.with_precision(precision);
zi = new_zi.with_precision(precision);
zr = new_zr.with_precision(precision).value();
zi = new_zi.with_precision(precision).value();
}
points
@@ -347,7 +358,7 @@ fn step(
FractalKind::BurningShip => {
// (|zr| + i|zi|)^2 = (zr^2 - zi^2) + 2|zr zi| i.
let re = &zr.sqr() - &zi.sqr() + cr;
let im = ((zr * zi) << 1).abs() + ci;
let im = big_abs((zr * zi) << 1) + ci;
(re, im)
}
FractalKind::Tricorn => {
@@ -362,14 +373,14 @@ fn step(
}
FractalKind::Celtic => {
// |Re(z^2)| + i·Im(z^2): abs the real output of the square.
let re = (&zr.sqr() - &zi.sqr()).abs() + cr;
let re = big_abs(&zr.sqr() - &zi.sqr()) + cr;
let im = ((zr * zi) << 1) + ci;
(re, im)
}
FractalKind::Perpendicular => {
// (x^2 - y^2) - 2·x·|y| i: abs the imaginary input.
let re = &zr.sqr() - &zi.sqr() + cr;
let im = if zi.is_negative() {
let im = if *zi < Big::ZERO {
ci + ((zr * zi) << 1)
} else {
ci - ((zr * zi) << 1)
@@ -378,8 +389,8 @@ fn step(
}
FractalKind::Buffalo => {
// |Re(z^2)| - |Im(z^2)| i: abs both outputs.
let re = (&zr.sqr() - &zi.sqr()).abs() + cr;
let im = ci - ((zr * zi) << 1).abs();
let re = big_abs(&zr.sqr() - &zi.sqr()) + cr;
let im = ci - big_abs((zr * zi) << 1);
(re, im)
}
FractalKind::Phoenix => {
@@ -392,7 +403,7 @@ fn step(
}
FractalKind::Lambda => {
// λ·z(1 - z) + c: logistic map plus the usual additive `c`.
let re2 = Big::from_f64(1.0, k.precision) - zr;
let re2 = 1 - zr;
let im2 = -zi;
let lzr = &k.lr * zr - &k.li * zi;
let lzi = &k.lr * zi + &k.li * zr;
@@ -407,20 +418,36 @@ fn step(
}
}
fn big_zero(precision: usize) -> Big {
Big::from(0i32).with_precision(precision).value()
}
/// Absolute value of a `Big`. The sign comes from the `Big` itself: through
/// f64, anything below ~1e-308 reads as ±0 and would keep its sign.
fn big_abs(x: Big) -> Big {
if x < Big::ZERO { -x } else { x }
}
/// `(zr + i zi)^power` by repeated complex multiply at `precision` bits.
fn complex_pow(zr: &Big, zi: &Big, power: u32, precision: usize) -> (Big, Big) {
let mut rr = Big::from_f64(1.0, precision);
let mut ri = Big::zero(precision);
let mut rr = Big::from(1i32).with_precision(precision).value();
let mut ri = big_zero(precision);
for _ in 0..power {
// (rr + i ri)(zr + i zi) = (rr zr - ri zi) + (rr zi + ri zr) i.
let nr = (&rr * zr - &ri * zi).with_precision(precision);
let ni = (&rr * zi + &ri * zr).with_precision(precision);
let nr = (&rr * zr - &ri * zi).with_precision(precision).value();
let ni = (&rr * zi + &ri * zr).with_precision(precision).value();
rr = nr;
ri = ni;
}
(rr, ri)
}
/// `true` if `x` is exactly zero (special-cases `ln(0)`). Not via f64,
/// which flushes values below ~1e-308 to zero.
fn is_big_zero(x: &Big) -> bool {
x.repr().significand().is_zero()
}
/// `(zr + i zi)^(pr + i pi)` for a complex exponent, via the principal branch
/// `z^p = exp(p·ln z)` where `ln z = ln|z| + i·arg(z)`. Used by
/// `ComplexMultibrot`; must be kept in sync with the shader's `cpow`.
@@ -428,14 +455,14 @@ fn complex_pow(zr: &Big, zi: &Big, power: u32, precision: usize) -> (Big, Big) {
/// panic; this is the correct limit for the `Re(p) > 0` region the UI
/// exposes).
fn complex_pow_complex(zr: &Big, zi: &Big, pr: &Big, pi: &Big, precision: usize) -> (Big, Big) {
if zr.is_zero() && zi.is_zero() {
return (Big::zero(precision), Big::zero(precision));
if is_big_zero(zr) && is_big_zero(zi) {
return (big_zero(precision), big_zero(precision));
}
let r2 = &zr.sqr() + &zi.sqr();
let ln_r = r2.ln() >> 1; // 0.5 * ln(r2) = ln(sqrt(r2)); exact halving.
let theta = zi.atan2(zr);
let exp_re = (pr * &ln_r - pi * &theta).with_precision(precision);
let exp_im = (pr * &theta + pi * &ln_r).with_precision(precision);
let exp_re = (pr * &ln_r - pi * &theta).with_precision(precision).value();
let exp_im = (pr * &theta + pi * &ln_r).with_precision(precision).value();
let mag = exp_re.exp();
let (sin_a, cos_a) = exp_im.sin_cos();
(&mag * &cos_a, &mag * &sin_a)
@@ -456,7 +483,7 @@ pub fn compute_set_reference(
complex_power: (f64, f64),
morph: Option<(FractalKind, f64)>,
) -> RefOrbit {
let zero = Big::zero(precision);
let zero = big_zero(precision);
compute_reference(
&zero,
&zero,
@@ -481,19 +508,19 @@ mod tests {
/// `to_f64` reads as ±0.
#[test]
fn sign_and_zero_below_f64_range() {
let tiny = Big::from_f64(1.0, 64) >> 5000;
assert!(!tiny.is_zero());
assert!(Big::zero(64).is_zero());
assert_eq!((-tiny.clone()).abs(), tiny);
assert_eq!(tiny.clone().abs(), tiny);
let tiny = Big::try_from(1.0_f64).unwrap().with_precision(64).value() >> 5000;
assert!(!is_big_zero(&tiny));
assert!(is_big_zero(&big_zero(64)));
assert_eq!(big_abs(-tiny.clone()), tiny);
assert_eq!(big_abs(tiny.clone()), tiny);
}
/// The high-precision reference must agree with a plain f64 iteration for a
/// shallow point (where f64 is accurate).
#[test]
fn reference_matches_naive_f64() {
let cr = Big::from_f64(-0.75, 53);
let ci = Big::from_f64(0.1, 53);
let cr = Big::try_from(-0.75_f64).unwrap();
let ci = Big::try_from(0.1_f64).unwrap();
let points = compute_set_reference(
&cr,
&ci,
@@ -626,8 +653,8 @@ mod tests {
/// A point inside the main cardioid never escapes: full-length orbit.
#[test]
fn interior_orbit_runs_full_length() {
let cr = Big::from_f64(-0.2, 53);
let ci = Big::from_f64(0.0, 53);
let cr = Big::try_from(-0.2_f64).unwrap();
let ci = Big::try_from(0.0_f64).unwrap();
let points = compute_set_reference(
&cr,
&ci,
@@ -646,8 +673,8 @@ mod tests {
/// Burning Ship reference matches a naive f64 iteration of the same formula.
#[test]
fn burning_ship_reference_matches_naive_f64() {
let cr = Big::from_f64(-1.75, 53);
let ci = Big::from_f64(-0.03, 53);
let cr = Big::try_from(-1.75_f64).unwrap();
let ci = Big::try_from(-0.03_f64).unwrap();
let points = compute_set_reference(
&cr,
&ci,
@@ -677,8 +704,8 @@ mod tests {
/// Multibrot (power 3) reference matches a naive f64 cube iteration.
#[test]
fn multibrot3_reference_matches_naive_f64() {
let cr = Big::from_f64(0.3, 53);
let ci = Big::from_f64(0.2, 53);
let cr = Big::try_from(0.3_f64).unwrap();
let ci = Big::try_from(0.2_f64).unwrap();
let points = compute_set_reference(
&cr,
&ci,
@@ -710,10 +737,10 @@ mod tests {
/// Julia orbit (fixed c, z0 = center) matches a naive f64 iteration.
#[test]
fn julia_reference_matches_naive_f64() {
let z0_re = Big::from_f64(0.15, 53);
let z0_im = Big::from_f64(-0.1, 53);
let c_re = Big::from_f64(-0.8, 53);
let c_im = Big::from_f64(0.156, 53);
let z0_re = Big::try_from(0.15_f64).unwrap();
let z0_im = Big::try_from(-0.1_f64).unwrap();
let c_re = Big::try_from(-0.8_f64).unwrap();
let c_im = Big::try_from(0.156_f64).unwrap();
let points = compute_reference(
&z0_re,
&z0_im,
@@ -748,10 +775,10 @@ mod tests {
let (lr, li) = (-0.5_f64, 0.2_f64);
let (cr, ci) = (0.1_f64, -0.3_f64);
let points = compute_reference(
&Big::from_f64(0.2, 53),
&Big::from_f64(0.1, 53),
&Big::from_f64(cr, 53),
&Big::from_f64(ci, 53),
&Big::try_from(0.2_f64).unwrap(),
&Big::try_from(0.1_f64).unwrap(),
&Big::try_from(cr).unwrap(),
&Big::try_from(ci).unwrap(),
60,
200,
FractalKind::Lambda,
@@ -777,8 +804,8 @@ mod tests {
/// Celtic reference matches a naive f64 iteration: real = |x^2 - y^2| + cr.
#[test]
fn celtic_reference_matches_naive_f64() {
let cr = Big::from_f64(-0.6, 53);
let ci = Big::from_f64(0.4, 53);
let cr = Big::try_from(-0.6_f64).unwrap();
let ci = Big::try_from(0.4_f64).unwrap();
let points = compute_set_reference(
&cr,
&ci,
@@ -809,8 +836,8 @@ mod tests {
/// real = x^2 - y^2 + cr, imag = -2·x·|y| + ci.
#[test]
fn perpendicular_reference_matches_naive_f64() {
let cr = Big::from_f64(-0.7, 53);
let ci = Big::from_f64(-0.2, 53);
let cr = Big::try_from(-0.7_f64).unwrap();
let ci = Big::try_from(-0.2_f64).unwrap();
let points = compute_set_reference(
&cr,
&ci,
@@ -841,8 +868,8 @@ mod tests {
/// real = |x^2 - y^2| + cr, imag = -|2·x·y| + ci.
#[test]
fn buffalo_reference_matches_naive_f64() {
let cr = Big::from_f64(-1.2, 53);
let ci = Big::from_f64(-0.35, 53);
let cr = Big::try_from(-1.2_f64).unwrap();
let ci = Big::try_from(-0.35_f64).unwrap();
let points = compute_set_reference(
&cr,
&ci,
@@ -873,8 +900,8 @@ mod tests {
/// `z_{n+1} = z_n^2 + c + p·z_{n-1}` (z_0 = 0, z_{-1} = 0).
#[test]
fn phoenix_reference_matches_naive_f64() {
let cr = Big::from_f64(0.5667, 53);
let ci = Big::from_f64(0.0, 53);
let cr = Big::try_from(0.5667_f64).unwrap();
let ci = Big::try_from(0.0_f64).unwrap();
let p = (-0.5_f64, 0.0_f64);
let points = compute_set_reference(
&cr,
@@ -912,8 +939,8 @@ mod tests {
/// iteration of `z^p = exp(p·ln z)`.
#[test]
fn complex_multibrot_reference_matches_naive_f64() {
let cr = Big::from_f64(0.1, 53);
let ci = Big::from_f64(-0.2, 53);
let cr = Big::try_from(0.1_f64).unwrap();
let ci = Big::try_from(-0.2_f64).unwrap();
let power = (2.5_f64, 0.3_f64);
let points = compute_set_reference(
&cr,
@@ -957,8 +984,8 @@ mod tests {
fn set_ref(cr: f64, ci: f64, kind: FractalKind, morph: Option<(FractalKind, f64)>) -> RefOrbit {
compute_set_reference(
&Big::from_f64(cr, 53),
&Big::from_f64(ci, 53),
&Big::try_from(cr).unwrap(),
&Big::try_from(ci).unwrap(),
60,
200,
kind,
+250 -1588
View File
File diff suppressed because it is too large Load Diff
+73 -457
View File
@@ -3,74 +3,28 @@
// event loop, no worker-thread debounce (nothing to debounce for a one-shot
// render); it just creates its own wgpu device, computes the reference orbit
// once, and renders through the same `ExportRender` path the "Export PNG"
// button uses. `--export-path -` writes to stdout instead: the PNG for a
// single image, or a raw RGBA8 video stream for an animation (for piping
// into ffmpeg).
// button uses.
use std::collections::{BTreeMap, HashMap};
use std::io::{IsTerminal, Write};
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering};
use std::collections::HashMap;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::sync::{Mutex, mpsc};
use eframe::egui_wgpu::wgpu;
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, RefOrbit, ShareState, encode_png,
export_to_png_blocking, render_readback_blocking, unpad_rgba,
ExportRender, FractalKind, FractalRenderer, PipelineKey, ShareState, encode_png,
export_to_png_blocking, render_readback_blocking,
};
use crate::view::{
Scale, ViewState, big_from_decimal_str, interpolate_f64, interpolate_view, parse_view_spec,
ViewState, big_from_decimal_str, interpolate_f64, interpolate_view, parse_view_spec,
precision_for,
};
/// Cap on the output image dimension (px), to stay within GPU texture limits.
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() {
return Err(
"--export-path - writes binary data to stdout; pipe it somewhere \
(e.g. `| ffmpeg ...`)"
.into(),
);
}
Ok(())
}
pub fn run(cli: Cli) -> Result<(), String> {
if cli.buddhabrot {
return Err("headless mode doesn't support --buddhabrot yet".into());
@@ -83,65 +37,45 @@ 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()?;
}
if targets.shard.is_some() && !targets.any() {
return Err("--shard/--shards only apply to animations (give a --to-* target)".into());
}
let mut app = FractalApp::default_state();
app.apply_cli(cli);
app.set_output_size(width, height);
if targets.any() {
return run_animation(app, targets, width, height, export_path, compression);
return run_animation(app, targets, width, height, export_path);
}
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…");
let points = job.compute();
app.compute_reference_blocking();
let (device, queue) = device_thread
.join()
.map_err(|_| "GPU setup panicked".to_string())??;
let auto_color = app.auto_color_active();
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}"),
None => eprintln!("auto color scale: nothing escaped, keeping the default"),
}
}
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 handles = renderer.export_handles(&device, &uniforms);
let er = ExportRender::new(
&device,
&queue,
&handles,
width,
height,
uniforms,
app.reference_points(),
app.lights(),
);
eprintln!("rendering {width}×{height}…");
let png = export_to_png_blocking(&device, &queue, &er, compression, |phase, fraction| {
let png = export_to_png_blocking(&device, &queue, &er, |phase, fraction| {
eprint!("\r{phase} {:>3.0}%", fraction * 100.0);
});
eprintln!();
if export_path == STDOUT_PATH {
let mut out = std::io::stdout().lock();
out.write_all(&png)
.and_then(|()| out.flush())
.map_err(|e| format!("writing to stdout failed: {e}"))?;
eprintln!("wrote PNG to stdout ({width}×{height})");
} else {
std::fs::write(&export_path, &png).map_err(|e| format!("save failed: {e}"))?;
println!("saved {export_path} ({width}×{height})");
}
std::fs::write(&export_path, &png).map_err(|e| format!("save failed: {e}"))?;
println!("saved {export_path} ({width}×{height})");
Ok(())
}
@@ -161,15 +95,10 @@ struct AnimTargets {
/// 3D camera, degrees.
to_yaw: Option<f32>,
to_pitch: Option<f32>,
to_color_scale: Option<f32>,
/// Zoom depth where `to_color_scale` is reached (else: at the end).
to_color_scale_at: Option<Scale>,
frames: Option<u32>,
fps: f64,
duration: Option<f64>,
linear: bool,
/// `--shard K --shards N`: render only the K-th (1-based) of N parts.
shard: Option<(u32, u32)>,
}
impl AnimTargets {
@@ -180,39 +109,6 @@ impl AnimTargets {
.transpose()
};
let to_cpow = pair("to-complex-power", &cli.to_complex_power)?;
let shard = match (cli.shard, cli.shards) {
(None, None) | (None, Some(1)) => None,
(Some(k), Some(n)) if (1..=n).contains(&k) => Some((k, n)),
(Some(k), Some(n)) => {
return Err(format!(
"--shard {k} is out of range 1..={n} (--shards {n})"
));
}
_ => return Err("--shard and --shards must be given together".into()),
};
if let Some(s) = cli.to_color_scale {
if !(s.is_finite() && s > 0.0) {
return Err(format!("invalid --to-color-scale: {s}"));
}
if cli.auto_color_scale {
return Err(
"--to-color-scale can't be combined with --auto-color-scale \
(the auto fit sets the scale on every frame)"
.into(),
);
}
}
let to_color_scale_at = cli
.to_color_scale_at
.as_deref()
.map(|s| {
s.parse::<Scale>()
.map_err(|_| format!("invalid --to-color-scale-at: {s}"))
})
.transpose()?;
if to_color_scale_at.is_some() && cli.to_color_scale.is_none() {
return Err("--to-color-scale-at needs --to-color-scale".into());
}
Ok(Self {
to_view: cli.to_view.clone(),
to_share: cli.to_share.clone(),
@@ -225,13 +121,10 @@ impl AnimTargets {
to_kind: cli.to_kind.map(Into::into),
to_yaw: cli.to_yaw,
to_pitch: cli.to_pitch,
to_color_scale: cli.to_color_scale,
to_color_scale_at,
frames: cli.frames,
fps: cli.fps,
duration: cli.duration,
linear: cli.linear,
shard,
})
}
@@ -248,25 +141,20 @@ impl AnimTargets {
|| self.to_kind.is_some()
|| self.to_yaw.is_some()
|| self.to_pitch.is_some()
|| self.to_color_scale.is_some()
}
}
/// Render a sequence of frames interpolating from the app's current (start)
/// state to `targets`, for feeding into ffmpeg: the camera, iteration count,
/// per-kind constants (c, p, λ, complex power) and, through a kind morph,
/// the iteration formula, the 3D camera angles and the colour scale.
/// Everything else (palette, offset, ...) stays fixed at whatever
/// `apply_cli` set up for the start. With `--export-path -`, frames are
/// streamed in order to stdout as raw RGBA8 (for ffmpeg's `rawvideo`
/// demuxer) instead of being written as PNGs.
/// the iteration formula, and the 3D camera angles. Everything else (colors, ...) stays fixed at
/// whatever `apply_cli` set up for the start.
fn run_animation(
mut app: FractalApp,
targets: AnimTargets,
width: u32,
height: u32,
export_path: Option<String>,
compression: png::Compression,
) -> Result<(), String> {
let fps = targets.fps;
let frames = match targets.frames {
@@ -281,16 +169,6 @@ fn run_animation(
if frames < 2 {
return Err("animation needs at least 2 frames".into());
}
// Frames are still timed against the whole animation (`apply_frame` takes
// the global index); a shard only picks which of them this run renders.
let range = match targets.shard {
Some((_, n)) if n > frames => {
return Err(format!("--shards {n} is more than the {frames} frames"));
}
Some((k, n)) => shard_range(frames, k, n),
None => 0..frames,
};
let (first, count) = (range.start, range.len());
let from = app.view_state().clone();
let (to, to_iterations_share) =
@@ -320,27 +198,9 @@ fn run_animation(
let (yaw0, pitch0) = app.camera_angles();
let yaw1 = targets.to_yaw.map_or(yaw0, f32::to_radians);
let pitch1 = targets.to_pitch.map_or(pitch0, f32::to_radians);
let (scale0, ci_lo0) = app.color_fit();
let scale1 = targets.to_color_scale.map(|s| s.clamp(1e-4, 1.0) as f64);
// With `--to-color-scale-at`, the scale follows the zoom depth (log2 of
// the half-height) from the start view's to that one, instead of `t`.
let depth0 = from.half_height.log2();
let depth_at = targets.to_color_scale_at.map(Scale::log2);
if depth_at == Some(depth0) {
return Err("--to-color-scale-at is the start view's depth".into());
}
let stream = export_path.as_deref() == Some(STDOUT_PATH);
let out_dir = export_path.unwrap_or_else(|| format!("frames-{}", unix_timestamp()));
if stream {
eprintln!(
"streaming raw video to stdout; ffmpeg input: \
-f rawvideo -pix_fmt rgba -s {width}x{height} -r {fps} -i -"
);
} else {
std::fs::create_dir_all(&out_dir)
.map_err(|e| format!("failed to create {out_dir}: {e}"))?;
}
std::fs::create_dir_all(&out_dir).map_err(|e| format!("failed to create {out_dir}: {e}"))?;
// Everything about frame `i` is a pure function of its `t`, so the app can
// be put into any frame's state at any time, in any order.
@@ -356,9 +216,7 @@ fn run_animation(
interpolate_f64(from_iterations as f64, to as f64, t).round() as u32,
);
}
let view = interpolate_view(&from, &to, t);
let depth = view.half_height.log2();
app.set_view(view);
app.set_view(interpolate_view(&from, &to, t));
app.set_constants(std::array::from_fn(|k| {
(
interpolate_f64(from_consts[k].0, to_consts[k].0, t),
@@ -370,21 +228,11 @@ fn run_animation(
interpolate_f64(yaw0 as f64, yaw1 as f64, t) as f32,
interpolate_f64(pitch0 as f64, pitch1 as f64, t) as f32,
);
// Geometrically: the useful range spans decades.
if let Some(scale1) = scale1 {
// The zoom is already eased; don't ease its depth again.
let u = depth_at.map_or(t, |at| ((depth - depth0) / (at - depth0)).clamp(0.0, 1.0));
let scale = interpolate_f64((scale0 as f64).ln(), scale1.ln(), u).exp();
app.set_color_fit((scale as f32, ci_lo0));
}
};
// Snapshot every frame's reference-orbit job up front (cheap: just the
// parameters), so the orbits themselves can be computed in parallel.
// `jobs[j]` is global frame `first + j`; the pipeline below works in
// local indices `j`, so the stdout writer's ordering is per shard.
let jobs: Vec<RefJob> = range
.clone()
let jobs: Vec<RefJob> = (0..frames)
.map(|i| {
apply_frame(&mut app, i);
app.reference_job()
@@ -392,34 +240,16 @@ fn run_animation(
.collect();
let (device, queue) = pollster::block_on(request_device())?;
// 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);
let format = wgpu::TextureFormat::Bgra8Unorm;
let renderer = FractalRenderer::new(&device, format);
let aspect = width as f64 / height as f64;
// Three-stage pipeline, connected by bounded channels (which also cap
// memory): `threads` workers compute reference orbits (CPU, the expensive
// part at deep zoom) → this thread renders each frame on the GPU → `threads`
// workers PNG-encode and write frames. Frames flow through out of order
// (at most ~`threads` apart); each is written under its own index.
//
// When streaming, the last stage instead unpads frames to raw RGBA and a
// single writer thread puts them back in order before writing to stdout.
// Its reorder buffer can't apply backpressure (blocking it while waiting
// for frame `k` could stall the pipeline before `k` gets through), so the
// orbit workers bound it instead: they don't start a frame more than
// `window` ahead of the last one written.
let threads = std::thread::available_parallelism().map_or(4, |n| n.get());
let window = threads * 4;
let next_job = AtomicUsize::new(0);
let saved = AtomicUsize::new(0);
let failed = AtomicBool::new(false);
@@ -429,50 +259,21 @@ fn run_animation(
error.lock().unwrap().get_or_insert(e);
};
if let Some((k, n)) = targets.shard {
eprintln!(
"shard {k}/{n}: frames {}–{} of {frames}",
range.start + 1,
range.end
);
}
eprintln!("rendering {count} frames ({width}×{height}) on {threads} threads…");
eprintln!("rendering {frames} frames ({width}×{height}) on {threads} threads…");
let (png_tx, png_rx) = mpsc::sync_channel::<(usize, Vec<u8>, u32, bool)>(threads * 2);
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, RefJob, RefOrbit)>(threads * 2);
let (ref_tx, ref_rx) = mpsc::sync_channel::<(usize, crate::fractal::RefOrbit)>(threads * 2);
for _ in 0..threads {
let ref_tx = ref_tx.clone();
let (jobs, probe, len_hint, rendered, next_job, saved, failed) = (
&jobs, &probe, &len_hint, &rendered, &next_job, &saved, &failed,
);
let (jobs, next_job, failed) = (&jobs, &next_job, &failed);
scope.spawn(move || {
loop {
let i = next_job.fetch_add(1, Ordering::Relaxed);
if i >= jobs.len() || failed.load(Ordering::Relaxed) {
break;
}
while stream
&& i >= saved.load(Ordering::Relaxed) + window
&& !failed.load(Ordering::Relaxed)
{
std::thread::sleep(std::time::Duration::from_millis(2));
}
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() {
if ref_tx.send((i, jobs[i].compute())).is_err() {
break;
}
}
@@ -480,34 +281,7 @@ fn run_animation(
}
drop(ref_tx);
if stream {
let (saved, fail) = (&saved, &fail);
scope.spawn(move || {
let mut out = std::io::stdout().lock();
let mut pending = BTreeMap::new();
let mut next = 0;
for (i, raw) in raw_rx.iter() {
pending.insert(i, raw);
while let Some(raw) = pending.remove(&next) {
if let Err(e) = out.write_all(&raw) {
fail(format!("writing to stdout failed: {e}"));
return;
}
next += 1;
saved.store(next, Ordering::Relaxed);
eprint!("\r[{next:>4}/{count}] streamed");
}
}
if let Err(e) = out.flush() {
fail(format!("writing to stdout failed: {e}"));
}
});
} else {
drop(raw_rx);
}
for _ in 0..threads {
let raw_tx = raw_tx.clone();
let (png_rx, out_dir, saved, failed, fail) =
(&png_rx, &out_dir, &saved, &failed, &fail);
scope.spawn(move || {
@@ -516,55 +290,53 @@ fn run_animation(
let Ok((i, padded, bpr, swap_rb)) = png_rx.lock().unwrap().recv() else {
break;
};
// After a failure, keep draining (without work) until the
// GPU stage hangs up, so it can't block on a full channel.
if failed.load(Ordering::Relaxed) {
continue;
break;
}
if stream {
let raw = unpad_rgba(&padded, width, height, bpr, swap_rb);
// Only fails once the writer has failed and hung up.
let _ = raw_tx.send((i, raw));
continue;
}
let png = encode_png(&padded, width, height, bpr, swap_rb, compression);
let path = format!("{out_dir}/frame-{:05}.png", first as usize + i + 1);
let png =
encode_png(&padded, width, height, bpr, swap_rb, png::Compression::Fast);
let path = format!("{out_dir}/frame-{:05}.png", i + 1);
if let Err(e) = std::fs::write(&path, &png) {
fail(format!("save failed: {e}"));
continue;
break;
}
let done = saved.fetch_add(1, Ordering::Relaxed) + 1;
eprint!("\r[{done:>4}/{count}] saved");
eprint!("\r[{done:>4}/{frames}] saved");
}
});
}
// 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; `exporter` builds each pipeline once.
let mut exporter = Exporter::new(&device, &queue, width, height, auto_color);
for (i, job, points) in ref_rx.iter() {
// frames during a kind morph; build each pipeline once.
let mut pipelines = HashMap::new();
for (i, points) in ref_rx.iter() {
if failed.load(Ordering::Relaxed) {
break;
}
apply_frame(&mut app, first + i as u32);
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);
}
apply_frame(&mut app, 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));
let er = ExportRender::new(
&device,
&queue,
handles,
width,
height,
uniforms,
app.reference_points(),
app.lights(),
);
let padded = render_readback_blocking(&device, &queue, &er);
if png_tx.send((i, padded, er.padded_bpr, er.swap_rb)).is_err() {
break;
}
}
// Dropping the channel ends lets the workers drain and exit.
drop(raw_tx);
drop(png_tx);
drop(ref_rx);
});
@@ -574,136 +346,15 @@ fn run_animation(
return Err(e);
}
let saved = saved.into_inner();
if saved != count {
return Err(format!("only {saved} of {count} frames were rendered"));
if saved != frames as usize {
return Err(format!("only {saved} of {frames} frames were rendered"));
}
if stream {
eprintln!("streamed {count} frames ({width}×{height})");
return Ok(());
}
println!("saved {count} frames to {out_dir}/ ({width}×{height})");
if targets.shard.is_some() {
println!(
"tip: once every shard is rendered into {out_dir}/, they form the full sequence; \
this shard alone: ffmpeg -framerate {fps} -start_number {} -i {out_dir}/frame-%05d.png \
-frames:v {count} -c:v libx264 -pix_fmt yuv420p out.mp4",
range.start + 1
);
} else {
println!(
"tip: ffmpeg -framerate {fps} -i {out_dir}/frame-%05d.png -c:v libx264 -pix_fmt yuv420p out.mp4"
);
}
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.
fn fit_auto_color(
app: &mut FractalApp,
er: &mut ExportRender,
device: &wgpu::Device,
queue: &wgpu::Queue,
) -> Option<(f32, f32)> {
let range = er.ci_range_blocking(device, queue)?;
app.apply_ci_range(range);
er.set_uniforms(
queue,
app.make_uniforms(er.width as f64 / er.height as f64, er.height as f64),
println!("saved {frames} frames to {out_dir}/ ({width}×{height})");
println!(
"tip: ffmpeg -framerate {fps} -i {out_dir}/frame-%05d.png -c:v libx264 -pix_fmt yuv420p out.mp4"
);
Some(range)
Ok(())
}
/// Parse `--to-view`/`--to-share` (at most one is used) into the end view
@@ -736,14 +387,6 @@ fn parse_animation_target(
)))
}
/// Global frame indices of shard `shard` (1-based) out of `shards` equal
/// parts of a `frames`-frame animation. Consecutive shards tile `0..frames`
/// with no gap or overlap.
fn shard_range(frames: u32, shard: u32, shards: u32) -> std::ops::Range<u32> {
let bound = |k: u32| (k as u64 * frames as u64 / shards as u64) as u32;
bound(shard - 1)..bound(shard)
}
/// Ease-in/ease-out pacing: slow at both ends, fast through the middle.
fn smoothstep(t: f64) -> f64 {
t * t * (3.0 - 2.0 * t)
@@ -768,30 +411,3 @@ async fn request_device() -> Result<(wgpu::Device, wgpu::Queue), String> {
.await
.map_err(|e| format!("failed to create device: {e}"))
}
#[cfg(test)]
mod tests {
use super::shard_range;
#[test]
fn shards_tile_all_frames() {
for frames in [2, 3, 10, 97, 1000, u32::MAX] {
for shards in [1, 2, 3, 7, 10] {
if shards > frames {
continue;
}
let mut next = 0;
for k in 1..=shards {
let r = shard_range(frames, k, shards);
assert_eq!(
r.start, next,
"gap/overlap at shard {k}/{shards} of {frames}"
);
assert!(!r.is_empty(), "empty shard {k}/{shards} of {frames}");
next = r.end;
}
assert_eq!(next, frames);
}
}
}
}
+1 -4
View File
@@ -1,9 +1,7 @@
use std::f32::consts::PI;
use bytemuck::{Pod, Zeroable};
use ecolor::Color32;
#[cfg(feature = "gui")]
use egui::Ui;
use egui::{Color32, Ui};
/// Maximum number of simultaneous lights.
pub const MAX_LIGHT_COUNT: usize = 16;
@@ -29,7 +27,6 @@ impl Default for Light {
}
impl Light {
#[cfg(feature = "gui")]
pub fn widget(&mut self, ui: &mut Ui) -> bool {
let formater = |v, _| format!("{}°", ((v * 180. / std::f64::consts::PI) as u32));
let parser = |s: &str| {
+7 -49
View File
@@ -1,8 +1,6 @@
// Without these, rust fails to infer Send/Sync trait impls
// Probably caused by the new trait solver
#![recursion_limit = "256"]
// Without the `gui` feature, UI-only state and helpers go unused.
#![cfg_attr(not(feature = "gui"), allow(dead_code, unused_imports))]
// Fractal Explorer — Rust + wgpu + egui + WGSL deep-zoom Mandelbrot.
//
@@ -11,7 +9,6 @@
// and calls the wasm `main`, which boots eframe onto the page's <canvas>.
mod app;
mod bignum;
mod camera;
mod fractal;
mod lights;
@@ -24,27 +21,15 @@ mod headless;
#[cfg(not(target_arch = "wasm32"))]
mod worker;
#[cfg(all(target_arch = "wasm32", not(feature = "gui")))]
compile_error!("the web build needs the `gui` feature");
#[cfg(feature = "gui")]
use app::FractalApp;
#[cfg(all(feature = "gui", not(target_arch = "wasm32")))]
type MainResult = eframe::Result;
#[cfg(all(not(feature = "gui"), not(target_arch = "wasm32")))]
type MainResult = Result<(), String>;
/// wgpu configuration for eframe. The fractal fragment shader reads the
/// 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:
/// 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:
/// * request the adapter's real limits (which include storage buffers), and
/// * 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")]
/// * force the WebGPU backend on the web (WebGL2 can't do storage buffers at
/// all) — failing cleanly on browsers without WebGPU, per the design.
fn wgpu_options() -> eframe::egui_wgpu::WgpuConfiguration {
use eframe::egui_wgpu::{WgpuSetup, wgpu};
@@ -57,35 +42,16 @@ fn wgpu_options() -> eframe::egui_wgpu::WgpuConfiguration {
required_limits: adapter.limits(),
..Default::default()
});
#[cfg(all(target_arch = "wasm32", not(feature = "webgl")))]
#[cfg(target_arch = "wasm32")]
{
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 {
fn main() -> eframe::Result {
use clap::Parser as _;
env_logger::builder()
@@ -104,13 +70,6 @@ fn main() -> MainResult {
};
}
#[cfg(not(feature = "gui"))]
{
eprintln!("error: built without the \"gui\" feature; only --headless is supported");
std::process::exit(1);
}
#[cfg(feature = "gui")]
let native_options = eframe::NativeOptions {
renderer: eframe::Renderer::Wgpu,
wgpu_options: wgpu_options(),
@@ -121,7 +80,6 @@ fn main() -> MainResult {
..Default::default()
};
#[cfg(feature = "gui")]
eframe::run_native(
"Fractal Explorer",
native_options,
-22
View File
@@ -1,22 +0,0 @@
// 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);
}
-27
View File
@@ -1,27 +0,0 @@
// Histogram of the escaped pixels' smoothed iteration count `ci`, for the
// auto colour scale (`CiStats` in renderer.rs). Reads the same data texture
// the colourise pass reads (R = ci, B = interior fraction). Bins are uniform
// in log2(1 + ci) over [0, CI_LOG2_MAX), so one fixed layout covers every
// zoom depth (`MAX_ITERATIONS` = 2^24). Must match `CI_BINS`/`CI_LOG2_MAX`
// in renderer.rs.
const CI_BINS: u32 = 1024u;
const CI_LOG2_MAX: f32 = 25.0;
@group(0) @binding(0) var data_tex: texture_2d<f32>;
@group(0) @binding(1) var<storage, read_write> hist: array<atomic<u32>, 1024>;
@compute @workgroup_size(16, 16)
fn cs_main(@builtin(global_invocation_id) id: vec3<u32>) {
let size = textureDimensions(data_tex);
if id.x >= size.x || id.y >= size.y {
return;
}
let d = textureLoad(data_tex, vec2<i32>(id.xy), 0);
if d.b >= 1.0 {
return; // fully interior: no escape time
}
let x = log2(1.0 + max(d.r, 0.0)) * (f32(CI_BINS) / CI_LOG2_MAX);
let bin = min(u32(max(x, 0.0)), CI_BINS - 1u);
atomicAdd(&hist[bin], 1u);
}
-47
View File
@@ -1,47 +0,0 @@
// 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);
}
-104
View File
@@ -1,104 +0,0 @@
// 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;
}
+33 -315
View File
@@ -18,45 +18,18 @@
// to the plain f32 loop once the delta is big enough (see `iterate_sample`).
@group(0) @binding(0) var<uniform> u: Uniforms;
// 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).
@group(0) @binding(1) var<storage, read> ref_orbit: array<vec2<f32>>;
// 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>;
// 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_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,
steps: u32,
};
// `frexp` result (see `frexp_f32`).
struct Frexp {
fract: f32,
exp: i32,
};
// 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>;
// Pipeline-overridable specialization constants, set per pipeline from the
// uniforms' `kind` / `is_julia` / `de_coloring` (see `PipelineKey` in
@@ -76,9 +49,6 @@ override MORPH: bool = false;
// and `u.span` / `u.dc_offset` are all in units of 2^scale_exp, and each pixel
// starts in the rescaled deep phase (see `iterate_sample`).
override DEEP: bool = false;
// Jump over runs of reference steps with the BLA table (every kind but
// Phoenix, no morph; see `bla_lookup`).
override BLA: bool = false;
struct VsOut {
@builtin(position) pos: vec4<f32>,
@@ -308,23 +278,7 @@ fn ldexp_sat(x: f32, k: i32) -> f32 {
if x == 0.0 {
return 0.0;
}
// 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 f = frexp(x);
let ex = f.exp + k;
if ex > 100 {
return select(-LDEXP_SAT, LDEXP_SAT, x > 0.0);
@@ -332,7 +286,7 @@ fn ldexp_sat(x: f32, k: i32) -> f32 {
if ex < -125 {
return 0.0;
}
return ldexp_f32(f.fract, ex);
return ldexp(f.fract, ex);
}
fn ldexp2_sat(v: vec2<f32>, k: i32) -> vec2<f32> {
@@ -351,16 +305,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_f32(a).exp;
let k = frexp(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_point(m);
let x = ref_orbit[m];
if DEEP {
let k = ref_exp_at(m);
let k = ref_exp[m];
if k != 0 {
return ldexp2_sat(x, k);
}
@@ -370,7 +324,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_point(m), ref_exp_at(m));
return fe_make(ref_orbit[m], ref_exp[m]);
}
// Complex log of m * 2^e (m != 0).
@@ -575,7 +529,7 @@ fn deep_log2(a: vec2<f32>, b: vec2<f32>) -> i32 {
if m == 0.0 {
return DEEP_ZERO;
}
return frexp_f32(m).exp;
return frexp(m).exp;
}
// f'(y) at the full value y = X + w * 2^s, as an `Fe`. Plain `fprime` in f32
@@ -623,108 +577,6 @@ 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> {
return vec2<f32>(dot(m.xy, v), dot(m.zw, v));
}
// log2|v|, from above (|v| <= sqrt(2)·max component). Not via dot(v, v):
// a delta ~2^-100 (a pixel offset at 1e-30 zoom) squares below f32's range,
// and log2(0) = -inf passed every radius test, jumping pixels far too early.
fn log2_mag(v: vec2<f32>) -> f32 {
return log2(max(abs(v.x), abs(v.y))) + 0.5;
}
// Longest BLA jump available at reference index `m` for a delta of
// log2 magnitude `e_log2`, of at most `budget` steps: (node index, steps),
// steps = 0 when there's none. Nodes start at 1 + i·2^l, so level l needs
// m - 1 aligned to 2^l. A longer run's radius is never larger than its first
// half's, so the search goes up from the shortest and stops at the first
// invalid level (usually right away: one load per failed attempt).
fn bla_lookup(m: u32, e_log2: f32, budget: u32) -> vec2<u32> {
var best = vec2<u32>(0u, 0u);
let levels = bla_meta_at(1u);
if levels == 0u || m == 0u {
return best;
}
let lmin = bla_meta_at(0u);
let j = m - 1u;
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 local = j >> l;
if steps > budget || local >= count {
break;
}
let idx = base + local;
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.
@@ -779,9 +631,6 @@ 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).
@@ -834,7 +683,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_point(1u) + offset;
let c = ref_orbit[1] + 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;
@@ -882,8 +731,6 @@ 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;
@@ -930,14 +777,6 @@ 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);
@@ -953,51 +792,6 @@ fn iterate_sample(offset: vec2<f32>, px: f32) -> Sample {
break;
}
// BLA: jump the whole run the table covers, straight to its
// output scale (usually many binades up, towards the f32 hand-off).
var jumped = false;
if BLA {
let e_log2 = f32(sx) + log2_mag(w);
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_node(hit.x);
if DE {
var accv = fe_make(mat2v(nd.m, v), nd.m_exp + sv);
if !IS_JULIA {
accv = fe_add(accv, fe_make(mat2v(nd.n, vec2<f32>(px, 0.0)), nd.n_exp + scale_e));
}
v = accv.m;
if accv.m.x != 0.0 || accv.m.y != 0.0 {
sv = accv.e;
if !IS_JULIA {
pd = ldexp_sat(px, scale_e - sv);
}
}
}
var acc = fe_make(mat2v(nd.m, w), nd.m_exp + sx);
if !IS_JULIA {
acc = fe_add(acc, fe_make(mat2v(nd.n, offset), nd.n_exp + scale_e));
}
w = acc.m;
if acc.m.x != 0.0 || acc.m.y != 0.0 {
sx = acc.e;
sc = ldexp_sat(1.0, sx);
if !IS_JULIA {
d = ldexp2_sat(offset, scale_e - sx);
}
}
w_old = w;
m = m + hit.y;
n = n + hit.y;
jumped = true;
}
}
if !jumped {
if DE {
let fp = deep_fprime(xf, w, sx, yt);
if fp.e == 0 {
@@ -1079,7 +873,6 @@ fn iterate_sample(offset: vec2<f32>, px: f32) -> Sample {
}
m = m + 1u;
n = n + 1u;
}
if m >= ref_len {
escaped = true; // see the f32 loop's reference-exhausted case
@@ -1093,10 +886,8 @@ 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 {
var q = ldexp2_sat(xf.m, xf.e - sx) + w;
let 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.
@@ -1114,8 +905,6 @@ fn iterate_sample(offset: vec2<f32>, px: f32) -> Sample {
xf = z0f;
xt = z0;
m = 0u;
seg_i = 0u;
seg_at = seg_first;
}
}
@@ -1185,19 +974,12 @@ 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 {
@@ -1212,49 +994,6 @@ fn iterate_sample(offset: vec2<f32>, px: f32) -> Sample {
// which only re-expresses the same value). Only when DE is enabled.
// Phoenix's two-term map adds p·dz_{n-1} and carries the previous dz.
// f'(z) of this step, shared by DE and the periodicity multiplier.
// BLA jump (see the deep phase). dc and px are taken unscaled from
// `offset`/`px`: at depth `step_add`/`px_t` have flushed to 0, but
// N·dc hasn't. The skipped steps' |f'|^2 product is |det M| (the
// steps are conformal, or folds of conformal maps). No skipped
// iterate can be the window's closest to the critical point: a run's
// radius is below ε·|X| for every X in it.
//
// With DE, dzs goes through M, the map's true Jacobian, where the
// plain loop multiplies by `fprime` (|2Z| for the abs kinds): same
// magnitude, since the folds are isometries.
let e_old = e;
let z_old = z;
var jumped = false;
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_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);
let a2 = ldexp_sat(det, 2 * nd.m_exp);
mult2 = mult2 * a2;
mult2_cand = mult2_cand * a2;
}
if DE {
var dn = ldexp2_sat(mat2v(nd.m, dzs), nd.m_exp);
if !IS_JULIA {
dn = dn + ldexp2_sat(mat2v(nd.n, vec2<f32>(px, 0.0)), nd.n_exp + se);
}
dzs = dn;
}
var en = ldexp2_sat(mat2v(nd.m, e), nd.m_exp);
if !IS_JULIA {
en = en + ldexp2_sat(mat2v(nd.n, offset), nd.n_exp + se);
}
e = en;
m = m + hit.y;
n = n + hit.y;
jumped = true;
}
}
if !jumped {
var fp = vec2<f32>(0.0, 0.0);
if DE || periodic {
fp = fprime(z);
@@ -1278,6 +1017,8 @@ fn iterate_sample(offset: vec2<f32>, px: f32) -> Sample {
// Advance the delta by this fractal's formula (+ dc for the set plane).
// Phoenix additionally adds p·e_{n-1} and carries the previous delta.
let e_old = e;
let z_old = z;
e = advance_delta(xm, e) + step_add;
if phoenix_w > 0.0 {
e = e + phoenix_w * cmul(u.phoenix_p, e_prev);
@@ -1285,7 +1026,6 @@ fn iterate_sample(offset: vec2<f32>, px: f32) -> Sample {
}
m = m + 1u;
n = n + 1u;
}
// Keep the reference index valid and the delta small.
if m >= ref_len {
@@ -1307,59 +1047,37 @@ 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 {
// 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;
// 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;
}
}
if n >= check_at {
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 {
period_streak = 0u;
}
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.)
while check_at <= n {
check_at = check_at * 2u;
}
check_at = check_at * 2u;
}
}
}
+60 -50
View File
@@ -1,6 +1,6 @@
//! Camera / view state over the complex plane.
//!
//! The center is stored in arbitrary precision ([`Big`]) — this is what lets us
//! The center is stored in arbitrary precision (`FBig`) — this is what lets us
//! zoom far past f64's ~1e13x limit. The pixel *scale* is a [`Scale`]: an
//! f64 mantissa with its own `i32` binary exponent, so it isn't bound by
//! f64's ~1e-308 range either (the floor, `Scale::MIN`, only keeps the GPU's
@@ -10,7 +10,11 @@
use core::str::FromStr;
pub use crate::bignum::Big;
use dashu_float::round::mode::HalfAway;
use dashu_float::{DBig, FBig};
/// Arbitrary-precision binary float (base 2, round-half-away). One coordinate.
pub type Big = FBig<HalfAway, 2>;
/// Half-height (complex units) of the default view; also the zoom-1 reference.
pub const DEFAULT_HALF_HEIGHT: f64 = 1.25;
@@ -190,37 +194,28 @@ impl core::fmt::Display for Scale {
};
}
// Out of f64's range: round the exact decimal expansion instead.
let big = self.to_big();
let sci = |sig: usize, pad: Option<usize>| {
let parts = big.to_decimal_parts(sig);
let digits = if parts.digits.is_empty() {
"0"
} else {
&parts.digits
};
// value = 0.digits · 10^exp10; move the point after the first digit.
let exp10 = parts.exp10 - 1;
let (head, tail) = digits.split_at(1);
let tail = match pad {
Some(p) => format!("{tail:0<p$}"),
None => tail.to_string(),
};
if tail.is_empty() {
format!("{head}e{exp10}")
} else {
format!("{head}.{tail}e{exp10}")
}
let sig = f.precision().map_or(17, |p| p + 1);
let dec = self
.to_big()
.to_decimal()
.value()
.with_precision(sig)
.value();
let repr = dec.repr();
let digits = repr.significand().to_string();
let digits = digits.trim_end_matches('0');
let digits = if digits.is_empty() { "0" } else { digits };
// value = significand · 10^exponent; move the point after the first digit.
let exp10 = repr.exponent() + repr.significand().to_string().len() as isize - 1;
let (head, tail) = digits.split_at(1);
let tail = match f.precision() {
Some(p) => format!("{tail:0<p$}"),
None => tail.to_string(),
};
match f.precision() {
Some(p) => f.write_str(&sci(p + 1, Some(p))),
None => {
// Like `{:e}` on f64: the shortest string that parses back.
let s = (1..17)
.map(|sig| sci(sig, None))
.find(|s| s.parse::<Scale>() == Ok(*self))
.unwrap_or_else(|| sci(17, None));
f.write_str(&s)
}
if tail.is_empty() {
write!(f, "{head}e{exp10}")
} else {
write!(f, "{head}.{tail}e{exp10}")
}
}
}
@@ -242,12 +237,18 @@ impl FromStr for Scale {
};
}
// Too small (or large) for f64: go through an exact decimal.
let bin = Big::from_decimal_str(s, 64).ok_or(())?;
if bin.is_negative() {
let dec = DBig::from_str(s).map_err(|_| ())?;
let bin: Big = dec.with_base_and_precision::<2>(64).value();
if bin < Big::ZERO {
return Err(());
}
let top = bin.log2_floor().ok_or(())?;
let m = (bin >> top).to_f64();
let repr = bin.repr();
let digits = repr.digits();
if digits == 0 {
return Err(());
}
let top = repr.exponent() + digits as isize - 1;
let m = (bin.clone() >> top).to_f64().value();
let e = top.clamp(i32::MIN as isize, i32::MAX as isize) as i32;
Ok(Self::from_parts(m, e))
}
@@ -311,10 +312,10 @@ impl ViewState {
pub fn sync_precision(&mut self) {
let bits = self.precision_bits();
if self.center_re.precision() < bits {
self.center_re = self.center_re.clone().with_precision(bits);
self.center_re = self.center_re.clone().with_precision(bits).value();
}
if self.center_im.precision() < bits {
self.center_im = self.center_im.clone().with_precision(bits);
self.center_im = self.center_im.clone().with_precision(bits).value();
}
}
@@ -359,7 +360,8 @@ impl ViewState {
/// Parse a decimal string (any number of digits) losslessly into a `Big` with at
/// least `bits` of precision. Used for share links and debug view specs.
pub fn big_from_decimal_str(s: &str, bits: usize) -> Option<Big> {
Big::from_decimal_str(s, bits)
let dec = DBig::from_str(s.trim()).ok()?;
Some(dec.with_base_and_precision::<2>(bits.max(53)).value())
}
/// Parse a "re,im,half_height[,iterations]" spec (re/im decimal, parsed at
@@ -438,10 +440,10 @@ pub fn interpolate_view(from: &ViewState, to: &ViewState, t: f64) -> ViewState {
// Zooming out: g = (1 - q^(t-1)) / (1 - q^-1), every term bounded.
big_from_f64(((t - 1.0) * d * ln2).exp_m1() / (-d * ln2).exp_m1(), bits)
};
let re0 = from.center_re.clone().with_precision(bits);
let im0 = from.center_im.clone().with_precision(bits);
let re1 = to.center_re.clone().with_precision(bits);
let im1 = to.center_im.clone().with_precision(bits);
let re0 = from.center_re.clone().with_precision(bits).value();
let im0 = from.center_im.clone().with_precision(bits).value();
let re1 = to.center_re.clone().with_precision(bits).value();
let im1 = to.center_im.clone().with_precision(bits).value();
let center_re = &re1 + &(&(&re0 - &re1) * &g_big);
let center_im = &im1 + &(&(&im0 - &im1) * &g_big);
ViewState::with_center(center_re, center_im, half_height)
@@ -454,7 +456,12 @@ pub fn interpolate_f64(from: f64, to: f64, t: f64) -> f64 {
/// Render a `Big` as a decimal string with `sig_digits` significant digits.
pub fn big_to_decimal_str(x: &Big, sig_digits: usize) -> String {
x.to_decimal_string(sig_digits)
let dec = x
.to_decimal()
.value()
.with_precision(sig_digits.max(1))
.value();
format!("{dec}")
}
/// Precision (bits) needed to resolve the center at a given half-height.
@@ -465,9 +472,12 @@ pub fn precision_for(half_height: Scale) -> usize {
(zoom_bits + GUARD_BITS).clamp(53, MAX_PRECISION_BITS)
}
/// Build a `Big` from an f64 with an explicit precision.
/// Build an `FBig` from an f64 with an explicit precision context.
pub fn big_from_f64(x: f64, bits: usize) -> Big {
Big::from_f64(x, bits)
Big::try_from(x)
.unwrap_or_default()
.with_precision(bits)
.value()
}
#[cfg(test)]
@@ -479,8 +489,8 @@ mod tests {
}
fn re_im_f64(v: &ViewState) -> (f64, f64) {
let re: f64 = v.center_re.to_f64();
let im: f64 = v.center_im.to_f64();
let re: f64 = v.center_re.to_decimal().value().to_f64().value();
let im: f64 = v.center_im.to_decimal().value().to_f64().value();
(re, im)
}
@@ -602,8 +612,8 @@ mod tests {
prev = mid.half_height;
// Offset from the target, in units of the view's half-height.
let k = -mid.half_height.exponent() as isize;
let dre = ((&mid.center_re - &to.center_re) << k).to_f64();
let dim = ((&mid.center_im - &to.center_im) << k).to_f64();
let dre = ((&mid.center_re - &to.center_re) << k).to_f64().value();
let dim = ((&mid.center_im - &to.center_im) << k).to_f64().value();
let ratio = (dre * dre + dim * dim).sqrt() / mid.half_height.scaled_f64(k as i32);
assert!(ratio > 0.01 && ratio < 10.0, "t={t}: ratio {ratio}");
}
+1 -1
View File
@@ -1,7 +1,7 @@
//! Native background worker for reference-orbit computation.
//!
//! At deep zoom the high-precision reference can take many milliseconds (tens of
//! thousands of `Big` iterations), which would stutter the UI if done inline.
//! thousands of `FBig` iterations), which would stutter the UI if done inline.
//! This runs it on a thread and coalesces bursts of requests (e.g. during a
//! drag) down to the most recent one. On the web we compute inline instead
//! (browsers need a Web Worker for threads); see `app.rs`.
+21 -272
View File
@@ -65,282 +65,49 @@ 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 `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();
/// Every specialization renderer.rs can build (`PipelineKey`: kind × Julia ×
/// DE × morph × deep), for every fragment entry point.
#[test]
fn mandelbrot_shader_specializations_compile() {
let (module, info) = validate("mandelbrot.wgsl", MANDELBROT_SRC);
for kind in 0..kind_count() {
for julia in [0.0, 1.0] {
for de in [0.0, 1.0] {
for morph in [0.0, 1.0] {
for deep in [0.0, 1.0] {
// BLA: every kind but Phoenix (7), no morph (`bla::applies`).
let blas: &[f64] = if kind != 7 && morph == 0.0 {
&[0.0, 1.0]
} else {
&[0.0]
};
for &bla in blas {
keys.push([
("KIND", kind as f64),
("IS_JULIA", julia),
("DE", de),
("MORPH", morph),
("DEEP", deep),
("BLA", bla),
]);
let constants = [
("KIND", kind as f64),
("IS_JULIA", julia),
("DE", de),
("MORPH", morph),
("DEEP", deep),
];
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]
@@ -402,21 +169,3 @@ 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(
"ci_stats.wgsl",
include_str!("../src/shaders/ci_stats.wgsl"),
);
}
-2
View File
@@ -1,2 +0,0 @@
results/
.worktrees/
-48
View File
@@ -1,48 +0,0 @@
# Benchmarks
`bench.sh` times `mandelbrot --headless` on a fixed set of views with
[hyperfine](https://github.com/sharkdp/hyperfine). That's the whole real
pipeline: the reference orbit on the CPU, then the GPU render, readback and PNG
encode. It builds the headless-only binary (`--no-default-features`) itself.
```sh
tools/bench/bench.sh --rev HEAD # did my uncommitted edits help? (vs last commit)
tools/bench/bench.sh --rev main seahorse-1e300 # one scenario vs another branch
tools/bench/bench.sh --quick # all scenarios, 960×540, 3 runs
tools/bench/bench.sh # all scenarios, 1920×1080, 5 runs
tools/bench/bench.sh --list
```
`--rev REF` checks REF out into `.worktrees/<sha>` and builds it there, with its
own target dir, so your `target/` stays warm. Each scenario then runs both
binaries back to back in one hyperfine call. The line to read is
`working tree ran 1.23 ± 0.04 times faster than main (…)`. A ratio within about
2σ of 1.00 is noise.
Results (hyperfine JSON and markdown per scenario) go to
`results/<sha>[-dirty]/`, or `results/<rev>-vs-<sha>/` with `--rev`.
Both `results/` and `.worktrees/` are git-ignored. To clean up:
`rm -rf tools/bench/.worktrees && git worktree prune`.
## Scenarios
| name | mostly measures |
|---|---|
| `shallow` | GPU, plain f32 path, f64 orbit fast path |
| `seahorse-1e30` | GPU f32 perturbation from a `Big` orbit |
| `seahorse-1e100` | the `DEEP` shader pipeline |
| `elephant-1e100-aa-de` | 2×2 antialiasing + DE shading |
| `burning-ship` | a non-holomorphic kind |
| `3d` | the raymarched 3D export path |
| `anim-zoom` | 24-frame zoom (⅓ size): the parallel orbit, GPU and PNG pipeline |
| `seahorse-1e300` *(slow)* | ~270k iterations per pixel on the deep path, ~40 s per run even with `--quick`. It's GPU-bound: the orbit itself is under a second. Only runs when named or with `--all` |
Views come from `tools/deep-zoom/LOCATIONS.md`. Each wall time includes process
start, device creation and shader compilation, so a small change to a GPU-bound
scenario shows up diluted.
## Tips
- Keep the machine idle and on AC power. Other GPU apps (browsers, video) add a lot of noise.
- Use `--quick` while you iterate and a full run to confirm.
- Timings are only comparable on the same machine and GPU.
-128
View File
@@ -1,128 +0,0 @@
#!/usr/bin/env bash
# Benchmark `mandelbrot --headless` on a fixed set of scenarios with hyperfine.
#
# Usage:
# bench.sh [--quick] [--runs N] [--rev REF] [--all] [--list] [scenario...]
#
# (default) time the working tree; results go to results/<sha>[-dirty]/
# --rev REF also build REF (in a git worktree) and time both binaries side
# by side; hyperfine prints "X ± σ times faster" per scenario
# --quick 960×540 and 3 runs instead of 1920×1080 and 5
# --runs N timed runs per command (after 1 warmup run)
# --all include the slow scenarios
# --list print the scenario names and exit
#
# With no scenario names, all but the slow ones run. See README.md.
set -euo pipefail
here=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
root=$(git -C "$here" rev-parse --show-toplevel)
# Views from tools/deep-zoom/LOCATIONS.md.
SEAHORSE_40='-0.77568376800905379745347652613832924487504096622022,0.13646736829469012473375311880735014411233827361594'
SEAHORSE_101='-0.77568376800905379746948350393474104572824650461579342765769586746577714101553375163935420167637213972439444483,0.13646736829469012473327440961784876519777211159246218448277041663416833530840062457397927487282583495378053495'
SEAHORSE_300='-0.775683768009053797469483503934741045728246504615800394794952001400666017222819589894883159368782255028252296689050972508942991790804637379375064948276511044167168394677127466362472192356953918438738697548775738756167744421444715134058363508346750264411321139485834882343906172015818621107808449401958194265462,0.136467368294690124733274409617848765197772111592467696407800195400835665974815500875448611244178656625706823059759836009902469392551108149827753781145338163746214967880988693412636771323356061132825037923307975359146666033691080243216637006179374407866237575096209504710178751614036006531433101633993532313930'
ELEPHANT_100='0.2920738619144539179997175176922057340804018914331633820622644536373359023331882946705674169275530423410817910,0.01577091721139011808246902823033833768260048863232968822435568049949556139801802963232184866659058960379114747'
# name -> headless args (no size or --export-path; those are added per run).
# Order matters for display, hence the separate list. SLOW ones (tens of
# seconds per run) only run when named or with --all.
SCENARIOS=(shallow seahorse-1e30 seahorse-1e100 elephant-1e100-aa-de burning-ship 3d anim-zoom)
SLOW=(seahorse-1e300)
declare -A ARGS=(
[shallow]="--view=-0.75,0,1.5"
[seahorse-1e30]="--view=$SEAHORSE_40,1e-30"
[seahorse-1e100]="--view=$SEAHORSE_101,3.4e-101"
[seahorse-1e300]="--view=$SEAHORSE_300,5.5e-300"
[elephant-1e100-aa-de]="--view=$ELEPHANT_100,1e-75 --antialias --de"
[burning-ship]="--kind burning-ship"
[3d]="--rendering-kind 3d --de --pitch -40 --view=-0.75,0,1.5"
[anim-zoom]="--view=-0.75,0,1.5 --to-view=$SEAHORSE_40,1e-30 --frames 24"
)
quick=0
runs=
rev=
picked=()
while (($#)); do
case $1 in
--quick) quick=1 ;;
--runs) runs=$2; shift ;;
--rev) rev=$2; shift ;;
--all) picked+=("${SCENARIOS[@]}" "${SLOW[@]}") ;;
--list) printf '%s\n' "${SCENARIOS[@]}"; printf '%s (slow)\n' "${SLOW[@]}"; exit 0 ;;
-h|--help) sed -n '2,16s/^# \{0,1\}//p' "$0"; exit 0 ;;
-*) echo "unknown option: $1" >&2; exit 2 ;;
*)
[[ -v ARGS[$1] ]] || { echo "unknown scenario: $1 (try --list)" >&2; exit 2; }
picked+=("$1") ;;
esac
shift
done
((${#picked[@]})) || picked=("${SCENARIOS[@]}")
if ((quick)); then
width=960 height=540 runs=${runs:-3}
else
width=1920 height=1080 runs=${runs:-5}
fi
command -v hyperfine >/dev/null || { echo "hyperfine not found (https://github.com/sharkdp/hyperfine)" >&2; exit 1; }
# Headless-only binary: no eframe/egui, faster to build, same render path.
build() { cargo build --release --no-default-features --quiet --manifest-path "$1/Cargo.toml"; }
echo "building working tree…" >&2
build "$root"
new_bin="$root/target/release/mandelbrot"
if [[ -n $rev ]]; then
rev_sha=$(git -C "$root" rev-parse --short "$rev^{commit}")
wt="$here/.worktrees/$rev_sha"
[[ -d $wt ]] || git -C "$root" worktree add --detach --quiet "$wt" "$rev_sha"
echo "building $rev ($rev_sha)…" >&2
# Separate target dir so switching revisions doesn't invalidate target/.
CARGO_TARGET_DIR="$here/.worktrees/target" build "$wt"
old_bin="$here/.worktrees/target/release/mandelbrot"
fi
tmp=$(mktemp -d)
trap 'rm -rf "$tmp"' EXIT
sha=$(git -C "$root" rev-parse --short HEAD)
git -C "$root" diff --quiet HEAD -- . ':!tools/bench' || sha+=-dirty
out="$here/results/${rev:+$rev_sha-vs-}$sha"
mkdir -p "$out"
# Full headless command line for scenario $2 with binary $1.
command_for() {
local bin=$1 name=$2 w=$width h=$height dest=$tmp/$2.png
if [[ $name == anim-* ]]; then
# Animation: a directory of frames, at a smaller size.
w=$((width / 3)) h=$((height / 3)) dest=$tmp/$name
fi
echo "$bin --headless --width $w --height $h --export-path $dest ${ARGS[$name]}"
}
for name in "${picked[@]}"; do
echo >&2
echo "=== $name ===" >&2
if [[ -n $rev ]]; then
cmds=(-n "$rev ($rev_sha)" "$(command_for "$old_bin" "$name")"
-n "working tree" "$(command_for "$new_bin" "$name")")
else
cmds=(-n "$name" "$(command_for "$new_bin" "$name")")
fi
hyperfine --warmup 1 --runs "$runs" --style basic \
--export-json "$out/$name.json" --export-markdown "$out/$name.md" \
"${cmds[@]}"
done
echo
echo "## Summary (${width}×${height}, $runs runs; results in ${out#"$root"/}/)"
for name in "${picked[@]}"; do
echo
echo "### $name"
cat "$out/$name.md"
done
-1
View File
@@ -1 +0,0 @@
out/
-248
View File
@@ -1,248 +0,0 @@
# Deep-zoom locations
Beautiful deep Mandelbrot locations, all computed with `find_deep.py` or `search.py` and
checked with a `--headless` render. Every one is an exact minibrot nucleus (Newton's method at
`2·depth + 60` digits), not a coordinate copied from somewhere, so the digits are right all
the way down.
## How to use them
Each location has two views on the same centre:
- **Minibrot:** half-height ≈ 3× the minibrot's size. A tiny copy of the whole set sits in
concentric colour bands, and there are more bands the deeper it is.
- **Embedded Julia set:** half-height ≈ size^0.75, about ¾ of the way down in log-zoom.
This is where each location looks unique. The minibrots all look alike.
```sh
cargo run --release -- --view=RE,IM,HALF_HEIGHT # interactive
cargo run --release -- --headless --view=RE,IM,HALF_HEIGHT --export-path shot.png
# zoom video from the full set down to a minibrot, piped to ffmpeg (see Makefile):
cargo run --release -- --headless --view=-0.75,0,1.5 --to-view=RE,IM,HALF_HEIGHT \
--fps 60 --duration 60 --export-path - | make hevc-nvenc
```
Pass negative coordinates as `--view=-0.77...` (with the `=`): clap would read `--view -0.77...` as a flag.
Iterations scale with depth automatically (about 90k at 10⁻¹⁰⁰ and 270k at 10⁻³⁰⁰), which is
enough for these periods.
## Infinite spirals (Misiurewicz points)
These are the anchor points. Zoom straight into one and the same spiral repeats forever,
at any depth. Every minibrot below sits just beside one of them.
| Region | Point | Preperiod, period | Looks like |
|---|---|---|---|
| Seahorse valley | `-0.7756837680090537974694835039347410457282465046158` `0.13646736829469012473327440961784876519777211159247` | 24, 2 | Two-armed spirals of seahorses, repeating at every depth. |
| Elephant valley | `0.29207386191445391799971751769220573408040189143315` `0.015770917211390118082469028230338337682600488632339` | 32, 3 | Three-armed spirals of elephant trunks. |
| Top antenna | `-0.10110375797210418675706890936004723524958119917843` `0.95629400795235409290719434118824484558046591980423` | 38, 4 | Four-armed branch points on the upper antenna, with thin dendrites instead of spirals. |
## Seahorse valley
### Seahorse valley, minibrot at 3.7e-41 (period 1034)
The embedded Julia set is a pale double spiral: two S-shaped arms of tiny seahorses wind into a bright centre, with a third lace band sweeping around them. The best one for a short video, and it renders in seconds.
```sh
# embedded Julia set
--view=-0.77568376800905379745347652613832924487504096622022,0.13646736829469012473375311880735014411233827361594,1e-30
# minibrot
--view=-0.77568376800905379745347652613832924487504096622022,0.13646736829469012473375311880735014411233827361594,1.1e-40
```
### Seahorse valley, minibrot at 1.14e-101 (period 2868)
At the Julia depth there's a dark blue field with a glowing core and lace threads crossing it.
```sh
# embedded Julia set
--view=-0.77568376800905379746948350393474104572824650461579342765769586746577714101553375163935420167637213972439444483,0.13646736829469012473327440961784876519777211159246218448277041663416833530840062457397927487282583495378053495,1e-76
# minibrot
--view=-0.77568376800905379746948350393474104572824650461579342765769586746577714101553375163935420167637213972439444483,0.13646736829469012473327440961784876519777211159246218448277041663416833530840062457397927487282583495378053495,3.4e-101
```
### Seahorse valley, minibrot at 1.37e-200 (period 5895)
Two filaments cross in an X over a warm brown background, with a small dark spiral where they meet.
```sh
# embedded Julia set
--view=-0.77568376800905379746948350393474104572824650461580039479495200140066601722281958989488315936878225494657853849784368247991666558116221905228489656259693587754973261632614186930985854124920967267440737850057557,0.13646736829469012473327440961784876519777211159246769640780019540083566597481550087544861124417865661202932094564677695883049019713653069907950852152823160218141353878979871215911794286224832089496659451498185,1e-150
# minibrot
--view=-0.77568376800905379746948350393474104572824650461580039479495200140066601722281958989488315936878225494657853849784368247991666558116221905228489656259693587754973261632614186930985854124920967267440737850057557,0.13646736829469012473327440961784876519777211159246769640780019540083566597481550087544861124417865661202932094564677695883049019713653069907950852152823160218141353878979871215911794286224832089496659451498185,4.1e-200
```
### Seahorse valley, minibrot at 1.83e-300 (period 8922)
Faint cream threads, and a spiral wound so tight it reads as a point. Period 8922, so the minibrot needs a long render.
```sh
# embedded Julia set
--view=-0.775683768009053797469483503934741045728246504615800394794952001400666017222819589894883159368782255028252296689050972508942991790804637379375064948276511044167168394677127466362472192356953918438738697548775738756167744421444715134058363508346750264411321139485834882343906172015818621107808449401958194265462,0.136467368294690124733274409617848765197772111592467696407800195400835665974815500875448611244178656625706823059759836009902469392551108149827753781145338163746214967880988693412636771323356061132825037923307975359146666033691080243216637006179374407866237575096209504710178751614036006531433101633993532313930,1e-225
# minibrot
--view=-0.775683768009053797469483503934741045728246504615800394794952001400666017222819589894883159368782255028252296689050972508942991790804637379375064948276511044167168394677127466362472192356953918438738697548775738756167744421444715134058363508346750264411321139485834882343906172015818621107808449401958194265462,0.136467368294690124733274409617848765197772111592467696407800195400835665974815500875448611244178656625706823059759836009902469392551108149827753781145338163746214967880988693412636771323356061132825037923307975359146666033691080243216637006179374407866237575096209504710178751614036006531433101633993532313930,5.5e-300
```
## Elephant valley
### Elephant valley, minibrot at 1.29e-100 (period 782)
A cream-coloured double S-spiral, like the seahorse one but with fatter, beaded arms.
```sh
# embedded Julia set
--view=0.2920738619144539179997175176922057340804018914331633820622644536373359023331882946705674169275530423410817910,0.01577091721139011808246902823033833768260048863232968822435568049949556139801802963232184866659058960379114747,1e-75
# minibrot
--view=0.2920738619144539179997175176922057340804018914331633820622644536373359023331882946705674169275530423410817910,0.01577091721139011808246902823033833768260048863232968822435568049949556139801802963232184866659058960379114747,3.9e-100
```
### Elephant valley, minibrot at 1.43e-199 (period 1585)
A single huge spiral arm made of blue beads curling across the whole frame.
```sh
# embedded Julia set
--view=0.2920738619144539179997175176922057340804018914331538397786950546981063169810374784665382516408545756138262706218874924432355556243165250541700374639889797148498919340003273815669351046658761147565052417000965,0.01577091721139011808246902823033833768260048863233880759961760295375606839216565332458201188913912642954367433579737643167232896069795830226759356080847862646789481028238105648099709502522309228500630759855757,1e-149
# minibrot
--view=0.2920738619144539179997175176922057340804018914331538397786950546981063169810374784665382516408545756138262706218874924432355556243165250541700374639889797148498919340003273815669351046658761147565052417000965,0.01577091721139011808246902823033833768260048863233880759961760295375606839216565332458201188913912642954367433579737643167232896069795830226759356080847862646789481028238105648099709502522309228500630759855757,4.3e-199
```
### Elephant valley, minibrot at 3.82e-300 (period 2395)
A spiral galaxy: several beaded arms around a pinwheel centre. One of the prettiest frames here.
```sh
# embedded Julia set
--view=0.292073861914453917999717517692205734080401891433153839778695054698106316981037478466538251640854575589843066619974864800862332115945960921998657430606126553202998390050225413256445451049563878137878839982267258218894836912449161037745627504826537881261626243871678392881757578278459983842286413975991353319739,0.0157709172113901180824690282303383376826004886323388075996176029537560683921656533245820118891391263013273917522825544701901299061542128984468742890308365571942081484001405437827548345359998503228665872823816067983725089244499770271352539008763406229496083105636482420467114597267096082878888045800333807911146,1e-225
# minibrot
--view=0.292073861914453917999717517692205734080401891433153839778695054698106316981037478466538251640854575589843066619974864800862332115945960921998657430606126553202998390050225413256445451049563878137878839982267258218894836912449161037745627504826537881261626243871678392881757578278459983842286413975991353319739,0.0157709172113901180824690282303383376826004886323388075996176029537560683921656533245820118891391263013273917522825544701901299061542128984468742890308365571942081484001405437827548345359998503228665872823816067983725089244499770271352539008763406229496083105636482420467114597267096082878888045800333807911146,1.1e-299
```
## Top antenna
### Top antenna, minibrot at 6.11e-101 (period 245)
A dark branching dendrite like a frost cross, with four-way junctions.
```sh
# embedded Julia set
--view=-0.10110375797210418675706890936004723524958119917842627217950669362738928440088634862532432662296073501093701563,0.95629400795235409290719434118824484558046591980423293884325556254155313535666457147658005358708674409029391915,1e-75
# minibrot
--view=-0.10110375797210418675706890936004723524958119917842627217950669362738928440088634862532432662296073501093701563,0.95629400795235409290719434118824484558046591980423293884325556254155313535666457147658005358708674409029391915,1.8e-100
```
### Top antenna, minibrot at 5.28e-200 (period 473)
A chain of six-armed snowflakes linked by thin filaments.
```sh
# embedded Julia set
--view=-0.10110375797210418675706890936004723524958119917842839398761868801597328463328677019373309617158827470368429189213012997868613724029746440432852247903869013157556141380437202406412221853553594880182186959159214,0.95629400795235409290719434118824484558046591980423399388630140415938010604675760901574969597486831722998038561988250849596064882005832681021199867736493316924923123916964900533995659228499205141785254396348248,1e-149
# minibrot
--view=-0.10110375797210418675706890936004723524958119917842839398761868801597328463328677019373309617158827470368429189213012997868613724029746440432852247903869013157556141380437202406412221853553594880182186959159214,0.95629400795235409290719434118824484558046591980423399388630140415938010604675760901574969597486831722998038561988250849596064882005832681021199867736493316924923123916964900533995659228499205141785254396348248,1.6e-199
```
### Top antenna, minibrot at 8.34e-301 (period 705)
A single twelve-armed star, very symmetric. The antenna minibrots have short periods (245-705), so these are the fastest deep renders.
```sh
# embedded Julia set
--view=-0.1011037579721041867570689093600472352495811991784283939876186880159732846332867701937330961715882746718394428627914481009391257007785408536971203165750666758077852384490279260184029373211737264310068845597273991782305778295187471341711226626762421910644338164121042775094463557363347706110614218633830535086184,0.9562940079523540929071943411882448455804659198042339938863014041593801060467576090157496959748683171680339080646917869452781885502668216669916185990922330667568398963038228431738928191227884090004548615469303071899797403388188723954061899156655653387543351937028936674153437083087070219108726088551230849901498,1e-225
# minibrot
--view=-0.1011037579721041867570689093600472352495811991784283939876186880159732846332867701937330961715882746718394428627914481009391257007785408536971203165750666758077852384490279260184029373211737264310068845597273991782305778295187471341711226626762421910644338164121042775094463557363347706110614218633830535086184,0.9562940079523540929071943411882448455804659198042339938863014041593801060467576090157496959748683171680339080646917869452781885502668216669916185990922330667568398963038228431738928191227884090004548615469303071899797403388188723954061899156655653387543351937028936674153437083087070219108726088551230849901498,2.5e-300
```
## Morphing zooms (no endless spiral)
A minibrot from `find_deep.py` sits at distance r from a Misiurewicz point and has size r², so
the first half of its zoom (in log scale) is the same spiral turning over and over. These are
built by `search.py` instead: a chain of minibrots, each picked inside the previous one's
embedded Julia set, off its centre. Every time the zoom passes one, the picture folds (z → z²
locally), so each stage shows the previous shape doubled instead of a repeat. The Misiurewicz
point is only used for the first few decades.
Each location has two end points. Zoom to the **last embedded Julia set** to keep changing
shape all the way down. The **minibrot** is about a third deeper, but that last stretch is
rings closing in on it, which looks the same for every minibrot.
The colour contrast washes out at these depths in headless renders (the default colour scale is
tuned for shallower views). Try `--palette` or the interactive app.
### Seahorse valley, 9 stages, minibrot at 1.95e-367 (period 13701)
Seed 2, the top scorer. Each stage doubles the pattern. Around 1e-150 it is an eight-armed star of seahorse-tail spirals, and by 1e-250 each arm has become a spiral arm of its own. The last Julia set is pale cyan S-spirals interlocked with small snowflakes.
```sh
# last embedded Julia set
--view=-0.7753452295156405956088382319063405041200389687755508065690758933972356154674766194756672970107824576987716506820473626377289966850477815993212514936989107755288403190421564405962299577965531281406098430140843315809148941148835642905077493477538626689716455579196401297663769682360083746728010029499252318437245060419975563373728583873423397522687593946164217423611237456686155,0.1364239581870775619072911253207719792041200901039288844939565392217863173195981034417860802937281884987101484785589683756503781834313063872897864695678156825572773750286514435594400277526505362588686964101890046172400600115486054295219300235694108056070084590715209580088595029634293379003635002553779969859087272620892813545216852862560609109477666596320676409189943462906183,1.7e-275
# minibrot
--view=-0.7753452295156405956088382319063405041200389687755508065690758933972356154674766194756672970107824576987716506820473626377289966850477815993212514936989107755288403190421564405962299577965531281406098430140843315809148941148835642905077493477538626689716455579196401297663769682360083746728010029499252318437245060419975563373728583873423397522687593946164217423611237456686155,0.1364239581870775619072911253207719792041200901039288844939565392217863173195981034417860802937281884987101484785589683756503781834313063872897864695678156825572773750286514435594400277526505362588686964101890046172400600115486054295219300235694108056070084590715209580088595029634293379003635002553779969859087272620892813545216852862560609109477666596320676409189943462906183,5.8e-367
```
### Seahorse valley, 9 stages, minibrot at 2.23e-332 (period 20771)
Seed 24. Ends on a deep-blue field with a ladder of two spiky rosettes up the middle and seahorse spirals hanging off both sides.
```sh
# last embedded Julia set
--view=-0.77581899776364093541231633878667591854940234460393623634560469682524602327917430132831992200028242018281986527945300983871854511115659304292671652789338745276924830204381603012151271794534404802657864351394053047466207495399034821695775654392586465718993627074907162608014351492003087712186151836540562594796512607687563345530430631968989769,0.13639016044733587310899816976451186522511735544614557616370747772490427471765768547942874390030670422507300887964841711805169647706659494431705444259263501596739281803768172126446068576798485059599688488281382970932839834055072153017771954773333653697740526075860787508424313537171575674813478338329140463605230166008829195653885760869703998,4.2e-249
# minibrot
--view=-0.77581899776364093541231633878667591854940234460393623634560469682524602327917430132831992200028242018281986527945300983871854511115659304292671652789338745276924830204381603012151271794534404802657864351394053047466207495399034821695775654392586465718993627074907162608014351492003087712186151836540562594796512607687563345530430631968989769,0.13639016044733587310899816976451186522511735544614557616370747772490427471765768547942874390030670422507300887964841711805169647706659494431705444259263501596739281803768172126446068576798485059599688488281382970932839834055072153017771954773333653697740526075860787508424313537171575674813478338329140463605230166008829195653885760869703998,6.7e-332
```
### Elephant valley, 10 stages, minibrot at 9.9e-376 (period 26330)
Seed 10. The busiest one. Around 1e-100 it is dense blue lace over dark red; around 1e-200 there are big pinwheel fans with curled trunk tips, the prettiest frame of the set. Toward the end it becomes a dark field of small starbursts.
```sh
# last embedded Julia set
--view=0.2919725609273281486648237582115998883600209040251439086749905948711563568174299074829283558691127379979884016672342155749823780016183197461740530259273568326709292748874665616014636798873898973811666320162356520760904526444122077135661892284506788063980999152039879384033195224044981383998272534314607724906042434605344003420578380980595202662299201627356955139354311024040150045335132,0.01609653145423751028823367722046071738201813858290104726012040624213292560317148577164650820980015376333402589301809392204612823423640558757865322964450320793537771158249026499009376062869974452053829363185721040089473699420550959606623588474079103727001609122830051578927796106929658205975868875493047686224923681237537000490733609889219929444859368575967702125530262379423175371468097,5.5e-282
# minibrot
--view=0.2919725609273281486648237582115998883600209040251439086749905948711563568174299074829283558691127379979884016672342155749823780016183197461740530259273568326709292748874665616014636798873898973811666320162356520760904526444122077135661892284506788063980999152039879384033195224044981383998272534314607724906042434605344003420578380980595202662299201627356955139354311024040150045335132,0.01609653145423751028823367722046071738201813858290104726012040624213292560317148577164650820980015376333402589301809392204612823423640558757865322964450320793537771158249026499009376062869974452053829363185721040089473699420550959606623588474079103727001609122830051578927796106929658205975868875493047686224923681237537000490733609889219929444859368575967702125530262379423175371468097,3.0e-375
```
### Elephant valley, 10 stages, minibrot at 2.58e-393 (period 31938)
Seed 6. Ends on a cream field covered in tiny orange starbursts, like frost on a window.
```sh
# last embedded Julia set
--view=0.291920245587041963891588502847402316252926795406554403678013521015333816452464592295071998432671814509111459555663776008730796899291641422047823143066182408211544669386206661368710007384581820315259562196579747306521924025557974076213683940172635312577637426632710121469687554303515614245960216389023574299414942997525087881669471153995469440602254536765333823609728596136514603489157828188139494926264,0.0160764363740117355209701377378165904185186672655973900712949768468968706838603774970184637138036946417491390244864230673560872881279816470698447551999091888703048347169598010650942657073167719830723550405395270691529274225324525523911917416786211773060643555546204329361883408672335674317068855354237389458235628771660652358504910575175071131870389768222336460879256178272208513228731902472063018497750,1.7e-295
# minibrot
--view=0.291920245587041963891588502847402316252926795406554403678013521015333816452464592295071998432671814509111459555663776008730796899291641422047823143066182408211544669386206661368710007384581820315259562196579747306521924025557974076213683940172635312577637426632710121469687554303515614245960216389023574299414942997525087881669471153995469440602254536765333823609728596136514603489157828188139494926264,0.0160764363740117355209701377378165904185186672655973900712949768468968706838603774970184637138036946417491390244864230673560872881279816470698447551999091888703048347169598010650942657073167719830723550405395270691529274225324525523911917416786211773060643555546204329361883408672335674317068855354237389458235628771660652358504910575175071131870389768222336460879256178272208513228731902472063018497750,7.7e-393
```
## Finding more
Zooms that keep changing shape (Julia morphing, see above), ranked by rendering them:
```sh
./search.py seahorse # 24 chains down to ~1e-300..1e-450, prints the best 5
./search.py elephant --depth 200 --candidates 40 --seed 100
./morph.py seahorse --seed 7 --all-stages # one chain, with every stage's views
./score.py --view=RE,IM,HALF_HEIGHT --debug # score any zoom (e.g. the entries above)
```
`search.py` builds chains on every core (a few seconds each), then renders 32 thumbnails
along each zoom on the GPU (10-60 s each, most of the run time). The score is detail
(gradient strength) times one minus the fraction of frames that repeat the ones before them.
That fraction comes from a rotation- and scale-invariant (Fourier-Mellin) frame descriptor,
and it's about 0.6 for the spiral zooms above versus ~0 for morphing chains. Contact sheets
(8 frames along the zoom) go to `out/`. The thumbnails have no AA, so deep frames look
noisier there than they really are: render the view before judging. Needs mpmath, numpy,
Pillow and `cargo build --release`. Antenna chains work too, but they're mostly empty
background with thin dendrites, so they score low.
Minibrots next to a Misiurewicz point (the spiral locations above):
```sh
./find_deep.py --list # known regions
./find_deep.py seahorse 250 # minibrot of size ~1e-500 near the seahorse point
./find_deep.py seahorse 100 0.2,0.7 # a different minibrot at the same depth
./find_deep.py -0.1011,0.9563,38,4 80 # any Misiurewicz point, given as re,im,k,p
```
A disk of radius 10⁻ᴰ around a Misiurewicz point holds a minibrot of size about 10⁻²ᴰ.
Newton sometimes fails to converge (elephant at depth 100 with the default offset did). The
script detects this from the size and asks for a different offset. Needs `mpmath`.
-147
View File
@@ -1,147 +0,0 @@
#!/usr/bin/env python3
"""Find deep Mandelbrot minibrots near a Misiurewicz point.
Misiurewicz points (preperiodic c, f^(k+p)(0) = f^k(0)) have self-similar
spirals at every depth. A disk of radius r = 10^-D around one contains a
minibrot of size ~r^2, found by:
1. the ball-period method: the first n where the disk's image covers 0
gives the period p of a nucleus inside it;
2. Newton's method on f^p(0) = 0 at high precision for the nucleus;
3. the standard size estimate (Heiland-Allen) for its scale.
Zooming at the nucleus shows spirals, then an embedded Julia set (around
size^0.75), then the minibrot (half-height ~3x size). The spirals take
the first half of the zoom: for zooms that keep changing shape, use
morph.py / search.py instead.
Usage:
find_deep.py REGION DEPTH [OFFSET_RE,OFFSET_IM]
find_deep.py --list
REGION is a name from REGIONS or "re,im,k,p" for any Misiurewicz point.
OFFSET (default 0.6,0.3, in units of r) picks a different minibrot at the
same depth. If the printed size is far below 10^-(2*DEPTH), Newton didn't
converge: try another offset.
Needs mpmath (pip install mpmath).
"""
import sys
from mpmath import log10, mp, mpc, mpf
# name: (approximate seed, preperiod k, period p). The exact point is
# refined by Newton at the requested precision.
REGIONS = {
"seahorse": (("-0.77568377", "0.13646737"), 24, 2),
"elephant": (("0.2925", "0.0149"), 32, 3),
"antenna": (("-0.1011", "0.9563"), 38, 4),
}
def converged(d):
return abs(d) < mpf(10) ** (-mp.dps + 20)
def misiurewicz(c, k, p, steps=200):
"""Newton on f^(k+p)(0) - f^k(0) = 0."""
for _ in range(steps):
z = dz = mpc(0)
zk = dzk = None
for i in range(1, k + p + 1):
dz = 2 * z * dz + 1
z = z * z + c
if i == k:
zk, dzk = z, dz
d = (z - zk) / (dz - dzk)
c -= d
if converged(d):
break
return c
def period_in_ball(c, r, maxit=1_000_000):
"""First n where the disk of radius r around c maps onto a disk containing 0."""
z = dz = mpc(0)
for n in range(1, maxit):
dz = 2 * z * dz + 1
z = z * z + c
if abs(z) < abs(dz) * r:
return n
if abs(z) > 4:
return None
return None
def nucleus(c, p, steps=200):
"""Newton on f^p(0) = 0."""
for _ in range(steps):
z = dz = mpc(0)
for _ in range(p):
dz = 2 * z * dz + 1
z = z * z + c
d = z / dz
c -= d
if converged(d):
break
return c
def size(c, p):
"""Approximate size of the minibrot with nucleus c and period p."""
z = mpc(0)
l = b = mpc(1)
for _ in range(1, p):
z = z * z + c
l = 2 * z * l
b = b + 1 / l
return abs(1 / (b * l * l))
def main(argv):
if len(argv) >= 1 and argv[0] == "--list":
for name, ((re, im), k, p) in REGIONS.items():
print(f"{name:10} ~{re}{'+' if not im.startswith('-') else ''}{im}i M({k},{p})")
return 0
if len(argv) not in (2, 3):
print(__doc__, file=sys.stderr)
return 2
region, depth = argv[0], int(argv[1])
if region in REGIONS:
(re, im), k, p = REGIONS[region]
else:
re, im, k, p = region.split(",")
k, p = int(k), int(p)
off_re, off_im = argv[2].split(",") if len(argv) == 3 else ("0.6", "0.3")
mp.dps = 2 * depth + 60
m = misiurewicz(mpc(re, im), k, p)
r = mpf(10) ** (-depth)
c0 = m + r * mpc(off_re, off_im)
period = period_in_ball(c0, r)
if period is None:
print("no period found (the disk escapes)", file=sys.stderr)
return 1
n = nucleus(c0, period)
s = size(n, period)
if s < mpf(10) ** (-2 * depth - 10):
print(f"size {mp.nstr(s, 3)} is implausibly small: Newton didn't converge, "
"try another offset", file=sys.stderr)
return 1
digits = int(-log10(s)) + 10
log_s = float(log10(s))
re_s = mp.nstr(n.real, digits, strip_zeros=False)
im_s = mp.nstr(n.imag, digits, strip_zeros=False)
print(f"# {region} depth={depth} period={period} size={mp.nstr(s, 3)}")
print("# minibrot:")
print(f"--view={re_s},{im_s},{mp.nstr(3 * s, 2)}")
print(f"# embedded Julia set on the way down:")
print(f"--view={re_s},{im_s},1e{round(0.75 * log_s)}")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
-200
View File
@@ -1,200 +0,0 @@
#!/usr/bin/env python3
"""Chain minibrots by Julia morphing, so a deep zoom keeps changing shape.
find_deep.py puts a minibrot of size r^2 at distance r from a Misiurewicz
point, so the first half of the zoom (in log scale) is the same spiral over
and over. Here the Misiurewicz point is only used shallowly (stage 0), and
each later minibrot is picked inside the previous one's embedded Julia set,
off its centre. Zooming past a minibrot's neighbourhood folds the picture
(locally z -> z^2), so every stage shows the previous shape doubled instead
of a repeat.
Usage:
morph.py REGION [--stages N] [--depth D] [--d0 D0] [--seed S]
REGION is a name from find_deep.REGIONS or "re,im,k,p". Prints each stage's
period, size and the views to look at. search.py tries many seeds and ranks
the resulting zooms by rendering them.
Needs mpmath.
"""
import argparse
import math
import random
import sys
from dataclasses import dataclass
from mpmath import exp, log10, mp, mpc, mpf, sqrt
from find_deep import REGIONS, misiurewicz, nucleus, period_in_ball, size
# The shader treats an exhausted reference as escaped, and the reference is
# requested with 1.5x headroom (app.rs), so periods past this can't render.
MAX_ITERATIONS = 1 << 24
@dataclass
class Stage:
nucleus: mpc
period: int
size: mpf
reach: mpf # distance from the previous stage's centre (stage 0: the disk radius)
rho: float = 0.0 # where the target was picked, in units of the previous julia scale
theta: float = 0.0
@property
def julia(self):
"""Half-height of the embedded Julia set: geometric midpoint of reach and size."""
return sqrt(self.size * self.reach)
@property
def depth(self):
return float(-log10(self.size))
def set_precision(depth):
mp.dps = int(2 * depth) + 60
def anchor_point(region):
if region in REGIONS:
(re, im), k, p = REGIONS[region]
else:
re, im, k, p = region.split(",")
k, p = int(k), int(p)
return mpc(re, im), k, p
def find_minibrot(center, radius, min_period):
"""Nucleus of the lowest-period minibrot whose atom covers the disk, or None.
Rejects periods <= min_period (an ancestor, not something new next to
the target) and Newton landing far from the disk (another nucleus of the
same period).
"""
p = period_in_ball(center, radius)
if p is None or p <= min_period:
return None
n = nucleus(center, p)
if abs(n - center) > 4 * radius:
return None
s = size(n, p)
if not s > 0:
return None
return n, p, s
def stage0(region, d0, rng):
"""Minibrot near the Misiurewicz point at distance 10^-d0: a short spiral."""
c, k, p = anchor_point(region)
set_precision(2 * d0)
m = misiurewicz(c, k, p)
r = mpf(10) ** (-d0)
for _ in range(20):
theta = rng.uniform(0, 2 * math.pi)
off = r * exp(1j * mpf(theta))
found = find_minibrot(m + off, r, 0)
# Size ~r^2; far below means Newton didn't converge (as in find_deep.py).
if found and r * r * 1e-10 < found[2] < r * r * 1e6:
n, per, s = found
return Stage(n, per, s, abs(n - m), 0.0, theta)
return None
def next_stage(prev, rng, max_depth, beta=0.05, tries=12):
"""A minibrot inside prev's embedded Julia set, off its centre."""
for _ in range(tries):
rho = rng.uniform(0.05, 0.6)
theta = rng.uniform(0, 2 * math.pi)
# Enough digits to place the target and find the period; the nucleus
# is polished at the new depth's precision below, which is the costly
# part (a few Newton steps instead of all of them).
mp.dps = int(-log10(prev.julia)) + 60
d = rho * prev.julia
t = prev.nucleus + d * exp(1j * mpf(theta))
found = find_minibrot(t, beta * d, prev.period)
if not found:
continue
n, p, s = found
# Newton didn't converge (implausibly small), no real progress, or
# past the target depth (renders get slow and views huge).
if s < prev.size ** 2.5 or s > prev.size ** 1.2 or -log10(s) > max_depth:
continue
set_precision(float(-log10(s)))
n = nucleus(n, p) # polish at the precision this depth needs
s2 = size(n, p)
if not s / 10 < s2 < s * 10: # the polish wandered off to another nucleus
continue
return Stage(n, p, s2, abs(n - prev.nucleus), rho, theta)
return None
def build_chain(region, stages, depth, d0, seed, max_period=200_000):
"""Stage list, deepest last, ending between depth and 1.5x depth if it can.
Stops early at max_period or a dead end (no stage within reach).
"""
rng = random.Random(seed)
s = stage0(region, d0, rng)
if s is None:
return []
chain = [s]
while len(chain) < stages and chain[-1].depth < depth:
s = next_stage(chain[-1], rng, 1.5 * depth)
if s is None or s.period > min(max_period, MAX_ITERATIONS // 2):
break
chain.append(s)
return chain
def view_args(stage, half_height):
set_precision(stage.depth)
digits = int(stage.depth) + 10
re = mp.nstr(stage.nucleus.real, digits, strip_zeros=False)
im = mp.nstr(stage.nucleus.imag, digits, strip_zeros=False)
return f"--view={re},{im},{mp.nstr(half_height, 2)}"
def minibrot_view(stage):
return view_args(stage, 3 * stage.size)
def julia_view(stage):
return view_args(stage, stage.julia)
def describe(chain):
lines = []
for i, s in enumerate(chain):
lines.append(f"# stage {i}: period={s.period} size={mp.nstr(s.size, 3)} "
f"julia={mp.nstr(s.julia, 3)} rho={s.rho:.2f} theta={s.theta:.2f}")
return lines
def main(argv):
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
ap.add_argument("region")
ap.add_argument("--stages", type=int, default=6)
ap.add_argument("--depth", type=float, default=300, help="stop past size 10^-DEPTH")
ap.add_argument("--d0", type=float, default=4, help="stage 0 distance 10^-D0 from the anchor")
ap.add_argument("--seed", type=int, default=1)
ap.add_argument("--max-period", type=int, default=200_000)
ap.add_argument("--all-stages", action="store_true", help="print every stage's views")
a = ap.parse_args(argv)
chain = build_chain(a.region, a.stages, a.depth, a.d0, a.seed, a.max_period)
if not chain:
print("no minibrot found near the anchor, try another seed", file=sys.stderr)
return 1
for line in describe(chain):
print(line)
for i, s in enumerate(chain if a.all_stages else chain[-1:]):
i = i if a.all_stages else len(chain) - 1
print(f"# stage {i} embedded Julia set:\n{julia_view(s)}")
print(f"# stage {i} minibrot:\n{minibrot_view(s)}")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
-160
View File
@@ -1,160 +0,0 @@
#!/usr/bin/env python3
"""Score a deep zoom by rendering thumbnails along it.
One `--headless` animation call streams the whole zoom (full set down to
the target, evenly spaced in log-depth) as raw RGBA thumbnails. Per frame:
- detail: mean gradient magnitude at half resolution, so flat bands and
empty voids score low and aliasing noise doesn't score high;
- a Fourier-Mellin descriptor (|FFT| resampled to log-polar, then |FFT| of
that), invariant to translation, rotation and scale. A Misiurewicz spiral
looks the same at every turn, so its frames all get the same descriptor.
A frame's novelty is its mean descriptor distance to the 3 frames before
it. boring = fraction of frames with novelty below BORING (at the default
32 frames, spiral zooms sit around 0.17, morphing chains around 0.28). score = mean detail x
(1 - boring) x (1 - empty fraction).
Usage:
score.py --view=RE,IM,HALF_HEIGHT [--frames 32] [--debug] [--sheet out.png]
Needs numpy and a release build (cargo build --release).
"""
import argparse
import os
import subprocess
import sys
from dataclasses import dataclass
import numpy as np
ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
BINARY = os.path.join(ROOT, "target", "release", "mandelbrot")
START_VIEW = "-0.75,0,1.5"
BORING = 0.21 # novelty below which a frame repeats the ones before it
LAGS = (1, 2, 3)
EMPTY = 0.02 # detail below which a frame counts as empty
def render_path(view, frames=32, width=192, height=108, start=START_VIEW):
"""Frames from the full set down to `view` (RE,IM,HALF_HEIGHT), shape (n, h, w, 3)."""
view = view.removeprefix("--view=")
cmd = [BINARY, "--headless", f"--view={start}", f"--to-view={view}",
"--frames", str(frames), "--linear", "--width", str(width),
"--height", str(height), "--export-path", "-"]
out = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
check=True).stdout
rgba = np.frombuffer(out, np.uint8).reshape(frames, height, width, 4)
return rgba[..., :3]
def edges(frame):
"""RGB gradient magnitude: filaments and band slopes, whatever the palette phase.
The cosine palettes offset the channels' phases, so the three channel
gradients never vanish together the way one brightness gradient does.
"""
f = frame.astype(np.float32) / 255.0
gy, gx = np.gradient(f, axis=(0, 1))
return np.sqrt((gx * gx + gy * gy).sum(axis=2))
def detail(frame):
"""Edge strength after a 2x2 box average.
Thumbnails are rendered without AA, so a deep frame's sub-pixel filaments
alias into noise. The average smooths that noise away but keeps real
filaments, so a noisy frame doesn't win on detail.
"""
h, w = frame.shape[0] // 2 * 2, frame.shape[1] // 2 * 2
f = frame[:h, :w].astype(np.float32)
f = (f[0::2, 0::2] + f[1::2, 0::2] + f[0::2, 1::2] + f[1::2, 1::2]) / 4
return float(edges(f.astype(np.uint8)).mean())
def structure(e):
"""Rank-normalised edge map: which pixels are filaments, not how bright they are."""
r = np.empty(e.size, np.float32)
r[np.argsort(e, axis=None, kind="stable")] = np.linspace(0, 1, e.size)
return r.reshape(e.shape)
def _log_polar_grid(h, w, n_r=32, n_a=64):
cy, cx = h / 2, w / 2
r = np.exp(np.linspace(np.log(2), np.log(min(cy, cx) - 1), n_r))
a = np.linspace(0, np.pi, n_a, endpoint=False) # |FFT| is point-symmetric
ys = (cy + r[:, None] * np.sin(a)[None, :]).astype(int)
xs = (cx + r[:, None] * np.cos(a)[None, :]).astype(int)
return ys, xs
def descriptor(g):
"""Translation-, rotation- and scale-invariant signature of a frame."""
g = (g - g.mean()) * np.outer(np.hanning(g.shape[0]), np.hanning(g.shape[1]))
mag = np.abs(np.fft.fftshift(np.fft.fft2(g)))
ys, xs = _log_polar_grid(*g.shape)
lp = np.log1p(mag[ys, xs])
lp -= lp.mean()
# Rotation and scale are shifts along the log-polar axes: drop them.
d = np.abs(np.fft.fft2(lp))[:8, :16].ravel()
return d / (np.linalg.norm(d) + 1e-12)
@dataclass
class PathScore:
score: float
detail: float
boring: float
empty: float
per_frame: list # (detail, novelty)
def score_frames(frames):
maps = [edges(f) for f in frames]
det = np.array([detail(f) for f in frames])
desc = [descriptor(structure(e)) for e in maps]
novelty = np.array([
np.mean([np.linalg.norm(desc[i] - desc[i - lag]) for lag in LAGS])
for i in range(max(LAGS), len(frames))
])
# The last frames close in on the minibrot, which is meant to look alike.
boring = float((novelty[:-2] < BORING).mean())
empty = float((det < EMPTY).mean())
per_frame = list(zip(det.tolist(), [0.0] * max(LAGS) + novelty.tolist()))
return PathScore(float(det.mean()) * (1 - boring) * (1 - empty),
float(det.mean()), boring, empty, per_frame)
def save_sheet(frames, path, picks=(0.25, 0.5, 0.75, 1.0), columns=4):
"""A grid of the frames at the given fractions of the zoom, row by row."""
from PIL import Image # optional: only needed for sheets
idx = [min(len(frames) - 1, round(p * (len(frames) - 1))) for p in picks]
rows = [np.concatenate([frames[i] for i in idx[r:r + columns]], axis=1)
for r in range(0, len(idx), columns)]
Image.fromarray(np.ascontiguousarray(np.concatenate(rows, axis=0))).save(path)
def main(argv):
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
ap.add_argument("--view", required=True, help="RE,IM,HALF_HEIGHT of the zoom target")
ap.add_argument("--frames", type=int, default=32)
ap.add_argument("--debug", action="store_true", help="print per-frame metrics")
ap.add_argument("--sheet", help="write a contact sheet PNG (needs Pillow)")
a = ap.parse_args(argv)
frames = render_path(a.view, a.frames)
s = score_frames(frames)
if a.debug:
for i, (d, nov) in enumerate(s.per_frame):
print(f"{i:3} detail={d:.3f} novelty={nov:.3f}")
print(f"score={s.score:.4f} detail={s.detail:.3f} boring={s.boring:.2f} empty={s.empty:.2f}")
if a.sheet:
save_sheet(frames, a.sheet)
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
-92
View File
@@ -1,92 +0,0 @@
#!/usr/bin/env python3
"""Random search for deep zooms that keep changing shape all the way down.
Builds many Julia-morphing chains (morph.py) from different seeds on every
core, renders each zoom's thumbnails on the GPU (score.py), and prints the
best ones with their views and a contact sheet (8 frames) in out/.
Zooms are scored down to the last embedded Julia set, not the minibrot:
the last quarter of the way to any minibrot is rings closing in on it (as
self-similar as a spiral) and looks the same in every chain.
Usage:
search.py REGION [--depth 300] [--candidates 24] [--seed 1] [--jobs N]
Needs mpmath, numpy, Pillow and a release build (cargo build --release).
"""
import argparse
import os
import subprocess
import sys
from concurrent.futures import ProcessPoolExecutor, as_completed
from morph import build_chain, describe, julia_view, minibrot_view
from score import render_path, save_sheet, score_frames
OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "out")
def chain_job(region, stages, depth, d0, seed, max_period):
chain = build_chain(region, stages, depth, d0, seed, max_period)
if not chain:
return seed, None
last = chain[-1]
return seed, {
"stages": describe(chain),
"depth": last.depth,
"period": last.period,
"julia": julia_view(last),
"minibrot": minibrot_view(last),
}
def main(argv):
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
ap.add_argument("region", help="find_deep.py region name, or re,im,k,p")
ap.add_argument("--stages", type=int, default=14)
ap.add_argument("--depth", type=float, default=300, help="stop past size 10^-DEPTH")
ap.add_argument("--d0", type=float, default=4, help="stage 0 distance 10^-D0 from the anchor")
ap.add_argument("--candidates", type=int, default=24)
ap.add_argument("--seed", type=int, default=1, help="first seed; candidates use seed, seed+1, ...")
ap.add_argument("--max-period", type=int, default=200_000)
ap.add_argument("--jobs", type=int, default=os.cpu_count())
ap.add_argument("--top", type=int, default=5)
a = ap.parse_args(argv)
os.makedirs(OUT, exist_ok=True)
results = []
with ProcessPoolExecutor(a.jobs) as pool:
futures = [pool.submit(chain_job, a.region, a.stages, a.depth, a.d0, s, a.max_period)
for s in range(a.seed, a.seed + a.candidates)]
# Chains finish in any order; render each as it arrives (one at a time on the GPU).
for f in as_completed(futures):
seed, r = f.result()
if r is None:
print(f"seed {seed}: no chain", file=sys.stderr)
continue
try:
frames = render_path(r["julia"])
except (OSError, subprocess.CalledProcessError) as e:
print(f"seed {seed}: render failed: {e}", file=sys.stderr)
continue
s = score_frames(frames)
sheet = os.path.join(OUT, f"{a.region.split(',')[0]}-{seed}.png")
save_sheet(frames, sheet, picks=[i / 7 for i in range(8)], columns=4)
print(f"seed {seed}: score={s.score:.4f} boring={s.boring:.2f} "
f"depth=1e-{r['depth']:.0f} period={r['period']}", file=sys.stderr)
results.append((s, seed, r, sheet))
results.sort(key=lambda x: -x[0].score)
for s, seed, r, sheet in results[:a.top]:
print(f"\n## seed {seed}: score={s.score:.4f} detail={s.detail:.3f} "
f"boring={s.boring:.2f} empty={s.empty:.2f}")
print(f"# contact sheet: {sheet}")
print("\n".join(r["stages"]))
print(f"# last embedded Julia set (end here to keep changing shape all the way):\n{r['julia']}")
print(f"# minibrot (the last quarter of the zoom is rings closing in):\n{r['minibrot']}")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))
-3
View File
@@ -1,3 +0,0 @@
clips/
work/
results/
-126
View File
@@ -1,126 +0,0 @@
# Encoder tuning
The x265 and SVT-AV1 settings in the `Makefile` come from this harness. It
encodes a few lossless 4K60 test clips with a list of configs, then scores
every encode against its source with VMAF (4K model) and CAMBI (banding).
```sh
tools/encode/make_clips.sh # render clips/ once (~20 min on a GTX 1650)
tools/encode/sweep.sh --tag x265 configs/x265-axes.txt
tools/encode/sweep.sh --clips julia --keep --tag try my-configs.txt
tools/encode/ladder.py results/x265-ladder.tsv # CRF / Mb/s where each family meets the targets
```
Needs ffmpeg with libx265, libsvtav1 and libvmaf, the libvmaf models in
`/usr/share/model` (`vmaf_4k_v0.6.1.json`, `vmaf_4k_v0.6.1neg.json`), and
python3. `clips/`, `work/` and `results/` are git-ignored.
## Clips
`make_clips.sh` pipes `mandelbrot --headless --antialias` through the same
RGBA → bt709 tv-range 10-bit conversion as the `Makefile` into lossless FFV1,
so the clips are exactly what the encoders see and VMAF measures the encoder
alone. Each is 4 s of 3840×2160 at 60 fps (`--size`/`--seconds` for quick tests).
| clip | content | what it stresses |
|---|---|---|
| `filaments` | seahorse valley, 1e-8 → 3e-15 | dense detail under fast scaling motion |
| `bands` | minibrot at 3.4e-21, 1e-18 → 1.1e-20 | smooth concentric gradients: banding, blocking |
| `julia` | embedded Julia set at 2e-30, slow zoom | low-contrast fine texture on a bright background |
`julia` turned out to be the hardest by far. At a CRF where the other two
already score VMAF 99, both encoders smear its faint speckles, so it decides
every tier's CRF.
## Configs and results
A config line is `name | ffmpeg output args`. `sweep.sh` encodes each clip,
times it, and appends one row per encode to `results/<tag>.tsv`:
| column | meaning |
|---|---|
| `fps` | encode speed, wall clock, all cores |
| `mbps` | bitrate |
| `vmaf`, `vmaf_p1`, `vmaf_min` | VMAF 4K mean, 1st percentile, min |
| `vmaf_neg` | VMAF NEG: like VMAF, but doesn't reward sharpening |
| `cambi`, `cambi_max` | banding, mean and worst frame (0 = none, above ~5 is visible) |
| `psnr_y` | luma PSNR |
VMAF uses every other frame (`n_subsample=2`). With 4 s clips that's 120
frames, so `vmaf_p1` is the worst sampled frame. Both inputs are retimed by
frame index before scoring. The MKV clips store 60 fps timestamps in whole
milliseconds, and pairing by timestamp compared every third frame with its
neighbour.
`ladder.py` groups configs into families by stripping a trailing `-CRF`
(`x265-rect-16` → `x265-rect`). It interpolates, per clip, the CRF and bitrate
where each target is met. A tier has one CRF for all content, so the lowest of
those CRFs binds it.
The configs files are in the order they were run:
- `speed.txt`: preset speed pass (which presets fit the time budget).
- `crf-probe.txt`: coarse CRF ranges, to see where VMAF 95–97 land.
- `x265-axes.txt`, `av1-axes.txt`: one option at a time from a baseline.
- `*-ladder.txt`, `*-ladder2.txt`: the promising combinations at several CRFs,
to compare them at matched bitrate rather than at a fixed CRF.
## Results (Ryzen 7 3700X, 8C/16T; ffmpeg 9.0, x265 4.3, SVT-AV1 4.2.0)
Tier targets: **delivery** = VMAF mean ≈ 95 and worst frame ≥ 90 on every
clip, smallest file. **Master** = worst frame ≥ 97 on every clip. `julia` binds
every tier. "Interp" rows are interpolated between the two ladder rungs around
that CRF (log bitrate, linear VMAF). Everything else was measured.
| target | CRF | clip | Mb/s | fps | VMAF mean | p1 = min | CAMBI mean / max | |
|---|---|---|---|---|---|---|---|---|
| `x265` | 17 | bands | 279 | 2.4 | 99.93 | 98.81 | 1.53 / 6.00 | interp 16–20 |
| | | filaments | 241 | 3.2 | 99.95 | 98.63 | 2.54 / 8.92 | interp 16–20 |
| | | julia | 68 | 6.1 | 94.81 | 92.75 | 0 / 0 | interp 16–20 |
| `x265-master` | 12 | bands | 466 | 1.8 | 100.00 | 100.00 | 1.58 / 6.19 | |
| | | filaments | 342 | 2.8 | 100.00 | 99.99 | 2.65 / 9.49 | |
| | | julia | 171 | 3.6 | 98.36 | 97.58 | 0 / 0 | |
| `av1` | 32 | bands | 180 | 6.0 | 99.95 | 97.07 | 1.47 / 4.70 | |
| | | filaments | 192 | 7.7 | 99.90 | 97.04 | 2.28 / 7.14 | |
| | | julia | 50 | 7.4 | 95.03 | 93.39 | 0 / 0 | |
| `av1-master` | 17 | bands | 451 | 6.9 | 100.00 | 99.49 | 1.23 / 4.87 | interp 14–20 |
| | | filaments | 380 | 8.6 | 100.00 | 99.50 | 2.40 / 7.67 | interp 14–20 |
| | | julia | 152 | 9.0 | 98.09 | 97.12 | 0 / 0 | interp 14–20 |
SVT-AV1 wins both tiers: the delivery files are 20–35% smaller than
x265's, and it encodes 1.2–2.5× faster. CAMBI max is the same at every CRF on
`filaments` (6–9), so it comes from the content, not the encoder.
What the sweeps showed (details as comments in the `Makefile`):
- **SVT-AV1:** `tune=0` + `enable-variance-boost=1` + `enable-qm=1` is the
combination that fixes faint texture. With the defaults, `julia` scores a
worst frame of 85 at CRF 26. The temporal filter (`enable-tf`) was the
suspect for smeared filaments, but turning it off or weakening it cost
35–50% more bits for lower VMAF and more banding. `qm-min=0` caps quality.
`sharpness`, `ac-bias` and `enable-overlays` did nothing measurable.
- **x265:** `rect`, `merange=92` and `rdoq-level=2:psy-rdoq=1` help. SAO hurts.
`aq-mode=4`, `deblock=-1`, `psy-rd=1`, `me=star`, `rc-lookahead=60` and
`bframes=8` didn't help at matched bitrate or cost too much speed.
- The worst SVT frames without variance boost sit in the clip's last
mini-GOP, so part of that p1 is an artefact of a 4 s clip.
**Speed budget.** It was 3–5 fps on an i7-1165G7 (4C/8T). Pinning this machine
to 4C/8T (`taskset -c 0-3,8-11`) as a proxy gives 1.5× (SVT) to 1.8× (x265)
for the full 16 threads, so here the budget is about 5–9 fps. SVT preset 6
fits at both tiers. x265 `medium` with these options doesn't: at the low CRFs
`julia` forces, it runs at 2–6 fps. This SVT-AV1 package also reports
`(debug)`: it's built without `NDEBUG`, but it's optimised and it's what
ffmpeg links.
**Not yet measured:** x265 `-preset fast` with these options (the speed fix
for x265) and `aq-strength=1.2` (`configs/x265-ladder2.txt`). Also a
confirming encode at `av1-master`'s interpolated CRF 17.
## Tips
- Keep the machine idle while sweeping: `fps` is wall clock time.
- A config that changes bitrate at a fixed CRF can't be judged from one row.
Put it on a ladder and compare with `ladder.py`.
- `--keep` keeps the encodes in `work/`, e.g. to extract frames to compare by eye:
`ffmpeg -i work/julia--x.mp4 -vf "select=eq(n\,120),crop=480:270:1680:945" -frames:v 1 x.png`.
-16
View File
@@ -1,16 +0,0 @@
# SVT-AV1 4.2 per-axis sweep: each line changes one thing from av1-base.
# Base = pass-1 settings (preset 6, no film grain) plus a 10 s GOP and scene-cut detection.
av1-base | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 30 -svtav1-params film-grain=0:keyint=600:scd=1
# ffmpeg's libsvtav1 defaults to tune=1 (PSNR); 0 is the visual-quality tune
av1-tune0 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 30 -svtav1-params film-grain=0:keyint=600:scd=1:tune=0
# Alt-ref temporal filter: prime suspect for smeared filaments during zooms
av1-tf0 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 30 -svtav1-params film-grain=0:keyint=600:scd=1:enable-tf=0
av1-tfs1 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 30 -svtav1-params film-grain=0:keyint=600:scd=1:tf-strength=1
# Variance boost: more bits to flat, low-variance blocks (gradient banding)
av1-vb | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 30 -svtav1-params film-grain=0:keyint=600:scd=1:enable-variance-boost=1
av1-vb3 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 30 -svtav1-params film-grain=0:keyint=600:scd=1:enable-variance-boost=1:variance-boost-strength=3
# Quantisation matrices, deblocking sharpness, AC bias (texture), overlays
av1-qm | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 30 -svtav1-params film-grain=0:keyint=600:scd=1:enable-qm=1:qm-min=0
av1-sharp1 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 30 -svtav1-params film-grain=0:keyint=600:scd=1:sharpness=1
av1-acb1 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 30 -svtav1-params film-grain=0:keyint=600:scd=1:ac-bias=1.0
av1-ov1 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 30 -svtav1-params film-grain=0:keyint=600:scd=1:enable-overlays=1
-19
View File
@@ -1,19 +0,0 @@
# SVT-AV1 candidate ladders: compare combinations at matched bitrate (results/av1-ladder.tsv)
av1-c0-14 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 14 -svtav1-params film-grain=0:keyint=600:scd=1
av1-c0-20 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 20 -svtav1-params film-grain=0:keyint=600:scd=1
av1-c0-26 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 26 -svtav1-params film-grain=0:keyint=600:scd=1
av1-qm-14 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 14 -svtav1-params film-grain=0:keyint=600:scd=1:enable-qm=1:qm-min=0
av1-qm-20 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 20 -svtav1-params film-grain=0:keyint=600:scd=1:enable-qm=1:qm-min=0
av1-qm-26 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 26 -svtav1-params film-grain=0:keyint=600:scd=1:enable-qm=1:qm-min=0
av1-tune0-14 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 14 -svtav1-params film-grain=0:keyint=600:scd=1:tune=0
av1-tune0-20 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 20 -svtav1-params film-grain=0:keyint=600:scd=1:tune=0
av1-tune0-26 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 26 -svtav1-params film-grain=0:keyint=600:scd=1:tune=0
av1-vb-14 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 14 -svtav1-params film-grain=0:keyint=600:scd=1:enable-variance-boost=1
av1-vb-20 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 20 -svtav1-params film-grain=0:keyint=600:scd=1:enable-variance-boost=1
av1-vb-26 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 26 -svtav1-params film-grain=0:keyint=600:scd=1:enable-variance-boost=1
av1-qm-vb-14 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 14 -svtav1-params film-grain=0:keyint=600:scd=1:enable-qm=1:qm-min=0:enable-variance-boost=1
av1-qm-vb-20 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 20 -svtav1-params film-grain=0:keyint=600:scd=1:enable-qm=1:qm-min=0:enable-variance-boost=1
av1-qm-vb-26 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 26 -svtav1-params film-grain=0:keyint=600:scd=1:enable-qm=1:qm-min=0:enable-variance-boost=1
av1-qm-vb-tune0-14 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 14 -svtav1-params film-grain=0:keyint=600:scd=1:enable-qm=1:qm-min=0:enable-variance-boost=1:tune=0
av1-qm-vb-tune0-20 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 20 -svtav1-params film-grain=0:keyint=600:scd=1:enable-qm=1:qm-min=0:enable-variance-boost=1:tune=0
av1-qm-vb-tune0-26 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 26 -svtav1-params film-grain=0:keyint=600:scd=1:enable-qm=1:qm-min=0:enable-variance-boost=1:tune=0
-12
View File
@@ -1,12 +0,0 @@
# SVT-AV1 round 2: tune0+VB without QM, default qm-min, delivery-range CRFs (results/av1-ladder2.tsv)
av1-vb-tune0-14 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 14 -svtav1-params film-grain=0:keyint=600:scd=1:tune=0:enable-variance-boost=1
av1-vb-tune0-20 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 20 -svtav1-params film-grain=0:keyint=600:scd=1:tune=0:enable-variance-boost=1
av1-vb-tune0-26 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 26 -svtav1-params film-grain=0:keyint=600:scd=1:tune=0:enable-variance-boost=1
av1-vb-tune0-32 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 32 -svtav1-params film-grain=0:keyint=600:scd=1:tune=0:enable-variance-boost=1
av1-qm8-vb-tune0-14 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 14 -svtav1-params film-grain=0:keyint=600:scd=1:tune=0:enable-qm=1:enable-variance-boost=1
av1-qm8-vb-tune0-20 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 20 -svtav1-params film-grain=0:keyint=600:scd=1:tune=0:enable-qm=1:enable-variance-boost=1
av1-qm8-vb-tune0-26 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 26 -svtav1-params film-grain=0:keyint=600:scd=1:tune=0:enable-qm=1:enable-variance-boost=1
av1-qm8-vb-tune0-32 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 32 -svtav1-params film-grain=0:keyint=600:scd=1:tune=0:enable-qm=1:enable-variance-boost=1
av1-qm-vb-tune0-32 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 32 -svtav1-params film-grain=0:keyint=600:scd=1:tune=0:enable-qm=1:qm-min=0:enable-variance-boost=1
av1-qm-vb-tune0-38 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 38 -svtav1-params film-grain=0:keyint=600:scd=1:tune=0:enable-qm=1:qm-min=0:enable-variance-boost=1
av1-tune0-10 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 10 -svtav1-params film-grain=0:keyint=600:scd=1:tune=0
-9
View File
@@ -1,9 +0,0 @@
# Coarse CRF probe: where do VMAF 95-97 land on each clip? (pass-1 baselines)
x265-crf22 | -pix_fmt yuv420p10le -c:v libx265 -profile:v main10 -preset medium -crf 22 -x265-params log-level=error:aq-mode=3:no-sao=1
x265-crf26 | -pix_fmt yuv420p10le -c:v libx265 -profile:v main10 -preset medium -crf 26 -x265-params log-level=error:aq-mode=3:no-sao=1
x265-crf30 | -pix_fmt yuv420p10le -c:v libx265 -profile:v main10 -preset medium -crf 30 -x265-params log-level=error:aq-mode=3:no-sao=1
x265-crf34 | -pix_fmt yuv420p10le -c:v libx265 -profile:v main10 -preset medium -crf 34 -x265-params log-level=error:aq-mode=3:no-sao=1
av1-crf32 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 32 -svtav1-params film-grain=0
av1-crf38 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 38 -svtav1-params film-grain=0
av1-crf44 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 44 -svtav1-params film-grain=0
av1-crf50 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 50 -svtav1-params film-grain=0
-8
View File
@@ -1,8 +0,0 @@
# Pass 1: which presets fit the 3-5 fps budget at 4K on this machine.
x265-fast | -pix_fmt yuv420p10le -c:v libx265 -profile:v main10 -preset fast -crf 18 -x265-params log-level=error:aq-mode=3:no-sao=1
x265-medium | -pix_fmt yuv420p10le -c:v libx265 -profile:v main10 -preset medium -crf 18 -x265-params log-level=error:aq-mode=3:no-sao=1
x265-slow | -pix_fmt yuv420p10le -c:v libx265 -profile:v main10 -preset slow -crf 18 -x265-params log-level=error:aq-mode=3:no-sao=1
av1-p5 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 5 -crf 26 -svtav1-params film-grain=0
av1-p6 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 6 -crf 26 -svtav1-params film-grain=0
av1-p7 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 7 -crf 26 -svtav1-params film-grain=0
av1-p8 | -pix_fmt yuv420p10le -c:v libsvtav1 -preset 8 -crf 26 -svtav1-params film-grain=0
-20
View File
@@ -1,20 +0,0 @@
# x265 per-axis sweep: each line changes one thing from x265-base.
# Base = pass-1 settings (preset medium, aq-mode 3, no SAO) plus a 10 s GOP.
x265-base | -pix_fmt yuv420p10le -c:v libx265 -profile:v main10 -preset medium -crf 20 -x265-params log-level=error:keyint=600:min-keyint=60:aq-mode=3:no-sao=1
# Adaptive quantisation
x265-aq4 | -pix_fmt yuv420p10le -c:v libx265 -profile:v main10 -preset medium -crf 20 -x265-params log-level=error:keyint=600:min-keyint=60:aq-mode=4:no-sao=1
x265-aqs08 | -pix_fmt yuv420p10le -c:v libx265 -profile:v main10 -preset medium -crf 20 -x265-params log-level=error:keyint=600:min-keyint=60:aq-mode=3:aq-strength=0.8:no-sao=1
x265-aqs12 | -pix_fmt yuv420p10le -c:v libx265 -profile:v main10 -preset medium -crf 20 -x265-params log-level=error:keyint=600:min-keyint=60:aq-mode=3:aq-strength=1.2:no-sao=1
# In-loop filters
x265-sao | -pix_fmt yuv420p10le -c:v libx265 -profile:v main10 -preset medium -crf 20 -x265-params log-level=error:keyint=600:min-keyint=60:aq-mode=3
x265-selsao2 | -pix_fmt yuv420p10le -c:v libx265 -profile:v main10 -preset medium -crf 20 -x265-params log-level=error:keyint=600:min-keyint=60:aq-mode=3:selective-sao=2
x265-deblk-1 | -pix_fmt yuv420p10le -c:v libx265 -profile:v main10 -preset medium -crf 20 -x265-params log-level=error:keyint=600:min-keyint=60:aq-mode=3:no-sao=1:deblock=-1,-1
# Psychovisual: medium has rdoq-level 0, so psy-rdoq needs rdoq-level 2 to do anything
x265-psyrdoq | -pix_fmt yuv420p10le -c:v libx265 -profile:v main10 -preset medium -crf 20 -x265-params log-level=error:keyint=600:min-keyint=60:aq-mode=3:no-sao=1:rdoq-level=2:psy-rdoq=1.0
x265-psyrd1 | -pix_fmt yuv420p10le -c:v libx265 -profile:v main10 -preset medium -crf 20 -x265-params log-level=error:keyint=600:min-keyint=60:aq-mode=3:no-sao=1:psy-rd=1.0
# Motion: zooms are scaling, not translation
x265-star | -pix_fmt yuv420p10le -c:v libx265 -profile:v main10 -preset medium -crf 20 -x265-params log-level=error:keyint=600:min-keyint=60:aq-mode=3:no-sao=1:me=star
x265-mer92 | -pix_fmt yuv420p10le -c:v libx265 -profile:v main10 -preset medium -crf 20 -x265-params log-level=error:keyint=600:min-keyint=60:aq-mode=3:no-sao=1:merange=92
x265-bf8 | -pix_fmt yuv420p10le -c:v libx265 -profile:v main10 -preset medium -crf 20 -x265-params log-level=error:keyint=600:min-keyint=60:aq-mode=3:no-sao=1:bframes=8
x265-la60 | -pix_fmt yuv420p10le -c:v libx265 -profile:v main10 -preset medium -crf 20 -x265-params log-level=error:keyint=600:min-keyint=60:aq-mode=3:no-sao=1:rc-lookahead=60
x265-rect | -pix_fmt yuv420p10le -c:v libx265 -profile:v main10 -preset medium -crf 20 -x265-params log-level=error:keyint=600:min-keyint=60:aq-mode=3:no-sao=1:rect=1
-13
View File
@@ -1,13 +0,0 @@
# x265 candidate ladders: compare combinations at matched bitrate (results/x265-ladder.tsv)
x265-c0-12 | -pix_fmt yuv420p10le -c:v libx265 -profile:v main10 -preset medium -crf 12 -x265-params log-level=error:keyint=600:min-keyint=60:aq-mode=3:no-sao=1:merange=92
x265-c0-16 | -pix_fmt yuv420p10le -c:v libx265 -profile:v main10 -preset medium -crf 16 -x265-params log-level=error:keyint=600:min-keyint=60:aq-mode=3:no-sao=1:merange=92
x265-c0-20 | -pix_fmt yuv420p10le -c:v libx265 -profile:v main10 -preset medium -crf 20 -x265-params log-level=error:keyint=600:min-keyint=60:aq-mode=3:no-sao=1:merange=92
x265-rect-12 | -pix_fmt yuv420p10le -c:v libx265 -profile:v main10 -preset medium -crf 12 -x265-params log-level=error:keyint=600:min-keyint=60:aq-mode=3:no-sao=1:merange=92:rect=1
x265-rect-16 | -pix_fmt yuv420p10le -c:v libx265 -profile:v main10 -preset medium -crf 16 -x265-params log-level=error:keyint=600:min-keyint=60:aq-mode=3:no-sao=1:merange=92:rect=1
x265-rect-20 | -pix_fmt yuv420p10le -c:v libx265 -profile:v main10 -preset medium -crf 20 -x265-params log-level=error:keyint=600:min-keyint=60:aq-mode=3:no-sao=1:merange=92:rect=1
x265-rect-psyrdoq-12 | -pix_fmt yuv420p10le -c:v libx265 -profile:v main10 -preset medium -crf 12 -x265-params log-level=error:keyint=600:min-keyint=60:aq-mode=3:no-sao=1:merange=92:rect=1:rdoq-level=2:psy-rdoq=1.0
x265-rect-psyrdoq-16 | -pix_fmt yuv420p10le -c:v libx265 -profile:v main10 -preset medium -crf 16 -x265-params log-level=error:keyint=600:min-keyint=60:aq-mode=3:no-sao=1:merange=92:rect=1:rdoq-level=2:psy-rdoq=1.0
x265-rect-psyrdoq-20 | -pix_fmt yuv420p10le -c:v libx265 -profile:v main10 -preset medium -crf 20 -x265-params log-level=error:keyint=600:min-keyint=60:aq-mode=3:no-sao=1:merange=92:rect=1:rdoq-level=2:psy-rdoq=1.0
x265-rect-aq4-12 | -pix_fmt yuv420p10le -c:v libx265 -profile:v main10 -preset medium -crf 12 -x265-params log-level=error:keyint=600:min-keyint=60:aq-mode=4:no-sao=1:merange=92:rect=1
x265-rect-aq4-16 | -pix_fmt yuv420p10le -c:v libx265 -profile:v main10 -preset medium -crf 16 -x265-params log-level=error:keyint=600:min-keyint=60:aq-mode=4:no-sao=1:merange=92:rect=1
x265-rect-aq4-20 | -pix_fmt yuv420p10le -c:v libx265 -profile:v main10 -preset medium -crf 20 -x265-params log-level=error:keyint=600:min-keyint=60:aq-mode=4:no-sao=1:merange=92:rect=1
-7
View File
@@ -1,7 +0,0 @@
# x265 round 2: preset fast for speed, aq-strength 1.2 for julia (results/x265-ladder2.tsv)
x265-fast-rp-12 | -pix_fmt yuv420p10le -c:v libx265 -profile:v main10 -preset fast -crf 12 -x265-params log-level=error:keyint=600:min-keyint=60:aq-mode=3:no-sao=1:merange=92:rect=1:rdoq-level=2:psy-rdoq=1.0
x265-fast-rp-16 | -pix_fmt yuv420p10le -c:v libx265 -profile:v main10 -preset fast -crf 16 -x265-params log-level=error:keyint=600:min-keyint=60:aq-mode=3:no-sao=1:merange=92:rect=1:rdoq-level=2:psy-rdoq=1.0
x265-fast-rp-20 | -pix_fmt yuv420p10le -c:v libx265 -profile:v main10 -preset fast -crf 20 -x265-params log-level=error:keyint=600:min-keyint=60:aq-mode=3:no-sao=1:merange=92:rect=1:rdoq-level=2:psy-rdoq=1.0
x265-rp-aqs12-12 | -pix_fmt yuv420p10le -c:v libx265 -profile:v main10 -preset medium -crf 12 -x265-params log-level=error:keyint=600:min-keyint=60:aq-mode=3:no-sao=1:merange=92:rect=1:rdoq-level=2:psy-rdoq=1.0:aq-strength=1.2
x265-rp-aqs12-16 | -pix_fmt yuv420p10le -c:v libx265 -profile:v main10 -preset medium -crf 16 -x265-params log-level=error:keyint=600:min-keyint=60:aq-mode=3:no-sao=1:merange=92:rect=1:rdoq-level=2:psy-rdoq=1.0:aq-strength=1.2
x265-rp-aqs12-20 | -pix_fmt yuv420p10le -c:v libx265 -profile:v main10 -preset medium -crf 20 -x265-params log-level=error:keyint=600:min-keyint=60:aq-mode=3:no-sao=1:merange=92:rect=1:rdoq-level=2:psy-rdoq=1.0:aq-strength=1.2
-62
View File
@@ -1,62 +0,0 @@
#!/usr/bin/env python3
"""Where does each config family meet a VMAF target? Reads sweep.sh TSVs.
tools/encode/ladder.py results/x265-ladder.tsv [--target vmaf:95 --target p1:90 ...]
A family is a config name minus its trailing -CRF (x265-rect-16 -> x265-rect;
x265-crf16 -> x265).
For each family and clip, log(Mb/s) and CRF are interpolated linearly in the
chosen metric between the two ladder rungs that bracket the target. A tier
uses one CRF for everything, so the clip needing the lowest CRF binds it; that
CRF is printed last as "all". A dash means the ladder doesn't reach the target.
"""
import argparse
import csv
import math
import re
from collections import defaultdict
ap = argparse.ArgumentParser()
ap.add_argument("tsv", nargs="+")
ap.add_argument("--target", action="append",
help="metric:value, metric one of vmaf, p1, min, neg (default vmaf:95, p1:90, p1:97)")
args = ap.parse_args()
targets = [(m, float(v)) for m, v in (t.split(":") for t in (args.target or ["vmaf:95", "p1:90", "p1:97"]))]
col = {"vmaf": "vmaf", "p1": "vmaf_p1", "min": "vmaf_min", "neg": "vmaf_neg"}
fam = defaultdict(lambda: defaultdict(list)) # family -> clip -> [(crf, row)]
for path in args.tsv:
for r in csv.DictReader(open(path), delimiter="\t"):
m = re.fullmatch(r"(.*)-(?:crf)?(\d+)", r["config"])
if m:
fam[m[1]][r["clip"]].append((int(m[2]), r))
def solve(pts, key, target):
"""(crf, mbps, fps) where metric `key` crosses `target`, or None."""
pts = sorted(pts, key=lambda p: p[0]) # quality falls as CRF rises
for (c0, a), (c1, b) in zip(pts, pts[1:]):
q0, q1 = float(a[key]), float(b[key])
if q0 >= target >= q1 and q0 != q1:
t = (q0 - target) / (q0 - q1)
lr = math.log(float(a["mbps"])) * (1 - t) + math.log(float(b["mbps"])) * t
fps = float(a["fps"]) * (1 - t) + float(b["fps"]) * t
return c0 + t * (c1 - c0), math.exp(lr), fps
return None
for metric, target in targets:
print(f"\n## {metric} >= {target:g} (CRF @ Mb/s, fps)")
clips = sorted({c for f in fam.values() for c in f})
print(f"{'family':24}" + "".join(f"{c:>22}" for c in clips) + f"{'all (binding clip)':>24}")
for f, per in fam.items():
cells, worst = [], None
for c in clips:
s = solve(per.get(c, []), col[metric], target)
cells.append(f"{s[0]:5.1f} @ {s[1]:6.1f}, {s[2]:4.1f}" if s else "-")
if s is None:
worst = "missing"
elif worst != "missing" and (worst is None or s[0] < worst[0]):
worst = (s[0], c)
w = "-" if worst in (None, "missing") else f"CRF {worst[0]:4.1f} ({worst[1]})"
print(f"{f:24}" + "".join(f"{x:>22}" for x in cells) + f"{w:>24}")
-70
View File
@@ -1,70 +0,0 @@
#!/usr/bin/env bash
# Render the lossless 4K60 test clips that sweep.sh encodes.
#
# Each clip goes through the same RGBA -> bt709 tv-range 10-bit conversion as
# the Makefile, then into lossless FFV1. The clips are therefore exactly what the
# encoders see, so VMAF against them measures the encoder alone.
#
# tools/encode/make_clips.sh [--size WxH] [--seconds S] [--force] [clip...]
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
root=$(cd "$here/../.." && pwd)
out="$here/clips"
size=3840x2160
seconds=4
fps=60
force=0
only=()
while [[ $# -gt 0 ]]; do
case $1 in
--size) size=$2; shift 2 ;;
--seconds) seconds=$2; shift 2 ;;
--force) force=1; shift ;;
-h|--help) sed -n '2,9p' "$0"; exit 0 ;;
*) only+=("$1"); shift ;;
esac
done
# Seahorse valley, minibrot at 3.7e-41 (tools/deep-zoom/LOCATIONS.md).
SH_RE=-0.77568376800905379745347652613832924487504096622022
SH_IM=0.13646736829469012473375311880735014411233827361594
# Seahorse valley, minibrot at 3.4e-21 (period 429, `find_deep.py seahorse 10`).
# Same look as the 1e-40 one for this purpose, but ~10x faster to render.
MB_RE=-0.775683767855941232535147681616
MB_IM=0.136467368300490586441979944945
# name | mandelbrot flags. Zoom speeds bracket a typical 60 s dive (~0.7 decade/s).
clips=(
# Worst case: dense filaments, 1.5 decades/s of scaling motion.
"filaments|--view=$SH_RE,$SH_IM,1e-8 --to-view=$SH_RE,$SH_IM,3e-15 --linear"
# Smooth concentric bands closing in on the minibrot: banding/blocking risk.
"bands|--view=$MB_RE,$MB_IM,1e-18 --to-view=$MB_RE,$MB_IM,1.1e-20 --linear"
# Embedded Julia set, slow drift: fine static texture, psy/detail retention.
"julia|--view=$SH_RE,$SH_IM,2e-30 --to-view=$SH_RE,$SH_IM,1e-30 --linear"
)
[[ -x $root/target/release/mandelbrot ]] || cargo build --release --manifest-path "$root/Cargo.toml"
mkdir -p "$out"
w=${size%x*}
h=${size#*x}
for entry in "${clips[@]}"; do
name=${entry%%|*}
flags=${entry#*|}
if [[ ${#only[@]} -gt 0 && ! " ${only[*]} " =~ " $name " ]]; then continue; fi
dst="$out/$name.mkv"
if [[ -f $dst && $force = 0 ]]; then echo "skip $name (exists, --force to redo)"; continue; fi
echo "render $name ($size, ${seconds}s @ ${fps}fps)"
# shellcheck disable=SC2086
"$root/target/release/mandelbrot" --headless --antialias $flags \
--width "$w" --height "$h" --fps "$fps" --duration "$seconds" --export-path - |
ffmpeg -hide_banner -loglevel error -y \
-f rawvideo -pix_fmt rgba -s "$size" -framerate "$fps" -i - \
-vf "scale=out_color_matrix=bt709:out_range=tv:flags=accurate_rnd+full_chroma_int+bitexact,format=yuv420p10le" \
-c:v ffv1 -level 3 -slices 16 -g 1 \
-colorspace bt709 -color_primaries bt709 -color_trc bt709 -color_range tv \
"$dst.tmp.mkv"
mv "$dst.tmp.mkv" "$dst"
done
-89
View File
@@ -1,89 +0,0 @@
#!/usr/bin/env bash
# Encode every test clip with every config, then score each encode.
#
# tools/encode/sweep.sh [--clips a,b] [--keep] [--tag NAME] CONFIG_FILE...
#
# A config line is `name | ffmpeg output args` (blank lines and # comments are
# skipped). The args go between `-i clip.mkv` and the output file, e.g.
# x265-crf18 | -c:v libx265 -preset medium -crf 18 -x265-params aq-mode=3
# Each row of results/<tag>.tsv has encode fps, bitrate, VMAF 4K (mean, 1st
# percentile, min), VMAF-NEG mean, CAMBI banding (mean, max) and PSNR-Y.
set -euo pipefail
here=$(cd "$(dirname "$0")" && pwd)
clipdir="$here/clips"
model=/usr/share/model
export SVT_LOG=1 # errors only
clips=""
keep=0
tag=$(date +%Y%m%d-%H%M%S)
configs=()
while [[ $# -gt 0 ]]; do
case $1 in
--clips) clips=$2; shift 2 ;;
--keep) keep=1; shift ;;
--tag) tag=$2; shift 2 ;;
-h|--help) sed -n '2,11p' "$0"; exit 0 ;;
*) configs+=("$1"); shift ;;
esac
done
[[ ${#configs[@]} -gt 0 ]] || { echo "usage: $0 [--clips a,b] [--keep] [--tag NAME] CONFIG_FILE..." >&2; exit 1; }
if [[ -z $clips ]]; then
clips=$(cd "$clipdir" && ls ./*.mkv | sed 's|^\./||; s|\.mkv$||' | paste -sd,)
fi
[[ -n $clips ]] || { echo "no clips in $clipdir: run make_clips.sh first" >&2; exit 1; }
mkdir -p "$here/results" "$here/work"
tsv="$here/results/$tag.tsv"
[[ -f $tsv ]] || printf 'clip\tconfig\tfps\tmbps\tvmaf\tvmaf_p1\tvmaf_min\tvmaf_neg\tcambi\tcambi_max\tpsnr_y\n' > "$tsv"
IFS=, read -ra clip_list <<< "$clips"
for cfg in "${configs[@]}"; do
while IFS= read -r line || [[ -n $line ]]; do
[[ $line =~ ^[[:space:]]*(#|$) ]] && continue
name=$(sed 's/[[:space:]]*|.*//' <<< "$line")
args=$(sed 's/^[^|]*|[[:space:]]*//' <<< "$line")
for clip in "${clip_list[@]}"; do
ref="$clipdir/$clip.mkv"
enc="$here/work/$clip--$name.mp4"
log="$here/work/$clip--$name.json"
frames=$(ffprobe -v error -count_packets -select_streams v:0 \
-show_entries stream=nb_read_packets -of csv=p=0 "$ref")
printf '%-10s %-40s ' "$clip" "$name"
t0=$(date +%s.%N)
# shellcheck disable=SC2086
ffmpeg -hide_banner -loglevel error -y -i "$ref" $args -an "$enc" < /dev/null
t1=$(date +%s.%N)
# 4K model for both VMAF variants; CAMBI flags banding, which VMAF
# barely sees and which is the main risk on smooth fractal gradients.
# Both streams are retimed by frame index: MKV stores 60 fps in whole
# ms, and pairing by PTS matched every third frame with its neighbour.
ffmpeg -hide_banner -loglevel error -i "$enc" -i "$ref" -lavfi \
"[0:v]settb=1/60,setpts=N[d];[1:v]settb=1/60,setpts=N[r];[d][r]libvmaf=log_fmt=json:log_path=$log:n_threads=$(nproc):n_subsample=2:model='path=$model/vmaf_4k_v0.6.1.json\\:name=vmaf|path=$model/vmaf_4k_v0.6.1neg.json\\:name=neg':feature='name=cambi|name=psnr'" \
-f null - < /dev/null
row=$(python3 - "$log" "$enc" "$frames" "$t0" "$t1" <<'PY'
import json, os, sys
log, enc, frames, t0, t1 = sys.argv[1], sys.argv[2], int(sys.argv[3]), float(sys.argv[4]), float(sys.argv[5])
fr = json.load(open(log))["frames"]
col = lambda k: sorted(f["metrics"][k] for f in fr)
v = col("vmaf")
p1 = v[max(0, int(0.01 * len(v)) - 1)] if len(v) >= 100 else v[0]
mean = lambda xs: sum(xs) / len(xs)
cambi = col("cambi")
fps = frames / (t1 - t0)
mbps = os.path.getsize(enc) * 8 / (frames / 60) / 1e6
print(f"{fps:.2f}\t{mbps:.1f}\t{mean(v):.2f}\t{p1:.2f}\t{v[0]:.2f}\t{mean(col('neg')):.2f}\t{mean(cambi):.2f}\t{cambi[-1]:.2f}\t{mean(col('psnr_y')):.2f}")
PY
)
printf '%s\t%s\t%s\n' "$clip" "$name" "$row" >> "$tsv"
awk -F'\t' '{printf "%6s fps %7s Mb/s vmaf %s p1 %s min %s neg %s cambi %s/%s psnr %s\n",$1,$2,$3,$4,$5,$6,$7,$8,$9}' <<< "$row"
[[ $keep = 1 ]] || rm -f "$enc"
done
done < "$cfg"
done
echo "results: $tsv"