From bc640e31584ebaa177ad9d8d9bd4c87705176588 Mon Sep 17 00:00:00 2001 From: Ralph Kuepper Date: Mon, 16 Nov 2026 12:52:48 +0100 Subject: [PATCH 1/5] fix(renderer): drop the material stub handles instead of forgetting them MaterialSystem::new mem::forget-ed a stub depth texture, two of its views and the comparison sampler, on the theory that the bind group keeps them alive. It does - without the forget. A forgotten wgpu handle never releases its reference, and every handle holds the device, so no renderer's device (or any memory heap it had allocated) was ever freed: ~580 MB per renderer on a Radeon 760M, on DX12 and Vulkan alike. The golden suite, which builds a renderer per test, ran out of GPU memory after ~30 (41 failures in a serial run on Windows). Measured with a create/drop loop: private bytes now stay flat. --- native/shared/src/renderer/material_system.rs | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/native/shared/src/renderer/material_system.rs b/native/shared/src/renderer/material_system.rs index d6dbbb4a..24a6998d 100644 --- a/native/shared/src/renderer/material_system.rs +++ b/native/shared/src/renderer/material_system.rs @@ -628,12 +628,18 @@ impl MaterialSystem { layout: &layouts.per_view, entries: &per_view_entries, }); - // The stub_depth texture and cmp_sampler outlive the bind group via - // wgpu internal Arc; we don't need to hold them in the struct. - std::mem::forget(stub_depth); - std::mem::forget(stub_depth_view); - std::mem::forget(stub_depth_array_view); - std::mem::forget(cmp_sampler); + // The stub depth texture, its views and cmp_sampler stay alive for as + // long as the bind group does (wgpu holds its own references), so the + // handles are simply dropped here. They used to be `mem::forget`-ed: + // a forgotten handle never releases its reference, and every handle + // holds the device, so no renderer's device (and none of the memory + // heaps it had allocated, ~580 MB on a Radeon 760M) was ever freed. + // A process that built renderers in turn (the golden suite) ran out + // of memory after about 30. + drop(stub_depth); + drop(stub_depth_view); + drop(stub_depth_array_view); + drop(cmp_sampler); // Default MaterialFactors UBO. let default_mf = MaterialFactorsUniforms::default(); From 099746c1e130a62bcb09852f69c2a1f372b51384 Mon Sep 17 00:00:00 2001 From: Ralph Kuepper Date: Mon, 16 Nov 2026 12:52:48 +0100 Subject: [PATCH 2/5] fix(renderer): rebuild targets from the window size; test output scale and renderer teardown set_temporal_upscale and rebuild_render_targets read native_width/height directly, which is 0 before the platform's first resize, and resize(0, 0) configures a 1x1 surface; they use native_size() now, like set_render_scale. Tests: the output scale stays applied once through render-scale and temporal-upscale changes (it compounded before set_render_scale's fix: a 4K window at 0.75 ended at 1215x683 after four dynamic-resolution steps), and dropping a renderer leaves no texture memory or views alive (82 KB and 3 views before the previous commit). --- native/shared/src/renderer/quality_preset.rs | 6 +- native/shared/tests/render_targets.rs | 72 ++++++++++++++++++++ 2 files changed, 76 insertions(+), 2 deletions(-) diff --git a/native/shared/src/renderer/quality_preset.rs b/native/shared/src/renderer/quality_preset.rs index a01bf0c7..2d0f3359 100644 --- a/native/shared/src/renderer/quality_preset.rs +++ b/native/shared/src/renderer/quality_preset.rs @@ -225,7 +225,7 @@ impl Renderer { } fn rebuild_render_targets(&mut self) { - let (w, h) = (self.native_width, self.native_height); + let (w, h) = self.native_size(); let (lw, lh) = (self.logical_width, self.logical_height); if w > 0 && h > 0 { self.resize(w, h, lw, lh); @@ -246,7 +246,9 @@ impl Renderer { self.taa_frame_index = 0; self.taa_history_valid = false; self.taa_history_written = false; - let (w, h) = (self.native_width, self.native_height); + // native_size(): before the platform's first resize native_width is 0, + // and resize(0, 0) would configure a 1 x 1 surface. + let (w, h) = self.native_size(); self.resize(w, h, self.logical_width, self.logical_height); } } diff --git a/native/shared/tests/render_targets.rs b/native/shared/tests/render_targets.rs index 5dc38b9b..0f9e0136 100644 --- a/native/shared/tests/render_targets.rs +++ b/native/shared/tests/render_targets.rs @@ -247,3 +247,75 @@ fn deferred_frame_writes_render_target_override() { px ); } + +/// The output scale applies once, to the window's size. Changing the render +/// scale (dynamic resolution does it all the time) or the temporal upscaler +/// rebuilds from the window, never from the already scaled surface: that once +/// applied the output scale again per change, and a 4K window at 0.75 ended at +/// 1215 x 683 after four render-scale steps. +#[test] +fn output_scale_does_not_compound_through_render_scale_changes() { + let Some(mut r) = try_renderer() else { + eprintln!("no GPU adapter — skipping"); + return; + }; + r.set_output_scale(0.5); + assert_eq!((r.physical_width(), r.physical_height()), (128, 128)); + for s in [0.75, 0.5, 1.0, 0.6, 0.85] { + r.set_render_scale(s); + assert_eq!( + (r.physical_width(), r.physical_height()), + (128, 128), + "surface shrank after set_render_scale({s})" + ); + assert_eq!(r.render_target_extent(), r.render_extent()); + } + r.set_temporal_upscale(false); + r.set_temporal_upscale(true); + assert_eq!((r.physical_width(), r.physical_height()), (128, 128)); + r.set_output_scale(1.0); + assert_eq!((r.physical_width(), r.physical_height()), (256, 256)); +} + +/// Dropping a renderer releases every GPU object it made. The material system +/// once `mem::forget`-ed a stub depth texture, two views and a sampler; each +/// handle holds the device, so no renderer's device or memory heaps were ever +/// freed (about 580 MB per renderer on a Radeon 760M, and the golden suite ran +/// out of memory after ~30 renderers). +#[test] +fn dropping_a_renderer_releases_its_textures() { + let instance = wgpu::Instance::new(wgpu::InstanceDescriptor { + backends: wgpu::Backends::from_env().unwrap_or(wgpu::Backends::all()), + ..wgpu::InstanceDescriptor::new_without_display_handle() + }); + let Ok(adapter) = + pollster::block_on(instance.request_adapter(&wgpu::RequestAdapterOptions::default())) + else { + eprintln!("no GPU adapter — skipping"); + return; + }; + if adapter.get_info().device_type == wgpu::DeviceType::Cpu { + eprintln!("software adapter — skipping"); + return; + } + let Ok((device, queue)) = pollster::block_on(adapter.request_device(&wgpu::DeviceDescriptor { + required_limits: adapter.limits(), + ..Default::default() + })) else { + return; + }; + let keep = device.clone(); + let mut r = Renderer::new_headless(device, queue, 256, 256); + r.begin_frame(); + r.end_frame(); + let live = keep.get_internal_counters().hal; + assert!(live.texture_memory.read() > 0, "wgpu counters are off: the check would be vacuous"); + drop(r); + let _ = keep.poll(wgpu::PollType::wait_indefinitely()); + let after = keep.get_internal_counters().hal; + assert_eq!( + (after.texture_memory.read(), after.texture_views.read()), + (0, 0), + "textures outlived their renderer" + ); +} From dfeeec1c38fe65d51c49b646f45cc6c85ce8d366 Mon Sep 17 00:00:00 2001 From: Ralph Kuepper Date: Mon, 16 Nov 2026 12:52:48 +0100 Subject: [PATCH 3/5] perf(renderer): skip planar probes nobody sees and draws too small to show A planar probe redraws the scene mirrored, almost all of it vertex work: in the shooter on a Radeon 760M the water probe cost 5 ms of a 27 ms fight frame (40.6 fps without it, 31.7 with). Two culls that cannot change the picture: - a probe renders only on frames where a draw whose material samples it is inside the main frustum (instanced or unbounded draws count as visible); - a cached model or scene node whose bounding sphere covers under 3 probe pixels, seen from the mirrored eye, is not drawn into the probe. --- native/shared/src/renderer/planar_pass.rs | 72 +++++++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/native/shared/src/renderer/planar_pass.rs b/native/shared/src/renderer/planar_pass.rs index 9ebbf2b8..2f6a3f4b 100644 --- a/native/shared/src/renderer/planar_pass.rs +++ b/native/shared/src/renderer/planar_pass.rs @@ -329,10 +329,52 @@ impl Renderer { // Iterate probes by index — we mutate `material_system`'s // commands view while iterating, so collect the work first. let probe_count = self.planar_probes.len(); + // Render a probe only on frames where something that samples it is in + // view. A probe redraws the scene mirrored (5 ms of a 27 ms fight frame + // on a Radeon 760M, almost all of it vertex work), and a reflection + // nobody sees is pure cost: in an arena whose river is behind the + // camera half the time, that was most frames. A probe skipped this way + // is simply not sampled; the frame the surface comes back into view + // renders it before the main pass reads it. + let probe_seen = { + let main_planes = crate::scene::extract_frustum_planes(&self.current_vp_matrix); + let ms = &self.material_system; + let mut seen = vec![false; probe_count]; + for cmd in ms.commands.iter().chain(ms.translucent_commands.iter()) { + let link = (cmd.material as usize) + .checked_sub(1) + .and_then(|m| ms.material_reflection_probe.get(m).copied().flatten()); + let slot = match link { + Some(p) if p >= 1 && (p as usize) <= probe_count => p as usize - 1, + _ => continue, + }; + if seen[slot] { + continue; + } + // Instanced or unknown bounds: assume visible. + let visible = match (cmd.instance, self.model_gpu_cache.get(&cmd.mesh_handle)) { + (None, Some(Some(meshes))) if cmd.mesh_idx < meshes.len() => { + let m = &meshes[cmd.mesh_idx]; + let (wmin, wmax) = transform_aabb(&cmd.model, m.local_min, m.local_max); + !(wmin[0] <= wmax[0] + && crate::scene::aabb_outside_frustum(&main_planes, wmin, wmax)) + } + _ => true, + }; + if visible { + seen[slot] = true; + } + } + seen + }; for i in 0..probe_count { + if !probe_seen[i] { + continue; + } let ( plane_y, normal, + probe_res, color_view, depth_view, aux_material_view, @@ -342,6 +384,7 @@ impl Renderer { Some(p) => ( p.plane_y, p.normal, + p.resolution, p.color_view.clone(), p.depth_view.clone(), p.aux_material_view.clone(), @@ -538,6 +581,29 @@ impl Renderer { // creation order decides who survives the cap, so games // should create hero geometry before filler (grass). let mirror_planes = crate::scene::extract_frustum_planes(&mirror_vp); + // Projected-size cull. The probe is small (512 px in the shooter) and + // the water shows it rippled, yet every draw the mirrored frustum can + // see used to be drawn at full detail: on an integrated GPU the forest + // in the reflection cost 5 ms of a 28 ms frame. A draw whose bounding + // sphere covers less than PROBE_MIN_PX probe pixels, seen from the + // mirrored eye, cannot show; skip it. (Vertical extent; proj[1][1] is + // cot(fov_y / 2) in both matrix conventions.) + const PROBE_MIN_PX: f32 = 3.0; + let px_per_unit_at_1m = proj[1][1] * probe_res as f32 * 0.5; + let too_small = |wmin: [f32; 3], wmax: [f32; 3]| -> bool { + if wmin[0] > wmax[0] { + return false; // no bounds: keep it + } + let c = [ + (wmin[0] + wmax[0]) * 0.5 - mirror_cam[0], + (wmin[1] + wmax[1]) * 0.5 - mirror_cam[1], + (wmin[2] + wmax[2]) * 0.5 - mirror_cam[2], + ]; + let e = [wmax[0] - wmin[0], wmax[1] - wmin[1], wmax[2] - wmin[2]]; + let r = 0.5 * (e[0] * e[0] + e[1] * e[1] + e[2] * e[2]).sqrt(); + let d = (c[0] * c[0] + c[1] * c[1] + c[2] * c[2]).sqrt(); + d > r && 2.0 * r / d * px_per_unit_at_1m < PROBE_MIN_PX + }; let mut reflect_draws: Vec<(u64, usize, u32)> = Vec::new(); let mut node_slots: Vec<(usize, u32)> = Vec::new(); if let Some(model_buf) = &self.reflect_model_buf { @@ -573,6 +639,9 @@ impl Renderer { { continue; } + if too_small(wmin, wmax) { + continue; + } let mirror_mvp = mat4_multiply(mirror_vp, cmd.model); let base = staged.len(); staged.resize(base + stride, 0); @@ -590,6 +659,9 @@ impl Renderer { { continue; } + if too_small(*wmin, *wmax) { + continue; + } let mirror_mvp = mat4_multiply(mirror_vp, *model); let base = staged.len(); staged.resize(base + stride, 0); From a1a4b83f78ecf0bb2651b73627d9d31c4e6afdce Mon Sep 17 00:00:00 2001 From: Ralph Kuepper Date: Mon, 16 Nov 2026 12:52:48 +0100 Subject: [PATCH 4/5] test(golden): WGPU_BACKEND picks the backend; memory gate accepts Vulkan's texture count wgpu-hal 29's Vulkan backend never counts a created texture (only add_raw_texture does) but subtracts on every destroy, so hal.textures reads negative there (-76), and Vulkan is the default pick on Windows: the static-ultra memory test failed its 'counters enabled' precondition. It now accepts live texture memory instead; texture memory and views are counted both ways on every backend and still catch a leaked texture in the growth check. WGPU_BACKEND=vulkan|dx12 narrows try_engine's adapter pick. --- native/shared/tests/golden_render.rs | 3 ++- native/shared/tests/golden_render/lighting_upload.rs | 7 ++++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/native/shared/tests/golden_render.rs b/native/shared/tests/golden_render.rs index 6fd0cc4d..1287edc5 100644 --- a/native/shared/tests/golden_render.rs +++ b/native/shared/tests/golden_render.rs @@ -383,7 +383,8 @@ fn capture_realtime_diagnostics(eng: &mut EngineState, final_rgba: &[u8]) { } fn try_engine() -> Option { let instance = wgpu::Instance::new(wgpu::InstanceDescriptor { - backends: wgpu::Backends::all(), + // WGPU_BACKEND=vulkan|dx12|metal|gl narrows the pick (Windows has two views of one GPU). + backends: wgpu::Backends::from_env().unwrap_or(wgpu::Backends::all()), ..wgpu::InstanceDescriptor::new_without_display_handle() }); let adapter = diff --git a/native/shared/tests/golden_render/lighting_upload.rs b/native/shared/tests/golden_render/lighting_upload.rs index 3f57edd6..facdfb9e 100644 --- a/native/shared/tests/golden_render/lighting_upload.rs +++ b/native/shared/tests/golden_render/lighting_upload.rs @@ -162,8 +162,13 @@ fn static_ultra_scene_has_stable_renderer_owned_memory_for_1000_frames() { run_frames(&mut eng, POOL_WARMUP_FRAMES); wait_for_gpu(&eng.renderer.device); let before = live_gpu_objects(&eng.renderer.device); + // wgpu-hal 29's Vulkan backend never counts a created texture (only + // add_raw_texture does) yet subtracts on every destroy, so `textures` reads + // negative there (-76 on a Radeon 760M, the default pick on Windows). + // Texture memory and views are counted both ways on every backend and still + // catch a leaked texture in the growth check below. assert!( - before.buffers > 0 && before.textures > 0, + before.buffers > 0 && (before.textures > 0 || before.texture_memory > 0), "wgpu test counters are disabled; this would be a vacuous memory gate: {before:?}" ); let paths_before: serde_json::Value = From 3134412f8debdd4322f83bb7f6ccdc883d93ec98 Mon Sep 17 00:00:00 2001 From: Ralph Kuepper Date: Mon, 16 Nov 2026 13:06:47 +0100 Subject: [PATCH 5/5] fix(taa): do not read history the frame has no use for With a current weight of 1 (a reset, a camera cut, the first frames) the resolve still loaded the history texture's provenance, and its stale confidence fed the reconstruction-detail term added to the output: the frame after reset_temporal_history() differed from a fresh render of the same pose by one 8-bit level. History is now read only when it can be used (the history_usable condition the blend already applies). Found by temporal_history::camera_motion_sequence_bounds_ghosting_flicker_and_cut_residue, which failed on DX12 and Vulkan on a Radeon 760M and now passes on both; golden_render 88/89 on both backends (the remaining failure, ssgi_hiz_immediate_scene_produces_finite_indirect_radiance, is SSIM 0.99844 against 0.9985 and fails on main too). --- native/shared/src/renderer/shaders/post.rs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/native/shared/src/renderer/shaders/post.rs b/native/shared/src/renderer/shaders/post.rs index 8d911156..5b295c2e 100644 --- a/native/shared/src/renderer/shaders/post.rs +++ b/native/shared/src/renderer/shaders/post.rs @@ -927,7 +927,11 @@ fn fs_main(in: VsOut) -> TaaOut { let history_in_bounds = prev_uv.x >= 0.0 && prev_uv.x <= 1.0 && prev_uv.y >= 0.0 && prev_uv.y <= 1.0; - if (history_in_bounds) { + // A current weight of 1 means there is no history to use (a reset, a camera + // cut, the first frames). Do not read it at all: its stale confidence used + // to feed the reconstruction-detail term below, so the frame after a cut + // still carried the previous camera's image at one 8-bit level. + if (history_in_bounds && current_weight < 0.999) { var h_sample = sample_history_reprojected(prev_uv, camera_moving, object_moving); if (native_camera_motion_px > 0.05) { h_sample = sample_history_catmull_rom(prev_uv);