feat: use webgl backend when webgpu is not available
This commit is contained in:
@@ -15,14 +15,14 @@ once a pixel is ~2^-124 wide (~10³⁴× at 1080p), so from 2^-122 per pixel
|
|||||||
rescaled deltas (f32 mantissa × 2^i32). There's no practical depth limit:
|
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
|
`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
|
`Scale::MIN` = 2^-(2^20) to keep shader exponent sums in i32. Runs
|
||||||
natively (Vulkan/Metal/DX12) and in the browser (WebGPU only — WebGL2 can't do
|
natively (Vulkan/Metal/DX12) and in the browser: WebGPU, plus a WebGL2
|
||||||
storage buffers, which the fragment shader needs for the reference orbit).
|
fallback with the `webgl` feature (see "WebGL2 fallback" below).
|
||||||
|
|
||||||
## Commands
|
## Commands
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
cargo run --release # native, run (release matters: fractal math is hot)
|
cargo run --release # native, run (release matters: fractal math is hot)
|
||||||
cargo test # reference-orbit math, share-link round-trip, WGSL validation
|
cargo test # reference-orbit math, share-link round-trip, WGSL validation (+ GLSL ES 3.00 via glslangValidator if installed)
|
||||||
cargo test --features wasm # same, on the web build's malachite big-float backend
|
cargo test --features wasm # same, on the web build's malachite big-float backend
|
||||||
cargo test --test shader_valid # just the WGSL parse/validate tests (naga, no GPU needed)
|
cargo test --test shader_valid # just the WGSL parse/validate tests (naga, no GPU needed)
|
||||||
cargo clippy
|
cargo clippy
|
||||||
@@ -31,12 +31,12 @@ cargo build --release --no-default-features # headless-only binary: no eframe/
|
|||||||
tools/bench/bench.sh --rev HEAD # perf of uncommitted edits vs HEAD (hyperfine; see tools/bench/README.md)
|
tools/bench/bench.sh --rev HEAD # perf of uncommitted edits vs HEAD (hyperfine; see tools/bench/README.md)
|
||||||
```
|
```
|
||||||
|
|
||||||
Web build (WebGPU):
|
Web build (WebGPU, with WebGL2 fallback):
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
rustup target add wasm32-unknown-unknown
|
rustup target add wasm32-unknown-unknown
|
||||||
cargo install wasm-bindgen-cli --version 0.2.128 # must match the wasm-bindgen crate version
|
cargo install wasm-bindgen-cli --version 0.2.128 # must match the wasm-bindgen crate version
|
||||||
./build-web.sh # -> ./dist (builds with --features wasm)
|
./build-web.sh # -> ./dist (builds with --features wasm,webgl)
|
||||||
python3 -m http.server -d dist 8080
|
python3 -m http.server -d dist 8080
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -192,6 +192,8 @@ 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
|
constants) is prepended to every shader. `iterate_uniforms.wgsl` (the
|
||||||
perturbation-pipeline `Uniforms` struct + `palette()`) is additionally
|
perturbation-pipeline `Uniforms` struct + `palette()`) is additionally
|
||||||
prepended to `mandelbrot.wgsl` and `colorize.wgsl`, which share that layout.
|
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
|
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
|
among those concatenated together for a given shader — don't redefine a
|
||||||
`common.wgsl`/`iterate_uniforms.wgsl` symbol locally.
|
`common.wgsl`/`iterate_uniforms.wgsl` symbol locally.
|
||||||
@@ -377,6 +379,40 @@ histogram buffer, tone-mapped by a fragment pass every frame. Its own
|
|||||||
`KIND_*` iteration formulas in `advance()` must be kept in sync with
|
`KIND_*` iteration formulas in `advance()` must be kept in sync with
|
||||||
`reference.rs` by hand (there's no shared code path).
|
`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.
|
||||||
|
`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`)
|
### Two-pass render + caching (`renderer.rs`)
|
||||||
|
|
||||||
The interactive path splits iteration (expensive, perturbation) from
|
The interactive path splits iteration (expensive, perturbation) from
|
||||||
|
|||||||
+7
-1
@@ -10,6 +10,12 @@ gui = ["dep:eframe", "dep:egui"]
|
|||||||
# Pure-Rust big floats for the web build (`rug` needs GMP/MPFR, which can't
|
# 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).
|
# target wasm32). Required for wasm32, optional natively (to test that backend).
|
||||||
wasm = ["dep:malachite-float", "dep:malachite-base"]
|
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]
|
[dependencies]
|
||||||
bytemuck = { version = "1.25.2", features = ["derive"] }
|
bytemuck = { version = "1.25.2", features = ["derive"] }
|
||||||
@@ -53,4 +59,4 @@ opt-level = 1
|
|||||||
opt-level = 3
|
opt-level = 3
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
naga = { version = "30", features = ["wgsl-in", "spv-out"] }
|
naga = { version = "30", features = ["wgsl-in", "spv-out", "glsl-out"] }
|
||||||
|
|||||||
+3
-2
@@ -1,14 +1,15 @@
|
|||||||
#!/usr/bin/env bash
|
#!/usr/bin/env bash
|
||||||
# Build the WebAssembly bundle into ./dist using wasm-bindgen.
|
# 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
|
# Serve it over HTTP (e.g. `python3 -m http.server -d dist 8080`) and open in a
|
||||||
# WebGPU-capable browser (recent Chrome/Edge, Firefox, or Safari 26+).
|
# WebGPU-capable browser (recent Chrome/Edge, Firefox, or Safari 26+); the
|
||||||
|
# `webgl` feature falls back to WebGL2 elsewhere (no Buddhabrot there).
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
export PATH="$HOME/.cargo/bin:$PATH"
|
export PATH="$HOME/.cargo/bin:$PATH"
|
||||||
OUT="${1:-dist}"
|
OUT="${1:-dist}"
|
||||||
|
|
||||||
echo "==> cargo build (wasm32, release)"
|
echo "==> cargo build (wasm32, release)"
|
||||||
cargo build --release --target wasm32-unknown-unknown --features wasm
|
cargo build --release --target wasm32-unknown-unknown --features wasm,webgl
|
||||||
|
|
||||||
echo "==> wasm-bindgen -> $OUT"
|
echo "==> wasm-bindgen -> $OUT"
|
||||||
mkdir -p "$OUT"
|
mkdir -p "$OUT"
|
||||||
|
|||||||
+3
-2
@@ -46,8 +46,9 @@
|
|||||||
const msg = (err && err.message) || String(err);
|
const msg = (err && err.message) || String(err);
|
||||||
if (!msg.includes("Using exceptions for control flow")) {
|
if (!msg.includes("Using exceptions for control flow")) {
|
||||||
document.getElementById("loading_text").innerHTML =
|
document.getElementById("loading_text").innerHTML =
|
||||||
"<p>Failed to start. This app needs a WebGPU-capable browser " +
|
"<p>Failed to start. This app needs WebGPU (recent Chrome/Edge, " +
|
||||||
"(recent Chrome/Edge, Firefox, or Safari 26+).</p>";
|
"Firefox, or Safari 26+) or, in builds with the <code>webgl</code> " +
|
||||||
|
"feature, WebGL2 with float render targets.</p>";
|
||||||
console.error(err);
|
console.error(err);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
+56
-5
@@ -597,6 +597,8 @@ pub struct FractalApp {
|
|||||||
/// Keep dispatching new sample batches every frame (progressive
|
/// Keep dispatching new sample batches every frame (progressive
|
||||||
/// accumulation). Turning it off freezes the current histogram.
|
/// accumulation). Turning it off freezes the current histogram.
|
||||||
buddha_accumulate: bool,
|
buddha_accumulate: bool,
|
||||||
|
/// The device can run Buddhabrot mode's compute pass (not on WebGL2).
|
||||||
|
buddhabrot_supported: bool,
|
||||||
/// Whether the controls side panel is expanded. Collapsible so the fractal
|
/// Whether the controls side panel is expanded. Collapsible so the fractal
|
||||||
/// can take (nearly) the whole screen — important on a phone.
|
/// can take (nearly) the whole screen — important on a phone.
|
||||||
controls_open: bool,
|
controls_open: bool,
|
||||||
@@ -717,16 +719,53 @@ impl FractalApp {
|
|||||||
.as_ref()
|
.as_ref()
|
||||||
.expect("eframe must run with the wgpu backend");
|
.expect("eframe must run with the wgpu backend");
|
||||||
|
|
||||||
|
let adapter_info = render_state.adapter.get_info();
|
||||||
|
// The iteration data textures are `Rgba32Float` render targets
|
||||||
|
// (`EXT_color_buffer_float` on WebGL2, which nearly every browser has).
|
||||||
|
if !render_state
|
||||||
|
.adapter
|
||||||
|
.get_texture_format_features(wgpu::TextureFormat::Rgba32Float)
|
||||||
|
.allowed_usages
|
||||||
|
.contains(wgpu::TextureUsages::RENDER_ATTACHMENT)
|
||||||
|
{
|
||||||
|
panic!(
|
||||||
|
"this GPU / browser can't render to 32-bit float textures \
|
||||||
|
({:?} on {})",
|
||||||
|
adapter_info.backend, adapter_info.name
|
||||||
|
);
|
||||||
|
}
|
||||||
let renderer = FractalRenderer::new(&render_state.device, render_state.target_format);
|
let renderer = FractalRenderer::new(&render_state.device, render_state.target_format);
|
||||||
let buddhabrot_renderer =
|
log::info!(
|
||||||
BuddhabrotRenderer::new(&render_state.device, render_state.target_format);
|
"GPU: {} ({:?}), data path {:?}",
|
||||||
|
adapter_info.name,
|
||||||
|
adapter_info.backend,
|
||||||
|
renderer.gpu_path()
|
||||||
|
);
|
||||||
|
// Buddhabrot accumulates with a compute pass and reads its histogram
|
||||||
|
// from a storage buffer in the fragment stage.
|
||||||
|
let buddhabrot_supported = render_state
|
||||||
|
.adapter
|
||||||
|
.get_downlevel_capabilities()
|
||||||
|
.flags
|
||||||
|
.contains(wgpu::DownlevelFlags::COMPUTE_SHADERS)
|
||||||
|
&& render_state
|
||||||
|
.device
|
||||||
|
.limits()
|
||||||
|
.max_storage_buffers_per_shader_stage
|
||||||
|
>= 1;
|
||||||
{
|
{
|
||||||
let mut guard = render_state.renderer.write();
|
let mut guard = render_state.renderer.write();
|
||||||
guard.callback_resources.insert(renderer);
|
guard.callback_resources.insert(renderer);
|
||||||
guard.callback_resources.insert(buddhabrot_renderer);
|
if buddhabrot_supported {
|
||||||
|
guard.callback_resources.insert(BuddhabrotRenderer::new(
|
||||||
|
&render_state.device,
|
||||||
|
render_state.target_format,
|
||||||
|
));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut app = Self::default_state();
|
let mut app = Self::default_state();
|
||||||
|
app.buddhabrot_supported = buddhabrot_supported;
|
||||||
|
|
||||||
// On the web, restore a shared view from the URL fragment (#...).
|
// On the web, restore a shared view from the URL fragment (#...).
|
||||||
#[cfg(target_arch = "wasm32")]
|
#[cfg(target_arch = "wasm32")]
|
||||||
@@ -786,6 +825,7 @@ impl FractalApp {
|
|||||||
buddha_exposure: 1.0,
|
buddha_exposure: 1.0,
|
||||||
buddha_palette: 0,
|
buddha_palette: 0,
|
||||||
buddha_accumulate: true,
|
buddha_accumulate: true,
|
||||||
|
buddhabrot_supported: true,
|
||||||
controls_open: true,
|
controls_open: true,
|
||||||
fullscreen: false,
|
fullscreen: false,
|
||||||
info_open: false,
|
info_open: false,
|
||||||
@@ -2351,12 +2391,18 @@ impl FractalApp {
|
|||||||
ui.horizontal(|ui| {
|
ui.horizontal(|ui| {
|
||||||
ui.radio_value(&mut self.mode, FractalMode::Mandelbrot, "Set");
|
ui.radio_value(&mut self.mode, FractalMode::Mandelbrot, "Set");
|
||||||
ui.radio_value(&mut self.mode, FractalMode::Julia, "Julia");
|
ui.radio_value(&mut self.mode, FractalMode::Julia, "Julia");
|
||||||
ui.radio_value(&mut self.mode, FractalMode::Buddhabrot, "Buddhabrot")
|
ui.add_enabled(
|
||||||
|
self.buddhabrot_supported,
|
||||||
|
egui::RadioButton::new(self.mode == FractalMode::Buddhabrot, "Buddhabrot"),
|
||||||
|
)
|
||||||
.on_hover_text(
|
.on_hover_text(
|
||||||
"Monte-Carlo density of escaping orbits instead of the ordinary \
|
"Monte-Carlo density of escaping orbits instead of the ordinary \
|
||||||
escape-time set. Plain f32 view (no deep zoom); the image \
|
escape-time set. Plain f32 view (no deep zoom); the image \
|
||||||
progressively sharpens while the view stays still.",
|
progressively sharpens while the view stays still.",
|
||||||
);
|
)
|
||||||
|
.on_disabled_hover_text("Needs compute shaders (WebGPU); not available on WebGL2.")
|
||||||
|
.clicked()
|
||||||
|
.then(|| self.mode = FractalMode::Buddhabrot);
|
||||||
});
|
});
|
||||||
if self.mode != prev_mode {
|
if self.mode != prev_mode {
|
||||||
self.morph = None;
|
self.morph = None;
|
||||||
@@ -3179,6 +3225,11 @@ impl FractalApp {
|
|||||||
#[cfg(feature = "gui")]
|
#[cfg(feature = "gui")]
|
||||||
impl eframe::App for FractalApp {
|
impl eframe::App for FractalApp {
|
||||||
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
|
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
|
||||||
|
// A CLI flag can ask for Buddhabrot on a device that can't run it.
|
||||||
|
if !self.buddhabrot_supported && self.mode == FractalMode::Buddhabrot {
|
||||||
|
self.mode = FractalMode::Mandelbrot;
|
||||||
|
self.status = Some("Buddhabrot mode needs WebGPU compute shaders".into());
|
||||||
|
}
|
||||||
self.poll_export(ui.ctx());
|
self.poll_export(ui.ctx());
|
||||||
self.poll_ci_stats(ui.ctx(), frame);
|
self.poll_ci_stats(ui.ctx(), frame);
|
||||||
self.update_fps(ui);
|
self.update_fps(ui);
|
||||||
|
|||||||
+680
-318
File diff suppressed because it is too large
Load Diff
+23
-6
@@ -36,12 +36,14 @@ type MainResult = eframe::Result;
|
|||||||
type MainResult = Result<(), String>;
|
type MainResult = Result<(), String>;
|
||||||
|
|
||||||
/// wgpu configuration for eframe. The fractal fragment shader reads the
|
/// wgpu configuration for eframe. The fractal fragment shader reads the
|
||||||
/// reference orbit from a **storage buffer**, so the device must allow storage
|
/// reference orbit from **storage buffers** where the device allows them in
|
||||||
/// buffers in the fragment stage. eframe's default requests WebGL2-downlevel
|
/// the fragment stage (`GpuPath` in renderer.rs). eframe's default requests
|
||||||
/// limits when a GL adapter is picked (storage buffers = 0), so we:
|
/// 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
|
/// * request the adapter's real limits (which include storage buffers), and
|
||||||
/// * force the WebGPU backend on the web (WebGL2 can't do storage buffers at
|
/// * on the web, use WebGPU only, failing cleanly on browsers without it,
|
||||||
/// all) — failing cleanly on browsers without WebGPU, per the design.
|
/// unless the `webgl` feature adds WebGL2 as a fallback (egui-wgpu
|
||||||
|
/// tries WebGPU first).
|
||||||
#[cfg(feature = "gui")]
|
#[cfg(feature = "gui")]
|
||||||
fn wgpu_options() -> eframe::egui_wgpu::WgpuConfiguration {
|
fn wgpu_options() -> eframe::egui_wgpu::WgpuConfiguration {
|
||||||
use eframe::egui_wgpu::{WgpuSetup, wgpu};
|
use eframe::egui_wgpu::{WgpuSetup, wgpu};
|
||||||
@@ -55,10 +57,25 @@ fn wgpu_options() -> eframe::egui_wgpu::WgpuConfiguration {
|
|||||||
required_limits: adapter.limits(),
|
required_limits: adapter.limits(),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
});
|
});
|
||||||
#[cfg(target_arch = "wasm32")]
|
#[cfg(all(target_arch = "wasm32", not(feature = "webgl")))]
|
||||||
{
|
{
|
||||||
setup.instance_descriptor.backends = wgpu::Backends::BROWSER_WEBGPU;
|
setup.instance_descriptor.backends = wgpu::Backends::BROWSER_WEBGPU;
|
||||||
}
|
}
|
||||||
|
#[cfg(all(target_arch = "wasm32", feature = "webgl"))]
|
||||||
|
{
|
||||||
|
// `?backend=webgl` forces the fallback, to test it in a browser
|
||||||
|
// that has WebGPU.
|
||||||
|
let force_gl = 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");
|
||||||
|
setup.instance_descriptor.backends = if force_gl {
|
||||||
|
wgpu::Backends::GL
|
||||||
|
} else {
|
||||||
|
wgpu::Backends::BROWSER_WEBGPU | wgpu::Backends::GL
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
options
|
options
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
// Auto colour scale without compute shaders (WebGL2): point-samples the data
|
||||||
|
// texture onto a small CI_SAMPLE_DIM² grid, read back and binned on the CPU
|
||||||
|
// like `ci_stats.wgsl` (`CiHistogram::Readback` in renderer.rs). The grid
|
||||||
|
// stretches to the source's aspect; percentiles don't care.
|
||||||
|
|
||||||
|
@group(0) @binding(0) var data_tex: texture_2d<f32>;
|
||||||
|
|
||||||
|
@vertex
|
||||||
|
fn vs_main(@builtin(vertex_index) idx: u32) -> @builtin(position) vec4<f32> {
|
||||||
|
return vec4<f32>(fullscreen_triangle_pos(idx), 0.0, 1.0);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Must match `CI_SAMPLE_DIM` in renderer.rs.
|
||||||
|
const CI_SAMPLE_DIM: f32 = 256.0;
|
||||||
|
|
||||||
|
@fragment
|
||||||
|
fn fs_main(@builtin(position) pos: vec4<f32>) -> @location(0) vec4<f32> {
|
||||||
|
let size = vec2<f32>(textureDimensions(data_tex));
|
||||||
|
let p = min(vec2<i32>(floor(pos.xy * size / CI_SAMPLE_DIM)), vec2<i32>(size) - 1);
|
||||||
|
let d = textureLoad(data_tex, p, 0);
|
||||||
|
return vec4<f32>(d.r, d.b, 0.0, 0.0);
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
// Reference orbit + BLA table as storage buffers, and the native float
|
||||||
|
// builtins: the data fragment of `mandelbrot.wgsl` on every device with
|
||||||
|
// fragment-stage storage buffers (WebGPU, Vulkan, Metal, DX12). Each
|
||||||
|
// accessor is a plain index that the shader compiler inlines. Must define
|
||||||
|
// the same functions as `data_texture.wgsl` (the WebGL2 fallback).
|
||||||
|
|
||||||
|
@group(0) @binding(1) var<storage, read> ref_orbit: array<vec2<f32>>;
|
||||||
|
@group(0) @binding(3) var<storage, read> ref_exp: array<i32>;
|
||||||
|
@group(0) @binding(4) var<storage, read> bla_nodes: array<Bla>;
|
||||||
|
@group(0) @binding(5) var<storage, read> bla_meta: array<u32>;
|
||||||
|
|
||||||
|
fn ref_point(m: u32) -> vec2<f32> {
|
||||||
|
return ref_orbit[m];
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ref_exp_at(m: u32) -> i32 {
|
||||||
|
return ref_exp[m];
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bla_node(i: u32) -> Bla {
|
||||||
|
return bla_nodes[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bla_r_log2(i: u32) -> f32 {
|
||||||
|
return bla_nodes[i].r_log2;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bla_steps(i: u32) -> u32 {
|
||||||
|
return bla_nodes[i].steps;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bla_meta_at(i: u32) -> u32 {
|
||||||
|
return bla_meta[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
fn frexp_f32(x: f32) -> Frexp {
|
||||||
|
let f = frexp(x);
|
||||||
|
return Frexp(f.fract, f.exp);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ldexp_f32(x: f32, k: i32) -> f32 {
|
||||||
|
return ldexp(x, k);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ctz_u32(x: u32) -> u32 {
|
||||||
|
return countTrailingZeros(x);
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
// Reference orbit + BLA table as textures, and bit-exact replacements for
|
||||||
|
// float builtins: the data fragment of `mandelbrot.wgsl` on devices without
|
||||||
|
// fragment-stage storage buffers (WebGL2, `GpuPath::Texture` in
|
||||||
|
// renderer.rs). Must define the same functions as `data_storage.wgsl`.
|
||||||
|
//
|
||||||
|
// Every array is laid out row-major in a texture DATA_TEX_WIDTH texels wide
|
||||||
|
// (element i at (i % W, i / W); `RefData` in renderer.rs). BLA nodes are 3
|
||||||
|
// `Rgba32Uint` texels each (m, n, then m_exp/n_exp/r_log2/steps), floats as
|
||||||
|
// raw bits: a float texture could flush the small i32 exponents, whose bit
|
||||||
|
// patterns are subnormal floats.
|
||||||
|
|
||||||
|
@group(0) @binding(1) var ref_orbit_tex: texture_2d<f32>;
|
||||||
|
@group(0) @binding(3) var ref_exp_tex: texture_2d<i32>;
|
||||||
|
@group(0) @binding(4) var bla_nodes_tex: texture_2d<u32>;
|
||||||
|
@group(0) @binding(5) var bla_meta_tex: texture_2d<u32>;
|
||||||
|
|
||||||
|
// Must match `DATA_TEX_WIDTH` in renderer.rs (2048, WebGL2's guaranteed
|
||||||
|
// minimum texture size).
|
||||||
|
const DATA_TEX_LOG2_W: u32 = 11u;
|
||||||
|
|
||||||
|
fn data_texel(i: u32) -> vec2<i32> {
|
||||||
|
return vec2<i32>(i32(i & ((1u << DATA_TEX_LOG2_W) - 1u)), i32(i >> DATA_TEX_LOG2_W));
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ref_point(m: u32) -> vec2<f32> {
|
||||||
|
return textureLoad(ref_orbit_tex, data_texel(m), 0).xy;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ref_exp_at(m: u32) -> i32 {
|
||||||
|
return textureLoad(ref_exp_tex, data_texel(m), 0).x;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bla_node(i: u32) -> Bla {
|
||||||
|
let a = textureLoad(bla_nodes_tex, data_texel(3u * i), 0);
|
||||||
|
let b = textureLoad(bla_nodes_tex, data_texel(3u * i + 1u), 0);
|
||||||
|
let c = textureLoad(bla_nodes_tex, data_texel(3u * i + 2u), 0);
|
||||||
|
return Bla(
|
||||||
|
bitcast<vec4<f32>>(a),
|
||||||
|
bitcast<vec4<f32>>(b),
|
||||||
|
bitcast<i32>(c.x),
|
||||||
|
bitcast<i32>(c.y),
|
||||||
|
bitcast<f32>(c.z),
|
||||||
|
c.w,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bla_r_log2(i: u32) -> f32 {
|
||||||
|
return bitcast<f32>(textureLoad(bla_nodes_tex, data_texel(3u * i + 2u), 0).z);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bla_steps(i: u32) -> u32 {
|
||||||
|
return textureLoad(bla_nodes_tex, data_texel(3u * i + 2u), 0).w;
|
||||||
|
}
|
||||||
|
|
||||||
|
fn bla_meta_at(i: u32) -> u32 {
|
||||||
|
return textureLoad(bla_meta_tex, data_texel(i), 0).x;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2^e for e in [-126, 127], built from its bits.
|
||||||
|
fn pow2_f32(e: i32) -> f32 {
|
||||||
|
return bitcast<f32>(u32(e + 127) << 23u);
|
||||||
|
}
|
||||||
|
|
||||||
|
// WGSL `frexp` from the exponent bits. naga's GLSL ES 3.00 polyfill goes
|
||||||
|
// through log2, which is wrong for negative x and off by one near powers of
|
||||||
|
// two. Subnormals are scaled up by 2^64 first (0 if the GPU flushes them).
|
||||||
|
fn frexp_f32(x: f32) -> Frexp {
|
||||||
|
var bits = bitcast<u32>(x);
|
||||||
|
var bias = 0;
|
||||||
|
if ((bits >> 23u) & 0xffu) == 0u {
|
||||||
|
if (bits & 0x7fffffffu) == 0u {
|
||||||
|
return Frexp(x, 0);
|
||||||
|
}
|
||||||
|
bits = bitcast<u32>(x * 18446744073709551616.0); // 2^64
|
||||||
|
bias = -64;
|
||||||
|
if ((bits >> 23u) & 0xffu) == 0u {
|
||||||
|
return Frexp(0.0, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let biased = i32((bits >> 23u) & 0xffu);
|
||||||
|
if biased == 255 {
|
||||||
|
return Frexp(x, 0); // inf / NaN
|
||||||
|
}
|
||||||
|
return Frexp(bitcast<f32>((bits & 0x807fffffu) | 0x3f000000u), biased - 126 + bias);
|
||||||
|
}
|
||||||
|
|
||||||
|
// WGSL `ldexp` (GLSL ES 3.10+) as two exact power-of-two multiplies, valid
|
||||||
|
// for |k| <= 252; with both halves the same sign, the intermediate is
|
||||||
|
// normal whenever the result is.
|
||||||
|
fn ldexp_f32(x: f32, k: i32) -> f32 {
|
||||||
|
let k1 = clamp(k / 2, -126, 127);
|
||||||
|
let k2 = clamp(k - k1, -126, 127);
|
||||||
|
return x * pow2_f32(k1) * pow2_f32(k2);
|
||||||
|
}
|
||||||
|
|
||||||
|
// WGSL `countTrailingZeros` (`findLSB` is GLSL ES 3.10+): the exponent of
|
||||||
|
// the lowest set bit, which converts to f32 exactly.
|
||||||
|
fn ctz_u32(x: u32) -> u32 {
|
||||||
|
if x == 0u {
|
||||||
|
return 32u;
|
||||||
|
}
|
||||||
|
let low = x & (~x + 1u);
|
||||||
|
return (bitcast<u32>(f32(low)) >> 23u) - 127u;
|
||||||
|
}
|
||||||
+40
-32
@@ -18,23 +18,27 @@
|
|||||||
// to the plain f32 loop once the delta is big enough (see `iterate_sample`).
|
// to the plain f32 loop once the delta is big enough (see `iterate_sample`).
|
||||||
|
|
||||||
@group(0) @binding(0) var<uniform> u: Uniforms;
|
@group(0) @binding(0) var<uniform> u: Uniforms;
|
||||||
@group(0) @binding(1) var<storage, read> ref_orbit: array<vec2<f32>>;
|
// Bindings 1 and 3-5 (reference orbit, its exponents, the BLA table) are
|
||||||
|
// declared by the data fragment concatenated after this file: storage
|
||||||
|
// buffers (`data_storage.wgsl`) or, where the device has none (WebGL2),
|
||||||
|
// textures (`data_texture.wgsl`). Both provide `ref_point`, `ref_exp_at`,
|
||||||
|
// `bla_node`, `bla_r_log2`, `bla_steps`, `bla_meta_at`, plus `frexp_f32`,
|
||||||
|
// `ldexp_f32` and `ctz_u32` (GLSL ES 3.00 lacks the builtins).
|
||||||
// Only read by `fs_color`'s shadow branch (custom-lights palette); the
|
// Only read by `fs_color`'s shadow branch (custom-lights palette); the
|
||||||
// iteration pass (`fs_data`) never touches it.
|
// iteration pass (`fs_data`) never touches it.
|
||||||
@group(0) @binding(2) var<uniform> lights: array<Light, 16>;
|
@group(0) @binding(2) var<uniform> lights: array<Light, 16>;
|
||||||
// Only read by the adaptive-AA refine pass (`fs_refine`): the 1-sample-per-
|
// 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.
|
// pixel data texture written by `fs_data`, which decides where to supersample.
|
||||||
@group(1) @binding(0) var coarse_tex: texture_2d<f32>;
|
@group(1) @binding(0) var coarse_tex: texture_2d<f32>;
|
||||||
// Per-point binary exponents of the reference orbit (`RefOrbit::exps`): the
|
// Reference orbit: point m is `ref_point(m)`, and the true X[m] is
|
||||||
// true X[m] is ref_orbit[m] * 2^ref_exp[m]. Non-zero only for points below
|
// ref_point(m) * 2^ref_exp_at(m). The exponent is non-zero only for points
|
||||||
// f32's range, which only deep references contain; only `DEEP` pipelines read
|
// below f32's range, which only deep references contain; only `DEEP`
|
||||||
// it (see `ref_at`).
|
// pipelines read it (see `ref_at`).
|
||||||
@group(0) @binding(3) var<storage, read> ref_exp: array<i32>;
|
|
||||||
// Bivariate linear approximation table (`fractal::bla`): node i of level l
|
// 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
|
// 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
|
// 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,
|
// N = n·2^n_exp are real 2x2 matrices, row-major (the Jacobian of the map,
|
||||||
// so the abs/conjugate kinds are covered too). `bla_meta` is
|
// so the abs/conjugate kinds are covered too). `bla_meta_at` reads
|
||||||
// [min_level, level_count, off_0, ..., off_{level_count}, seg_count,
|
// [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
|
// 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
|
// `steps` steps from seg_start_i (see `bla_seg_find`). Only `BLA` pipelines
|
||||||
@@ -47,8 +51,12 @@ struct Bla {
|
|||||||
r_log2: f32,
|
r_log2: f32,
|
||||||
steps: u32,
|
steps: u32,
|
||||||
};
|
};
|
||||||
@group(0) @binding(4) var<storage, read> bla_nodes: array<Bla>;
|
|
||||||
@group(0) @binding(5) var<storage, read> bla_meta: array<u32>;
|
// `frexp` result (see `frexp_f32`).
|
||||||
|
struct Frexp {
|
||||||
|
fract: f32,
|
||||||
|
exp: i32,
|
||||||
|
};
|
||||||
|
|
||||||
// Pipeline-overridable specialization constants, set per pipeline from the
|
// Pipeline-overridable specialization constants, set per pipeline from the
|
||||||
// uniforms' `kind` / `is_julia` / `de_coloring` (see `PipelineKey` in
|
// uniforms' `kind` / `is_julia` / `de_coloring` (see `PipelineKey` in
|
||||||
@@ -316,7 +324,7 @@ fn ldexp_sat(x: f32, k: i32) -> f32 {
|
|||||||
}
|
}
|
||||||
return bitcast<f32>(bitcast<i32>(bits) + (k << 23u));
|
return bitcast<f32>(bitcast<i32>(bits) + (k << 23u));
|
||||||
}
|
}
|
||||||
let f = frexp(x);
|
let f = frexp_f32(x);
|
||||||
let ex = f.exp + k;
|
let ex = f.exp + k;
|
||||||
if ex > 100 {
|
if ex > 100 {
|
||||||
return select(-LDEXP_SAT, LDEXP_SAT, x > 0.0);
|
return select(-LDEXP_SAT, LDEXP_SAT, x > 0.0);
|
||||||
@@ -324,7 +332,7 @@ fn ldexp_sat(x: f32, k: i32) -> f32 {
|
|||||||
if ex < -125 {
|
if ex < -125 {
|
||||||
return 0.0;
|
return 0.0;
|
||||||
}
|
}
|
||||||
return ldexp(f.fract, ex);
|
return ldexp_f32(f.fract, ex);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn ldexp2_sat(v: vec2<f32>, k: i32) -> vec2<f32> {
|
fn ldexp2_sat(v: vec2<f32>, k: i32) -> vec2<f32> {
|
||||||
@@ -343,16 +351,16 @@ fn fe_make(v: vec2<f32>, e: i32) -> Fe {
|
|||||||
if a == 0.0 {
|
if a == 0.0 {
|
||||||
return Fe(vec2<f32>(0.0, 0.0), 0);
|
return Fe(vec2<f32>(0.0, 0.0), 0);
|
||||||
}
|
}
|
||||||
let k = frexp(a).exp;
|
let k = frexp_f32(a).exp;
|
||||||
return Fe(ldexp2_sat(v, -k), e + k);
|
return Fe(ldexp2_sat(v, -k), e + k);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Reference point X[m] as f32 (points stored normalized flush to 0 here;
|
// Reference point X[m] as f32 (points stored normalized flush to 0 here;
|
||||||
// only deep references have any, see `ref_exp`).
|
// only deep references have any, see `ref_exp`).
|
||||||
fn ref_at(m: u32) -> vec2<f32> {
|
fn ref_at(m: u32) -> vec2<f32> {
|
||||||
let x = ref_orbit[m];
|
let x = ref_point(m);
|
||||||
if DEEP {
|
if DEEP {
|
||||||
let k = ref_exp[m];
|
let k = ref_exp_at(m);
|
||||||
if k != 0 {
|
if k != 0 {
|
||||||
return ldexp2_sat(x, k);
|
return ldexp2_sat(x, k);
|
||||||
}
|
}
|
||||||
@@ -362,7 +370,7 @@ fn ref_at(m: u32) -> vec2<f32> {
|
|||||||
|
|
||||||
// X[m] with its full exponent range (deep phase only).
|
// X[m] with its full exponent range (deep phase only).
|
||||||
fn ref_fe(m: u32) -> Fe {
|
fn ref_fe(m: u32) -> Fe {
|
||||||
return fe_make(ref_orbit[m], ref_exp[m]);
|
return fe_make(ref_point(m), ref_exp_at(m));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Complex log of m * 2^e (m != 0).
|
// Complex log of m * 2^e (m != 0).
|
||||||
@@ -567,7 +575,7 @@ fn deep_log2(a: vec2<f32>, b: vec2<f32>) -> i32 {
|
|||||||
if m == 0.0 {
|
if m == 0.0 {
|
||||||
return DEEP_ZERO;
|
return DEEP_ZERO;
|
||||||
}
|
}
|
||||||
return frexp(m).exp;
|
return frexp_f32(m).exp;
|
||||||
}
|
}
|
||||||
|
|
||||||
// f'(y) at the full value y = X + w * 2^s, as an `Fe`. Plain `fprime` in f32
|
// f'(y) at the full value y = X + w * 2^s, as an `Fe`. Plain `fprime` in f32
|
||||||
@@ -639,13 +647,13 @@ fn log2_mag(v: vec2<f32>) -> f32 {
|
|||||||
// invalid level (usually right away: one load per failed attempt).
|
// invalid level (usually right away: one load per failed attempt).
|
||||||
fn bla_lookup(m: u32, e_log2: f32, budget: u32) -> vec2<u32> {
|
fn bla_lookup(m: u32, e_log2: f32, budget: u32) -> vec2<u32> {
|
||||||
var best = vec2<u32>(0u, 0u);
|
var best = vec2<u32>(0u, 0u);
|
||||||
let levels = bla_meta[1];
|
let levels = bla_meta_at(1u);
|
||||||
if levels == 0u || m == 0u {
|
if levels == 0u || m == 0u {
|
||||||
return best;
|
return best;
|
||||||
}
|
}
|
||||||
let lmin = bla_meta[0];
|
let lmin = bla_meta_at(0u);
|
||||||
let j = m - 1u;
|
let j = m - 1u;
|
||||||
let tz = countTrailingZeros(j); // 32 when j == 0
|
let tz = ctz_u32(j); // 32 when j == 0
|
||||||
if tz < lmin {
|
if tz < lmin {
|
||||||
return best;
|
return best;
|
||||||
}
|
}
|
||||||
@@ -654,7 +662,7 @@ fn bla_lookup(m: u32, e_log2: f32, budget: u32) -> vec2<u32> {
|
|||||||
// dependent load each): level 0 starts at 0 and each level has half the
|
// dependent load each): level 0 starts at 0 and each level has half the
|
||||||
// previous one's nodes, rounded down (`bla::build`).
|
// previous one's nodes, rounded down (`bla::build`).
|
||||||
var base = 0u;
|
var base = 0u;
|
||||||
var count = bla_meta[3];
|
var count = bla_meta_at(3u);
|
||||||
for (var k: u32 = 0u; k <= top; k = k + 1u) {
|
for (var k: u32 = 0u; k <= top; k = k + 1u) {
|
||||||
let l = lmin + k;
|
let l = lmin + k;
|
||||||
let steps = 1u << l;
|
let steps = 1u << l;
|
||||||
@@ -663,7 +671,7 @@ fn bla_lookup(m: u32, e_log2: f32, budget: u32) -> vec2<u32> {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
let idx = base + local;
|
let idx = base + local;
|
||||||
if !(e_log2 < bla_nodes[idx].r_log2) {
|
if !(e_log2 < bla_r_log2(idx)) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
best = vec2<u32>(idx, steps);
|
best = vec2<u32>(idx, steps);
|
||||||
@@ -679,14 +687,14 @@ fn bla_lookup(m: u32, e_log2: f32, budget: u32) -> vec2<u32> {
|
|||||||
// (`seg_i`, starting at `seg_at`); m only grows between rebases, so that
|
// (`seg_i`, starting at `seg_at`); m only grows between rebases, so that
|
||||||
// only moves forward.
|
// only moves forward.
|
||||||
fn bla_seg_count() -> u32 {
|
fn bla_seg_count() -> u32 {
|
||||||
return bla_meta[bla_meta[1] + 3u];
|
return bla_meta_at(bla_meta_at(1u) + 3u);
|
||||||
}
|
}
|
||||||
|
|
||||||
fn bla_seg_start(i: u32) -> u32 {
|
fn bla_seg_start(i: u32) -> u32 {
|
||||||
if i >= bla_seg_count() {
|
if i >= bla_seg_count() {
|
||||||
return 0xffffffffu;
|
return 0xffffffffu;
|
||||||
}
|
}
|
||||||
return bla_meta[bla_meta[1] + 4u + i];
|
return bla_meta_at(bla_meta_at(1u) + 4u + i);
|
||||||
}
|
}
|
||||||
|
|
||||||
// First segment from `lo` on that starts at or after `m` (binary search: a
|
// First segment from `lo` on that starts at or after `m` (binary search: a
|
||||||
@@ -696,7 +704,7 @@ fn bla_seg_find(lo: u32, m: u32) -> u32 {
|
|||||||
var b = bla_seg_count();
|
var b = bla_seg_count();
|
||||||
while a < b {
|
while a < b {
|
||||||
let mid = (a + b) / 2u;
|
let mid = (a + b) / 2u;
|
||||||
if bla_meta[bla_meta[1] + 4u + mid] < m {
|
if bla_meta_at(bla_meta_at(1u) + 4u + mid) < m {
|
||||||
a = mid + 1u;
|
a = mid + 1u;
|
||||||
} else {
|
} else {
|
||||||
b = mid;
|
b = mid;
|
||||||
@@ -709,9 +717,9 @@ fn bla_seg_find(lo: u32, m: u32) -> u32 {
|
|||||||
// else `bla_lookup`'s: (node index, steps), steps = 0 when there's none.
|
// 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> {
|
fn bla_jump(m: u32, seg_i: u32, seg_at: u32, e_log2: f32, budget: u32) -> vec2<u32> {
|
||||||
if seg_at == m {
|
if seg_at == m {
|
||||||
let idx = bla_meta[bla_meta[1] + 2u] + seg_i;
|
let idx = bla_meta_at(bla_meta_at(1u) + 2u) + seg_i;
|
||||||
let steps = bla_nodes[idx].steps;
|
let steps = bla_steps(idx);
|
||||||
if e_log2 < bla_nodes[idx].r_log2 && steps <= budget {
|
if e_log2 < bla_r_log2(idx) && steps <= budget {
|
||||||
return vec2<u32>(idx, steps);
|
return vec2<u32>(idx, steps);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -826,7 +834,7 @@ fn iterate_sample(offset: vec2<f32>, px: f32) -> Sample {
|
|||||||
// so skip the test once a pixel is smaller than that error (deep zoom),
|
// so skip the test once a pixel is smaller than that error (deep zoom),
|
||||||
// where it could misclassify pixels right at the boundary.
|
// where it could misclassify pixels right at the boundary.
|
||||||
if KIND == KIND_MANDELBROT && !MORPH && !IS_JULIA && !DEEP && ref_len > 1u && px > 1e-6 {
|
if KIND == KIND_MANDELBROT && !MORPH && !IS_JULIA && !DEEP && ref_len > 1u && px > 1e-6 {
|
||||||
let c = ref_orbit[1] + offset;
|
let c = ref_point(1u) + offset;
|
||||||
let xq = c.x - 0.25;
|
let xq = c.x - 0.25;
|
||||||
let q = xq * xq + c.y * c.y;
|
let q = xq * xq + c.y * c.y;
|
||||||
let in_cardioid = q * (q + xq) <= 0.25 * c.y * c.y;
|
let in_cardioid = q * (q + xq) <= 0.25 * c.y * c.y;
|
||||||
@@ -956,7 +964,7 @@ fn iterate_sample(offset: vec2<f32>, px: f32) -> Sample {
|
|||||||
}
|
}
|
||||||
let hit = bla_jump(m, seg_i, seg_at, e_log2, min(max_iter - n, ref_len - 1u - m));
|
let hit = bla_jump(m, seg_i, seg_at, e_log2, min(max_iter - n, ref_len - 1u - m));
|
||||||
if hit.y != 0u {
|
if hit.y != 0u {
|
||||||
let nd = bla_nodes[hit.x];
|
let nd = bla_node(hit.x);
|
||||||
if DE {
|
if DE {
|
||||||
var accv = fe_make(mat2v(nd.m, v), nd.m_exp + sv);
|
var accv = fe_make(mat2v(nd.m, v), nd.m_exp + sv);
|
||||||
if !IS_JULIA {
|
if !IS_JULIA {
|
||||||
@@ -1187,8 +1195,8 @@ fn iterate_sample(offset: vec2<f32>, px: f32) -> Sample {
|
|||||||
// Level nodes start at 1 + i·2^min_level, so only those steps can jump
|
// 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).
|
// (tested before `log2_mag` and the lookup: most steps here are plain).
|
||||||
var bla_align = 0xffffffffu;
|
var bla_align = 0xffffffffu;
|
||||||
if BLA && bla_meta[1] != 0u {
|
if BLA && bla_meta_at(1u) != 0u {
|
||||||
bla_align = (1u << bla_meta[0]) - 1u;
|
bla_align = (1u << bla_meta_at(0u)) - 1u;
|
||||||
}
|
}
|
||||||
loop {
|
loop {
|
||||||
// (`escaped` may already be set by the deep phase.)
|
// (`escaped` may already be set by the deep phase.)
|
||||||
@@ -1220,7 +1228,7 @@ fn iterate_sample(offset: vec2<f32>, px: f32) -> Sample {
|
|||||||
if BLA && m != 0u && ((m - 1u) & bla_align) == 0u {
|
if BLA && m != 0u && ((m - 1u) & bla_align) == 0u {
|
||||||
let hit = bla_lookup(m, log2_mag(e), min(max_iter - n, ref_len - 1u - m));
|
let hit = bla_lookup(m, log2_mag(e), min(max_iter - n, ref_len - 1u - m));
|
||||||
if hit.y != 0u {
|
if hit.y != 0u {
|
||||||
let nd = bla_nodes[hit.x];
|
let nd = bla_node(hit.x);
|
||||||
let se = select(0, u.scale_exp, DEEP);
|
let se = select(0, u.scale_exp, DEEP);
|
||||||
if periodic {
|
if periodic {
|
||||||
let det = abs(nd.m.x * nd.m.w - nd.m.y * nd.m.z);
|
let det = abs(nd.m.x * nd.m.w - nd.m.y * nd.m.z);
|
||||||
|
|||||||
+242
-8
@@ -65,22 +65,33 @@ fn specialize(
|
|||||||
.unwrap_or_else(|e| panic!("{name} {entry_point} {constants:?}: SPIR-V error: {e:?}"));
|
.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!(
|
const MANDELBROT_SRC: &str = concat!(
|
||||||
include_str!("../src/shaders/common.wgsl"),
|
include_str!("../src/shaders/common.wgsl"),
|
||||||
include_str!("../src/shaders/iterate_uniforms.wgsl"),
|
include_str!("../src/shaders/iterate_uniforms.wgsl"),
|
||||||
include_str!("../src/shaders/mandelbrot.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]
|
#[test]
|
||||||
fn mandelbrot_shader_is_valid() {
|
fn mandelbrot_shader_is_valid() {
|
||||||
validate("mandelbrot.wgsl", MANDELBROT_SRC);
|
validate("mandelbrot.wgsl", MANDELBROT_SRC);
|
||||||
|
validate("mandelbrot.wgsl (texture)", MANDELBROT_TEXTURE_SRC);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Every specialization renderer.rs can build (`PipelineKey`: kind × Julia ×
|
/// Every `PipelineKey` renderer.rs can build: kind × Julia × DE × morph ×
|
||||||
/// DE × morph × deep × BLA), for every fragment entry point.
|
/// deep × BLA, as override constants.
|
||||||
#[test]
|
fn pipeline_keys() -> Vec<[(&'static str, f64); 6]> {
|
||||||
fn mandelbrot_shader_specializations_compile() {
|
let mut keys = Vec::new();
|
||||||
let (module, info) = validate("mandelbrot.wgsl", MANDELBROT_SRC);
|
|
||||||
for kind in 0..kind_count() {
|
for kind in 0..kind_count() {
|
||||||
for julia in [0.0, 1.0] {
|
for julia in [0.0, 1.0] {
|
||||||
for de in [0.0, 1.0] {
|
for de in [0.0, 1.0] {
|
||||||
@@ -93,17 +104,36 @@ fn mandelbrot_shader_specializations_compile() {
|
|||||||
&[0.0]
|
&[0.0]
|
||||||
};
|
};
|
||||||
for &bla in blas {
|
for &bla in blas {
|
||||||
let constants = [
|
keys.push([
|
||||||
("KIND", kind as f64),
|
("KIND", kind as f64),
|
||||||
("IS_JULIA", julia),
|
("IS_JULIA", julia),
|
||||||
("DE", de),
|
("DE", de),
|
||||||
("MORPH", morph),
|
("MORPH", morph),
|
||||||
("DEEP", deep),
|
("DEEP", deep),
|
||||||
("BLA", bla),
|
("BLA", bla),
|
||||||
];
|
]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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"] {
|
for entry in ["fs_data", "fs_refine", "fs_color"] {
|
||||||
specialize(
|
specialize(
|
||||||
"mandelbrot.wgsl",
|
name,
|
||||||
&module,
|
&module,
|
||||||
&info,
|
&info,
|
||||||
naga::ShaderStage::Fragment,
|
naga::ShaderStage::Fragment,
|
||||||
@@ -113,9 +143,203 @@ fn mandelbrot_shader_specializations_compile() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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}");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -179,6 +403,16 @@ fn buddhabrot_shader_specializations_compile() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const CI_SAMPLE_SRC: &str = concat!(
|
||||||
|
include_str!("../src/shaders/common.wgsl"),
|
||||||
|
include_str!("../src/shaders/ci_sample.wgsl"),
|
||||||
|
);
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn ci_sample_shader_is_valid() {
|
||||||
|
validate("ci_sample.wgsl", CI_SAMPLE_SRC);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn ci_stats_shader_is_valid() {
|
fn ci_stats_shader_is_valid() {
|
||||||
validate(
|
validate(
|
||||||
|
|||||||
Reference in New Issue
Block a user