Blur behind panels: render path, zero cost when off (#8876) (#9809)

* claim: #8876

* Add optional viewport-only Kawase blur and native UI composition

* Fix vendored panel hook imports and deprecated float constant import

* Drain texture updates in the full GPU blur fixture

* Hold the blur evidence fixture camera fixed across radii

* Address blur compositor lint checks

* Share animated Render preview background with blur source

* Use resolved Design background for blur source

* Exercise blur rendering independently of software adapter policy in CI

* Use stock egui hosts instead of vendoring the full crate

* Preserve feature-window open handling with stock egui hosts

* Target the native Window in close-handling regression fixture
This commit is contained in:
Nathan Dane
2026-11-01 01:37:44 +00:00
committed by GitHub
parent 60d79e7ea2
commit 7366fe0ecc
22 changed files with 2803 additions and 94 deletions
+1 -1
View File
@@ -139,7 +139,7 @@ pub fn native_backends() -> wgpu::Backends {
}
}
pub(crate) fn tier_of(t: wgpu::DeviceType) -> Tier {
pub fn tier_of(t: wgpu::DeviceType) -> Tier {
match t {
wgpu::DeviceType::Cpu => Tier::Software,
wgpu::DeviceType::DiscreteGpu | wgpu::DeviceType::IntegratedGpu | wgpu::DeviceType::VirtualGpu | wgpu::DeviceType::Other => Tier::Hardware,
+1 -1
View File
@@ -3290,7 +3290,7 @@ fn can_reuse(ss_ready: bool, cached: Option<u64>, key: u64) -> bool {
/// section, images, analysis, accessibility map, ambient occlusion and the theme's hover and
/// selection tints. The same key draws the same picture (pipelines and shaders are fixed for the
/// renderer).
fn frame_key(cb: &Frame) -> u64 {
pub fn frame_key(cb: &Frame) -> u64 {
use std::hash::Hash as _;
let mut h = std::collections::hash_map::DefaultHasher::new();
cb.product.hash(&mut h);
+10 -12
View File
@@ -106,24 +106,22 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
app.agent_chat.dock_space = Some(Rect::from_x_y_ranges(screen.x_range(), available.y_range()));
let t = Tokens::get();
let left = app.preferences.agent_chat_side == "left";
let side = |id: Id| Container::new(ui.ctx(), Surface::Panel).edge(id, if left { Edge::Left } else { Edge::Right });
let host = Container::new(ui.ctx(), Surface::Panel);
let side = |id: Id| host.edge(id, if left { Edge::Left } else { Edge::Right });
if app.preferences.agent_chat_minimized {
let r = side(Id::new("sc_agent_chat_strip"))
.exact_size(STRIP)
.resizable(false)
.frame(Container::new(ui.ctx(), Surface::Panel).edge_frame(t.panel))
.show(ui, |ui| strip(app, ui));
let r = host
.show_edge(ui, side(Id::new("sc_agent_chat_strip")).exact_size(STRIP).resizable(false), host.edge_frame(t.panel), |ui| strip(app, ui));
app.agent_chat.drop_rect = Some(r.response.rect);
show_drop_hint(app, &ctx);
return;
}
let width = app.preferences.agent_chat_width.clamp(MIN_WIDTH, MAX_WIDTH);
let r = side(panel_id(left))
.default_size(width)
.size_range(MIN_WIDTH..=MAX_WIDTH)
.resizable(true)
.frame(Container::new(ui.ctx(), Surface::Panel).edge_frame(t.dialog_body))
.show(ui, |ui| ui_kit::scope(ui, |ui| body(app, ui, left)));
let r = host.show_edge(
ui,
side(panel_id(left)).default_size(width).size_range(MIN_WIDTH..=MAX_WIDTH).resizable(true),
host.edge_frame(t.dialog_body),
|ui| ui_kit::scope(ui, |ui| body(app, ui, left)),
);
crate::scenario::publish_rect("agent_chat:panel", r.response.rect);
app.agent_chat.panel_rect = Some(r.response.rect);
#[cfg(not(target_arch = "wasm32"))]
+118
View File
@@ -0,0 +1,118 @@
//! Optional viewport-only blur. Plain frames do not record markers or own effect resources.
use egui::{Color32, Frame, Painter, Rect, Shape};
use serde::Serialize;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
pub enum Capability {
Available,
Unavailable(&'static str),
}
#[derive(Clone, Copy, Debug, Default, Serialize)]
pub struct Counters {
pub textures_created: u64,
pub buffers_created: u64,
pub bind_groups_created: u64,
pub pipelines_created: u64,
pub source_passes: u64,
pub blur_passes: u64,
pub composition_passes: u64,
pub present_passes: u64,
pub markers_emitted: u64,
pub markers_drawn: u64,
pub cache_hits: u64,
pub live_bytes: u64,
pub live_textures: u64,
pub live_buffers: u64,
pub live_bind_groups: u64,
pub live_pipelines: u64,
}
impl Counters {
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn clear_live(&mut self) {
self.live_bytes = 0;
self.live_textures = 0;
self.live_buffers = 0;
self.live_bind_groups = 0;
self.live_pipelines = 0;
}
}
pub fn validate_radius(radius: f32) -> Result<f32, &'static str> {
if radius.is_finite() && (0.0..=40.0).contains(&radius) {
Ok(radius)
} else {
Err("blur radius must be finite and between 0 and 40 physical pixels")
}
}
/// Original Kawase schedule. Offsets are in input texels; the first level is half sized.
pub fn schedule(radius: f32) -> Option<(usize, f32)> {
if validate_radius(radius).ok()? == 0.0 {
return None;
}
let steps = if radius <= 8.0 {
2
} else if radius <= 18.0 {
3
} else if radius <= 30.0 {
4
} else {
5
};
// Per-axis tap variance: down 1/2, up 4/3, scaled by input texel size.
// Target tap sigma = radius / 2. Resampling adds its own measurable footprint.
let variance = (35.0 / 18.0) * (4.0_f32.powi(steps as i32) - 1.0);
Some((steps, radius / (2.0 * variance.sqrt())))
}
#[cfg(not(target_arch = "wasm32"))]
#[path = "blur_native.rs"]
mod implementation;
#[cfg(not(target_arch = "wasm32"))]
pub use implementation::*;
#[cfg(target_arch = "wasm32")]
mod implementation {
use super::*;
#[derive(Default)]
pub struct State {
radius: f32,
}
impl State {
pub fn install(&mut self, _: &egui_wgpu::RenderState, _: bool) {}
pub fn set_radius(&mut self, radius: f32) -> Result<(), &'static str> {
self.radius = validate_radius(radius)?;
Ok(())
}
pub fn radius(&self) -> f32 {
self.radius
}
pub fn capability(&self) -> Capability {
Capability::Unavailable("web compositor integration unavailable")
}
pub fn capability_for(&self, _: egui::ViewportId) -> Capability {
self.capability()
}
pub fn counters(&self) -> Counters {
Counters::default()
}
pub fn begin(&mut self, _: &egui::Context, _: bool) {}
pub fn set_surface_alpha(&mut self, _: Option<u8>) {}
}
pub fn enabled() -> bool {
false
}
pub fn panel_fill(fill: Color32) -> Color32 {
fill
}
pub fn decorate(_: &Painter, _: Frame, _: Rect, shape: Shape) -> Shape {
shape
}
pub fn viewport(painter: &Painter, rect: Rect, cb: crate::gpu::ViewportCallback, _: Rect, _: [Color32; 2]) {
painter.add(egui_wgpu::Callback::new_paint_callback(rect, cb));
}
}
#[cfg(target_arch = "wasm32")]
pub use implementation::*;
+70
View File
@@ -0,0 +1,70 @@
// Original SolidCraft viewport-only dual-Kawase and rounded panel composition.
struct Params { a: vec4<f32>, rect: vec4<f32>, corners: vec4<f32>, top: vec4<f32>, bottom: vec4<f32>, outside: vec4<f32> }
@group(0) @binding(0) var image: texture_2d<f32>;
@group(0) @binding(1) var filtering: sampler;
@group(0) @binding(2) var<uniform> p: Params;
struct Vertex { @builtin(position) position: vec4<f32>, @location(0) uv: vec2<f32> }
@vertex fn vertex(@builtin(vertex_index) i: u32) -> Vertex {
let uv = vec2<f32>(f32((i << 1u) & 2u), f32(i & 2u));
return Vertex(vec4<f32>(uv * vec2<f32>(2.0, -2.0) + vec2<f32>(-1.0, 1.0), 0.0, 1.0), uv);
}
fn linear(c: vec3<f32>) -> vec3<f32> {
return select(c / 12.92, pow((c + vec3<f32>(0.055)) / 1.055, vec3<f32>(2.4)), c > vec3<f32>(0.04045));
}
fn gamma(c: vec3<f32>) -> vec3<f32> {
return select(c * 12.92, 1.055 * pow(max(c, vec3<f32>(0.0)), vec3<f32>(1.0 / 2.4)) - vec3<f32>(0.055), c > vec3<f32>(0.0031308));
}
fn load_linear(at: vec2<i32>) -> vec4<f32> {
let c = textureLoad(image, clamp(at, vec2<i32>(0), vec2<i32>(textureDimensions(image)) - vec2<i32>(1)), 0);
// Only the source is gamma encoded on unorm targets. It is opaque, so decoding
// each texel BEFORE bilinear interpolation avoids filtering encoded colors.
return vec4<f32>(linear(c.rgb), c.a);
}
fn sample_at(uv: vec2<f32>) -> vec4<f32> {
if p.a.y < 0.5 { return textureSampleLevel(image, filtering, uv, 0.0); }
let q = uv * vec2<f32>(textureDimensions(image)) - vec2<f32>(0.5);
let lo = vec2<i32>(floor(q)); let f = fract(q);
return mix(mix(load_linear(lo), load_linear(lo + vec2<i32>(1, 0)), f.x),
mix(load_linear(lo + vec2<i32>(0, 1)), load_linear(lo + vec2<i32>(1, 1)), f.x), f.y);
}
@fragment fn down(v: Vertex) -> @location(0) vec4<f32> {
let d = vec2<f32>(p.a.x) / vec2<f32>(textureDimensions(image));
return (4.0 * sample_at(v.uv) + sample_at(v.uv + d) + sample_at(v.uv - d)
+ sample_at(v.uv + d * vec2<f32>(1.0, -1.0)) + sample_at(v.uv + d * vec2<f32>(-1.0, 1.0))) / 8.0;
}
@fragment fn up(v: Vertex) -> @location(0) vec4<f32> {
let d = vec2<f32>(p.a.x) / vec2<f32>(textureDimensions(image));
return (sample_at(v.uv + vec2<f32>(-2.0*d.x, 0.0)) + sample_at(v.uv + vec2<f32>(2.0*d.x, 0.0))
+ sample_at(v.uv + vec2<f32>(0.0, -2.0*d.y)) + sample_at(v.uv + vec2<f32>(0.0, 2.0*d.y))
+ 2.0 * (sample_at(v.uv + d) + sample_at(v.uv - d)
+ sample_at(v.uv + d * vec2<f32>(1.0, -1.0)) + sample_at(v.uv + d * vec2<f32>(-1.0, 1.0)))) / 12.0;
}
@fragment fn background(v: Vertex) -> @location(0) vec4<f32> {
let q = v.position.xy;
var c = p.outside;
if all(q >= p.rect.xy) && all(q < p.rect.zw) && all(q >= p.corners.xy) && all(q < p.corners.zw) {
c = mix(p.top, p.bottom, clamp((q.y - p.rect.y) / max(1.0, p.rect.w - p.rect.y), 0.0, 1.0));
}
if p.a.z > 0.5 { return vec4<f32>(linear(c.rgb), 1.0); }
return vec4<f32>(c.rgb, 1.0);
}
@fragment fn panel(v: Vertex) -> @location(0) vec4<f32> {
let center = (p.rect.xy + p.rect.zw) * 0.5;
let half_size = (p.rect.zw - p.rect.xy) * 0.5;
let relative = v.position.xy - center;
let upper = relative.y < 0.0;
let radius = select(select(p.corners.w, p.corners.z, relative.x < 0.0), select(p.corners.y, p.corners.x, relative.x < 0.0), upper);
let r = min(radius, min(half_size.x, half_size.y));
let d = abs(relative) - half_size + vec2<f32>(r);
let distance = min(max(d.x, d.y), 0.0) + length(max(d, vec2<f32>(0.0))) - r;
let alpha = clamp(0.5 - distance, 0.0, 1.0) * p.a.w;
let c = textureSample(image, filtering, v.position.xy / vec2<f32>(textureDimensions(image)));
// Match egui: coverage/opacity multiply gamma-premultiplied RGB BEFORE the
// framebuffer conversion. B itself remains linear, opaque viewport color.
let premultiplied_gamma = gamma(c.rgb) * alpha;
let rgb = select(premultiplied_gamma, linear(premultiplied_gamma), p.a.z > 0.5);
return vec4<f32>(rgb, alpha);
}
@fragment fn present(v: Vertex) -> @location(0) vec4<f32> {
return textureSample(image, filtering, v.uv);
}
File diff suppressed because it is too large Load Diff
+58
View File
@@ -555,6 +555,43 @@ fn dispatch(app: &mut SolveApp, ctx: &egui::Context, method: &str, p: &Value) ->
let f = |k: &str| p.get(k).and_then(Value::as_f64).filter(|x| x.is_finite());
let b = |k: &str| p.get(k).and_then(Value::as_bool).unwrap_or(false);
match method {
"ui.blur" => {
// Internal rendering harness; deliberately no saved preference or product UI.
let radius = if let Some(radius) = p.get("radius_px") {
let Some(radius) = radius.as_f64().filter(|v| v.is_finite() && (0.0..=40.0).contains(v)) else {
return err("radius_px must be finite and between 0 and 40");
};
Some(radius as f32)
} else {
None
};
let alpha = if let Some(alpha) = p.get("surface_alpha") {
let alpha = if alpha.is_null() {
None
} else {
let Some(alpha) = alpha.as_f64().filter(|v| v.is_finite() && (0.0..=1.0).contains(v)) else {
return err("surface_alpha must be null or between 0 and 1");
};
Some((alpha * 255.0).round() as u8)
};
Some(alpha)
} else {
None
};
if let Some(radius) = radius {
if let Err(error) = app.blur.set_radius(radius) {
return err(error);
}
ctx.request_repaint();
}
if let Some(alpha) = alpha {
app.blur.set_surface_alpha(alpha);
ctx.request_repaint();
}
ok(
json!({"radius_px":app.blur.radius(), "max_radius_px":40, "capability":app.blur.capability_for(ctx.viewport_id()), "counters":app.blur.counters()}),
)
}
"ui.status_fixture" => wrap(crate::viewport_status_fixture::control(app, p)),
"ui.workspace" => {
if let Some(workspace) = s("workspace") {
@@ -1370,6 +1407,27 @@ pub(crate) fn write_screenshot(image: &egui::ColorImage, path: &str) -> Result<(
#[cfg(test)]
mod tests {
#[test]
fn blur_control_validates_before_mutation_and_reports_no_gpu() {
let mut h = crate::scenario::Harness::new();
for invalid in [json!(-1), json!(41), json!("18"), json!(null)] {
let reply = h.call("ui.blur", json!({"radius_px":invalid}));
assert_eq!(reply["ok"], false, "{reply}");
assert_eq!(h.app.blur.radius(), 0.0);
}
let reply = h.call("ui.blur", json!({"radius_px":18,"surface_alpha":2}));
assert_eq!(reply["ok"], false);
assert_eq!(h.app.blur.radius(), 0.0);
let reply = h.call("ui.blur", json!({"radius_px":18,"surface_alpha":0.7}));
assert_eq!(reply["ok"], true);
assert!(matches!(h.app.blur.capability(), crate::blur::Capability::Unavailable(_)));
h.frames(2);
assert_eq!(h.app.blur.counters().textures_created, 0);
assert_eq!(h.app.blur.counters().markers_emitted, 0);
h.call("ui.blur", json!({"radius_px":0,"surface_alpha":null}));
assert_eq!(h.app.blur.radius(), 0.0);
}
use serde_json::json;
use solidcraft_engine::{Sel, Session};
+445
View File
@@ -646,6 +646,451 @@ impl OffscreenFrames {
#[cfg(test)]
mod tests {
#[test]
fn blur_radius_schedule_and_hostile_values() {
use crate::blur::{schedule, validate_radius};
for radius in [f32::NAN, f32::INFINITY, -1.0, 40.01] {
assert!(validate_radius(radius).is_err());
assert!(schedule(radius).is_none());
}
assert!(schedule(0.0).is_none());
for (radius, steps) in [(1.0, 2), (8.0, 2), (9.0, 3), (18.0, 3), (19.0, 4), (30.0, 4), (31.0, 5), (40.0, 5)] {
let (actual, offset) = schedule(radius).unwrap();
assert_eq!(actual, steps);
assert!(offset.is_finite() && offset > 0.0);
let variance = (35.0 / 18.0) * (4.0_f32.powi(steps as i32) - 1.0);
assert!((offset * variance.sqrt() - radius / 2.0).abs() < 0.0001);
}
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn blur_target_budget_rejects_empty_and_excessive_sizes() {
for size in [[0, 1], [1, 0], [u32::MAX, 2], [16384, 16384]] {
assert!(crate::blur::fixture_budget(size, 5).is_none());
}
for steps in 2..=5 {
assert!(crate::blur::fixture_budget([1, 1], steps).is_some());
assert!(crate::blur::fixture_budget([800, 600], steps).is_some());
}
}
/// Full egui GPU harness: actual app UI, callbacks, fonts, marker slots and pass owner.
/// This is intentionally distinct from model-only `ui.render`/OffscreenFrames.
#[cfg(not(target_arch = "wasm32"))]
struct BlurFixture {
app: crate::SolveApp,
ctx: egui::Context,
renderer: std::sync::Arc<egui::epaint::mutex::RwLock<egui_wgpu::Renderer>>,
adapter: egui_wgpu::wgpu::Adapter,
device: egui_wgpu::wgpu::Device,
queue: egui_wgpu::wgpu::Queue,
output: egui_wgpu::wgpu::Texture,
size: [u32; 2],
jobs: usize,
root_transform: egui::emath::TSTransform,
root_layer: Option<egui::LayerId>,
}
#[cfg(not(target_arch = "wasm32"))]
impl BlurFixture {
fn new(srgb: bool, policy: crate::blur::FixturePolicy) -> Option<Self> {
use super::*;
let Some((adapter, device, queue)) = offscreen_device() else {
assert!(std::env::var_os("SOLIDCRAFT_REQUIRE_GPU").is_none(), "GPU adapter required for blur fixture");
eprintln!("skipped blur fixture: no admitted adapter/device");
return None;
};
let format = if srgb { wgpu::TextureFormat::Rgba8UnormSrgb } else { wgpu::TextureFormat::Rgba8Unorm };
let renderer = Arc::new(egui::epaint::mutex::RwLock::new(egui_wgpu::Renderer::new(&device, format, Default::default())));
let mut app = crate::test_support::app_with_script(serde_json::json!({"commands":[
{"command":"solid.box", "params":{"length":40,"width":30,"height":25}}
]}));
app.home.open = false;
app.preferences.ambient_occlusion = false;
app.cpu_meshing = true;
app.cam.distance = 110.0;
app.cam.target = solidcraft_engine::geom::Vec3::new(20.0, 15.0, 12.5);
let window = GpuTarget { format, depth: None, samples: 1, tess: false, oit: false };
let scene = GpuTarget { depth: Some(solidcraft_gpu::depth_format(&device, true)), ..window };
let view = Renderer::with_window_target(&device, scene, window, None);
app.viewport.gpu = Some(view.target());
app.viewport.draw_stats = Some(view.stats());
renderer.write().callback_resources.insert(view);
app.blur = crate::blur::fixture_state(&adapter, &device, &queue, &renderer, format, policy);
if policy == crate::blur::FixturePolicy::Rendering {
assert_eq!(app.blur.capability(), crate::blur::Capability::Available, "blur fixture requires real rendering capabilities");
}
let size = [800, 600];
let output = device.create_texture(&wgpu::TextureDescriptor {
label: Some("full egui fixture"),
size: wgpu::Extent3d { width: size[0], height: size[1], depth_or_array_layers: 1 },
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
});
let ctx = crate::fonts::test_context();
Some(Self {
app,
ctx,
renderer,
adapter,
device,
queue,
output,
size,
jobs: 0,
root_transform: egui::emath::TSTransform::IDENTITY,
root_layer: None,
})
}
fn frame(&mut self) -> f64 {
use super::*;
let started = std::time::Instant::now();
// Keep local layout/input stationary, then transform only after emission.
if let Some(layer) = self.root_layer {
self.ctx.set_transform_layer(layer, egui::emath::TSTransform::IDENTITY);
}
let raw = egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(self.size[0] as f32, self.size[1] as f32))),
time: Some(1.0),
focused: true,
..Default::default()
};
let app = &mut self.app;
let transform = self.root_transform;
let mut root_layer = None;
let mut out = self.ctx.run_ui(raw, |ui| {
root_layer = Some(ui.layer_id());
app.logic(ui.ctx());
app.ui(ui);
ui.ctx().set_transform_layer(ui.layer_id(), transform);
});
self.root_layer = root_layer;
let jobs = self.ctx.tessellate(out.shapes, out.pixels_per_point);
self.jobs = jobs.len();
let screen = egui_wgpu::ScreenDescriptor { size_in_pixels: self.size, pixels_per_point: out.pixels_per_point };
let mut encoder = self.device.create_command_encoder(&Default::default());
let mut renderer = self.renderer.write();
for (id, deltas) in out.textures_delta.set.drain() {
for delta in deltas {
renderer.update_texture(&self.device, &self.queue, id, &delta);
}
}
if let Some(effect) = &renderer.frame_compositor {
effect.begin_viewport(egui::ViewportId::ROOT.0.value());
}
let extra = renderer.update_buffers(&self.device, &self.queue, &mut encoder, &jobs, &screen);
let target = self.output.create_view(&Default::default());
let composed = renderer
.frame_compositor
.as_ref()
.is_some_and(|effect| effect.render(&renderer, &mut encoder, &target, &jobs, &screen, [0.0, 0.0, 0.0, 1.0]));
if !composed {
let mut pass = encoder
.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("fixture ordinary UI"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &target,
resolve_target: None,
depth_slice: None,
ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), store: wgpu::StoreOp::Store },
})],
depth_stencil_attachment: None,
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
})
.forget_lifetime();
renderer.render(&mut pass, &jobs, &screen);
}
self.queue.submit(extra.into_iter().chain([encoder.finish()]));
if let Some(effect) = &renderer.frame_compositor {
effect.submitted();
}
for id in out.textures_delta.free.drain() {
renderer.free_texture(&id);
}
drop(renderer);
self.device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
started.elapsed().as_secs_f64() * 1000.0
}
fn pixels(&self, source: bool) -> Vec<u8> {
use super::*;
let texture = if source { self.app.blur.source_texture().unwrap() } else { self.output.clone() };
let size = texture.size();
let stride = (size.width * 4).div_ceil(256) * 256;
let read = self.device.create_buffer(&wgpu::BufferDescriptor {
label: Some("full egui readback"),
size: u64::from(stride) * u64::from(size.height),
usage: wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ,
mapped_at_creation: false,
});
let mut encoder = self.device.create_command_encoder(&Default::default());
encoder.copy_texture_to_buffer(
texture.as_image_copy(),
wgpu::TexelCopyBufferInfo {
buffer: &read,
layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(stride), rows_per_image: Some(size.height) },
},
size,
);
self.queue.submit([encoder.finish()]);
let slice = read.slice(..);
slice.map_async(wgpu::MapMode::Read, |_| {});
self.device.poll(wgpu::PollType::wait_indefinitely()).unwrap();
let bytes = slice.get_mapped_range().unwrap();
bytes.chunks_exact(stride as usize).flat_map(|row| row[..size.width as usize * 4].iter().copied()).collect()
}
fn evidence(&self, name: &str) {
let directory = std::env::var_os("SOLIDCRAFT_BLUR_EVIDENCE");
let goldens = std::env::var_os("SOLIDCRAFT_BLUR_GOLDENS");
if directory.is_none() && goldens.is_none() {
return;
}
let image = image::RgbaImage::from_raw(self.size[0], self.size[1], self.pixels(false)).unwrap();
if let Some(dir) = directory {
let path = std::path::PathBuf::from(dir);
std::fs::create_dir_all(&path).unwrap();
image.save(path.join(format!("{name}.png"))).unwrap();
std::fs::write(path.join(format!("{name}-counters.json")), serde_json::to_vec_pretty(&self.app.blur.counters()).unwrap()).unwrap();
}
if let Some(goldens) = goldens {
let expected = image::open(std::path::PathBuf::from(goldens).join(format!("{name}.png"))).unwrap().to_rgba8();
assert_eq!(image.as_raw(), expected.as_raw(), "golden {name}");
}
}
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn blur_production_policy_rejects_software_adapter() {
use crate::blur::{Capability, FixturePolicy};
let Some(mut f) = BlurFixture::new(false, FixturePolicy::Production) else { return };
if solidcraft_gpu::select::tier_of(f.adapter.get_info().device_type) != solidcraft_gpu::select::Tier::Software {
eprintln!("skipped software policy assertion: selected adapter is not software");
return;
}
let unavailable = Capability::Unavailable("software adapter (gpu-software)");
assert_eq!(f.app.blur.capability(), unavailable);
f.app.blur.set_radius(18.0).unwrap();
for _ in 0..6 {
f.frame();
}
assert_eq!(f.app.blur.capability(), unavailable);
let counts = f.app.blur.counters();
assert_eq!((counts.textures_created, counts.buffers_created, counts.bind_groups_created, counts.pipelines_created), (0, 0, 0, 0));
assert_eq!((counts.markers_emitted, counts.markers_drawn), (0, 0));
assert_eq!(counts.live_bytes, 0);
assert!(f.app.blur.source_texture().is_none());
assert!(f.renderer.read().frame_compositor.is_none());
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn blur_full_egui_composition() {
for srgb in [false, true] {
let Some(mut f) = BlurFixture::new(srgb, crate::blur::FixturePolicy::Rendering) else { return };
for _ in 0..6 {
f.frame();
}
assert_eq!(f.app.blur.capability(), crate::blur::Capability::Available);
let plain = f.pixels(false);
let plain_jobs = f.jobs;
let original_camera = f.app.cam;
let original_background = f.app.preferences.viewport_background;
let original_theme = f.app.preferences.theme.clone();
let original_dark = f.app.ui.dark;
assert_eq!(f.app.blur.counters().textures_created, 0);
for dark in [false, true] {
f.app.preferences.theme = if dark { "dark" } else { "light" }.into();
f.app.ui.dark = dark;
f.app.blur.set_surface_alpha(Some(180));
f.app.cam = original_camera;
f.app.preferences.viewport_background = original_background;
f.app.blur.set_radius(0.0).unwrap();
for _ in 0..3 {
f.frame();
}
// The zero reference uses the same camera, view settings and panel alpha.
let zero_reference = f.pixels(false);
f.frame();
assert_eq!(zero_reference, f.pixels(false), "stable zero reference");
f.evidence(&format!("blur-{}-0-{}", if dark { "dark" } else { "light" }, if srgb { "srgb" } else { "unorm" }));
for radius in [8.0, 18.0, 40.0] {
f.app.cam = original_camera;
f.app.preferences.viewport_background = original_background;
f.app.blur.set_radius(radius).unwrap();
for _ in 0..3 {
f.frame();
}
let before = f.app.blur.counters();
let source = f.pixels(true);
f.frame();
let after = f.app.blur.counters();
assert_eq!(before.source_passes, after.source_passes, "resting source");
assert_eq!(before.blur_passes, after.blur_passes, "resting chain");
assert!(after.cache_hits > before.cache_hits);
assert!(after.markers_drawn > before.markers_drawn);
assert_eq!(f.pixels(true), source);
// Change panels only: the immutable source must be byte-identical.
f.app.blur.set_surface_alpha(Some(120));
f.frame();
assert_eq!(f.pixels(true), source);
assert_eq!(f.app.blur.counters().source_passes, after.source_passes);
f.app.blur.set_surface_alpha(Some(180));
f.frame();
let positive = f.pixels(false);
let changed_pixels = zero_reference
.as_chunks::<4>()
.0
.iter()
.zip(positive.as_chunks::<4>().0.iter())
.filter(|(zero, blurred)| (0..3).any(|channel| zero[channel].abs_diff(blurred[channel]) > 1))
.count();
assert!(changed_pixels > 0, "radius {radius} must change RGB pixels with the same camera, alpha and theme");
let name = format!("blur-{}-{}-{}", if dark { "dark" } else { "light" }, radius as u32, if srgb { "srgb" } else { "unorm" });
f.evidence(&name);
let before = f.app.blur.counters();
f.app.cam.yaw += 0.2;
f.frame();
let after = f.app.blur.counters();
assert_eq!(after.source_passes, before.source_passes + 1);
assert_eq!(after.blur_passes - before.blur_passes, 2 * crate::blur::schedule(radius).unwrap().0 as u64);
f.app.cam = original_camera;
f.frame();
f.app.preferences.viewport_background = Some([3, 37, 93]);
let before = f.app.blur.counters();
f.frame();
let after = f.app.blur.counters();
assert_eq!(after.source_passes, before.source_passes + 1, "background invalidation");
assert_eq!(after.textures_created, before.textures_created, "background changes reuse storage");
f.app.preferences.viewport_background = original_background;
f.frame();
}
f.app.blur.set_radius(0.0).unwrap();
for _ in 0..2 {
f.frame();
}
assert_eq!(zero_reference, f.pixels(false), "on -> off preserves the fixed scene and tint");
}
f.app.blur.set_surface_alpha(None);
f.app.cam = original_camera;
f.app.preferences.theme = original_theme;
f.app.ui.dark = original_dark;
// Compare two stable zero frames after resources are dropped.
for _ in 0..3 {
f.frame();
}
let zero = f.pixels(false);
let before = f.app.blur.counters();
for _ in 0..3 {
f.frame();
}
assert_eq!(zero, f.pixels(false));
assert_eq!(plain, zero, "on -> off restores the original decoded pixels");
assert_eq!(plain_jobs, f.jobs, "plain primitive count is restored");
assert_eq!(before.textures_created, f.app.blur.counters().textures_created);
assert_eq!(before.markers_emitted, f.app.blur.counters().markers_emitted);
assert_eq!(before.source_passes, f.app.blur.counters().source_passes);
assert_eq!(f.app.blur.counters().live_bytes, 0);
assert!(f.renderer.read().frame_compositor.is_none());
assert!(plain.iter().any(|v| *v != 0));
assert!(plain_jobs > 0);
}
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn blur_steady_frame_benchmark() {
let Some(mut f) = BlurFixture::new(false, crate::blur::FixturePolicy::Rendering) else { return };
f.app.blur.set_surface_alpha(Some(180));
let mut rows = Vec::new();
for radius in [0.0, 18.0, 0.0] {
f.app.blur.set_radius(radius).unwrap();
for _ in 0..6 {
f.frame();
}
let before = f.app.blur.counters();
let mut times: Vec<f64> = (0..30).map(|_| f.frame()).collect();
times.sort_by(f64::total_cmp);
let after = f.app.blur.counters();
assert_eq!(after.source_passes, before.source_passes);
assert_eq!(after.blur_passes, before.blur_passes);
rows.push(serde_json::json!({"radius_px":radius, "samples":times.len(), "min_ms":times[0],
"median_ms":(times[14] + times[15]) / 2.0, "max_ms":times[29], "before":before, "after":after}));
}
if let Some(dir) = std::env::var_os("SOLIDCRAFT_BLUR_EVIDENCE") {
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(std::path::PathBuf::from(dir).join("fixture-frame-timings.json"), serde_json::to_vec_pretty(&rows).unwrap()).unwrap();
}
eprintln!("full egui UI/encode/GPU-completion milliseconds: {rows:?}");
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn blur_suspend_releases_targets() {
let Some(mut f) = BlurFixture::new(false, crate::blur::FixturePolicy::Rendering) else { return };
f.app.blur.set_surface_alpha(Some(180));
f.app.blur.set_radius(18.0).unwrap();
for _ in 0..3 {
f.frame();
}
assert!(f.app.blur.counters().live_textures > 0);
f.renderer.read().frame_compositor.as_ref().unwrap().suspend();
assert_eq!(f.app.blur.counters().live_bytes, 0);
f.frame();
assert!(f.app.blur.counters().live_textures > 0);
f.app.blur.set_radius(0.0).unwrap();
assert_eq!(f.app.blur.counters().live_textures, 0);
assert_eq!(f.app.blur.counters().live_bind_groups, 0);
assert_eq!(f.app.blur.counters().live_pipelines, 0);
assert_eq!(f.app.blur.counters().live_buffers, 0);
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn blur_late_layer_transform_moves_source_and_invalidates_cache() {
let Some(mut f) = BlurFixture::new(false, crate::blur::FixturePolicy::Rendering) else { return };
f.app.blur.set_radius(18.0).unwrap();
f.app.blur.set_surface_alpha(Some(180));
for _ in 0..6 {
f.frame();
}
let local = f.app.blur.source_geometry().unwrap();
let before = f.app.blur.counters();
let original = f.pixels(true);
let x = (local[2].right() - 4.0).clamp(0.0, (f.size[0] - 1) as f32) as usize;
let y = local[2].center().y.clamp(0.0, (f.size[1] - 1) as f32) as usize;
let offset = (y * f.size[0] as usize + x) * 4;
let outside = crate::theme::Tokens::get().app_bar.to_array();
assert_ne!(&original[offset..offset + 4], &outside, "probe starts in the viewport background");
// Same local geometry/camera; applied after app.ui has emitted the callback.
let transform = egui::emath::TSTransform { translation: egui::vec2(-23.0, 17.0), scaling: 0.75 };
f.root_transform = transform;
f.frame();
assert_eq!(f.app.blur.source_geometry().unwrap(), local.map(|r| transform.mul_rect(r)), "viewport, clip and background all transform once");
let after = f.app.blur.counters();
assert_eq!(after.source_passes, before.source_passes + 1);
assert_eq!(after.blur_passes, before.blur_passes + 6);
assert_eq!(after.textures_created, before.textures_created, "placement changes reuse storage");
assert_eq!(&f.pixels(true)[offset..offset + 4], &outside, "old location is outside the transformed clip");
f.frame();
assert_eq!(f.app.blur.counters().source_passes, after.source_passes, "unchanged transformed placement is cached");
assert_eq!(f.app.blur.counters().blur_passes, after.blur_passes);
// A forced miss must still paint at the transformed location, not merely hash it.
f.app.cam.yaw += 0.1;
f.frame();
assert_eq!(f.app.blur.counters().source_passes, after.source_passes + 1);
assert_eq!(&f.pixels(true)[offset..offset + 4], &outside);
}
/// Bodies are drawn from their plans on the GPU from the frame the evaluation shader has
/// compiled, and built on the CPU until then (#4860).
#[cfg(not(target_arch = "wasm32"))]
+6
View File
@@ -14,6 +14,7 @@ pub mod agent_chat;
pub mod agent_cursor;
pub mod ai_connect;
pub mod bidi;
pub mod blur;
pub mod bom_panel;
pub mod browser;
pub mod browser_canvas;
@@ -505,6 +506,7 @@ pub(crate) enum EscapeOwner {
}
pub struct SolveApp {
pub blur: blur::State,
pub(crate) viewport_status: ui_kit::StatusPresentation,
pub(crate) viewport_status_fixture: viewport_status_fixture::Fixture,
/// Compact browser embed: retain model panels and joint controls without application chrome.
@@ -776,6 +778,7 @@ impl SolveApp {
solidcraft_engine::slicer_files::clean_old();
let mut app = SolveApp {
viewport_status: Default::default(),
blur: Default::default(),
viewport_status_fixture: Default::default(),
session,
ui: UiState::default(),
@@ -950,6 +953,7 @@ impl SolveApp {
}
fn set_wgpu_targets(&mut self, rs: &egui_wgpu::RenderState, scene: crate::gpu::GpuTarget, window: crate::gpu::GpuTarget) {
self.blur.install(rs, scene.depth.is_some() && window.depth.is_none() && window.samples == 1);
#[allow(unused_mut)] // Only native hosts can wait for the startup readback.
let (mut installed, stats, tess_ready) = gpu::install(rs, scene, window, !self.cpu_meshing);
#[cfg(not(target_arch = "wasm32"))]
@@ -2863,6 +2867,8 @@ impl SolveApp {
/// Lay out the whole window.
pub fn ui(&mut self, ui: &mut egui::Ui) {
let blur_source = !self.home.open && !render_workspace::result_active(self);
let _blur_scope = self.blur.begin(ui.ctx(), blur_source);
value_step::set_enabled(ui.ctx(), self.preferences.step_values);
canvas::set_boxes_shown(ui.ctx(), self.preferences.value_boxes_in_view);
recent_colors::share(ui.ctx(), &mut self.ui.recent_colors);
+3 -2
View File
@@ -2019,7 +2019,8 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
} else {
app.viewport.hover = None;
}
crate::gpu::paint_background(ui.painter(), viewport, &preview_background(app));
let background = preview_background(app);
crate::gpu::paint_background(ui.painter(), viewport, &background);
let result = (|| -> Result<(), String> {
if app.viewport.gpu.is_none() {
return Err(crate::i18n::tr("render.error_gpu_preview").into());
@@ -2124,7 +2125,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
[f32::from(c.r()) / 255.0, f32::from(c.g()) / 255.0, f32::from(c.b()) / 255.0]
},
});
ui.painter().add(egui_wgpu::Callback::new_paint_callback(rect, callback));
crate::blur::viewport(ui.painter(), rect, callback, viewport, [background.viewport_top, background.viewport_bottom]);
Ok(())
})();
if let Err(error) = result {
+10 -9
View File
@@ -668,18 +668,19 @@ pub fn timeline(app: &mut SolveApp, ui: &mut egui::Ui) {
app.shell.history = Some(rect);
crate::scenario::publish_rect("history:card", rect);
let mut child = ui.new_child(UiBuilder::new().id_salt("sc_timeline").max_rect(rect));
Container::paint_frame(ui.painter(), Container::new(ui.ctx(), Surface::Panel).frame(ui.ctx(), t.timeline, crate::frame::Side::Left), rect);
Container::paint_panel_frame(
ui.painter(),
Container::new(ui.ctx(), Surface::Panel).frame(ui.ctx(), t.timeline, crate::frame::Side::Left),
rect,
);
child.set_clip_rect(rect);
timeline_contents(app, &mut child, true);
} else {
let response = Container::new(ui.ctx(), Surface::Panel)
.edge("sc_timeline", Edge::Bottom)
.exact_size(40.0)
.frame(Container::new(ui.ctx(), Surface::Panel).edge_frame(t.timeline))
.show(ui, |ui| {
timeline_contents(app, ui, false);
});
let frame = Container::new(ui.ctx(), Surface::Panel).edge_frame(t.timeline);
let host = Container::new(ui.ctx(), Surface::Panel);
let response = host.show_edge(ui, host.edge("sc_timeline", Edge::Bottom).exact_size(40.0), host.edge_frame(t.timeline), |ui| {
timeline_contents(app, ui, false);
});
let frame = host.edge_frame(t.timeline);
Container::paint_inset(ui.painter(), response.response.rect - frame.outer_margin, frame);
app.shell.history = Some(response.response.rect);
crate::scenario::publish_rect("history:strip", response.response.rect);
+8 -7
View File
@@ -268,16 +268,17 @@ pub fn left_panel(app: &mut SolveApp, ui: &mut egui::Ui) {
return;
}
// Held by a dialog, the docked panel stays allocated but empty, so the view keeps its size.
let response = Container::new(ui.ctx(), Surface::Panel)
.edge("sc_timeline_left", Edge::Left)
.exact_size(width)
.resizable(false)
.frame(Container::new(ui.ctx(), Surface::Panel).edge_frame(t.panel).inner_margin(t.space_4))
.show(ui, |ui| {
let host = Container::new(ui.ctx(), Surface::Panel);
let response = host.show_edge(
ui,
host.edge("sc_timeline_left", Edge::Left).exact_size(width).resizable(false),
host.edge_frame(t.panel).inner_margin(t.space_4),
|ui| {
if !held {
left_timeline(app, ui);
}
});
},
);
app.shell.history = Some(response.response.rect);
if !held {
crate::scenario::publish_rect("history:vertical", response.response.rect);
+2 -2
View File
@@ -1362,7 +1362,7 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) {
let host = Container::for_layout(layout, Surface::Chrome);
let ribbon = host.edge("sc_toolbar", Edge::Top);
let frame = host.edge_frame(fill);
let chrome = ribbon.exact_size(height).show_separator_line(false).frame(frame).show(ui, |ui| {
let chrome = host.show_edge(ui, ribbon.exact_size(height).show_separator_line(false), frame, |ui| {
let r = if floating { Rect::from_min_max(cards.workspace.min, cards.ribbon.max) } else { frame.outer_rect(ui.max_rect()) };
let ws = if floating { cards.workspace } else { Rect::from_min_size(r.left_top(), vec2(WORKSPACE_WIDTH, ribbon_height - 1.0)) };
let ribbon_left = if floating { cards.ribbon.left() } else { ws.right() };
@@ -1371,7 +1371,7 @@ pub fn toolbar(app: &mut SolveApp, ui: &mut egui::Ui) {
let fill =
if crate::render_workspace::active(app) && card == ws { crate::theme::TabAccent::current(ui.ctx()).soft } else { t.toolbar };
let frame = host.frame(ui.ctx(), fill, crate::frame::Side::Left);
ui.painter().add(frame.paint(card));
host.paint_background(ui.painter(), frame, card);
// Blank card space owns clicks as well as its buttons.
ui.interact(card, ui.id().with(("shell_card", card.left().to_bits())), Sense::click_and_drag());
}
+146
View File
@@ -5,6 +5,70 @@ use crate::frame::Side;
use crate::{shell::LayoutMode, theme::Tokens};
use egui::{Color32, Context, Frame, Id, Stroke, WidgetText};
pub(super) type Background = fn(&egui::Painter, Frame, egui::Rect, egui::Shape) -> egui::Shape;
/// The feature sheet's deliberately restricted stock Window (no title, scrolling or fades).
/// Keep its builder private: the marker's layer and host clip are owned here.
pub(crate) struct FeatureWindow<'a> {
window: egui::Window<'a>,
id: Id,
frame: Frame,
}
impl<'a> FeatureWindow<'a> {
pub(super) fn new(window: egui::Window<'a>, id: Id, frame: Frame) -> Self {
Self { window, id, frame }
}
pub(crate) fn fixed_size(mut self, size: egui::Vec2) -> Self {
self.window = self.window.fixed_size(size);
self
}
/// Borrow a caller's open flag only for this showing, retaining stock close handling.
pub(crate) fn open<'open>(self, open: &'open mut bool) -> FeatureWindow<'open>
where
'a: 'open,
{
let window: egui::Window<'open> = self.window;
FeatureWindow { window: window.open(open), id: self.id, frame: self.frame }
}
pub(crate) fn show<R>(self, ctx: &Context, body: impl FnOnce(&mut egui::Ui) -> R) -> Option<egui::InnerResponse<Option<R>>> {
let background = Container::floating_card(Surface::Feature).background(ctx, self.frame);
self.show_background(ctx, background, body)
}
pub(super) fn show_background<R>(
self,
ctx: &Context,
background: Option<Background>,
body: impl FnOnce(&mut egui::Ui) -> R,
) -> Option<egui::InnerResponse<Option<R>>> {
let Some(background) = background else { return self.window.show(ctx, body) };
let painter = ctx.layer_painter(egui::LayerId::new(egui::Order::Middle, self.id));
let slot = painter.add(egui::Shape::Noop);
let mut host_painter = None;
let shown = self.window.show(ctx, |ui| {
// Resize's content clip omits the frame border/padding. This bounded Window
// uses Area's default viewport clip, with no fades or native title bar.
let mut painter = ui.painter().clone();
painter.set_clip_rect(ctx.content_rect());
host_painter = Some(painter);
body(ui)
});
if let (Some(shown), Some(painter)) = (&shown, host_painter) {
// Window relocates inner_margin into an internal content Frame. Its final
// Area response still includes all margins and the original stroke width.
let content = shown.response.rect - self.frame.total_margin();
if painter.is_visible() && painter.clip_rect().intersects(self.frame.widget_rect(content)) {
painter.set(slot, background(&painter, self.frame, content, egui::Shape::Noop));
}
}
shown
}
}
/// Persistent panels adapt to the layout; transient UI retains its anchoring and modality.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Surface {
@@ -187,6 +251,7 @@ impl Container {
/// Tokenised outer chrome. Callers may supply content padding, not another card surface.
pub fn frame(self, ctx: &Context, fill: Color32, side: crate::frame::Side) -> Frame {
let fill = if self.adaptive() { crate::blur::panel_fill(fill) } else { fill };
let t = Tokens::get();
let flat = Frame::NONE.fill(fill);
match self.surface {
@@ -220,6 +285,7 @@ impl Container {
/// Surface of an allocated dock or internal pinned band. Floating card decoration is
/// supplied by `frame`; edge-hosted panes must not acquire outer shadows or card gaps.
pub fn edge_frame(self, fill: Color32) -> Frame {
let fill = if self.adaptive() { crate::blur::panel_fill(fill) } else { fill };
if self.adaptive() && !self.floating() {
Self::compact_frame(fill, Tokens::get().primary_border(Tokens::get().border), self.joined.unwrap_or(DockEdges::ALL))
} else {
@@ -261,6 +327,28 @@ impl Container {
bounds: egui::Rect,
body: impl FnOnce(&mut egui::Ui) -> R,
) -> egui::InnerResponse<R> {
let background = self.background(ui.ctx(), frame);
self.show_frame_background(ui, frame, bounds, background, body)
}
fn background(self, ctx: &Context, frame: Frame) -> Option<Background> {
// Keep the off path to boundary checks only: no painter, shape slot or allocation.
if self.adaptive() && crate::blur::enabled() && ctx.viewport_id() == egui::ViewportId::ROOT && (1..255).contains(&frame.fill.a()) {
Some(crate::blur::decorate)
} else {
None
}
}
pub(super) fn show_frame_background<R>(
self,
ui: &mut egui::Ui,
frame: Frame,
bounds: egui::Rect,
background: Option<Background>,
body: impl FnOnce(&mut egui::Ui) -> R,
) -> egui::InnerResponse<R> {
let slot = background.map(|_| ui.painter().add(egui::Shape::Noop));
let mut prepared = frame.begin(ui);
let inner = body(&mut prepared.content_ui);
if self.adaptive() && !self.floating() {
@@ -273,6 +361,12 @@ impl Container {
prepared.frame.corner_radius = Self::compact_rounding(edges);
}
let frame = prepared.frame;
if let (Some(background), Some(slot)) = (background, slot)
&& ui.is_rect_visible(frame.widget_rect(prepared.content_ui.min_rect()))
{
let painter = ui.painter();
painter.set(slot, background(painter, frame, prepared.content_ui.min_rect(), egui::Shape::Noop));
}
let response = prepared.end(ui);
Self::paint_inset(ui.painter(), response.rect - frame.outer_margin, frame);
egui::InnerResponse { inner, response }
@@ -315,6 +409,17 @@ impl Container {
Self::paint_inset(painter, frame.widget_rect(content), frame);
}
/// Semantic manually painted workspace surface; HUDs keep `paint_frame`.
pub(crate) fn paint_background(self, painter: &egui::Painter, frame: Frame, content: egui::Rect) {
let shape = frame.paint(content);
painter.add(if self.adaptive() && crate::blur::enabled() { crate::blur::decorate(painter, frame, content, shape) } else { shape });
}
pub(crate) fn paint_panel_frame(painter: &egui::Painter, frame: Frame, content: egui::Rect) {
Self::floating_card(Surface::Panel).paint_background(painter, frame, content);
Self::paint_inset(painter, frame.widget_rect(content), frame);
}
/// Decorate the content-hugging frame of a popup or feature sheet after its contents.
pub(crate) fn finish_content(ui: &egui::Ui, frame: Frame) {
Self::paint_inset(ui.painter(), frame.widget_rect(ui.min_rect()), frame);
@@ -340,6 +445,47 @@ impl Container {
if self.adaptive() && !self.floating() { panel.show_separator_line(false) } else { panel }
}
/// Stock Panel owns layout, persistence, interaction and its unmodified semantic Frame.
/// Only ordinary `show` is exposed; animated hosts need their own clip contract.
pub(crate) fn show_edge<R>(
self,
ui: &mut egui::Ui,
panel: egui::Panel,
frame: Frame,
body: impl FnOnce(&mut egui::Ui) -> R,
) -> egui::InnerResponse<R> {
let background = self.background(ui.ctx(), frame);
Self::show_edge_background(ui, panel, frame, background, body)
}
pub(super) fn show_edge_background<R>(
ui: &mut egui::Ui,
panel: egui::Panel,
frame: Frame,
background: Option<Background>,
body: impl FnOnce(&mut egui::Ui) -> R,
) -> egui::InnerResponse<R> {
let Some(background) = background else { return panel.frame(frame).show(ui, body) };
let slot = ui.painter().add(egui::Shape::Noop);
let mut host = None;
let shown = panel.frame(frame).show(ui, |ui| {
// Capture before the body can narrow the clip or change opacity. Frame adds
// no content clip, so this is the host/slide clip including its padding.
let painter = ui.painter().clone();
let inner = body(ui);
host = Some((painter, ui.min_rect()));
inner
});
if let Some((painter, content)) = host
&& painter.is_visible()
&& painter.clip_rect().intersects(frame.widget_rect(content))
{
// min_rect is the actual Frame content, even if Panel clamps its response.
painter.set(slot, background(&painter, frame, content, egui::Shape::Noop));
}
shown
}
pub(super) fn window<'a>(self, title: impl Into<WidgetText>) -> egui::Window<'a> {
egui::Window::new(title).enabled(self.input_enabled())
}
+6 -5
View File
@@ -670,18 +670,18 @@ impl<'a> Panel<'a> {
self.joined.map_or(container, |edges| container.joined(edges)).tool_frame(self.frame, right >= self.viewport.right() - 0.5)
}
pub(crate) fn window(&self, ctx: &egui::Context) -> egui::Window<'a> {
pub(crate) fn window(&self, ctx: &egui::Context) -> super::container::FeatureWindow<'a> {
self.window_placed(ctx, None)
}
/// The same window for contents the caller holds to `size` (egui's `fixed_size`); the card
/// is that plus its frame.
pub(crate) fn fixed_window(&self, ctx: &egui::Context, size: egui::Vec2) -> egui::Window<'a> {
pub(crate) fn fixed_window(&self, ctx: &egui::Context, size: egui::Vec2) -> super::container::FeatureWindow<'a> {
let outer = size.x + self.positioned_frame(ctx).total_margin().sum().x;
self.window_placed(ctx, Some(outer)).fixed_size(size)
}
fn window_placed(&self, ctx: &egui::Context, outer_width: Option<f32>) -> egui::Window<'a> {
fn window_placed(&self, ctx: &egui::Context, outer_width: Option<f32>) -> super::container::FeatureWindow<'a> {
let gap = super::Container::new(ctx, super::Surface::Feature).gap();
let viewport = self.viewport;
let anchor = self.bounded_anchor(ctx);
@@ -701,7 +701,7 @@ impl<'a> Panel<'a> {
};
// Keep drawing safe when even the header/footer cannot fit. egui clips the contents to
// the remaining viewport; the normal small-height case still keeps both actions visible.
super::Container::new(ctx, super::Surface::Feature)
let window = super::Container::new(ctx, super::Surface::Feature)
.window(self.title)
.id(self.id)
.title_bar(false)
@@ -720,7 +720,8 @@ impl<'a> Panel<'a> {
.default_height(0.0)
.fade_in(false)
.fade_out(false)
.order(egui::Order::Middle)
.order(egui::Order::Middle);
super::container::FeatureWindow::new(window, self.id, frame)
}
/// Feature header, scrolling padded body, pinned actions, drag target and compute status.
+322
View File
@@ -4,6 +4,328 @@ use crate::ui_kit::*;
use crate::{scenario, theme::Tokens};
use egui::Ui;
#[derive(Clone, Copy, Debug)]
enum BlurHost {
Frame,
Edge(Edge),
Window,
}
const BLUR_HOSTS: [BlurHost; 6] = [
BlurHost::Frame,
BlurHost::Edge(Edge::Left),
BlurHost::Edge(Edge::Right),
BlurHost::Edge(Edge::Top),
BlurHost::Edge(Edge::Bottom),
BlurHost::Window,
];
struct HostMarker {
frame: egui::Frame,
opacity: f32,
}
fn host_marker(painter: &egui::Painter, frame: egui::Frame, content: egui::Rect, ordinary: egui::Shape) -> egui::Shape {
egui::Shape::Vec(vec![
egui::Shape::Callback(egui::PaintCallback {
rect: frame.widget_rect(content),
callback: std::sync::Arc::new(HostMarker { frame, opacity: painter.opacity() }),
}),
ordinary,
])
}
/// Compare the actual stock hosts against the app helpers without requiring a GPU.
/// mode: 0 = stock, 1 = production zero path, 2 = injected positive marker.
fn blur_host_fixture(host: BlurHost, mode: u8, position: egui::Pos2, transform: egui::emath::TSTransform) -> (egui::FullOutput, String) {
let ctx = crate::fonts::test_context();
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(640.0, 480.0));
let container = Container::for_layout(crate::shell::LayoutMode::Floating, Surface::Feature);
let frame = container
.frame(&ctx, egui::Color32::from_rgba_unmultiplied(40, 80, 100, 180), crate::frame::Side::Left)
.stroke(egui::Stroke::new(2.5, egui::Color32::WHITE))
.inner_margin(egui::Margin { left: 9, right: 13, top: 7, bottom: 11 })
.outer_margin(egui::Margin { left: -2, right: 3, top: -1, bottom: 4 })
.corner_radius(egui::CornerRadius { nw: 3, ne: 7, sw: 11, se: 15 });
let id = egui::Id::new("stock host fixture");
let mut output = egui::FullOutput::default();
let mut observation = String::new();
for _ in 0..3 {
output = crate::test_support::frame(&ctx, egui::RawInput { screen_rect: Some(screen), ..Default::default() }, |ui| {
ui.multiply_opacity(0.75);
let mut body = |ui: &mut egui::Ui| {
let stack: Vec<_> = ui.stack().iter().map(|node| (node.id, node.kind(), *node.frame())).collect();
let semantic = format!("{:?}", (ui.id(), ui.max_rect(), ui.clip_rect(), ui.stack().bg_color(), stack));
ui.allocate_space(egui::vec2(83.0, 47.0));
let response = ui.button("Content stays above its frame");
// A child changing its content clip must not cut the host's padding/border.
ui.set_clip_rect(ui.clip_rect().shrink(6.0));
observation = format!("{semantic} {:?}", (response.id, response.rect, ui.min_rect()));
};
let background: Option<container::Background> = (mode == 2).then_some(host_marker);
let response = match host {
BlurHost::Frame => {
if mode == 0 {
let shown = frame.show(ui, &mut body);
Container::paint_inset(ui.painter(), shown.response.rect - frame.outer_margin, frame);
shown.response
} else if mode == 1 {
container.show_frame(ui, frame, screen, &mut body).response
} else {
container.show_frame_background(ui, frame, screen, background, &mut body).response
}
}
BlurHost::Edge(edge) => {
let panel = container.edge(id, edge).exact_size(170.0).resizable(false);
if mode == 0 {
panel.frame(frame).show(ui, &mut body).response
} else if mode == 1 {
container.show_edge(ui, panel, frame, &mut body).response
} else {
Container::show_edge_background(ui, panel, frame, background, &mut body).response
}
}
BlurHost::Window => {
let window = container
.window("Stock host fixture")
.id(id)
.title_bar(false)
.collapsible(false)
.resizable(false)
.scroll(false)
.fade_in(false)
.fade_out(false)
.constrain(false)
.fixed_pos(position)
.frame(frame);
if mode == 0 {
window.show(&ctx, &mut body).unwrap().response
} else {
let window = container::FeatureWindow::new(window, id, frame);
if mode == 1 { window.show(&ctx, &mut body) } else { window.show_background(&ctx, background, &mut body) }.unwrap().response
}
}
};
observation.push_str(&format!(" {:?}", (response.id, response.rect)));
let layer = if matches!(host, BlurHost::Window) { egui::LayerId::new(egui::Order::Middle, id) } else { ui.layer_id() };
ctx.set_transform_layer(layer, transform);
});
}
(output, observation)
}
fn blur_host_shapes(output: &egui::FullOutput, omit_markers: bool) -> Vec<String> {
let mut shapes = Vec::new();
for clipped in &output.shapes {
crate::test_support::each_shape(&clipped.shape, &mut |shape| {
if omit_markers && (matches!(shape, egui::Shape::Noop) || matches!(shape, egui::Shape::Callback(cb) if cb.callback.is::<HostMarker>())) {
return;
}
shapes.push(format!("{:?} {shape:?}", clipped.clip_rect));
});
}
shapes
}
#[test]
fn blur_stock_hosts_zero_has_identical_shapes_noops_geometry_and_ids() {
for host in BLUR_HOSTS {
let (stock, semantics) = blur_host_fixture(host, 0, egui::pos2(30.0, 35.0), egui::emath::TSTransform::IDENTITY);
let (off, off_semantics) = blur_host_fixture(host, 1, egui::pos2(30.0, 35.0), egui::emath::TSTransform::IDENTITY);
assert_eq!(semantics, off_semantics, "{host:?}");
assert_eq!(blur_host_shapes(&stock, false), blur_host_shapes(&off, false), "no extra shapes, including Noop slots: {host:?}");
}
}
#[test]
fn blur_stock_window_open_flag_preserves_closed_close_and_reopen_behavior() {
fn record(mode: u8, omit_markers: bool) -> Vec<(Vec<String>, String)> {
let ctx = crate::fonts::test_context();
let container = Container::for_layout(crate::shell::LayoutMode::Floating, Surface::Feature);
let frame = container.frame(&ctx, Tokens::get().dialog_body, crate::frame::Side::Left);
let id = egui::Id::new("open flag fixture");
let mut recorded = Vec::new();
for (index, mut keep) in [false, false, true, true, true, false, false, false, true, true, true].into_iter().enumerate() {
let mut observation = String::new();
let mut called = false;
let output = crate::test_support::frame(&ctx, egui::RawInput { time: Some(index as f64), ..Default::default() }, |_| {
let window = container
.window("Open flag fixture")
.id(id)
.title_bar(false)
.collapsible(false)
.resizable(false)
.scroll(false)
.fade_in(false)
.fade_out(false)
.frame(frame);
let mut body = |ui: &mut egui::Ui| {
called = true;
ui.label("Window body");
if index == 4 {
// Window contains a closable Collapsible even with title/collapse
// controls disabled. Target the Window, not that nearer ancestor.
ui.close_kind(egui::UiKind::Window);
}
};
let shown = if mode == 0 {
window.open(&mut keep).show(&ctx, &mut body)
} else {
// A long-lived builder must accept this frame-local mutable borrow.
let window: container::FeatureWindow<'static> = container::FeatureWindow::new(window, id, frame);
let window = window.open(&mut keep);
if mode == 1 { window.show(&ctx, &mut body) } else { window.show_background(&ctx, Some(host_marker), &mut body) }
};
if index == 0 || index == 7 {
assert!(shown.is_none(), "initially closed and settled closed windows stay hidden");
}
if index == 4 {
assert!(shown.as_ref().is_some_and(|shown| shown.response.should_close()), "the Window response carries the close request");
}
observation = format!("{:?}", (keep, shown.map(|shown| (shown.response.id, shown.response.rect, shown.inner))));
});
if index == 0 || index == 7 {
assert!(!called);
}
if index == 4 {
assert!(!keep, "stock close requests update the caller's flag");
}
if index == 10 {
assert!(called && keep, "the same persistent window can reopen");
}
let mut markers = 0;
for clipped in &output.shapes {
crate::test_support::each_shape(&clipped.shape, &mut |shape| {
if matches!(shape, egui::Shape::Callback(cb) if cb.callback.is::<HostMarker>()) {
markers += 1;
}
});
}
if !called {
assert_eq!(markers, 0, "hidden windows emit no marker");
}
if mode == 2 && index == 10 {
assert_eq!(markers, 1, "reopened windows regain their marker");
}
recorded.push((blur_host_shapes(&output, omit_markers), observation));
}
recorded
}
assert_eq!(record(0, false), record(1, false), "zero keeps stock shapes, including Noop counts and hidden windows");
assert_eq!(record(0, true), record(2, true), "positive markers preserve stock visibility, close handling, geometry and IDs");
}
#[test]
fn blur_stock_hosts_marker_precedes_original_chrome_with_semantics_and_clip_intact() {
for host in BLUR_HOSTS {
let position = egui::pos2(30.0, 35.0);
let (stock, semantics) = blur_host_fixture(host, 0, position, egui::emath::TSTransform::IDENTITY);
let (marked, marked_semantics) = blur_host_fixture(host, 2, position, egui::emath::TSTransform::IDENTITY);
assert_eq!(semantics, marked_semantics, "bg_color, frame metadata, geometry and persistent IDs: {host:?}");
assert_eq!(blur_host_shapes(&stock, true), blur_host_shapes(&marked, true), "original shadow/fill/stroke/content: {host:?}");
let mut marker = None;
let mut fills = 0;
let mut callbacks = 0;
let mut shadows = 0;
for clipped in &marked.shapes {
crate::test_support::each_shape(&clipped.shape, &mut |shape| match shape {
egui::Shape::Callback(cb) if cb.callback.is::<HostMarker>() => {
let info = cb.callback.downcast_ref::<HostMarker>().unwrap();
assert_eq!(info.frame.stroke.width, 2.5);
assert_eq!(info.opacity, if matches!(host, BlurHost::Window) { 1.0 } else { 0.75 });
marker = Some((cb.rect, clipped.clip_rect, info.frame.corner_radius));
callbacks += 1;
}
egui::Shape::Rect(rect) if rect.blur_width > 0.0 => {
assert!(marker.is_some(), "the marker must also precede the original shadow: {host:?}");
shadows += 1;
}
egui::Shape::Rect(rect) if marker.is_some_and(|(r, _, _)| r == rect.rect) => {
let (_, clip, corners) = marker.unwrap();
assert_eq!(rect.corner_radius, corners);
assert_eq!(clip, clipped.clip_rect, "use the outer host clip, including padding/border");
assert!(clip.contains(rect.rect.center()));
fills += 1;
}
_ => {}
});
}
assert_eq!(callbacks, 1, "{host:?}");
assert_eq!(shadows, 1, "{host:?}");
assert_eq!(fills, 1, "marker before the matching original fill: {host:?}");
}
}
#[test]
fn blur_stock_hosts_late_scaled_layers_and_moved_windows_keep_final_geometry() {
let transform = egui::emath::TSTransform { translation: egui::vec2(19.0, -7.0), scaling: 0.75 };
for host in BLUR_HOSTS {
for position in [egui::pos2(30.0, 35.0), egui::pos2(-8.0, 135.0)] {
let (local, _) = blur_host_fixture(host, 2, position, egui::emath::TSTransform::IDENTITY);
let (moved, _) = blur_host_fixture(host, 2, position, transform);
let marker = |output: &egui::FullOutput| {
let mut result = None;
for clipped in &output.shapes {
crate::test_support::each_shape(&clipped.shape, &mut |shape| {
if let egui::Shape::Callback(cb) = shape
&& cb.callback.is::<HostMarker>()
{
result = Some((cb.rect, clipped.clip_rect));
}
});
}
result.unwrap()
};
let (rect, clip) = marker(&local);
let (moved_rect, moved_clip) = marker(&moved);
assert_eq!(moved_rect, transform.mul_rect(rect), "{host:?}");
assert_eq!(moved_clip, transform.mul_rect(clip), "host clipping transforms once: {host:?}");
}
}
}
#[test]
fn blur_stock_frame_marker_uses_final_joined_corner_radii() {
let ctx = crate::fonts::test_context();
let output = crate::test_support::frame(&ctx, egui::RawInput::default(), |ui| {
let host = Container::for_layout(crate::shell::LayoutMode::Docked, Surface::Feature).joined(DockEdges::default());
let frame = host.frame(ui.ctx(), Tokens::get().dialog_body, crate::frame::Side::Left);
let bounds = ui.available_rect_before_wrap();
host.show_frame_background(ui, frame, bounds, Some(host_marker), |ui| {
ui.allocate_space(egui::vec2(90.0, 40.0));
});
});
let mut matched = false;
for clipped in &output.shapes {
crate::test_support::each_shape(&clipped.shape, &mut |shape| {
if let egui::Shape::Callback(cb) = shape
&& let Some(marker) = cb.callback.downcast_ref::<HostMarker>()
{
assert_eq!(marker.frame.corner_radius, egui::CornerRadius { nw: 0, ne: 0, sw: 0, se: Tokens::get().radius_lg });
matched = true;
}
});
}
assert!(matched);
}
#[test]
fn blur_zero_has_no_marker_or_tint_override() {
let mut state = crate::blur::State::default();
state.set_radius(0.0).unwrap();
let ctx = crate::fonts::test_context();
let _scope = state.begin(&ctx, true);
assert!(!crate::blur::enabled());
let fill = egui::Color32::from_rgba_unmultiplied(40, 80, 100, 180);
assert_eq!(crate::blur::panel_fill(fill), fill);
let original = egui::Shape::rect_filled(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(80.0, 40.0)), 9, fill);
let painter = ctx.layer_painter(egui::LayerId::background());
let unchanged = crate::blur::decorate(&painter, egui::Frame::NONE.fill(fill), egui::Rect::NOTHING, original.clone());
assert_eq!(format!("{original:?}"), format!("{unchanged:?}"));
assert_eq!(state.counters().markers_emitted, 0);
assert_eq!(state.counters().textures_created, 0);
}
#[test]
fn checkbox_grid_and_close_header_are_clickable() {
let ctx = crate::fonts::test_context();
+1 -1
View File
@@ -4447,7 +4447,7 @@ pub fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
},
sky: sky_uniform(app.preferences.dark_parts_shading, proj.cam.up),
});
painter.add(egui_wgpu::Callback::new_paint_callback(rect, cb));
crate::blur::viewport(&painter, rect, cb, rect, [t.viewport_top, t.viewport_bottom]);
// The graphics card had no memory for the view's frame (#7296): say once why it looks
// coarser.
if !app.viewport.lowered_noted && app.viewport.draw_stats.as_ref().is_some_and(|s| s.lock().is_ok_and(|s| s.lowered)) {
+341
View File
@@ -0,0 +1,341 @@
# Blur behind panels (#9809)
Implementation note for PR 5 of the #8876 series. Native implementation and
manager-run harnesses are present. No preference, product UI or default changes
are introduced. No build, test, GPU run, screenshot, benchmark or pixel comparison
has been run by this worker. Direct rustfmt is the only executable formatting work.
## Accepted CPU budget
The human decision is: **"Allow measured CPU checks; keep the change small."**
This replaces the spike's proposed static policy propagation and its unresolved
single-check requirement. The implementation has cheap per-host checks, a root
UI scope, and outer GPU preparation/composition/submission checks. It does **not**
claim one check per frame, two total dispatches, or measured zero CPU overhead.
There are no blur branches in `egui_wgpu::Renderer::render`'s primitive loop.
The initial source integration is for the root native viewport. The pass owner
supplies its viewport id before preparation; other native viewports use plain
painting and `capability_for` reports their missing source integration. They
cannot sample the root window's source or retain its pending submission key.
At radius zero, `Container` uses the original frame shape/painting path; no
marker, Arc/Box for a blur callback, metadata vector, blur pipeline, texture,
uniform, binding or extra pass is created. The plain Window/Panel hook delegates
to the original `Frame::show` path, including its existing content boxing. A
previously enabled effect is detached and its CPU/GPU storage dropped on zero;
wgpu retains any in-flight references until their submitted work completes.
Existing viewport/MSAA/AO/OIT resources are baseline resources, not blur resources.
An explicit harness tint override intentionally changes ordinary panel fills even
at zero; leave `surface_alpha` null for comparisons against main.
## Actual frame path and insertion points
The pinned dependencies are egui/egui-wgpu/eframe 0.36.2 and wgpu 30.0.1.
eframe and egui remain registry dependencies; only egui-wgpu has local compositor
changes for blur. The egui dependency is the published 0.36.2 crate.
| Stage | Actual path |
| --- | --- |
| Build UI | Native `eframe::App::ui` calls `SolveApp::ui` (`crates/ui-egui/src/lib.rs`). `blur::State::begin` installs a stack-scoped thread-local host policy. `cad_ui` draws the workspace under floating cards, or in the remaining central rectangle for docked layout. |
| View background | `viewport.rs::show` emits an egui gradient mesh before the viewport callback. `render_workspace.rs::show` emits its effective preview background, shared with the blur source. Neither is contained in the GPU renderer's scene texture. |
| Prepare scene | `gpu.rs::ViewportCallback::prepare` calls `solidcraft_gpu::view::Renderer::prepare`. Native `set_wgpu_split` already draws scene depth/MSAA/OIT offscreen. The UI target has one sample and no depth. The resolved scene is transparent outside geometry. |
| Acquire/order | `vendor/egui-wgpu/src/winit.rs::Painter::paint_and_update_textures` acquires/probes the drawable before preparing callbacks. `Renderer::update_buffers` uploads meshes, runs all callback `prepare`s, then all `finish_prepare`s. The enabled frame hook supplies actual physical target extent and the effective scale, including surface clamping. |
| Build source/blur | The enabled `blur_native.rs::Source` replaces the viewport callback. Its `prepare` delegates unchanged to the original callback. Its `finish_prepare` draws the independent background/prepared viewport into S, then the blur chain, all on the same encoder. A cache hit encodes neither source nor blur passes. |
| UI composition | The native pass owner selects an installed `FrameCompositor` before beginning the UI pass. It renders the unchanged egui primitive stream into C. At semantic markers, `PanelMarker::paint` samples B; ordinary panel fill/content follow in their original order. |
| Present/capture | A final triangle presents C into the normal drawable or existing capture texture. Existing screenshot copying, queue guard, texture frees and presentation remain after that. `submitted` commits a pending source key only after queue submission. |
`CallbackTrait::paint` receives an already active pass, not its encoder or target;
it cannot redirect the UI or start blur passes. Callback command buffers execute
before the main encoder. Source production and its dependent blur therefore use
the same encoder and return no additional callback command buffers.
## Independent source and color contract
S, B and C are separate textures with separate jobs:
- **S** is full-target, single-sample viewport/background color. Its construction
takes the explicit background rectangle/colors, inherited clip and prepared
`ViewportCallback::Frame`. The background pipeline has a uniform-only bind
group: it cannot sample C or a panel texture. The source viewport paint uses
the same prepared renderer, with its actual screen placement/scissor.
- **B** is the final full-target linear RGBA16F Kawase result, shared by every
eligible panel in that native viewport. Intermediate down/up targets are also
RGBA16F and are distinct read/write textures on every pass.
- **C** has the UI target's format and contains the normal sharp viewport plus
egui UI/markers. Only the final presentation samples C. C never feeds S or B.
No prefix of the UI paint list is blurred. A docked panel or window can precede
the viewport in that list; this does not affect source construction. Panels,
menus, HUDs, toasts, dimension editors, cursors and input shields are excluded.
The source does include model/sketch/highlight/preview geometry, section caps,
reference images and point clouds drawn by the GPU viewport. A panel outside
the model rectangle sees the deterministic source background, not invented
geometry behind a dock. Extending the projection under docks is a separate change.
Render preview uses its original product `Frame`, lighting, resolution reduction
and effective preview background, including authored-scene precedence and the
animated tab gradient. It does not call a model snapshot renderer or
replace the Render scene settings. Home/result-image contexts are unavailable;
a missing source callback in a painted frame drops target storage and reports
unavailable instead of sampling a previous workspace's pixels.
Source color is opaque viewport/background color. Translucent custom viewport
or outside backgrounds report unavailable before effect GPU allocation; their
composition with a transparent native window is not silently approximated.
For an unorm UI target, the
first down pass decodes each source texel before bilinear interpolation; for an
sRGB target, texture sampling performs the decode. All subsequent filtering is
linear. Marker output follows egui's gamma-premultiplied convention: convert B
to gamma, multiply RGB/alpha by rounded coverage and host opacity, and for an
sRGB attachment decode that premultiplied RGB before framebuffer conversion.
This matches egui's existing shader ordering rather than treating its output as
straight-alpha linear color. Presentation samples C in its own format; it does
not apply a second manual gamma transform. The harness exercises both unorm and
sRGB formats. The worker has not yet verified those images on hardware.
## Semantic hosts, clipping and rounding
Eligible surfaces are `Panel`, `Feature`, `Palette` and `Chrome`, with nonzero,
translucent outer fill. `Container` owns eligibility; alpha alone does not select
arbitrary UI. Opaque fills have no marker. Viewport, native application bar,
Canvas, InputShield, HUDs, Toast, Window and Popup are outside the initial policy.
The app uses stock egui 0.36.2 public APIs. In the positive eligible path,
`Container::show_frame`, `show_edge` and the bounded `FeatureWindow::show`
reserve an early painter slot before invoking the original host. Once geometry
is known they populate that slot with a marker; the original shadow, fill,
stroke and contents remain in their original slots. The zero path reserves
nothing and calls the existing `Prepared::end`, `Panel::show` or `Window::show`.
No host becomes transparent, and child `UiStack` frame/background metadata,
styles, margins, stroke widths, IDs and interactions remain stock.
`show_frame` owns `Frame::begin` and uses the final content rectangle and
joined-edge corner rounding. `show_edge` captures the panel painter before the
body can narrow its clip or change opacity, then measures the actual frame
content (the response may be clamped on overflow). Its marker uses the original
host clip, including padding/borders and any host clipping. Current adaptive
edge callers use ordinary `show`; the helper deliberately exposes no animated
panel entry point.
Only `Panel::window_placed` creates an adaptive stock Window. Its small
`FeatureWindow` wrapper keeps the existing builder private and forwards only
`fixed_size`, `open` and `show`. The open flag is forwarded with a shortened borrow
lifetime; stock Window owns visibility and close-request handling. These sheets
explicitly disable native title bars, collapse, resize, scrolling and fades,
and use an explicit persistent ID and
Middle layer. The early slot is on that exact layer. The final Area response
includes the outer margins; subtracting the original total margins reconstructs
the content rectangle for marker geometry even though stock Window relocates
`inner_margin` into an internal Frame. The marker inherits the host painter's
visibility/opacity and Area's viewport clip, rather than Resize's content-only
clip. System windows (`Surface::Window`) remain outside blur eligibility.
Manual workspace ribbon cards and History retain semantic background painting;
manual HUD painting remains plain. No private storage access, extra outer
visual container, duplicate frame or search for matching colors/rectangles is
used. The tests inject a marker function into these same helpers without a GPU
to compare stock and decorated output, geometry, IDs and semantic metadata.
A marker precedes the ordinary shadow, fill, border and content on the same
layer. It retains all four final corner radii and painter
opacity. At paint it uses the final transformed callback rectangle and actual
physical scale, matching egui rectangle snapping when enabled. It changes the
GPU viewport to the full target, retains the renderer's inherited scissor, and
uses an antialiased rounded distance mask at the original unclipped rectangle.
Thus clipping an edge does not invent a new rounded corner. UVs come from screen
position, so a moved panel samples the corresponding source pixels. Distinct
retained marker uniforms prevent one panel's queue write from changing another's
draw. Marker count is bounded to 256. Nested/overlapping panels sample the same B,
never each other's fill or content.
## Radius, cache, allocation and recovery
Radius is finite physical pixels in 0..40; invalid requests are refused before
mutation. Zero selects plain rendering. Positive tiers have N down and N up passes:
| Radius | N | First down target |
| --- | --- | --- |
| >0..8 | 2 | ceil-half resolution |
| >8..18 | 3 | ceil-half resolution |
| >18..30 | 4 | ceil-half resolution |
| >30..40 | 5 | ceil-half resolution |
Every subsequent dimension is ceil-halved with a minimum of one pixel. Upsampling
ends at full resolution B. The original kernel has a center-plus-four-corners
down filter (weights 4,1,1,1,1) and an eight-tap up filter (axis weight 1,
diagonal weight 2). The offset, in input texels, is
`radius / (2 * sqrt((35/18) * (4^N - 1)))`. This normalizes the filters' tap sigma
across tier changes; resampling contributes an additional footprint. This is a
documented radius mapping, not a measured Gaussian-radius equivalence. Physical
spread and tier-boundary appearance still require the manager's impulse/golden review.
`view::frame_key` is exposed without changing its existing behavior. The blur
signature includes that exact scene signature (including camera, lighting,
selection/hover, preview, images/clouds, analysis, section, AO and supersampling),
source/background rectangles and clip after the source layer's final global
transform, background colors, physical target extent,
effective scale, target encoding and radius. It is per device/host; installation
on a replacement device retires the old state. A pending key becomes valid only
after submission. A resting repaint reuses B with zero source/blur passes; normal
UI composition/presentation still occurs. Panel-only tint/layout changes reuse
the full-target source unless they change projection, source placement or extent.
No repaint timer is added to keep blur alive.
The source captures its Context/layer only in the enabled branch. `finish_prepare`
queries `layer_transform_to_global` after UI emission, including a transform set
after the callback shape was emitted. One validated snapshot transforms viewport,
background and inherited clip for both the cache key and source painting. The
callback shape stays local so egui applies its own transformation exactly once.
All effect GPU allocation is lazy and bounded. The target budget is 256 MiB,
computed with checked arithmetic before allocation, using four-byte S/C and
eight-byte down/up targets. Uniform bytes are also reported. The budget does not
claim to account for opaque driver pipeline/binding memory. Actual device limits
and format capabilities are queried. Resource creation/marker growth use error
scopes and return unavailable on refusal; failures latch until radius/host/size
changes, avoiding an allocation retry storm. Positive radius changes currently
retire/recreate effect storage, including pipelines; this is deliberately simple
but cold activation cost must be measured before PR 6 adds an interactive slider.
Native zero physical window size suspends the effect before callback preparation,
including when the surface was clamped to 1x1. Geometry/scale is checked before
casts or allocation. Device loss suspends storage before further effect work;
existing device probing and acquired-frame lifetime handling are retained.
Replacement size/device rebuilds from a fresh signature. No explicit destruction
of in-flight textures, new unsafe block, unwrap/expect/panic path, synchronous
readback, or GPU completion wait was added to production painting.
## Capability and other integrations
`blur::Capability` is `Available` or `Unavailable(reason)`. `State::capability`
distinguishes missing GPU/native split integration, software adapter, unsupported
filterable/renderable formats, unsupported source context, missing source frame,
resource/size refusal and lost device. The actual window adapter is classified
with the same `gpu::select::tier_of` as headless captures; no renderer-name guessing.
Software adapters and web paths allocate no effect resources or markers.
Web still uses eframe's unvendored `src/web/web_painter_wgpu.rs`, not the native
pass owner. Both WebGPU and WebGL2 report unavailable until that owner is wired
with equivalent acquire/zero-size/error ordering. This is an integration limit,
not a claim that WebGPU fragment blur is impossible. No eframe/epaint patch is used.
`ui.render`, CLI snapshots and scenario `shot` remain model-only captures, through
`engine::capture`/`gpu::capture::Capturer` or the existing CPU fallback. They do not
paint egui panels and cannot prove blur correctness. Their code paths are unchanged.
The full GPU fixture in existing `gpu.rs::tests` renders actual app egui output,
font textures, viewport callbacks and compositor into a readback target. Tests
remain in the existing area modules; no per-issue test module was added.
PR 6 must consume the capability/reason and finite 0..40 contract, leave saved
user intent intact on fallback, and request a frame on changes. It must not create
resources by opening Preferences. There is no persistent blur preference in PR 5.
## Internal activation and manager-only validation
The control hook is `ui.blur {radius_px?, surface_alpha?}`. `surface_alpha` is an
internal capture-only override in 0..1; null restores ordinary fills. Transparent
host frames remain transparent. The hook returns requested radius, maximum,
capability and cumulative counters. Activation is control-only and session-only;
default construction is zero and performs no environment lookup or GPU probe.
The adapter capability probe is cached lazily on activation or an explicit query.
Counters increment at actual `create_texture`, buffer/bind-group/pipeline creation,
source/chain/UI/present encoding and marker emission/drawing. They include cache
hits and live texture/buffer/group/pipeline counts and texture/uniform bytes.
They are effect counters, not a fabricated whole-frame allocator or driver trace.
At zero, test deltas must remain zero and all live effect counts must be zero.
CPU allocations must additionally be measured with an external allocator/profiler;
no unsafe counting allocator was added. Timing alone cannot prove zero allocations.
No commands below were run by this worker. Manager's minimal focused checks:
```powershell
cargo test --locked --profile ci -p solidcraft-ui-egui --lib blur_stock_ -- --nocapture
cargo test --locked --profile ci -p solidcraft-ui-egui --lib blur_ -- --nocapture
cargo build --locked --profile ci -p solidcraft
```
The five `blur_stock_` tests compare stock and app-owned hosts without a GPU:
zero output includes identical Noop counts; positive output preserves chrome,
semantic fill/frame information and persistent IDs; asymmetric margins, stroke
width, host clipping, final joined corners and late layer transforms are covered.
They replace the old test of the vendored Window hook. They are authored only,
not executed by this worker. Open-flag forwarding also covers initially hidden,
closed and reopened windows, including stock close-request propagation via
`ui.close_kind(egui::UiKind::Window)`. Plain `ui.close()` targets Window's nearer
internal Collapsible, even when native title/collapse controls are disabled.
The other blur tests remain; the broader `blur_` filter selects fourteen tests.
Cargo.lock was restored as text to the egui 0.36.2 registry source and checksum
from the matching local crates.io index entry; dependency versions are unchanged.
The full vendored egui copy and its path patch were removed; the egui-wgpu patch
and licences remain. No cargo execution was used. Set `SOLIDCRAFT_REQUIRE_GPU=1` to require an adapter
(hardware or software); a missing adapter/device fails every blur fixture consumer.
The explicit `cfg(test)` rendering fixture runs all positive compositor, cache,
pixel and suspension assertions on CI software adapters independently of production
software policy, retaining real adapter identity and format/device requirements.
A separate production-policy test asserts that actual software adapters report
`Unavailable("software adapter (gpu-software)")`, allocate no blur resources and
emit no markers. Production software blur remains unavailable.
To export fixed-scene 8/18/40 and zero light/dark images, counters, and warmed
UI/encode/GPU-completion benchmark samples:
```powershell
$env:SOLIDCRAFT_REQUIRE_GPU = '1'
$env:SOLIDCRAFT_BLUR_EVIDENCE = Join-Path $env:TEMP 'solidcraft-9809-blur-review'
cargo test --locked --profile ci -p solidcraft-ui-egui --lib blur_ -- --nocapture
```
`SOLIDCRAFT_BLUR_GOLDENS` can name a separate reviewed PNG directory for decoded
RGBA equality. No expected pixels were invented or automatically blessed here.
The fixed fixture tests both target encodings, source independence from panel
tint, rest/cache hits, camera invalidation, exact tier pass counts, on/off pixel
restoration, hostile sizes/radii, suspension/resource release, host-slot ordering,
and late layer translation/scaling. The latter checks transformed viewport,
background/clip placement, cache invalidation/reuse, and pixels outside the moved
clip even on a forced miss. Further device-loss, resize/DPI, clipping/overlap and
calibrated radius review remain manager validation work, not claimed test results.
For actual window evidence after the manager builds, start the branch app with
the same sample, dimensions, camera/theme and graphics settings as the baseline.
Use the manager's isolated TEMP settings/control-blur launch environment and its
written token file (`$blurTokenPath` below). Port 38876 is the user review app and
must not be contacted or relaunched; blur validation uses explicit port 38877:
```powershell
.\target\ci\solidcraft.exe --sample --control 38877
# In a second shell; always choose a NEW output directory:
.\scripts\blur-evidence.ps1 -Port 38877 -TokenPath $blurTokenPath -OutputDirectory "$env:TEMP\solidcraft-9809-window-review"
```
The collector saves ordinary zero UI/model captures before applying a tint,
light/dark 0/18 UI screenshots, feature counters, and warmed CPU `frame_ms` plus
screenshot-roundtrip timing samples. Roundtrip timing includes PNG readback/I/O
and is explicitly not GPU frame timing. The full fixture benchmark separately
waits for GPU completion, only in test code. For before/after zero CPU timing,
connect the collector to the manager's separately running main baseline with
`-Baseline -Port <baseline-port> -OutputDirectory <another-new-directory>`.
It never launches/builds the baseline or overwrites existing evidence. Baseline
artifacts under TEMP/solidcraft-8876-evidence and its checkout were not modified.
Compare decoded images, not PNG file bytes. If ffmpeg is available, its RGBA
framemd5 output provides pixel hashes and dimensions without Pillow:
```powershell
$mainPng = "$env:TEMP\solidcraft-8876-evidence\blur-main-zero-ui.png"
$branchPng = "$env:TEMP\solidcraft-9809-window-review\zero-ui.png"
$mainDecoded = (& ffmpeg -v error -i $mainPng -frames:v 1 -pix_fmt rgba -f framemd5 -) -join "`n"
if ($LASTEXITCODE -ne 0) { throw 'Baseline decode failed' }
$branchDecoded = (& ffmpeg -v error -i $branchPng -frames:v 1 -pix_fmt rgba -f framemd5 -) -join "`n"
if ($LASTEXITCODE -ne 0) { throw 'Branch decode failed' }
if ($mainDecoded -cne $branchDecoded) { throw 'Decoded RGBA/dimensions differ' }
```
Report timing medians/ranges, machine, adapter/backend/driver, size/DPI and power
settings from alternating warmed baseline/branch runs. Use PIX/RenderDoc or an
allocator profiler for complete GPU/CPU allocation/pass accounting. The manager
measured the exact prerequisite base `f1c2fc880`; comparisons require identical
restored UI/model settings. Current validation records belong in the PR body;
the new fixture is not a substitute for that comparison. Later manager gates are
wasm, layers, licences, lists, containers/clippy, then full CI before commit/merge.
Worker execution counts: tests/builds/checks/cargo/xtask/UI runs/screenshots = 0.
+9
View File
@@ -28,6 +28,15 @@ The control channel is **on by default**. SolidCraft listens on `127.0.0.1` only
so agents can drive the app without a launch flag. Every connection still needs this launch's
token (below); nothing else on the machine, and nothing off it, can send a command.
Internal rendering harness: `ui.blur {radius_px?, surface_alpha?}` queries or sets
session-only panel blur. Radius is finite physical pixels in 0..40; the optional
capture tint is 0..1 (`null` restores ordinary fills). This is not a saved
preference. The reply contains requested radius, capability/reason and cumulative
actual effect counters, including live resources and encoded passes. Unsupported
software/web/source contexts stay on ordinary painting. Use `ui.screenshot` for
panel evidence; `ui.render` remains a model-only capture. Activation, full egui GPU
fixture and manager-run evidence commands are in [blur-behind.md](blur-behind.md).
| Launch | What listens |
|---|---|
| `solidcraft --control PORT`, or `SOLIDCRAFT_CONTROL_PORT=PORT` | exactly `127.0.0.1:PORT` (the flag wins over the variable), whatever the setting |
+77
View File
@@ -0,0 +1,77 @@
# Manager-run local evidence collector. Does not launch/build anything or modify baseline files.
param(
[Parameter(Mandatory = $true)][int]$Port,
[Parameter(Mandatory = $true)][string]$OutputDirectory,
[string]$TokenPath,
[switch]$Baseline,
[ValidateRange(1, 1000)][int]$Frames = 30
)
$ErrorActionPreference = 'Stop'
if (-not $TokenPath) { $TokenPath = Join-Path $env:LOCALAPPDATA "SolidCraft/control/$Port.token" }
$blurToken = (Get-Content -LiteralPath $TokenPath -Raw).Trim()
$blurOutput = [IO.Path]::GetFullPath($OutputDirectory)
if (Test-Path -LiteralPath $blurOutput) { throw 'Use a new output directory; existing evidence is never overwritten.' }
New-Item -ItemType Directory -Path $blurOutput | Out-Null
$blurClient = [Net.Sockets.TcpClient]::new('127.0.0.1', $Port)
$blurClient.ReceiveTimeout = 60000
$blurClient.SendTimeout = 60000
$blurStream = $blurClient.GetStream()
$blurReader = [IO.StreamReader]::new($blurStream)
$blurWriter = [IO.StreamWriter]::new($blurStream, [Text.UTF8Encoding]::new($false))
$blurWriter.AutoFlush = $true
$script:blurRequestId = 0
function Invoke-BlurControl([string]$Method, $Parameters = @{}) {
$script:blurRequestId++
$blurWriter.WriteLine((@{ id = $script:blurRequestId; token = $blurToken; method = $Method; params = $Parameters } | ConvertTo-Json -Compress -Depth 30))
$blurLine = $blurReader.ReadLine()
if (-not $blurLine) { throw 'Control connection closed.' }
$blurReply = $blurLine | ConvertFrom-Json
if (-not $blurReply.ok) { throw "$Method failed: $($blurReply.error)" }
return $blurReply.result
}
function Save-BlurShot([string]$Name) {
Invoke-BlurControl 'ui.screenshot' @{ path = (Join-Path $blurOutput "$Name.png"); allow_paths = @($blurOutput) } | Out-Null
}
try {
$blurInitial = Invoke-BlurControl 'ui.inspect'
$blurPrefs = Invoke-BlurControl 'ui.prefs'
$blurInitial | ConvertTo-Json -Depth 30 | Set-Content -LiteralPath (Join-Path $blurOutput 'initial-inspect.json')
if (-not $Baseline) { Invoke-BlurControl 'ui.blur' @{ radius_px = 0; surface_alpha = $null } | Out-Null }
# Leave the current scene/theme/size untouched for the main/branch zero comparison.
$blurTimings = @()
for ($blurIndex = 0; $blurIndex -lt ($Frames + 5); $blurIndex++) {
$blurClock = [Diagnostics.Stopwatch]::StartNew()
# A screenshot forces a presented frame. Reuse only this collector's scratch file.
Save-BlurShot 'timing-scratch'
$blurClock.Stop()
$blurInspect = Invoke-BlurControl 'ui.inspect'
if ($blurIndex -ge 5) {
$blurTimings += @{ ui_cpu_ms = $blurInspect.frame_ms; screenshot_roundtrip_ms = $blurClock.Elapsed.TotalMilliseconds }
}
}
$blurReport = @{ machine = $env:COMPUTERNAME; mode = $(if ($Baseline) { 'baseline' } else { 'branch-zero' }); samples = $blurTimings; inspect = $blurInitial }
if (-not $Baseline) { $blurReport.counters = Invoke-BlurControl 'ui.blur' }
$blurReport | ConvertTo-Json -Depth 30 | Set-Content -LiteralPath (Join-Path $blurOutput 'zero-timing.json')
Save-BlurShot 'zero-ui'
Invoke-BlurControl 'ui.render' @{ path = (Join-Path $blurOutput 'zero-model.png'); allow_paths = @($blurOutput) } | Out-Null
if (-not $Baseline) {
foreach ($blurTheme in @('light', 'dark')) {
Invoke-BlurControl 'ui.prefs' @{ theme = $blurTheme } | Out-Null
foreach ($blurRadius in @(0, 18)) {
Invoke-BlurControl 'ui.blur' @{ radius_px = $blurRadius; surface_alpha = 0.7 } | Out-Null
Save-BlurShot "$blurTheme-$blurRadius"
$blurState = Invoke-BlurControl 'ui.blur'
$blurState | ConvertTo-Json -Depth 12 | Set-Content -LiteralPath (Join-Path $blurOutput "$blurTheme-$blurRadius-counters.json")
if ($blurRadius -gt 0 -and $blurState.capability -ne 'Available') { throw "Blur unavailable: $($blurState.capability | ConvertTo-Json -Compress)" }
}
}
}
} finally {
try {
if (-not $Baseline) { Invoke-BlurControl 'ui.blur' @{ radius_px = 0; surface_alpha = $null } | Out-Null }
if (-not $Baseline -and $blurPrefs -and $blurPrefs.theme) { Invoke-BlurControl 'ui.prefs' @{ theme = $blurPrefs.theme } | Out-Null }
if (-not $Baseline -and $blurInitial -and $null -ne $blurInitial.ui.dark) { Invoke-BlurControl 'ui.set' @{ dark = $blurInitial.ui.dark } | Out-Null }
} finally {
$blurWriter.Dispose(); $blurReader.Dispose(); $blurClient.Dispose()
}
}
+29
View File
@@ -129,6 +129,29 @@ pub struct ScreenDescriptor {
pub pixels_per_point: f32,
}
/// SolidCraft: optional ownership of a complete frame, outside the primitive loop.
/// Returning false keeps the ordinary pass. No effect resources exist by default.
pub trait FrameCompositor: Send + Sync {
/// SolidCraft: select the native viewport before any effect preparation/painting.
fn begin_viewport(&self, _viewport: u64) {}
/// SolidCraft: actual acquired target geometry, before callback preparation.
fn screen(&self, _screen: &ScreenDescriptor, _resources: &mut CallbackResources) {}
/// SolidCraft: release target-dependent state on zero size or a lost device.
fn suspend(&self) {}
fn render(
&self,
renderer: &Renderer,
encoder: &mut wgpu::CommandEncoder,
target: &wgpu::TextureView,
jobs: &[epaint::ClippedPrimitive],
screen: &ScreenDescriptor,
clear: [f32; 4],
) -> bool;
/// Called only after the commands producing cached pixels have been submitted.
fn submitted(&self) {}
}
impl ScreenDescriptor {
/// size in "logical" points
fn screen_size_in_points(&self) -> [f32; 2] {
@@ -263,6 +286,8 @@ pub struct Renderer {
///
/// See also [`CallbackTrait`].
pub callback_resources: CallbackResources,
/// SolidCraft: installed lazily by an enabled effect; the ordinary loop is unchanged.
pub frame_compositor: Option<std::sync::Arc<dyn FrameCompositor>>,
}
impl Renderer {
@@ -469,6 +494,7 @@ impl Renderer {
samplers: HashMap::default(),
options,
callback_resources: CallbackResources::default(),
frame_compositor: None,
}
}
@@ -933,6 +959,9 @@ impl Renderer {
profiling::function_scope!();
self.skip_frame = false;
if let Some(effect) = &self.frame_compositor {
effect.screen(screen_descriptor, &mut self.callback_resources);
}
let screen_size_in_points = screen_descriptor.screen_size_in_points();
let uniform_buffer_content = UniformBuffer {
+93 -54
View File
@@ -663,6 +663,11 @@ impl Painter {
.as_ref()
.is_some_and(|rs| rs.device_lost.is_lost())
{
if let Some(rs) = &self.render_state
&& let Some(effect) = &rs.renderer.read().frame_compositor
{
effect.suspend();
}
// The app's frame (not this paint) acts on it: keep its frames coming.
self.context
.request_repaint_after_for(std::time::Duration::from_millis(250), viewport_id);
@@ -702,11 +707,22 @@ impl Painter {
let Some(render_state) = self.render_state.as_mut() else {
return vsync_sec;
};
if let Some(effect) = &render_state.renderer.read().frame_compositor {
effect.begin_viewport(viewport_id.0.value());
}
let mut render_queue_guard = RendererQueueGuard {
queue: &render_state.queue,
commands_submitted: false,
};
// SolidCraft: a minimized native window may retain a clamped 1x1 surface.
if let Some(effect) = &render_state.renderer.read().frame_compositor {
let extent = window.inner_size();
if extent.width == 0 || extent.height == 0 {
effect.suspend();
return vsync_sec;
}
}
let Some(surface_state) = self.surfaces.get_mut(&viewport_id) else {
return vsync_sec;
@@ -794,6 +810,9 @@ impl Painter {
// is still there. The first queue write to meet a lost device panics inside wgpu (#4172);
// the submission meets it instead, marks it lost, and the frame is dropped unpresented.
if render_state.device_lost.probe(&render_state.queue) {
if let Some(effect) = &render_state.renderer.read().frame_compositor {
effect.suspend();
}
render_queue_guard.commands_submitted = true;
log::error!(
"The graphics device was lost: {}",
@@ -867,62 +886,79 @@ impl Painter {
(texture_view, Some(&target_view))
});
let render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("egui_render"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view,
resolve_target,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color {
r: clear_color[0] as f64,
g: clear_color[1] as f64,
b: clear_color[2] as f64,
a: clear_color[3] as f64,
}),
store: wgpu::StoreOp::Store,
},
depth_slice: None,
})],
depth_stencil_attachment: self.depth_texture_view.get(&viewport_id).map(|view| {
wgpu::RenderPassDepthStencilAttachment {
// SolidCraft: the pass owner selects offscreen composition once, never in render's loop.
let composed = self.options.msaa_samples == 1
&& self.options.depth_stencil_format.is_none()
&& renderer.frame_compositor.as_ref().is_some_and(|effect| {
effect.render(
&renderer,
&mut encoder,
&target_view,
clipped_primitives,
&screen_descriptor,
clear_color,
)
});
if !composed {
let render_pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
label: Some("egui_render"),
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view,
depth_ops: self
.options
.depth_stencil_format
.is_some_and(|depth_stencil_format| {
depth_stencil_format.has_depth_aspect()
})
.then_some(wgpu::Operations {
load: wgpu::LoadOp::Clear(1.0),
// It is very unlikely that the depth buffer is needed after egui finished rendering
// so no need to store it. (this can improve performance on tiling GPUs like mobile chips or Apple Silicon)
store: wgpu::StoreOp::Discard,
resolve_target,
ops: wgpu::Operations {
load: wgpu::LoadOp::Clear(wgpu::Color {
r: clear_color[0] as f64,
g: clear_color[1] as f64,
b: clear_color[2] as f64,
a: clear_color[3] as f64,
}),
stencil_ops: self
.options
.depth_stencil_format
.is_some_and(|depth_stencil_format| {
depth_stencil_format.has_stencil_aspect()
})
.then_some(wgpu::Operations {
load: wgpu::LoadOp::Clear(0),
store: wgpu::StoreOp::Discard,
}),
}
}),
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
store: wgpu::StoreOp::Store,
},
depth_slice: None,
})],
depth_stencil_attachment: self.depth_texture_view.get(&viewport_id).map(
|view| {
wgpu::RenderPassDepthStencilAttachment {
view,
depth_ops: self
.options
.depth_stencil_format
.is_some_and(|depth_stencil_format| {
depth_stencil_format.has_depth_aspect()
})
.then_some(wgpu::Operations {
load: wgpu::LoadOp::Clear(1.0),
// It is very unlikely that the depth buffer is needed after egui finished rendering
// so no need to store it. (this can improve performance on tiling GPUs like mobile chips or Apple Silicon)
store: wgpu::StoreOp::Discard,
}),
stencil_ops: self
.options
.depth_stencil_format
.is_some_and(|depth_stencil_format| {
depth_stencil_format.has_stencil_aspect()
})
.then_some(wgpu::Operations {
load: wgpu::LoadOp::Clear(0),
store: wgpu::StoreOp::Discard,
}),
}
},
),
timestamp_writes: None,
occlusion_query_set: None,
multiview_mask: None,
});
// Forgetting the pass' lifetime means that we are no longer compile-time protected from
// runtime errors caused by accessing the parent encoder before the render pass is dropped.
// Since we don't pass it on to the renderer, we should be perfectly safe against this mistake here!
renderer.render(
&mut render_pass.forget_lifetime(),
clipped_primitives,
&screen_descriptor,
);
// Forgetting the pass' lifetime means that we are no longer compile-time protected from
// runtime errors caused by accessing the parent encoder before the render pass is dropped.
// Since we don't pass it on to the renderer, we should be perfectly safe against this mistake here!
renderer.render(
&mut render_pass.forget_lifetime(),
clipped_primitives,
&screen_descriptor,
);
}
if capture && let Some(capture_state) = &mut self.screen_capture_state {
capture_buffer = Some(capture_state.copy_textures(
@@ -951,6 +987,10 @@ impl Painter {
// Ensure that the queue guard does not do unnecessary work when dropped
render_queue_guard.commands_submitted = true;
// SolidCraft: caches become valid only after the producer encoder was submitted.
if let Some(effect) = &render_state.renderer.read().frame_compositor {
effect.submitted();
}
// Free textures marked for destruction **after** queue submit since they might still be used in the current frame.
// Calling `wgpu::Texture::destroy` on a texture that is still in use would invalidate the command buffer(s) it is used in.
@@ -1015,4 +1055,3 @@ impl Painter {
// TODO(emilk): something here?
}
}