From 63043aa99edf03a8eec02bc8d5894499375550c8 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Wed, 11 Nov 2026 00:34:26 -0500 Subject: [PATCH] Fix GPU test setup and rendering cache lifetimes --- Cargo.lock | 1 + crates/render/src/gpu_trace.rs | 60 ++++++++++++++++----- crates/ui-egui/Cargo.toml | 2 + crates/ui-egui/src/render_mode.rs | 18 +++++-- crates/ui-egui/src/render_mode/tests.rs | 70 +++++++++++++++++++++++-- crates/ui-egui/tests/ui_snapshots.rs | 1 + 6 files changed, 130 insertions(+), 22 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 384c4457..9846b729 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4421,6 +4421,7 @@ dependencies = [ "image", "js-sys", "log", + "pollster 0.4.0", "rayon", "rfd", "serde", diff --git a/crates/render/src/gpu_trace.rs b/crates/render/src/gpu_trace.rs index fe423795..601e097e 100644 --- a/crates/render/src/gpu_trace.rs +++ b/crates/render/src/gpu_trace.rs @@ -507,20 +507,26 @@ impl GpuTracer { Ok(true) } - /// Start over at `width × height` (the accumulation buffers are cleared or reallocated). + /// Start over at `width × height`, keeping the active render intact if allocation fails. pub fn reset(&mut self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, width: u32, height: u32) -> Result<(), String> { let (width, height) = (width.clamp(1, 8192), height.clamp(1, 8192)); - self.samples = 0; + let bytes = u64::from(width) * u64::from(height) * 16; + let limits = device.limits(); + + // Reject unsupported sizes before invalidating the displayed render + if bytes > limits.max_storage_buffer_binding_size.min(limits.max_buffer_size) { + return Err(format!("a {width}×{height} render exceeds this GPU's buffer limit")); + } + if let Some(accumulation) = self.acc.as_ref().filter(|accumulation| (accumulation.width, accumulation.height) == (width, height)) { for buffer in &accumulation.acc { encoder.clear_buffer(buffer, 0, None); } + self.samples = 0; return Ok(()); } - self.bind = None; - // Reused buffers must not retain samples from the previous view if let Some(spare) = self.spare_acc.take_if(|accumulation| (accumulation.width, accumulation.height) == (width, height)) { for buffer in spare.acc.iter().chain(&spare.illum) { @@ -528,15 +534,13 @@ impl GpuTracer { } self.spare_acc = self.acc.replace(spare); + self.bind = None; + self.samples = 0; return Ok(()); } - self.spare_acc = self.acc.take(); - let bytes = u64::from(width) * u64::from(height) * 16; - let limits = device.limits(); - if bytes > limits.max_storage_buffer_binding_size.min(limits.max_buffer_size) { - return Err(format!("a {width}×{height} render exceeds this GPU's buffer limit")); - } + // Retire the obsolete spare before allocating, but keep the active render until success + self.spare_acc = None; let create_buffer = |label| { device.create_buffer(&wgpu::BufferDescriptor { @@ -546,12 +550,15 @@ impl GpuTracer { mapped_at_creation: false, }) }; - self.acc = Some(scoped(device, "GPU path tracing: accumulation buffers", || Accum { + let accumulation = scoped(device, "GPU path tracing: accumulation buffers", || Accum { width, height, acc: ["tc_acc_hit", "tc_acc_albedo", "tc_acc_normal", "tc_acc_env"].map(create_buffer), illum: ["tc_illum_a", "tc_illum_b"].map(create_buffer), - })?); + })?; + self.spare_acc = self.acc.replace(accumulation); + self.bind = None; + self.samples = 0; #[cfg(test)] { self.acc_allocations += 1; @@ -831,6 +838,7 @@ mod tests { read_buffer(h, &t.acc.as_ref().unwrap().acc[0]) } + /// Read a completed buffer to check its contents across resets and reuse. fn read_buffer(headless: &Headless, buffer: &wgpu::Buffer) -> Vec<[f32; 4]> { let bytes = buffer.size(); let staging = headless.device.create_buffer(&wgpu::BufferDescriptor { @@ -848,6 +856,7 @@ mod tests { bytemuck::cast_slice(&staging.slice(..).get_mapped_range().unwrap()).to_vec() } + /// Two cached sizes reuse cleared buffers, and leaving Rendering mode releases both. #[test] fn switching_between_two_sizes_reuses_the_accumulation_buffers() { let Some((headless, mut tracer)) = gpu() else { return }; @@ -880,6 +889,33 @@ mod tests { assert!(tracer.acc.is_none() && tracer.spare_acc.is_none(), "leaving Rendering mode frees both sizes"); } + /// Rejecting an oversized render preserves the image and lets tracing continue. + #[test] + fn failed_reset_retains_the_active_render() { + let Some((mut headless, mut tracer)) = gpu() else { return }; + let scene = sphere_scene(&mut headless, crate::ibl::environment("Studio Soft", 32), &WHITE); + let camera = camera(); + let settings = TraceSettings::default(); + let display = TraceDisplay::from_display(&Default::default()); + tracer.render(&headless.device, &headless.queue, &headless.renderer, &scene, &camera, &settings, &display, [32, 24], 2).unwrap(); + let before = accumulation(&headless, &tracer); + + let mut encoder = headless.device.create_command_encoder(&Default::default()); + let error = tracer.reset(&headless.device, &mut encoder, 8192, 8192).unwrap_err(); + + assert!(error.contains("exceeds this GPU's buffer limit")); + assert!(tracer.acc.is_some(), "a rejected resize must keep the active buffers"); + assert!(tracer.bind.is_some(), "a rejected resize must keep the active bindings"); + assert_eq!(tracer.samples(), 2, "a rejected resize must keep the accumulated samples"); + assert_eq!(accumulation(&headless, &tracer), before); + assert!(tracer.pass(&headless.device, &headless.queue, &mut encoder, &camera, &settings, 1)); + let output = GpuTracer::output_texture(&headless.device, 32, 24); + assert!(tracer.resolve(&headless.device, &headless.queue, &mut encoder, &display, &output.create_view(&Default::default()))); + headless.queue.submit([encoder.finish()]); + assert!(crate::readback::Readback::blocking(&headless.device, &headless.queue, &output).is_some()); + assert_eq!(tracer.samples(), 3); + } + const WHITE: [(Channel, [f32; 3]); 3] = [(Channel::BaseColor, [1.0; 3]), (Channel::Metallic, [0.0; 3]), (Channel::Roughness, [0.5; 3])]; #[test] diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index fdc45c70..46f84fd7 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -55,4 +55,6 @@ web-sys = { version = "0.3", features = ["Window", "Document", "HtmlElement", "H eframe = { workspace = true, features = ["x11"] } # Offscreen pictures of the whole window (tests/ui_snapshots.rs). egui_kittest = { version = "0.37", features = ["wgpu", "eframe"] } +# Fallible setup of the exact GPU device used by rendering regression tests. +pollster = "0.4" image = { workspace = true } diff --git a/crates/ui-egui/src/render_mode.rs b/crates/ui-egui/src/render_mode.rs index fd4ffd0d..cef71ed1 100644 --- a/crates/ui-egui/src/render_mode.rs +++ b/crates/ui-egui/src/render_mode.rs @@ -14,6 +14,7 @@ use std::sync::{Mutex, PoisonError}; use eframe::egui_wgpu::{self, CallbackResources, CallbackTrait, ScreenDescriptor}; use egui::{Color32, ColorImage, Rect, RichText, TextureHandle, TextureOptions, Ui, vec2}; +use texturecraft_engine::compose::ImageRes; use texturecraft_engine::geom::{Bvh, Mesh, OrbitCamera}; use texturecraft_render::displace::trace_geometry; use texturecraft_render::gpu_trace::GpuTracer; @@ -248,9 +249,8 @@ pub struct RenderView { env: Mutex)>>, } -/// What a traced environment is built from: the display's environment name and the identity of -/// its imported image (0: none). -type EnvKey = (String, usize); +/// The display's environment name and its retained imported image (None: built-in). +type EnvKey = (String, Option>); /// Viewport resolution of a CPU render (the web renders at half size: it has one thread). fn render_size(rect: Rect) -> (u32, u32) { @@ -287,12 +287,19 @@ fn trace_scene(app: &TextureCraftApp) -> TraceScene { }; drop(cached); - let env_key: EnvKey = (display.environment.clone(), env_image.map_or(0, |image| Arc::as_ptr(image) as usize)); let mut env_cached = app.render.env.lock().unwrap_or_else(PoisonError::into_inner); + let same_image = |source: &Option>| match (source, env_image) { + (Some(cached), Some(current)) => Arc::ptr_eq(cached, current), + (None, None) => true, + _ => false, + }; let env = match env_cached.as_ref() { - Some((cached_key, environment)) if *cached_key == env_key => environment.clone(), + Some(((name, source), environment)) if *name == display.environment && same_image(source) => environment.clone(), _ => { let environment = Arc::new(TraceScene::display_env(display, env_image.map(|image| image.as_ref()))); + + // Retaining the source prevents a later image from reusing its cached identity + let env_key = (display.environment.clone(), env_image.cloned()); *env_cached = Some((env_key, environment.clone())); environment } @@ -711,6 +718,7 @@ impl TraceCallback { } impl CallbackTrait for TraceCallback { + /// Submit tracing work and report its samples or failure to the next UI frame. fn prepare( &self, device: &wgpu::Device, diff --git a/crates/ui-egui/src/render_mode/tests.rs b/crates/ui-egui/src/render_mode/tests.rs index 2ae14be2..247acd98 100644 --- a/crates/ui-egui/src/render_mode/tests.rs +++ b/crates/ui-egui/src/render_mode/tests.rs @@ -9,6 +9,7 @@ use super::{ use texturecraft_engine::Session; use texturecraft_engine::geom::primitives; +/// A small, fully composed sphere avoids unrelated texture-loading transitions. fn session() -> Session { let mut session = Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap(); session.update(); @@ -16,6 +17,7 @@ fn session() -> Session { session } +/// Bump-strength edits invalidate GPU scene data even without displaced geometry. #[test] fn height_strength_changes_restart_the_gpu_scene_without_displacement() { let mut session = session(); @@ -28,19 +30,67 @@ fn height_strength_changes_restart_the_gpu_scene_without_displacement() { assert_ne!(gpu_scene_key(&session), before, "the GPU shader must receive the new bump strength"); } +/// Keeping an imported image alive prevents its cached identity from being reused for another image. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn environment_cache_retains_source_identity_until_replaced() { + use std::sync::Arc; + use texturecraft_engine::compose::ImageRes; + + // The harness draws once; parallel translation tests must not change its language mid-frame + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut app = egui_kittest::Harness::builder().build_eframe(|context| crate::TextureCraftApp::new(context, session())).into_state(); + app.session.doc.project.display.environment = "resource:environment".into(); + let source = Arc::new(ImageRes { width: 2, height: 1, rgba: vec![[1.0, 0.0, 0.0, 1.0]; 2], srgb: false }); + let original_source = Arc::downgrade(&source); + app.session.images.insert("environment".into(), source); + let first = super::trace_scene(&app).env; + assert!(Arc::ptr_eq(&first, &super::trace_scene(&app).env), "unchanged images reuse the decoded environment"); + + let replacement = Arc::new(ImageRes { width: 2, height: 1, rgba: vec![[0.0, 1.0, 0.0, 1.0]; 2], srgb: false }); + app.session.images.insert("environment".into(), replacement.clone()); + + assert!(original_source.upgrade().is_some(), "the cache must retain its source so its address cannot be reused"); + let second = super::trace_scene(&app).env; + assert!(!Arc::ptr_eq(&first, &second)); + assert_ne!(first.data, second.data, "replacing the image changes the lighting"); + assert!(Arc::ptr_eq(&second, &super::trace_scene(&app).env)); + assert!(original_source.upgrade().is_none(), "replacing the cache releases the previous source"); + + app.session.images.insert("renamed".into(), replacement); + app.session.doc.project.display.environment = "resource:renamed".into(); + assert!(!Arc::ptr_eq(&second, &super::trace_scene(&app).env), "the environment name is also part of the key"); +} + +/// Create one harness device, skipping unavailable or non-compute backends. #[cfg(not(target_arch = "wasm32"))] fn gpu_app() -> Option { - match texturecraft_render::headless::Headless::new() { - Ok(headless) if super::GpuTracer::supported(&headless.device) => {} - _ => { - eprintln!("skipping: no compute-capable GPU adapter"); + use eframe::egui_wgpu::{RenderState, RendererOptions, WgpuConfiguration}; + use egui_kittest::wgpu::{WgpuTestRenderer, default_wgpu_setup}; + + let setup = default_wgpu_setup(); + let instance = pollster::block_on(setup.new_instance()); + let configuration = WgpuConfiguration { wgpu_setup: setup, ..Default::default() }; + let render_state = match pollster::block_on(RenderState::create(&configuration, &instance, None, RendererOptions::PREDICTABLE)) { + Ok(render_state) => render_state, + Err(error) => { + eprintln!("skipping: could not create the harness GPU device: {error}"); return None; } + }; + + let adapter = render_state.adapter.get_info(); + if !super::GpuTracer::supported(&render_state.device) { + eprintln!("skipping: harness adapter {} ({:?}) cannot run the GPU tracer", adapter.name, adapter.backend); + return None; } + eprintln!("GPU lifecycle test adapter: {} ({:?})", adapter.name, adapter.backend); + // The harness draws once; parallel translation tests must not change its language mid-frame + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let mut app = egui_kittest::Harness::builder() .with_size(egui::vec2(800.0, 600.0)) - .wgpu() + .renderer(WgpuTestRenderer::from_render_state(render_state)) .build_eframe(|context| crate::TextureCraftApp::new(context, session())) .into_state(); app.session.update(); @@ -51,6 +101,7 @@ fn gpu_app() -> Option { Some(app) } +/// Build a GPU rendering frame at a controlled time without executing its callback. #[cfg(not(target_arch = "wasm32"))] fn draw_gpu(app: &mut crate::TextureCraftApp, context: &egui::Context, time: f64) -> egui::FullOutput { context.run_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { @@ -58,6 +109,7 @@ fn draw_gpu(app: &mut crate::TextureCraftApp, context: &egui::Context, time: f64 }) } +/// A first completed callback must survive a slow frame's switch to full resolution. #[cfg(not(target_arch = "wasm32"))] #[test] fn settling_after_the_first_gpu_frame_keeps_its_image() { @@ -80,6 +132,7 @@ fn settling_after_the_first_gpu_frame_keeps_its_image() { assert_eq!(view.held, Some(previous_texture)); } +/// A finished low-sample render must wake again to release its retained preview. #[cfg(not(target_arch = "wasm32"))] #[test] fn a_low_sample_limit_schedules_the_held_image_timeout() { @@ -159,6 +212,7 @@ fn a_moving_camera_traces_smaller_and_a_still_one_at_full_size() { assert_eq!(traced_size((20, 400), true), (16, 200)); } +/// Camera changes and unfinished uploads keep the preview small until activity settles. #[test] fn motion_starts_on_a_camera_change_and_settles_after_a_moment() { let mut motion = Motion::default(); @@ -176,6 +230,7 @@ fn motion_starts_on_a_camera_change_and_settles_after_a_moment() { assert!(!motion.moving(&camera, 5.0 + MOTION_SETTLE_S * 1.5, false)); } +/// Either sufficient samples or the deadline replaces the retained preview. #[test] fn the_soft_image_stays_until_the_full_size_render_has_samples_or_time_runs_out() { assert!(holds_previous(0, 0.0)); @@ -184,6 +239,7 @@ fn the_soft_image_stays_until_the_full_size_render_has_samples_or_time_runs_out( assert!(!holds_previous(0, SETTLE_HOLD_MAX_S), "a slow GPU: don't hold it forever"); } +/// Sampling grows gradually, holds through jitter and cuts promptly on overload. #[test] fn samples_per_frame_grow_slowly_hold_in_between_and_drop_fast() { let (floor, free) = (1.0 / 144.0, SPP_GROW_PAUSE_FRAMES); @@ -251,6 +307,7 @@ fn a_few_very_quick_frames_do_not_collapse_the_samples_per_frame() { assert!(spp >= 4, "12 ms frames after 3 ms ones are fine: {spp}"); } +/// Invalid timings are ignored and old timings expire within the bounded window. #[test] fn the_frame_floor_is_the_quickest_recent_frame_within_range() { let mut floor = FrameFloor::default(); @@ -267,6 +324,7 @@ fn the_frame_floor_is_the_quickest_recent_frame_within_range() { assert_eq!(floor.push(0.2), FLOOR_RANGE_S.1, "only recent frames count, and at most 1/30 s"); } +/// Resolution changes preserve approximate tracing work within the sample limits. #[test] fn samples_per_frame_follow_the_pixel_count_when_the_size_changes() { assert_eq!(rescale_spp(12, (500, 400), (1000, 800)), 3, "four times the pixels: a quarter of the samples"); @@ -275,6 +333,7 @@ fn samples_per_frame_follow_the_pixel_count_when_the_size_changes() { assert_eq!(rescale_spp(16, (100, 100), (10, 10)), MAX_SPP, "never above the cap"); } +/// Loading throttles texture synchronization without delaying the first or settled update. #[test] fn loading_textures_are_taken_in_at_a_limited_rate() { assert!(take_in_textures(false, 1.0, 1.0), "not loading: every frame"); @@ -283,6 +342,7 @@ fn loading_textures_are_taken_in_at_a_limited_rate() { assert!(take_in_textures(true, 0.0, f64::MIN), "the first frame always"); } +/// The placeholder appears only before the first image has been traced. #[test] fn nothing_traced_yet_shows_the_placeholder() { assert!(!show_image(false, 0)); diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 61593bc9..4ca66c96 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -28,6 +28,7 @@ fn save(h: &mut Harness<'_, TextureCraftApp>, dir: &Path, name: &str) { eprintln!("wrote {}", path.display()); } +/// Capture the moving preview and settled render after submitting real GPU callbacks. #[test] #[ignore] fn rendering_mode_snapshots() {