Graphics: 1x anti-aliasing where the multisampled view draws nothing (#5819, #5870) (#5832)

This commit is contained in:
raykholo
2026-10-25 22:10:04 +00:00
committed by GitHub
parent 5d17fa970b
commit 36a60a70d9
7 changed files with 363 additions and 17 deletions
+51 -8
View File
@@ -578,13 +578,22 @@ fn scene_samples(backend: eframe::wgpu::Backend, samples: u32, supported: &[u32]
}
}
/// Anti-aliasing samples from Preferences (4 when unset).
fn msaa() -> u16 {
/// Keep the default until the installed renderer's startup check proves a fallback is needed.
fn scene_msaa_request(saved: Option<u16>) -> u16 {
saved.unwrap_or(MSAA)
}
/// Query the scene's colour/depth intersection, rather than the depthless window's counts.
fn scene_sample_choices(depth_bits: u8, stencil_bits: u8, query: impl FnOnce(Option<eframe::wgpu::TextureFormat>) -> Vec<u32>) -> Vec<u32> {
query(eframe::egui_wgpu::depth_format_from_bits(depth_bits, stencil_bits))
}
/// An explicitly saved anti-aliasing choice, absent until Graphics changes it.
fn msaa() -> Option<u16> {
graphics()
.and_then(|v| v.get("msaa").and_then(serde_json::Value::as_u64))
.and_then(|m| u16::try_from(m).ok())
.filter(|m| [1, 2, 4, 8].contains(m))
.unwrap_or(MSAA)
}
/// Windows and Linux: no OS title bar; the application bar is the title bar
@@ -688,7 +697,7 @@ fn main() -> eframe::Result {
if safe_mode {
notes.push("Safe mode: default settings (yours are kept for the next normal start), no recovery offer, software rendering.".into());
}
let samples = if safe_mode { MSAA } else { msaa() };
let saved_samples = if safe_mode { None } else { msaa() };
let wgpu_options = wgpu_options(cpu_renderer, if safe_mode { None } else { backend_preference() }.as_deref());
let depth_bits = if !safe_mode && startup::float_depth_everywhere(&wgpu_options) { FLOAT_DEPTH_BITS } else { DEPTH_BITS };
// Crashes leave a report in the crash folder (solidcraft_engine::crash, docs/crash-reports.md).
@@ -818,18 +827,24 @@ fn main() -> eframe::Result {
(info.name.clone(), format!("{} ({:?}, {:?})", info.name, info.device_type, info.backend))
})
.collect();
let scene_samples = scene_samples(rs.adapter.get_info().backend, u32::from(samples), &rs.msaa_supported);
let info = rs.adapter.get_info();
let samples = scene_msaa_request(saved_samples);
let supported = scene_sample_choices(depth_bits, STENCIL_BITS, |depth| {
eframe::egui_wgpu::supported_msaa_samples(&rs.adapter, &rs.device, rs.target_format, depth)
});
let scene_samples = scene_samples(info.backend, u32::from(samples), &supported);
eprintln!("SolidCraft graphics: {:?}, MSAA {scene_samples}x (requested {}x)", rs.adapter.get_info().backend, samples);
solidcraft_engine::crash::phase("viewport pipelines (shader compile)");
app.set_wgpu_split(rs, depth_bits, STENCIL_BITS, scene_samples);
let scene_samples = app.set_wgpu_split(rs, depth_bits, STENCIL_BITS, scene_samples);
app.msaa_supported = supported;
app.preferences.msaa = u32::from(samples);
solidcraft_ui_egui::gpu::install_picture_renderer(rs);
// The graphics driver is loaded now; it may have put its own exception filter
// in front of ours.
#[cfg(target_os = "windows")]
native_crash::reinstall();
// A saved anti-aliasing the device can't do: back to the default, with a notice.
// Reflect a confirmed probe fallback or an unsupported saved count in Graphics.
solidcraft_ui_egui::prefs::check_msaa(&mut app, u32::from(samples));
let info = rs.adapter.get_info();
solidcraft_engine::crash::set_environment(&format!(
"Renderer: {:?} {} ({}), MSAA {scene_samples}x",
info.backend, info.name, info.driver
@@ -1202,6 +1217,34 @@ mod msaa_tests {
}
}
#[test]
fn scene_sample_choices_include_the_scene_depth_format() {
use eframe::wgpu::TextureFormat;
for (bits, expected) in [(24, TextureFormat::Depth24PlusStencil8), (32, TextureFormat::Depth32FloatStencil8)] {
// A synthetic colour target supports 8x, but the scene depth supports only 1x/4x.
let supported = super::scene_sample_choices(bits, 8, |depth| match depth {
Some(format) if format == expected => vec![1, 4],
None => vec![1, 4, 8],
other => panic!("unexpected scene depth: {other:?}"),
});
assert_eq!(supported, [1, 4]);
assert_eq!(super::scene_samples(eframe::wgpu::Backend::Dx12, 8, &supported), 4);
}
}
#[test]
fn scene_msaa_keeps_four_samples_by_default_and_explicit_choices() {
use eframe::wgpu::Backend;
let default = super::scene_msaa_request(None);
assert_eq!(default, 4);
for backend in [Backend::Dx12, Backend::Vulkan, Backend::Metal] {
assert_eq!(super::scene_samples(backend, u32::from(default), &[1, 4]), 4);
}
for saved in [1, 2, 4, 8] {
assert_eq!(super::scene_msaa_request(Some(saved)), saved);
}
}
#[test]
fn the_scene_follows_the_backend_policy_too() {
use eframe::wgpu::Backend;
@@ -0,0 +1,11 @@
{
"en": {
"prefs.anti_aliasing_amd_dx12": "Anti-aliasing uses 1× because the startup check drew nothing with multisampling and passed at 1×. You can choose another setting above; restart to apply it if the check passes."
},
"ja": {
"prefs.anti_aliasing_amd_dx12": "起動時のチェックでマルチサンプリングでは何も描画されず、1×では正常に描画されたため、アンチエイリアシングを1×に設定しました。上で別の設定を選択できます。再起動後のチェックに合格すると、その設定が適用されます。"
},
"zh": {
"prefs.anti_aliasing_amd_dx12": "由于启动检查在启用多重采样时未绘制任何内容,而在1×时通过了检查,抗锯齿已设为1×。您可以在上方选择其他设置;重启后若检查通过,该设置将生效。"
}
}
+36
View File
@@ -17,7 +17,11 @@ use wgpu::util::DeviceExt;
use crate::pbr;
mod ao;
#[cfg(not(target_arch = "wasm32"))]
mod msaa_check;
mod oit;
#[cfg(not(target_arch = "wasm32"))]
pub use msaa_check::MsaaCheck;
/// Triangle vertex: position (3 × f32), normal (3 × f32), sRGB colour (4 × u8).
pub const TRI_SIZE: usize = 28;
@@ -3481,6 +3485,38 @@ mod glass_tests {
assert!(preview[2] > preview[0] + 60, "the preview shows its own blue square: {preview:?}");
}
#[test]
fn startup_msaa_check_passes_and_detects_a_blank_resolve() {
let (adapter, device, queue) = crate::open_headless().expect("software adapter required for the startup check");
let depth = crate::depth_format(&device, true);
for format in [wgpu::TextureFormat::Rgba8Unorm, wgpu::TextureFormat::Bgra8Unorm, wgpu::TextureFormat::Bgra8UnormSrgb] {
let window = GpuTarget { format, depth: None, samples: 1, tess: false };
for samples in [1, 4] {
if ![format, depth].iter().all(|f| adapter.get_texture_format_features(*f).flags.sample_count_supported(samples)) {
continue;
}
let target = GpuTarget { depth: Some(depth), samples, ..window };
let mut renderer = Renderer::with_window_target(&device, target, window, None);
let start = std::time::Instant::now();
assert_eq!(renderer.check_msaa(&device, &queue).unwrap(), super::MsaaCheck::Passed);
eprintln!("startup check: {} {format:?} {samples}x: {:?}", adapter.get_info().name, start.elapsed());
assert!(
renderer.model.key.is_none() && renderer.highlight.key.is_none() && renderer.ss.is_none(),
"probe uploads must not replace the first real frame"
);
assert_eq!(renderer.target().samples, samples);
assert_eq!(renderer.check_msaa_with(&device, &queue, 1).unwrap(), super::MsaaCheck::FailedAtOne);
assert_eq!(renderer.target().samples, samples, "a blank 1x result must preserve the selected count");
assert_eq!(
renderer.check_msaa_with(&device, &queue, 4).unwrap(),
if samples > 1 { super::MsaaCheck::Fallback } else { super::MsaaCheck::Passed }
);
assert_eq!(renderer.target().samples, 1);
assert_eq!(renderer.check_msaa(&device, &queue).unwrap(), super::MsaaCheck::Passed);
}
}
}
/// Two see-through squares, one at z = 5 (near) and one at z = -5, in `near` and `far`
/// colours, given near first or far first.
fn two_layers(near: [u8; 4], far: [u8; 4], near_first: bool) -> GpuScene {
+202
View File
@@ -0,0 +1,202 @@
//! A startup probe of the installed viewport, including highlights, depth, resolve, and blit.
use super::*;
use crate::{GpuError, Result};
/// The startup check never changes a setting unless a working 1x replacement is proven.
#[derive(Debug, PartialEq, Eq)]
pub enum MsaaCheck {
Passed,
Fallback,
FailedAtOne,
}
impl Renderer {
/// Check a tiny scene through the installed pipelines and window format. On a blank
/// multisampled result, replace this renderer only if the same scene works at 1x.
/// Native only: browsers cannot synchronously poll a device. No result is cached on disk.
pub fn check_msaa(&mut self, device: &wgpu::Device, queue: &wgpu::Queue) -> Result<MsaaCheck> {
self.check_msaa_with(device, queue, 0)
}
pub(super) fn check_msaa_with(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, blank_samples: u32) -> Result<MsaaCheck> {
if self.probe_msaa(device, queue, blank_samples)? {
return Ok(MsaaCheck::Passed);
}
if self.target.samples == 1 {
return Ok(MsaaCheck::FailedAtOne);
}
let scopes = [wgpu::ErrorFilter::OutOfMemory, wgpu::ErrorFilter::Internal, wgpu::ErrorFilter::Validation].map(|f| device.push_error_scope(f));
let mut replacement = Self::with_window_target(device, GpuTarget { samples: 1, ..self.target }, self.window, None);
let mut error = None;
for scope in scopes.into_iter().rev() {
if let Some(e) = crate::popped(scope.pop()) {
error.get_or_insert(e);
}
}
if let Some(error) = error {
return Err(GpuError::Render(error.to_string()));
}
if !replacement.probe_msaa(device, queue, blank_samples)? {
return Ok(MsaaCheck::FailedAtOne);
}
replacement.tess = self.tess.take();
*self = replacement;
Ok(MsaaCheck::Fallback)
}
fn probe_msaa(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, blank_samples: u32) -> Result<bool> {
if !matches!(
self.window.format,
wgpu::TextureFormat::Rgba8Unorm
| wgpu::TextureFormat::Rgba8UnormSrgb
| wgpu::TextureFormat::Bgra8Unorm
| wgpu::TextureFormat::Bgra8UnormSrgb
) {
return Err(GpuError::Unsupported("anti-aliasing check colour format".into()));
}
let scopes = [wgpu::ErrorFilter::OutOfMemory, wgpu::ErrorFilter::Internal, wgpu::ErrorFilter::Validation].map(|f| device.push_error_scope(f));
let result = self.probe_pixels(device, queue, blank_samples);
// Discard the probe's uploads and picture even on errors, before the real scene arrives.
self.model = Batches::default();
self.sketch = Batches::default();
self.highlight = Batches::default();
self.preview = Batches::default();
self.ss = None;
self.ss_key = None;
self.ss_ready = false;
self.cached = None;
let mut error = None;
for scope in scopes.into_iter().rev() {
if let Some(e) = crate::popped(scope.pop()) {
error.get_or_insert(e);
}
}
if let Some(error) = error {
return Err(GpuError::Render(error.to_string()));
}
result
}
fn probe_pixels(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, blank_samples: u32) -> Result<bool> {
const SIZE: u32 = 16;
let mut model = GpuScene::default();
for p in [[-0.9, -0.9, 0.0], [0.9, -0.9, 0.0], [0.0, 0.9, 0.0]] {
model.tri(p, [0.0, 0.0, 1.0], [255, 0, 0, 255]);
}
let mut highlight = GpuScene::default();
for p in [[-0.8, -0.8, 0.0], [0.8, -0.8, 0.0], [0.8, 0.8, 0.0], [-0.8, -0.8, 0.0], [0.8, 0.8, 0.0], [-0.8, 0.8, 0.0]] {
highlight.xray_tri(p, [0.0, 0.0, 1.0], [0, 0, 255, 64]);
}
let slot = |scene| Arc::new(Mutex::new(scene));
let frame = Frame {
product: false,
key: 1,
slot: slot(Some(model)),
sketch_key: 2,
sketch_slot: slot(None),
hl_key: 3,
hl_slot: slot(Some(highlight)),
pv_key: 4,
pv_slot: slot(None),
pv_hide: false,
view_proj: [[1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.5, 1.0]],
back: [0.0, 0.0, 1.0],
size_px: [SIZE as f32; 2],
clip: [0.0; 4],
cap: [0.0; 4],
images: Vec::new(),
analysis: [0.0; 8],
analysis_colors: [0.0; 36],
access: None,
outline: false,
eye: [0.0, 0.0, 100.0, 0.0],
ao_radius: 0.0,
ssaa: 1.0,
hover_tint: [0.0; 3],
selection_tint: [0.0; 3],
};
let size = wgpu::Extent3d { width: SIZE, height: SIZE, depth_or_array_layers: 1 };
let color = device.create_texture(&wgpu::TextureDescriptor {
label: Some("sc_msaa_check"),
size,
mip_level_count: 1,
sample_count: 1,
dimension: wgpu::TextureDimension::D2,
format: self.window.format,
usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::COPY_SRC,
view_formats: &[],
});
let view = color.create_view(&Default::default());
let mut encoder = device.create_command_encoder(&Default::default());
self.prepare(device, queue, &mut encoder, &frame);
// Tests reproduce a driver returning a blank resolve, without changing production draws.
#[cfg(test)]
if (blank_samples == 1 || blank_samples == self.target.samples)
&& let Some(resolve) = self.ss.as_ref().map(|ss| ss.resolve.as_ref().unwrap_or(&ss.color))
{
let _pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor {
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: resolve,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), store: wgpu::StoreOp::Store },
})],
..Default::default()
});
}
#[cfg(not(test))]
let _ = blank_samples;
{
let mut pass = encoder
.begin_render_pass(&wgpu::RenderPassDescriptor {
color_attachments: &[Some(wgpu::RenderPassColorAttachment {
view: &view,
depth_slice: None,
resolve_target: None,
ops: wgpu::Operations { load: wgpu::LoadOp::Clear(wgpu::Color::BLACK), store: wgpu::StoreOp::Store },
})],
..Default::default()
})
.forget_lifetime();
self.paint(&frame, &mut pass, [0.0, 0.0, SIZE as f32, SIZE as f32]);
}
// Three interior pixels in one row, padded to the copy alignment.
let read = device.create_buffer(&wgpu::BufferDescriptor {
label: Some("sc_msaa_check_read"),
size: 256,
usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST,
mapped_at_creation: false,
});
encoder.copy_texture_to_buffer(
wgpu::TexelCopyTextureInfo { origin: wgpu::Origin3d { x: 7, y: 8, z: 0 }, ..color.as_image_copy() },
wgpu::TexelCopyBufferInfo {
buffer: &read,
layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(256), rows_per_image: Some(1) },
},
wgpu::Extent3d { width: 3, height: 1, depth_or_array_layers: 1 },
);
queue.submit([encoder.finish()]);
let slice = read.slice(..);
let (tx, rx) = std::sync::mpsc::sync_channel(1);
slice.map_async(wgpu::MapMode::Read, move |r| {
let _ = tx.send(r);
});
// No submission index: a lost device must not turn a stale submission into a panic.
// Software adapters can take seconds on their first draw. Keep the wait bounded;
// a timeout remains an inconclusive check and preserves the selected sample count.
device
.poll(wgpu::PollType::Wait { submission_index: None, timeout: Some(std::time::Duration::from_secs(10)) })
.map_err(|e| GpuError::Render(format!("anti-aliasing check wait: {e}")))?;
rx.try_recv()
.map_err(|e| GpuError::Render(format!("anti-aliasing check callback: {e}")))?
.map_err(|e| GpuError::Render(format!("anti-aliasing check map: {e}")))?;
let bytes = slice.get_mapped_range().map_err(|e| GpuError::Render(e.to_string()))?;
let bgra = matches!(self.window.format, wgpu::TextureFormat::Bgra8Unorm | wgpu::TextureFormat::Bgra8UnormSrgb);
Ok(bytes.get(..12).is_some_and(|pixels| {
pixels.as_chunks::<4>().0.iter().all(|p| {
let (red, green, blue) = if bgra { (p[2], p[1], p[0]) } else { (p[0], p[1], p[2]) };
red > 80 && red > green.saturating_add(40) && blue > 20
})
}))
}
}
+32 -5
View File
@@ -486,8 +486,10 @@ pub struct SolveApp {
pub stand_up_occurrence: Option<u64>,
/// The file's header names an exporter that saves Y up (SolidWorks): the offer says so.
pub stand_up_reason: bool,
/// The anti-aliasing sample counts the graphics device supports (empty without a GPU).
/// The anti-aliasing sample counts the scene colour/depth formats support (empty without a GPU).
pub msaa_supported: Vec<u32>,
/// The startup check selected 1x; Graphics explains the workaround.
pub msaa_compatibility: bool,
/// Settings put back at start because they kept SolidCraft from starting, one line each,
/// shown until dismissed (`prefs::show_reset_notice`).
pub settings_reset: Vec<prefs::SettingReset>,
@@ -636,6 +638,7 @@ impl SolveApp {
stand_up_occurrence: None,
stand_up_reason: false,
msaa_supported: Vec::new(),
msaa_compatibility: false,
settings_reset: Vec::new(),
big_operation: false,
autosave_minutes: 5.0,
@@ -702,8 +705,9 @@ impl SolveApp {
/// Draw the viewport on the GPU with the scene drawn offscreen: `depth_bits`/`stencil_bits`
/// and `samples` are the scene's, while the window's pass (egui's) has no depth and one
/// sample. The scene keeps its depth and anti-aliasing; the UI pass pays for neither.
pub fn set_wgpu_split(&mut self, rs: &egui_wgpu::RenderState, depth_bits: u8, stencil_bits: u8, samples: u32) {
/// sample. Native hosts check the installed renderer and fall back to 1x only when that
/// succeeds where multisampling fails. Returns the effective scene sample count.
pub fn set_wgpu_split(&mut self, rs: &egui_wgpu::RenderState, depth_bits: u8, stencil_bits: u8, samples: u32) -> u32 {
let scene = crate::gpu::GpuTarget {
format: rs.target_format,
depth: egui_wgpu::depth_format_from_bits(depth_bits, stencil_bits),
@@ -712,11 +716,34 @@ impl SolveApp {
};
let window = crate::gpu::GpuTarget { format: rs.target_format, depth: None, samples: 1, tess: false };
self.set_wgpu_targets(rs, scene, window);
self.viewport.gpu.map_or(samples, |g| g.samples)
}
fn set_wgpu_targets(&mut self, rs: &egui_wgpu::RenderState, scene: crate::gpu::GpuTarget, window: crate::gpu::GpuTarget) {
let (target, stats) = gpu::install(rs, scene, window, !self.cpu_meshing);
self.viewport.gpu = Some(target);
#[allow(unused_mut)] // Only native hosts can wait for the startup readback.
let (mut installed, stats) = gpu::install(rs, scene, window, !self.cpu_meshing);
#[cfg(not(target_arch = "wasm32"))]
if scene.depth.is_some() && window.depth.is_none() && window.samples == 1 {
let mut renderer = rs.renderer.write();
if let Some(res) = renderer.callback_resources.get_mut::<gpu::Renderer>() {
match res.check_msaa(&rs.device, &rs.queue) {
Ok(solidcraft_gpu::view::MsaaCheck::Passed) => {}
Ok(solidcraft_gpu::view::MsaaCheck::Fallback) => {
installed.samples = 1;
self.msaa_compatibility = true;
eprintln!(
"SolidCraft graphics: anti-aliasing check failed at {}x and passed at 1x; using 1x for this session",
scene.samples
);
}
Ok(solidcraft_gpu::view::MsaaCheck::FailedAtOne) => {
eprintln!("SolidCraft graphics: anti-aliasing check also failed at 1x; keeping {}x", scene.samples);
}
Err(error) => eprintln!("SolidCraft graphics: anti-aliasing check error; keeping {}x: {error}", scene.samples),
}
}
}
self.viewport.gpu = Some(installed);
self.viewport.draw_stats = Some(stats);
render_workspace::invalidate_scene(self);
let (samples, has_depth) = self.viewport.gpu.map_or((1, false), |g| (g.samples.max(1), g.depth.is_some()));
+28 -4
View File
@@ -1221,11 +1221,14 @@ fn save_graphics(app: &SolveApp) {
}
}
/// At start, with the graphics device known: the saved anti-aliasing (`requested` samples, as
/// the host read it) is more than the device supports. The window would not have opened with it,
/// so the renderer fell back; put the setting back to its default (or the largest supported
/// count below it) and tell the user what changed.
/// At start, reflect a confirmed startup fallback in Graphics, or reset an unsupported
/// saved count to the supported default. The compatibility hint keeps higher choices
/// available for another try; a probe result alone does not overwrite the saved choice.
pub fn check_msaa(app: &mut SolveApp, requested: u32) {
if app.msaa_compatibility {
app.preferences.msaa = 1;
return;
}
let supported = &app.msaa_supported;
if requested <= 1 || supported.is_empty() || supported.contains(&requested) {
return;
@@ -3619,6 +3622,27 @@ mod tests {
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn startup_msaa_check_keeps_the_default_unless_fallback_is_confirmed() {
let mut app = SolveApp::new(solidcraft_engine::Session::default(), crate::Services::default());
app.msaa_supported = vec![1, 4, 8];
for requested in [1, 4, 8] {
app.preferences.msaa = requested;
app.msaa_compatibility = false;
check_msaa(&mut app, requested);
assert_eq!(app.preferences.msaa, requested, "a passing check preserves the choice, including the 4x default");
assert!(app.settings_reset.is_empty());
}
app.preferences.msaa = 4;
app.msaa_compatibility = true;
check_msaa(&mut app, 4);
assert_eq!(app.preferences.msaa, 1, "Graphics must show the confirmed fallback so it can be changed back");
assert!(app.msaa_supported.contains(&4), "the original choice stays available");
assert!(app.msaa_compatibility, "Graphics explains the fallback");
assert!(set(&mut app, &serde_json::json!({ "msaa": 4 })).is_ok());
assert_eq!(app.preferences.msaa, 4);
}
#[test]
fn unsupported_saved_msaa_is_reset_to_the_default_with_a_notice() {
let dir = std::env::temp_dir().join(format!("sc_msaa_reset_{}", std::process::id()));
+3
View File
@@ -105,6 +105,9 @@ pub(super) fn show(app: &mut SolveApp, ui: &mut egui::Ui) {
}
});
ui_kit::text(ui, app.tr("prefs.anti_aliasing_note"), ui_kit::Text::Hint("msaa"));
if app.msaa_compatibility {
ui_kit::text(ui, app.tr("prefs.anti_aliasing_amd_dx12"), ui_kit::Text::Hint("msaa_compatibility"));
}
ui.add_space(t.space_6);
ui_kit::text(ui, app.tr("ui.supersampling"), ui_kit::Text::Heading("supersampling"));
ui.horizontal_wrapped(|ui| {