From 86e6a9f08fab394f043308bea46172d2723508af Mon Sep 17 00:00:00 2001 From: Timon Date: Thu, 3 Dec 2026 23:21:38 +0000 Subject: [PATCH] Park adjustment uploads in the texture pool (fixup #4997) --- .../wgpu-executor/src/vello_adjustments.rs | 121 ++++++++++-------- .../wgpu-executor/src/vello_effects.rs | 19 ++- .../wgpu-executor/src/vello_render.rs | 3 +- 3 files changed, 81 insertions(+), 62 deletions(-) diff --git a/node-graph/libraries/wgpu-executor/src/vello_adjustments.rs b/node-graph/libraries/wgpu-executor/src/vello_adjustments.rs index ba606470cc..3456fd0dfd 100644 --- a/node-graph/libraries/wgpu-executor/src/vello_adjustments.rs +++ b/node-graph/libraries/wgpu-executor/src/vello_adjustments.rs @@ -2,10 +2,13 @@ //! from `vello_adjustments.wgsl`, while the kinds that compilers struggle to build inside its loop each get a shader and pass of their own. Steps read their //! settings from a texture, so changing those recompiles nothing. +use crate::WgpuExecutor; use crate::vello_effects::{WORKING_FORMAT, pass_pipeline}; use core_types::graphene_hash::CacheHash; +use glam::UVec2; use graphic_types::Adjustment; use raster_kernels::adjustment_steps::{AdjustmentSteps, StepKind, shader_constants}; +use raster_types::{Texture, TextureWeakRef}; use std::cmp::Reverse; use std::collections::HashMap; use std::ops::Range; @@ -22,11 +25,8 @@ const STANDALONE_KINDS: [StepKind; 2] = [StepKind::GradientMap, StepKind::ColorL /// How many runs of adjustments keep their encoded and uploaded steps past the render that last used them. Their tables are kept apart. const MAX_CACHED_RUNS: usize = 8; -/// How many bytes of tables stay uploaded past the render that last used them, the least recently used making way first. -const TABLE_CACHE_BYTES: u64 = 256 << 20; - -/// The most texels a run's tables span (128 MiB), past which they are resampled to fit. That's half of what the cache keeps and of the largest buffer -/// wgpu allocates by default, which an upload passes through. +/// The most texels a run's tables span (128 MiB), past which they are resampled to fit. That's half of the largest buffer wgpu allocates by default, +/// which an upload passes through. const MAX_TABLE_TEXELS: usize = 1 << 23; /// The format each pass of a run split across several hands its result on to the next in, where the GPU can render into it, so the split rounds nothing. @@ -344,15 +344,15 @@ fn texels_texture_descriptor(label: &'static str, width: u32, height: u32) -> wg } /// A texture holding `texels` in rows as wide as the GPU allows, the last padded out, or `None` if they need more rows than it allows too. -fn upload_texels(device: &wgpu::Device, queue: &wgpu::Queue, label: &'static str, texels: &[[f32; 4]]) -> Option { - let max_dimension = device.limits().max_texture_dimension_2d as usize; +fn upload_texels(executor: &WgpuExecutor, queue: &wgpu::Queue, texels: &[[f32; 4]]) -> Option { + let max_dimension = executor.context().device.limits().max_texture_dimension_2d as usize; let width = texels.len().clamp(1, max_dimension); let height = texels.len().div_ceil(width).max(1); if height > max_dimension { return None; } - let texture = device.create_texture(&texels_texture_descriptor(label, width as u32, height as u32)); + let texture = executor.request_texture_with_format(UVec2::new(width as u32, height as u32), wgpu::TextureFormat::Rgba32Float); let write_rows = |first_row: usize, rows: usize, data: &[[f32; 4]]| { let texture_rows = wgpu::TexelCopyTextureInfo { texture: &texture, @@ -397,12 +397,12 @@ pub(crate) struct PreparedPass { /// The shader and the uploaded steps of each pass carrying out a run with these `steps`, each pass's texels starting with its step count, /// or `None` if any holds more than the GPU can read. -fn upload_passes(device: &wgpu::Device, queue: &wgpu::Queue, steps: &AdjustmentSteps) -> Option> { +fn upload_passes(executor: &WgpuExecutor, queue: &wgpu::Queue, steps: &AdjustmentSteps) -> Option> { (pass_steps(steps.kinds()).into_iter()) .map(|pass| { let shader = AdjustmentShader::for_pass(&steps.kinds()[pass.clone()]); let texels: Vec<[f32; 4]> = std::iter::once([pass.len() as f32, 0., 0., 0.]).chain(steps.step_texels(pass).iter().copied()).collect(); - upload_texels(device, queue, "vello_adjustments_steps", &texels).map(|texture| (shader, texture)) + upload_texels(executor, queue, &texels).map(|texture| (shader, texture)) }) .collect() } @@ -419,15 +419,14 @@ pub(crate) struct AdjustmentUploads { struct CachedRun { hash: u64, steps: AdjustmentSteps, - passes: Option>, + passes: Option>, last_used: u64, } /// The tables of a run as uploaded, shared by every run reading the same ones, or `None` in place of the upload for tables too large for the GPU even resampled. struct CachedTables { key: u64, - uploaded: Option, - bytes: u64, + uploaded: Option, last_used: u64, } @@ -438,70 +437,92 @@ pub(crate) fn adjustment_run_hash(run: &[&Adjustment]) -> u64 { std::hash::Hasher::finish(&hasher) } +fn downgrade_passes(passes: &[(AdjustmentShader, Texture)]) -> Vec<(AdjustmentShader, TextureWeakRef)> { + passes.iter().map(|(shader, texture)| (*shader, texture.downgrade())).collect() +} + impl AdjustmentUploads { - /// What each pass carrying out `run` reads in turn, encoding and uploading only what no recent render has. A run that changes no color - /// or that holds more than the GPU can read takes no passes. Only the 64-bit hashes of the runs and of the tables' content tell them apart. - pub(crate) fn prepare(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, run: &[&Adjustment], render_count: u64) -> Vec { + /// What each pass carrying out `run` reads in turn, encoding and uploading only what no recent render has, with the uploads it reads added to `held`. + /// A run that changes no color or that holds more than the GPU can read takes no passes. Only the 64-bit hashes of the runs and of the tables' content tell them apart. + pub(crate) fn prepare(&mut self, executor: &WgpuExecutor, queue: &wgpu::Queue, run: &[&Adjustment], render_count: u64, held: &mut Vec) -> Vec { let hash = adjustment_run_hash(run); + let mut uploaded = None; let index = self.runs.iter().position(|cached| cached.hash == hash).unwrap_or_else(|| { let steps = AdjustmentSteps::encode(run); - let passes = upload_passes(device, queue, &steps); - if passes.is_none() { + uploaded = upload_passes(executor, queue, &steps); + if uploaded.is_none() { log::error!("Adjustments hold more settings than the GPU can read, so they're left out"); } self.runs.push(CachedRun { hash, steps, - passes, + passes: uploaded.as_deref().map(downgrade_passes), last_used: render_count, }); self.runs.len() - 1 }); let cached_run = &mut self.runs[index]; cached_run.last_used = render_count; - let Some(passes) = cached_run.passes.clone() else { return Vec::new() }; + let Some(cached_passes) = &cached_run.passes else { return Vec::new() }; + let parked = cached_passes.iter().map(|(shader, texture)| Some((*shader, texture.upgrade()?))).collect(); + let passes = match uploaded.or(parked) { + Some(passes) => passes, + None => { + let Some(passes) = upload_passes(executor, queue, &cached_run.steps) else { return Vec::new() }; + cached_run.passes = Some(downgrade_passes(&passes)); + passes + } + }; if passes.is_empty() { return Vec::new(); } let tables = match cached_run.steps.table_key() { Some(key) => { - let index = self.tables.iter().position(|cached| cached.key == key).unwrap_or_else(|| { - // As many texels as one texture holds and one upload carries - let limits = device.limits(); - let max_dimension = limits.max_texture_dimension_2d as usize; - let max_uploaded = (limits.max_buffer_size / size_of::<[f32; 4]>() as u64) as usize; - let texels = cached_run.steps.table_texels(MAX_TABLE_TEXELS.min(max_dimension * max_dimension).min(max_uploaded)); + let index = self.tables.iter().position(|cached| cached.key == key); + let parked = index.map(|index| self.tables[index].uploaded.as_ref().map(TextureWeakRef::upgrade)); + let tables = match parked { + Some(None) => return Vec::new(), + Some(Some(Some(tables))) => Some(tables), + Some(Some(None)) | None => { + // As many texels as one texture holds and one upload carries + let limits = executor.context().device.limits(); + let max_dimension = limits.max_texture_dimension_2d as usize; + let max_uploaded = (limits.max_buffer_size / size_of::<[f32; 4]>() as u64) as usize; + let texels = cached_run.steps.table_texels(MAX_TABLE_TEXELS.min(max_dimension * max_dimension).min(max_uploaded)); - let uploaded = upload_texels(device, queue, "vello_adjustments_tables", &texels); - if uploaded.is_none() { - log::error!("Adjustments read lookup tables holding more data than the GPU can read, so they're left out"); + let uploaded = upload_texels(executor, queue, &texels); + if uploaded.is_none() { + log::error!("Adjustments read lookup tables holding more data than the GPU can read, so they're left out"); + } + let cached = CachedTables { + key, + uploaded: uploaded.as_ref().map(Texture::downgrade), + last_used: render_count, + }; + match index { + Some(index) => self.tables[index] = cached, + None => self.tables.push(cached), + } + uploaded } - - self.tables.push(CachedTables { - key, - bytes: uploaded - .as_ref() - .map_or(0, |texture| u64::from(texture.width()) * u64::from(texture.height()) * size_of::<[f32; 4]>() as u64), - uploaded, - last_used: render_count, - }); - self.tables.len() - 1 - }); - let cached_tables = &mut self.tables[index]; - cached_tables.last_used = render_count; - let Some(uploaded) = cached_tables.uploaded.clone() else { return Vec::new() }; - Some(uploaded) + }; + let Some(tables) = tables else { return Vec::new() }; + if let Some(index) = index { + self.tables[index].last_used = render_count; + } + Some(tables) } None => None, }; + held.extend(passes.iter().map(|(_, steps)| steps.clone()).chain(tables.clone())); (passes.into_iter()) .map(|(shader, steps)| PreparedPass { shader, - steps, - tables: tables.clone(), + steps: (*steps).clone(), + tables: tables.as_ref().map(|tables| (**tables).clone()), }) .collect() } @@ -513,13 +534,7 @@ impl AdjustmentUploads { let used_this_render = self.runs.iter().take_while(|cached| cached.last_used == render_count).count(); self.runs.truncate(used_this_render.max(MAX_CACHED_RUNS)); - // Tables are kept within a byte budget instead, since one can take up hundreds of megabytes - self.tables.sort_by_key(|cached| Reverse(cached.last_used)); - let mut kept_bytes = 0; - self.tables.retain(|cached| { - kept_bytes += cached.bytes; - cached.last_used == render_count || kept_bytes <= TABLE_CACHE_BYTES - }); + self.tables.retain(|cached| cached.uploaded.as_ref().is_none_or(|tables| tables.upgrade().is_some())); } #[cfg(test)] diff --git a/node-graph/libraries/wgpu-executor/src/vello_effects.rs b/node-graph/libraries/wgpu-executor/src/vello_effects.rs index 7b8117fdb4..c8eb12f199 100644 --- a/node-graph/libraries/wgpu-executor/src/vello_effects.rs +++ b/node-graph/libraries/wgpu-executor/src/vello_effects.rs @@ -1000,7 +1000,7 @@ impl EffectPasses { // The content at full strength is read only by an operation after the run, or shown as the result where no fill fades it let full_is_read = filled.is_none() || position + run.len() < operations.len(); - let prepared_passes = recorder.textures.prepare_adjustments(device, queue, &run); + let prepared_passes = recorder.textures.prepare_adjustments(recorder.executor, queue, &run); // Each pass but the last hands its result on in the chained format, so splitting the run rounds nothing for (index, prepared) in prepared_passes.iter().enumerate() { @@ -2014,8 +2014,8 @@ pub(crate) struct EffectTextures { impl EffectTextures { /// What each pass carrying out a run of adjustments reads, as [`AdjustmentUploads::prepare`] gives it. - pub(crate) fn prepare_adjustments(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, run: &[&Adjustment]) -> Vec { - self.adjustments.prepare(device, queue, run, self.render_count) + pub(crate) fn prepare_adjustments(&mut self, executor: &WgpuExecutor, queue: &wgpu::Queue, run: &[&Adjustment]) -> Vec { + self.adjustments.prepare(executor, queue, run, self.render_count, &mut self.held) } pub(crate) fn acquire(&mut self, executor: &WgpuExecutor, size: UVec2, format: wgpu::TextureFormat) -> wgpu::Texture { @@ -2231,7 +2231,10 @@ mod tests { #[test] fn a_table_stays_uploaded_while_the_settings_beside_it_change() { - let Some(context) = futures::executor::block_on(crate::WgpuContext::for_tests()) else { return }; + let Some(executor) = futures::executor::block_on(crate::WgpuContext::for_tests()).and_then(crate::WgpuExecutor::with_context) else { + return; + }; + let context = executor.context(); let queue = context.queue.lock(); let lookup = Adjustment::ColorLookup { @@ -2241,7 +2244,7 @@ mod tests { let prepare = |textures: &mut EffectTextures, posterize_levels| { let posterize = Adjustment::Posterize { levels: posterize_levels }; // Color Lookup's pass and then Posterize's, which share the run's tables - let mut prepared = textures.prepare_adjustments(&context.device, &queue, &[&lookup, &posterize]); + let mut prepared = textures.prepare_adjustments(&executor, &queue, &[&lookup, &posterize]); prepared.pop().map(|prepared| (prepared.steps, prepared.tables)) }; @@ -2253,11 +2256,13 @@ mod tests { panic!("The run reads its table") }; assert!(first_steps == again_steps && first_table == again_table); + let Some((other_steps, _)) = prepare(&mut textures, 5) else { panic!("The run reads its table") }; + assert!(other_steps != first_steps); for levels in 5..20 { - let Some((steps, Some(table))) = prepare(&mut textures, levels) else { + let Some((_, Some(table))) = prepare(&mut textures, levels) else { panic!("The run reads its table") }; - assert!(steps != first_steps && table == first_table); + assert!(table == first_table); textures.finish_render(); } diff --git a/node-graph/libraries/wgpu-executor/src/vello_render.rs b/node-graph/libraries/wgpu-executor/src/vello_render.rs index 1cdddefb57..994e51cc53 100644 --- a/node-graph/libraries/wgpu-executor/src/vello_render.rs +++ b/node-graph/libraries/wgpu-executor/src/vello_render.rs @@ -622,7 +622,6 @@ impl ImageTextures { precise_format: wgpu::TextureFormat, held: &mut Vec, ) -> Option { - let device = &executor.context().device; let (effect_passes, effect_textures) = effects; let run: Vec<&Adjustment> = run.iter().collect(); let run_hash = adjustment_run_hash(&run); @@ -643,7 +642,7 @@ impl ImageTextures { image_texture.adjusted.retain(|copy| copy.run_hash != run_hash); // A run that changes no color draws the texture itself - let prepared = effect_textures.prepare_adjustments(device, queue, &run); + let prepared = effect_textures.prepare_adjustments(executor, queue, &run); if prepared.is_empty() { return Some(image.create_view(&wgpu::TextureViewDescriptor::default())); }