feat: add auto color scale option
This commit is contained in:
@@ -328,6 +328,14 @@ 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`).
|
||||
|
||||
+66
-7
@@ -517,6 +517,13 @@ pub struct FractalApp {
|
||||
auto_iterations: bool,
|
||||
color_scale: f32,
|
||||
color_offset: f32,
|
||||
/// When set, `color_scale` stretches one palette cycle across the `ci`
|
||||
/// range on screen (read back from the GPU, `FractalRenderer::take_ci_range`)
|
||||
/// and the palette starts at its low end, `ci_lo`.
|
||||
auto_color_scale: bool,
|
||||
/// Lowest on-screen `ci` from the last auto fit; 0 while auto is off.
|
||||
/// `color_offset` is relative to it (see `effective_color_offset`).
|
||||
ci_lo: f32,
|
||||
palette: u32,
|
||||
shadow_palette: u32,
|
||||
/// Supersample each pixel 2×2 for smoother edges (costs ~4× fragment work).
|
||||
@@ -716,6 +723,8 @@ impl FractalApp {
|
||||
auto_iterations: true,
|
||||
color_scale: 0.15,
|
||||
color_offset: 0.0,
|
||||
auto_color_scale: false,
|
||||
ci_lo: 0.0,
|
||||
palette: 0,
|
||||
shadow_palette: 0,
|
||||
antialias: false,
|
||||
@@ -1052,7 +1061,7 @@ impl FractalApp {
|
||||
lambda_l: self.lambda_l,
|
||||
complex_power: self.complex_power,
|
||||
color_scale: self.color_scale,
|
||||
color_offset: self.color_offset,
|
||||
color_offset: self.effective_color_offset(),
|
||||
palette: self.palette,
|
||||
shadow_palette: self.shadow_palette,
|
||||
}
|
||||
@@ -1074,6 +1083,9 @@ impl FractalApp {
|
||||
self.complex_power = s.complex_power;
|
||||
self.color_scale = s.color_scale;
|
||||
self.color_offset = s.color_offset;
|
||||
// Like the iteration count: the link's explicit scale wins.
|
||||
self.auto_color_scale = false;
|
||||
self.ci_lo = 0.0;
|
||||
self.palette = (s.palette as usize).min(PALETTE_NAMES.len() - 1) as u32;
|
||||
self.shadow_palette =
|
||||
(s.shadow_palette as usize).min(SHADOW_PALETTE_NAMES.len() - 1) as u32;
|
||||
@@ -1402,6 +1414,37 @@ impl FractalApp {
|
||||
/// Whether the classic escape-time palette (and its scale / offset /
|
||||
/// palette controls) is in use: always in classic mode, and in shadow/3D
|
||||
/// modes under the "Classic" shading palette.
|
||||
/// The palette offset the shaders get: `color_offset`, shifted so the
|
||||
/// palette starts at the auto fit's lowest on-screen `ci`.
|
||||
fn effective_color_offset(&self) -> f32 {
|
||||
(self.color_offset - self.ci_lo * self.color_scale).rem_euclid(1.0)
|
||||
}
|
||||
|
||||
/// Pick up the GPU's latest on-screen `ci` range and refit the colour
|
||||
/// scale to it (auto colour scale).
|
||||
#[cfg(feature = "gui")]
|
||||
fn poll_ci_stats(&mut self, ctx: &egui::Context, frame: &eframe::Frame) {
|
||||
let Some(rs) = frame.wgpu_render_state() else {
|
||||
return;
|
||||
};
|
||||
let mut guard = rs.renderer.write();
|
||||
let Some(renderer) = guard.callback_resources.get_mut::<FractalRenderer>() else {
|
||||
return;
|
||||
};
|
||||
let range = renderer.take_ci_range(&rs.device);
|
||||
// Also one frame after a readback lands: the view may have changed
|
||||
// while it was in flight, and that frame histograms it again.
|
||||
if renderer.ci_stats_pending() || range.is_some() {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
if self.auto_color_scale
|
||||
&& let Some((lo, hi)) = range
|
||||
{
|
||||
self.color_scale = (1.0 / (hi - lo).max(1e-3)).clamp(1e-4, 1.0);
|
||||
self.ci_lo = lo;
|
||||
}
|
||||
}
|
||||
|
||||
fn uses_classic_palette(&self) -> bool {
|
||||
self.rendering_mode == 0 || self.shadow_palette == SHADOW_PALETTE_CLASSIC
|
||||
}
|
||||
@@ -1458,7 +1501,7 @@ impl FractalApp {
|
||||
],
|
||||
max_iter: self.max_iterations.min(MAX_REF_POINTS as u32 - 1),
|
||||
ref_len: self.reference.len() as u32,
|
||||
color_offset: self.color_offset,
|
||||
color_offset: self.effective_color_offset(),
|
||||
color_scale: self.color_scale,
|
||||
bailout_sq: bailout_sq(self.ref_kind.unwrap_or(self.kind), self.power),
|
||||
is_julia: matches!(self.mode, FractalMode::Julia) as u32,
|
||||
@@ -2323,11 +2366,25 @@ impl FractalApp {
|
||||
});
|
||||
}
|
||||
if self.uses_classic_palette() {
|
||||
ui.add(
|
||||
egui::Slider::new(&mut self.color_scale, 0.01..=1.0)
|
||||
.text("color scale")
|
||||
.logarithmic(true),
|
||||
);
|
||||
let was_auto = self.auto_color_scale;
|
||||
ui.checkbox(&mut self.auto_color_scale, "Auto color scale")
|
||||
.on_hover_text(
|
||||
"Stretch one palette cycle across the escape-time range visible on screen.",
|
||||
);
|
||||
if was_auto && !self.auto_color_scale {
|
||||
// Fold the fit's start into the offset so nothing jumps.
|
||||
self.color_offset = self.effective_color_offset();
|
||||
self.ci_lo = 0.0;
|
||||
}
|
||||
if self.auto_color_scale {
|
||||
ui.label(format!("color scale: {:.4} (auto)", self.color_scale));
|
||||
} else {
|
||||
ui.add(
|
||||
egui::Slider::new(&mut self.color_scale, 0.0001..=1.0)
|
||||
.text("color scale")
|
||||
.logarithmic(true),
|
||||
);
|
||||
}
|
||||
ui.add(egui::Slider::new(&mut self.color_offset, 0.0..=1.0).text("color offset"));
|
||||
egui::ComboBox::from_label("palette")
|
||||
.selected_text(PALETTE_NAMES[self.palette as usize])
|
||||
@@ -2978,6 +3035,7 @@ impl FractalApp {
|
||||
reference: Arc::clone(&self.reference),
|
||||
generation: self.generation,
|
||||
size_px,
|
||||
auto_color: self.auto_color_scale && self.uses_classic_palette(),
|
||||
},
|
||||
));
|
||||
}
|
||||
@@ -2987,6 +3045,7 @@ impl FractalApp {
|
||||
impl eframe::App for FractalApp {
|
||||
fn ui(&mut self, ui: &mut egui::Ui, frame: &mut eframe::Frame) {
|
||||
self.poll_export(ui.ctx());
|
||||
self.poll_ci_stats(ui.ctx(), frame);
|
||||
self.update_fps(ui);
|
||||
// Track the real fullscreen state (e.g. the user pressing Esc/F11 or the
|
||||
// browser leaving fullscreen) so the toggle button label stays correct.
|
||||
|
||||
@@ -421,6 +421,198 @@ fn lipschitz_slots(width: u32, height: u32) -> Vec<u32> {
|
||||
(0..=top).rev().chain(std::iter::once(0)).collect()
|
||||
}
|
||||
|
||||
/// Histogram bins of `ci_stats.wgsl` (must match its `CI_BINS`).
|
||||
const CI_BINS: usize = 1024;
|
||||
/// Upper end of the histogram's log2(1 + ci) range (`CI_LOG2_MAX` in WGSL).
|
||||
const CI_LOG2_MAX: f32 = 25.0;
|
||||
/// Fraction of escaped pixels ignored at each end of the `ci` range the auto
|
||||
/// colour scale fits: the few pixels hugging the boundary have `ci` near
|
||||
/// `max_iter` and would otherwise squash the rest into one palette band.
|
||||
const CI_TAIL: f64 = 0.005;
|
||||
|
||||
/// Where the `ci` histogram readback is (see [`CiStats`]).
|
||||
enum CiStatsState {
|
||||
Idle,
|
||||
/// Histogram copied into `staging` by an encoder egui hasn't submitted
|
||||
/// yet: mapping must wait for the next frame.
|
||||
Copied,
|
||||
/// `map_async` issued; the flag is set once the mapping completes.
|
||||
Mapping(Arc<std::sync::atomic::AtomicBool>),
|
||||
}
|
||||
|
||||
/// Auto colour scale: a compute pass bins the data texture's `ci` into a
|
||||
/// histogram (`ci_stats.wgsl`), read back asynchronously one or two frames
|
||||
/// later by [`FractalRenderer::take_ci_range`].
|
||||
struct CiStats {
|
||||
pipeline: wgpu::ComputePipeline,
|
||||
layout: wgpu::BindGroupLayout,
|
||||
hist: wgpu::Buffer,
|
||||
staging: wgpu::Buffer,
|
||||
state: CiStatsState,
|
||||
/// The data texture changed since the last histogram was recorded.
|
||||
stale: bool,
|
||||
}
|
||||
|
||||
impl CiStats {
|
||||
fn new(device: &wgpu::Device) -> Self {
|
||||
let module = unsafe {
|
||||
device.create_shader_module_trusted(
|
||||
wgpu::ShaderModuleDescriptor {
|
||||
label: Some("ci stats"),
|
||||
source: wgpu::ShaderSource::Wgsl(
|
||||
include_str!("../shaders/ci_stats.wgsl").into(),
|
||||
),
|
||||
},
|
||||
wgpu::ShaderRuntimeChecks::unchecked(),
|
||||
)
|
||||
};
|
||||
let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
|
||||
label: Some("ci stats bind group layout"),
|
||||
entries: &[
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 0,
|
||||
visibility: wgpu::ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Texture {
|
||||
sample_type: wgpu::TextureSampleType::Float { filterable: false },
|
||||
view_dimension: wgpu::TextureViewDimension::D2,
|
||||
multisampled: false,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
wgpu::BindGroupLayoutEntry {
|
||||
binding: 1,
|
||||
visibility: wgpu::ShaderStages::COMPUTE,
|
||||
ty: wgpu::BindingType::Buffer {
|
||||
ty: wgpu::BufferBindingType::Storage { read_only: false },
|
||||
has_dynamic_offset: false,
|
||||
min_binding_size: None,
|
||||
},
|
||||
count: None,
|
||||
},
|
||||
],
|
||||
});
|
||||
let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor {
|
||||
label: Some("ci stats pipeline layout"),
|
||||
bind_group_layouts: &[Some(&layout)],
|
||||
immediate_size: 0,
|
||||
});
|
||||
let pipeline = device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor {
|
||||
label: Some("ci stats pipeline"),
|
||||
layout: Some(&pipeline_layout),
|
||||
module: &module,
|
||||
entry_point: Some("cs_main"),
|
||||
compilation_options: Default::default(),
|
||||
cache: None,
|
||||
});
|
||||
let size = (CI_BINS * std::mem::size_of::<u32>()) as u64;
|
||||
let hist = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("ci histogram"),
|
||||
size,
|
||||
usage: wgpu::BufferUsages::STORAGE
|
||||
| wgpu::BufferUsages::COPY_SRC
|
||||
| wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
let staging = device.create_buffer(&wgpu::BufferDescriptor {
|
||||
label: Some("ci histogram readback"),
|
||||
size,
|
||||
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
|
||||
mapped_at_creation: false,
|
||||
});
|
||||
Self {
|
||||
pipeline,
|
||||
layout,
|
||||
hist,
|
||||
staging,
|
||||
state: CiStatsState::Idle,
|
||||
stale: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Record the histogram of `data` (`width`×`height`) and its copy into
|
||||
/// `staging`. The caller checks the state is `Idle`.
|
||||
fn record(
|
||||
&mut self,
|
||||
device: &wgpu::Device,
|
||||
encoder: &mut wgpu::CommandEncoder,
|
||||
data: &wgpu::TextureView,
|
||||
width: u32,
|
||||
height: u32,
|
||||
) {
|
||||
let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {
|
||||
label: Some("ci stats bind group"),
|
||||
layout: &self.layout,
|
||||
entries: &[
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 0,
|
||||
resource: wgpu::BindingResource::TextureView(data),
|
||||
},
|
||||
wgpu::BindGroupEntry {
|
||||
binding: 1,
|
||||
resource: self.hist.as_entire_binding(),
|
||||
},
|
||||
],
|
||||
});
|
||||
encoder.clear_buffer(&self.hist, 0, None);
|
||||
{
|
||||
let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor {
|
||||
label: Some("ci stats pass"),
|
||||
timestamp_writes: None,
|
||||
});
|
||||
pass.set_pipeline(&self.pipeline);
|
||||
pass.set_bind_group(0, &bind_group, &[]);
|
||||
pass.dispatch_workgroups(width.div_ceil(16), height.div_ceil(16), 1);
|
||||
}
|
||||
encoder.copy_buffer_to_buffer(&self.hist, 0, &self.staging, 0, None);
|
||||
self.state = CiStatsState::Copied;
|
||||
self.stale = false;
|
||||
}
|
||||
|
||||
/// Start mapping a histogram copied on an earlier (now submitted) frame.
|
||||
fn start_map(&mut self) {
|
||||
if let CiStatsState::Copied = self.state {
|
||||
let done = Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||
let flag = Arc::clone(&done);
|
||||
self.staging
|
||||
.slice(..)
|
||||
.map_async(wgpu::MapMode::Read, move |res| {
|
||||
if res.is_ok() {
|
||||
flag.store(true, std::sync::atomic::Ordering::Release);
|
||||
}
|
||||
});
|
||||
self.state = CiStatsState::Mapping(done);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The `ci` range `[lo, hi]` between the [`CI_TAIL`] percentiles of a
|
||||
/// `ci_stats.wgsl` histogram, or `None` if no pixel escaped.
|
||||
fn ci_range(hist: &[u32]) -> Option<(f32, f32)> {
|
||||
let total: u64 = hist.iter().map(|&n| n as u64).sum();
|
||||
if total == 0 {
|
||||
return None;
|
||||
}
|
||||
let bin_ci = |i: usize| {
|
||||
let x = (i as f32 + 0.5) * (CI_LOG2_MAX / CI_BINS as f32);
|
||||
x.exp2() - 1.0
|
||||
};
|
||||
let percentile = |p: f64| {
|
||||
let target = (p * total as f64).ceil().max(1.0) as u64;
|
||||
let mut acc = 0;
|
||||
for (i, &n) in hist.iter().enumerate() {
|
||||
acc += n as u64;
|
||||
if acc >= target {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
hist.len() - 1
|
||||
};
|
||||
Some((
|
||||
bin_ci(percentile(CI_TAIL)),
|
||||
bin_ci(percentile(1.0 - CI_TAIL)),
|
||||
))
|
||||
}
|
||||
|
||||
/// The interactive iteration pipelines for one [`PipelineKey`].
|
||||
struct IteratePipelines {
|
||||
/// 1-spp perturbation iterate → data texture (`fs_data`).
|
||||
@@ -587,6 +779,8 @@ pub struct FractalRenderer {
|
||||
iterated: Option<IterState>,
|
||||
/// What the colour texture holds; `None` forces a recolour.
|
||||
colored: Option<ColorState>,
|
||||
/// Auto colour scale's `ci` histogram + readback.
|
||||
ci_stats: CiStats,
|
||||
}
|
||||
|
||||
impl FractalRenderer {
|
||||
@@ -948,9 +1142,35 @@ impl FractalRenderer {
|
||||
cache: None,
|
||||
iterated: None,
|
||||
colored: None,
|
||||
ci_stats: CiStats::new(device),
|
||||
}
|
||||
}
|
||||
|
||||
/// The on-screen `ci` range from the latest auto-colour histogram, once
|
||||
/// its readback has landed (`None` before that, or if nothing escaped).
|
||||
pub fn take_ci_range(&mut self, device: &wgpu::Device) -> Option<(f32, f32)> {
|
||||
let CiStatsState::Mapping(done) = &self.ci_stats.state else {
|
||||
return None;
|
||||
};
|
||||
let _ = device.poll(wgpu::PollType::Poll);
|
||||
if !done.load(std::sync::atomic::Ordering::Acquire) {
|
||||
return None;
|
||||
}
|
||||
let staging = &self.ci_stats.staging;
|
||||
let range = {
|
||||
let data = staging.slice(..).get_mapped_range().ok()?;
|
||||
ci_range(bytemuck::cast_slice(&data))
|
||||
};
|
||||
staging.unmap();
|
||||
self.ci_stats.state = CiStatsState::Idle;
|
||||
range
|
||||
}
|
||||
|
||||
/// A histogram is on its way back: keep repainting to pick it up.
|
||||
pub fn ci_stats_pending(&self) -> bool {
|
||||
!matches!(self.ci_stats.state, CiStatsState::Idle)
|
||||
}
|
||||
|
||||
/// Ensure the cache textures exist at `width`×`height` (plus the AA refine
|
||||
/// target iff `aa`). Recreates them (and their bind groups) on a change,
|
||||
/// invalidating any previous render.
|
||||
@@ -1917,6 +2137,9 @@ pub struct FractalCallback {
|
||||
pub generation: u64,
|
||||
/// Widget size in physical pixels — the cache texture resolution.
|
||||
pub size_px: [u32; 2],
|
||||
/// Histogram each new iteration for the auto colour scale
|
||||
/// ([`FractalRenderer::take_ci_range`]).
|
||||
pub auto_color: bool,
|
||||
}
|
||||
|
||||
#[cfg(feature = "gui")]
|
||||
@@ -1966,6 +2189,28 @@ impl egui_wgpu::CallbackTrait for FractalCallback {
|
||||
|| color_differs(&c.uniforms, &self.uniforms)
|
||||
});
|
||||
|
||||
// Last frame's histogram copy has been submitted by now: map it.
|
||||
renderer.ci_stats.start_map();
|
||||
if iter_dirty {
|
||||
renderer.ci_stats.stale = true;
|
||||
}
|
||||
// Histogram the data texture when auto colour needs one: after this
|
||||
// frame's iteration (recorded below), or now if the texture is
|
||||
// already current (auto just turned on, or a readback was in flight
|
||||
// when it last changed).
|
||||
let wants_stats = self.auto_color
|
||||
&& renderer.ci_stats.stale
|
||||
&& matches!(renderer.ci_stats.state, CiStatsState::Idle);
|
||||
if wants_stats
|
||||
&& !iter_dirty
|
||||
&& let Some(cache) = &renderer.cache
|
||||
{
|
||||
let src = cache.aa.as_ref().map_or(&cache.data_view, |(v, _)| v);
|
||||
renderer
|
||||
.ci_stats
|
||||
.record(device, egui_encoder, src, cache.width, cache.height);
|
||||
}
|
||||
|
||||
if !color_dirty {
|
||||
return Vec::new(); // cache still valid; paint() just blits it
|
||||
}
|
||||
@@ -2057,6 +2302,12 @@ impl egui_wgpu::CallbackTrait for FractalCallback {
|
||||
band_count(width, height, max_iter, aa * aa),
|
||||
);
|
||||
}
|
||||
if wants_stats {
|
||||
let src = cache.aa.as_ref().map_or(&cache.data_view, |(v, _)| v);
|
||||
renderer
|
||||
.ci_stats
|
||||
.record(device, egui_encoder, src, width, height);
|
||||
}
|
||||
}
|
||||
|
||||
// Shadow / 3D Complex Multibrot: rebuild the DE as a distance field.
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
// 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);
|
||||
}
|
||||
@@ -169,3 +169,11 @@ fn buddhabrot_shader_specializations_compile() {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ci_stats_shader_is_valid() {
|
||||
validate(
|
||||
"ci_stats.wgsl",
|
||||
include_str!("../src/shaders/ci_stats.wgsl"),
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user