diff --git a/Cargo.lock b/Cargo.lock index 95942518d..4f7cae72e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6141,6 +6141,7 @@ dependencies = [ "chrono", "craft-usd", "epaint_default_fonts", + "half", "image", "processkit", "rayon", diff --git a/apps/texturecraft/src/gpu.rs b/apps/texturecraft/src/gpu.rs index 0bb474c38..b69a382db 100644 --- a/apps/texturecraft/src/gpu.rs +++ b/apps/texturecraft/src/gpu.rs @@ -142,6 +142,9 @@ pub fn configure(options: &mut NativeOptions, cli_gpu: Option, cli_power if let WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup { create.power_preference = effective_power; + + // Allocations past the system's GPU memory budget fail cleanly, so the compositor frees its caches and retries + create.instance_descriptor.memory_budget_thresholds = texturecraft_ui_egui::gpu_memory::instance_thresholds(); let device_descriptor = create.device_descriptor.clone(); create.device_descriptor = Arc::new(move |adapter| { let mut descriptor = device_descriptor(adapter); diff --git a/crates/automation/Cargo.toml b/crates/automation/Cargo.toml index 7177c869c..a11320762 100644 --- a/crates/automation/Cargo.toml +++ b/crates/automation/Cargo.toml @@ -37,3 +37,4 @@ rustix = { workspace = true } [dev-dependencies] tempfile = "3" rmcp = { workspace = true, features = ["client"] } +texturecraft-render = { workspace = true, features = ["test-support"] } diff --git a/crates/automation/src/headless.rs b/crates/automation/src/headless.rs index 81c957087..499b497a6 100644 --- a/crates/automation/src/headless.rs +++ b/crates/automation/src/headless.rs @@ -443,8 +443,8 @@ impl Headless { let session = &mut self.session; let out = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| gpu.render(session, kind, size, camera))); let (w, h, rgba) = match out { - Ok(Some(px)) => px, - Ok(None) => return Err(AutomationError::Other("the GPU returned no image".into())), + Ok(Ok(px)) => px, + Ok(Err(error)) => return Err(AutomationError::Other(format!("cannot render: {error}"))), Err(_) => { self.gpu = None; return Err(AutomationError::Other("the GPU renderer failed".into())); diff --git a/crates/automation/src/render.rs b/crates/automation/src/render.rs index 11d6b2c23..3a625a695 100644 --- a/crates/automation/src/render.rs +++ b/crates/automation/src/render.rs @@ -9,10 +9,16 @@ use texturecraft_engine::compose::{DisplayKind, ImageRes, all_tiles, tile_bytes} use texturecraft_engine::core::AoMixing; use texturecraft_engine::{Session, ViewMode}; use texturecraft_render::displace::trace_geometry; +use texturecraft_render::gpu_aux_view::AuxSource; +use texturecraft_render::gpu_composite::CompositeProgram; use texturecraft_render::gpu_trace::GpuTracer; use texturecraft_render::trace::{TraceDisplay, TraceScene, TraceSet, TraceSettings, Tracer}; use texturecraft_render::{Frame, Shade, ViewKind}; +mod refused; + +use refused::Refused; + /// A headless GPU device that remembers what it already holds of the session. pub struct Gpu { h: texturecraft_render::headless::Headless, @@ -21,12 +27,52 @@ pub struct Gpu { env: (String, Option>), /// The GPU path tracer, created by the first [`Gpu::path_trace`]. tracer: Option, + /// Whether texture sets composite their layers on the GPU (the default); off, every set + /// composites on the CPU + gpu_compositing: bool, + /// Per texture set, the material the GPU last composited or refused (None: neither yet) + composited: Vec>, + /// Whether the GPU draws the mesh-map, image and ID-mask views: on a hardware adapter, also + /// where its layer compositing is off (GL), unless compositing on the CPU was chosen + gpu_views: bool, +} + +/// What a texture set's GPU composite was made from: the mesh, the set's material revision and +/// size, and the environment a lit program read +#[derive(Clone, PartialEq)] +struct GpuComposite { + mesh: u64, + revision: u64, + size: (u32, u32), + /// The environment's name, image and turn, for a program lit by it + environment: Option<(String, usize, f32)>, + /// Whether the GPU composited the set (false: the GPU refused it, so the CPU composites it) + on_gpu: bool, } impl Gpu { /// Errors when there is no GPU (or software) adapter. pub fn new() -> Result { - Ok(Gpu { h: texturecraft_render::headless::Headless::new()?, mesh_id: 0, sets: Vec::new(), env: Default::default(), tracer: None }) + let h = texturecraft_render::headless::Headless::new()?; + + // A software or GL adapter is no GPU to composite on: like the desktop app, the CPU does + let info = h.device.adapter_info(); + let gpu_views = info.device_type != texturecraft_render::wgpu::DeviceType::Cpu; + let gpu_compositing = gpu_views && info.backend != texturecraft_render::wgpu::Backend::Gl; + Ok(Gpu { h, mesh_id: 0, sets: Vec::new(), env: Default::default(), tracer: None, gpu_compositing, composited: Vec::new(), gpu_views }) + } + + /// Composite layers on the GPU (the default on a hardware adapter) or on the CPU only. + pub fn set_gpu_compositing(&mut self, on: bool) { + self.gpu_views = on && self.h.device.adapter_info().device_type != texturecraft_render::wgpu::DeviceType::Cpu; + if !self.gpu_views { + self.h.renderer.release_aux_view_sources(); + } + if on != self.gpu_compositing { + self.gpu_compositing = on; + self.composited.clear(); + self.sets.clear(); + } } pub fn adapter(&self) -> &str { @@ -34,8 +80,7 @@ impl Gpu { } /// Bring the GPU up to date with the session (mesh, texture sets, environment, dirty tiles). - fn sync(&mut self, session: &mut Session) { - session.update(); + fn sync(&mut self, session: &mut Session) -> Result<(), String> { let headless = &mut self.h; let mut reupload = false; if self.mesh_id != session.mesh_id { @@ -59,6 +104,27 @@ impl Gpu { self.env = (display.environment.clone(), image.map(Arc::downgrade)); } + // Uploaded view sources stay only while a view drawn from them is shown + if !matches!(session.view, ViewMode::MeshMap(_) | ViewMode::Image) { + headless.renderer.release_aux_view_sources(); + } + + // The GPU composites first, so the CPU never composites the tiles of a set it holds + self.composited.resize(session.caches.len(), None); + if reupload { + self.composited.iter_mut().for_each(|composited| *composited = None); + } + let mut on_gpu = vec![false; session.caches.len()]; + for (ts, gpu) in on_gpu.iter_mut().enumerate() { + let was_gpu = self.composited[ts].as_ref().is_some_and(|done| done.on_gpu); + *gpu = self.gpu_compositing && composite_set(headless, session, ts, &mut self.composited[ts])?; + if was_gpu && !*gpu { + // Back on the CPU: every tile it has ready replaces the GPU's + session.caches[ts].queue_ready_uploads(); + } + } + session.update_for_view_where(f64::INFINITY, || 0.0, Default::default(), |ts| !on_gpu.get(ts).copied().unwrap_or(false)); + for set_index in 0..session.caches.len() { let mut tiles = session.take_uploads(set_index); let Some(cache) = session.caches.get(set_index) else { continue }; @@ -72,7 +138,7 @@ impl Gpu { // Limit live converted pixels while retaining parallel conversion within each batch const UPLOAD_TILES_PER_BATCH: usize = 64; - for batch in tiles.chunks(UPLOAD_TILES_PER_BATCH) { + for batch in tiles.chunks(UPLOAD_TILES_PER_BATCH).filter(|_| !on_gpu[set_index]) { let bytes: Vec<_> = batch .par_iter() .flat_map_iter(|&(tile_x, tile_y)| DisplayKind::ALL.into_iter().map(move |kind| (kind, tile_x, tile_y))) @@ -84,46 +150,71 @@ impl Gpu { } // The aux texture behind the mesh-map and mask views (rebuilt every render) - let resolution = texturecraft_render::aux_size(cache.size); + let shift = texturecraft_render::set_shift(cache.size, 0, headless.device.limits().max_texture_dimension_2d); + let extent = texturecraft_render::aux_extent(cache.size, shift); let aux = match session.view { - ViewMode::MeshMap(map) => Some(( - (resolution, resolution), - texturecraft_render::mesh_maps::mesh_map_rgba(session.doc.baked.get(&set_index), map, resolution, cache.size, &composite.block_scales), - )), + ViewMode::MeshMap(map) if self.gpu_views => { + let source = AuxSource::mesh_map(session.doc.baked.get(&set_index), map, &composite.block_scales); + headless.renderer.draw_aux_view(&headless.device, &headless.queue, set_index, &source)?; + None + } + ViewMode::MeshMap(map) => { + Some(texturecraft_render::mesh_maps::mesh_map_rgba(session.doc.baked.get(&set_index), map, extent, cache.size, &composite.block_scales)) + } ViewMode::Mask(id) if session.doc.project.locate(id).is_some_and(|(set, _, _)| set == set_index) => { - let extent = texturecraft_render::mask_view_extent(cache.size); - session.mask_view_rgba(id, extent).map(|rgba| (extent, rgba)) + if self.gpu_compositing && composite_mask(headless, session, set_index, id)? { None } else { session.mask_view_rgba(id, extent) } } _ => None, }; - if let Some((extent, rgba)) = aux { - headless.renderer.upload_aux_sized(&headless.device, &headless.queue, set_index, extent, &rgba); + if let Some(rgba) = aux { + headless.renderer.upload_aux(&headless.device, &headless.queue, set_index, extent, &rgba); } } + Ok(()) } - /// Upload one resampled image at a time to the sets this viewport draws. - fn upload_view_image(&mut self, session: &Session, kind: ViewKind) { - let mut sets_by_resolution = BTreeMap::>::new(); + /// Show the "Other..." view image on the sets this viewport draws: drawn on the GPU where + /// layers composite there, else resampled on the CPU once per aux size. + fn upload_view_image(&mut self, session: &Session, kind: ViewKind) -> Result<(), String> { + let image = session.view_image.as_deref().and_then(|name| session.images.get(name)); + let mut sets_by_extent = BTreeMap::<(u32, u32), Vec>::new(); + let max_side = self.h.device.limits().max_texture_dimension_2d; for (index, set) in session.doc.project.texture_sets.iter().enumerate() { if set.visible && !matches!(kind, ViewKind::Uv { ts, .. } if ts != index) { - sets_by_resolution.entry(texturecraft_render::aux_size(set.size())).or_default().push(index); + if self.gpu_views { + if let Some(image) = image { + self.h.renderer.draw_aux_view(&self.h.device, &self.h.queue, index, &AuxSource::Image(image.clone()))?; + } + continue; + } + sets_by_extent + .entry(texturecraft_render::aux_extent(set.size(), texturecraft_render::set_shift(set.size(), 0, max_side))) + .or_default() + .push(index); } } - for (resolution, sets) in sets_by_resolution { - let Some(pixels) = session.image_view_rgba(resolution) else { continue }; + for (extent, sets) in sets_by_extent { + let Some(pixels) = session.image_view_rgba(extent) else { continue }; for index in sets { - self.h.renderer.upload_aux(&self.h.device, &self.h.queue, index, resolution, &pixels); + self.h.renderer.upload_aux(&self.h.device, &self.h.queue, index, extent, &pixels); } } + Ok(()) } - /// Render `s` with `kind` at `size` through `camera`; RGBA8 (sRGB) pixels. - pub fn render(&mut self, s: &mut Session, kind: ViewKind, size: [u32; 2], camera: texturecraft_engine::geom::OrbitCamera) -> Option<(u32, u32, Vec)> { - self.sync(s); + /// Render `s` with `kind` at `size` through `camera`; RGBA8 (sRGB) pixels. Errors when the + /// GPU reports an error compositing or drawing a view (nothing is redone on the CPU). + pub fn render( + &mut self, + s: &mut Session, + kind: ViewKind, + size: [u32; 2], + camera: texturecraft_engine::geom::OrbitCamera, + ) -> Result<(u32, u32, Vec), String> { + self.sync(s)?; if s.view == ViewMode::Image { - self.upload_view_image(s, kind); + self.upload_view_image(s, kind)?; } let frame = Frame { @@ -135,7 +226,7 @@ impl Gpu { visible: s.doc.project.texture_sets.iter().map(|t| t.visible).collect(), overlay: Vec::new(), }; - self.h.render(&frame) + self.h.render(&frame).ok_or_else(|| "the GPU returned no image".to_string()) } /// [`path_trace`] on the GPU (compute shaders); errors when the adapter or the scene does @@ -148,7 +239,7 @@ impl Gpu { samples: u32, settings: &TraceSettings, ) -> Result<(u32, u32, Vec), String> { - self.sync(s); + self.sync(s)?; let (scene, display) = trace_inputs(s); let h = &self.h; let tracer = match &mut self.tracer { @@ -159,6 +250,93 @@ impl Gpu { } } +/// The project the GPU compiles for the view: a soloed layer's isolated copy for the material, +/// the document's own for a mask (the desktop viewport's `view_project`) +fn view_project(session: &Session, mask_view: bool) -> std::borrow::Cow<'_, texturecraft_engine::core::Project> { + let solo = session.solo.filter(|_| !mask_view); + let soloed = solo.and_then(|solo| texturecraft_engine::compose::solo_project(&session.doc.project, solo.layer, solo.ignore_mask)); + soloed.map_or(std::borrow::Cow::Borrowed(&session.doc.project), std::borrow::Cow::Owned) +} + +/// Composite texture set `ts` into its display textures on the GPU, as the desktop viewport does +/// (`SetCompositor::plan`), unless `composited` says they already hold this material. False when +/// the set composites on the CPU: padding across UV seams, no covered texels or a layer stack the +/// GPU compositor does not support. A GPU error (after the renderer's one retry when memory ran +/// out) is returned: the set is not composited on the CPU instead. +fn composite_set(h: &mut texturecraft_render::headless::Headless, session: &Session, ts: usize, composited: &mut Option) -> Result { + let Some(cache) = session.caches.get(ts) else { return Ok(false) }; + let display = &session.doc.project.display; + let image = display.environment_resource().and_then(|name| session.images.get(name)).map_or(0, |image| Arc::as_ptr(image) as usize); + let current = |lit: bool, on_gpu: bool| GpuComposite { + mesh: session.mesh_id, + revision: cache.material_revision, + size: cache.size, + environment: lit.then(|| (display.environment.clone(), image, display.env_rotation)), + on_gpu, + }; + if let Some(done) = composited.as_ref().filter(|done| **done == current(done.environment.is_some(), done.on_gpu)) { + return Ok(done.on_gpu); + } + + match composite_program(h, session, ts) { + Ok(lit) => { + *composited = Some(current(lit, true)); + Ok(true) + } + Err(Refused::Cpu) => { + *composited = Some(current(false, false)); + Ok(false) + } + Err(Refused::Device(error)) => { + *composited = None; + Err(format!("GPU layer compositing failed for texture set {}: {error}", ts + 1)) + } + } +} + +/// Compile texture set `ts`'s layers for the GPU and composite them; whether the program reads +/// the environment, or why the GPU did not +fn composite_program(h: &mut texturecraft_render::headless::Headless, session: &Session, ts: usize) -> Result { + let cache = session.caches.get(ts).ok_or(Refused::Cpu)?; + let padding = cache.dilation.mixed_coverage(); + if cache.dilation.needs_seam_padding() || (!cache.dilation.fully_covered() && padding.is_none()) { + return Err(Refused::Cpu); + } + + let project = view_project(session, false); + let mut program = CompositeProgram::try_compile_region(&project, &session.doc.pixels, ts, None).map_err(|_| Refused::Cpu)?; + if let Some(padding) = padding { + program.set_coverage(padding, texturecraft_engine::session::DISPLAY_PADDING); + } + program.set_surface_inputs(&session.mesh, &cache.gbuf, session.doc.baked.get(&ts)).map_err(|_| Refused::Cpu)?; + program.set_tile_images(&session.images); + h.renderer.composite_on_gpu(&h.device, &h.queue, ts, &program).map_err(Refused::of)?; + Ok(program.environment().is_some()) +} + +/// Composite the mask view of `layer` on texture set `ts` into its aux texture on the GPU; false +/// when the mask composites on the CPU, the GPU's error when it reported one. +fn composite_mask( + h: &mut texturecraft_render::headless::Headless, + session: &Session, + ts: usize, + layer: texturecraft_engine::core::LayerId, +) -> Result { + let Some(cache) = session.caches.get(ts) else { return Ok(false) }; + let project = view_project(session, true); + let Ok(mut program) = CompositeProgram::try_compile_mask_preview(&project, &session.doc.pixels, ts, layer, None, None) else { return Ok(false) }; + if program.set_surface_inputs(&session.mesh, &cache.gbuf, session.doc.baked.get(&ts)).is_err() { + return Ok(false); + } + + program.set_tile_images(&session.images); + match h.renderer.composite_on_gpu(&h.device, &h.queue, ts, &program).map_err(Refused::of) { + Ok(()) => Ok(true), + Err(Refused::Cpu) => Ok(false), + Err(Refused::Device(error)) => Err(format!("GPU mask view failed for texture set {}: {error}", ts + 1)), + } +} + /// The session's 3D view as the path tracers see it, and how Rendering mode shows it (denoised). fn trace_inputs(s: &mut Session) -> (TraceScene, TraceDisplay) { s.update(); @@ -247,6 +425,146 @@ mod tests { out } + /// A headless render composites the layers on the GPU, leaving every CPU tile dirty, and + /// shows what the CPU route shows + #[test] + fn headless_renders_composite_layers_on_the_gpu() { + let mesh = texturecraft_engine::geom::primitives::material_ball(); + let mut session = Session::new_project("Test", mesh, "builtin:material_ball", None, 128).unwrap(); + session.doc.project.display.taa = false; + execute(&mut session, "layer.add.fill", &json!({"color": [0.75, 0.42, 0.23], "roughness": 0.3, "metallic": 0.4})).unwrap(); + let Some(headless) = texturecraft_render::headless::Headless::for_required_tests() else { return }; + let mut gpu = Gpu { + h: headless, + mesh_id: 0, + sets: Vec::new(), + env: Default::default(), + tracer: None, + gpu_compositing: true, + composited: Vec::new(), + gpu_views: true, + }; + + let camera = session.camera; + let (_, _, on_gpu) = gpu.render(&mut session, ViewKind::Scene, [96, 64], camera).unwrap(); + assert!(!session.caches[0].dirty.is_empty(), "the CPU composited no tile of the set"); + + gpu.set_gpu_compositing(false); + let (_, _, on_cpu) = gpu.render(&mut session, ViewKind::Scene, [96, 64], camera).unwrap(); + assert!(session.caches[0].dirty.is_empty(), "the CPU route composites every tile"); + let worst = on_gpu.iter().zip(&on_cpu).map(|(gpu, cpu)| gpu.abs_diff(*cpu)).max().unwrap_or(0); + assert!(worst <= 3, "the GPU render differs from the CPU's by {worst} levels"); + assert!(on_gpu.chunks(4).any(|pixel| pixel[0] > pixel[2] + 40), "the orange fill shows"); + } + + /// Tiling: a set whose UV coverage exceeds the device's storage binding composites on the + /// GPU in row bands (no CPU tile), with the Base Color a device holding it whole composites + #[test] + fn a_set_larger_than_a_gpu_binding_renders_on_the_gpu_in_bands() { + // UVs inset in the tile, so the set has uncovered texels and composites with UV padding + let mut mesh = texturecraft_engine::geom::primitives::plane(2.0, 1); + for uv in &mut mesh.uvs { + *uv = *uv * 0.5 + texturecraft_engine::geom::glam::Vec2::splat(0.25); + } + let mut session = Session::new_project("Test", mesh, "plane", None, 1024).unwrap(); + session.doc.project.display.taa = false; + execute(&mut session, "layer.add.fill", &json!({"color": [0.75, 0.42, 0.23], "roughness": 0.3, "metallic": 0.4})).unwrap(); + + // 1024 rows of 32 coverage words (128 KiB) on a device binding 40 KiB per storage buffer + let mut render = |binding: Option| { + let limits = |adapter: &texturecraft_render::wgpu::Adapter| { + let limits = texturecraft_render::device_limits(adapter); + texturecraft_render::wgpu::Limits { max_storage_buffer_binding_size: binding.unwrap_or(limits.max_storage_buffer_binding_size), ..limits } + }; + let headless = texturecraft_render::headless::Headless::for_tests_with_limits(limits).ok()?; + let mut gpu = Gpu { + h: headless, + mesh_id: 0, + sets: Vec::new(), + env: Default::default(), + tracer: None, + gpu_compositing: true, + composited: Vec::new(), + gpu_views: true, + }; + let camera = session.camera; + gpu.render(&mut session, ViewKind::Scene, [96, 64], camera).unwrap(); + assert!(gpu.composited[0].as_ref().is_some_and(|done| done.on_gpu), "the GPU refused the set"); + assert!(!session.caches[0].dirty.is_empty(), "the CPU composited the set"); + let texture = gpu.h.renderer.display_textures()[0][0]; + texturecraft_render::readback::Readback::blocking(&gpu.h.device, &gpu.h.queue, texture).map(|(_, _, texels)| texels) + }; + let Some(banded) = render(Some(40 << 10)) else { return }; + let Some(whole) = render(None) else { return }; + assert!(banded.len() >= 1024 * 1024 * 4, "the set's Base Color was not composited"); + let differing = banded.iter().zip(&whole).filter(|(banded, whole)| banded != whole).count(); + assert_eq!(differing, 0, "the banded Base Color differs from the whole set's"); + } + + /// A GPU error that outlasts the renderer's one retry fails the render with that error; the + /// CPU does not composite the set instead + #[test] + fn a_gpu_composite_error_fails_the_render_without_a_cpu_composite() { + let mesh = texturecraft_engine::geom::primitives::plane(2.0, 1); + let mut session = Session::new_project("Test", mesh, "plane", None, 128).unwrap(); + execute(&mut session, "layer.add.fill", &json!({"color": [0.75, 0.42, 0.23]})).unwrap(); + let Some(headless) = texturecraft_render::headless::Headless::for_required_tests() else { return }; + let mut gpu = Gpu { + h: headless, + mesh_id: 0, + sets: Vec::new(), + env: Default::default(), + tracer: None, + gpu_compositing: true, + composited: Vec::new(), + gpu_views: true, + }; + gpu.h.renderer.fail_next_gpu_attempts(2); + + let camera = session.camera; + let result = gpu.render(&mut session, ViewKind::Scene, [32, 32], camera); + + let error = result.err().unwrap_or_default(); + assert!(error.contains("Not enough GPU memory"), "{error}"); + assert!(!session.caches[0].dirty.is_empty(), "the CPU composited no tile of the set"); + } + + /// The GPU draws the "Other..." image view and a color selection's ID mask image as the CPU + /// resamples them (`Session::image_view_rgba`, `Session::id_mask_view_rgba`) + #[test] + fn the_gpu_draws_the_image_and_id_mask_views_as_the_cpu_resamples_them() { + let mesh = texturecraft_engine::geom::primitives::plane(2.0, 1); + let mut session = Session::new_project("Test", mesh, "plane", None, 128).unwrap(); + let Some(mut h) = texturecraft_render::headless::Headless::for_required_tests() else { return }; + let size = session.caches[0].size; + h.renderer.set_texture_sets(&h.device, &h.queue, &[(size, 0)], 1); + let extent = texturecraft_render::aux_extent(size, 0); + + // Odd sizes and HDR values, so bilinear weights and clamping both matter + let texels = |width: u32, height: u32| (0..width * height).map(|i| [(i % 5) as f32 * 0.4, (i % 3) as f32 * 0.35, (i % 7) as f32 / 7.0, 1.0]).collect(); + let image = Arc::new(ImageRes::new(5, 3, texels(5, 3), false)); + session.images.insert("view".into(), image.clone()); + session.view_image = Some("view".into()); + execute(&mut session, "layer.add.fill", &json!({"color": [0.9, 0.1, 0.1]})).unwrap(); + let effect = + execute(&mut session, "mask.add.colorSelection", &json!({"color": [0.0, 0.0, 1.0], "tolerance": 0.05})).unwrap()["effect"].as_u64().unwrap(); + let effect = texturecraft_engine::core::LayerId(effect); + let id = Arc::new(ImageRes::new(7, 5, texels(7, 5), false)); + session.images.insert("id".into(), id.clone()); + execute(&mut session, "effect.set", &json!({"effect": effect.0, "idMap": "id"})).unwrap(); + + let views = + [(AuxSource::Image(image), session.image_view_rgba(extent).unwrap()), (AuxSource::IdMask(id), session.id_mask_view_rgba(effect, extent).unwrap())]; + for (source, cpu) in views { + h.renderer.draw_aux_view(&h.device, &h.queue, 0, &source).unwrap(); + let (width, height, gpu) = texturecraft_render::readback::Readback::blocking(&h.device, &h.queue, h.renderer.aux_texture(0).unwrap()).unwrap(); + + assert_eq!((width, height), extent); + let worst = gpu.iter().zip(&cpu).map(|(gpu, cpu)| gpu.abs_diff(*cpu)).max().unwrap_or(0); + assert!(worst <= 1, "{source:?}: GPU and CPU views differ by {worst} levels"); + } + } + #[test] fn renders_with_an_imported_hdr_environment() { let mesh = texturecraft_engine::geom::primitives::material_ball(); @@ -313,15 +631,15 @@ mod tests { let (_, _, first) = gpu.render(&mut session, uv(0), [128, 128], camera).unwrap(); - assert_eq!(gpu.h.renderer.aux_size(0), Some(128)); - assert_eq!(gpu.h.renderer.aux_size(1), Some(1), "the other set keeps its placeholder"); + assert_eq!(gpu.h.renderer.aux_extent(0), Some((128, 128))); + assert_eq!(gpu.h.renderer.aux_extent(1), Some((1, 1)), "the other set keeps its placeholder"); assert!(first.as_chunks::<4>().0.iter().any(|pixel| pixel[0] > 200 && pixel[1] < 20)); let (_, _, second) = gpu.render(&mut session, uv(1), [128, 128], camera).unwrap(); assert!(second.as_chunks::<4>().0.iter().any(|pixel| pixel[0] > 200 && pixel[1] < 20)); - assert_eq!(gpu.h.renderer.aux_size(1), Some(128)); + assert_eq!(gpu.h.renderer.aux_extent(1), Some((128, 128))); } #[test] diff --git a/crates/automation/src/render/refused.rs b/crates/automation/src/render/refused.rs new file mode 100644 index 000000000..fc6b73e75 --- /dev/null +++ b/crates/automation/src/render/refused.rs @@ -0,0 +1,13 @@ +/// Why the GPU did not composite a set +pub(super) enum Refused { + /// The set composites on the CPU (its layout or layer stack) + Cpu, + /// The GPU reported an error + Device(String), +} + +impl Refused { + pub(super) fn of(error: String) -> Refused { + if texturecraft_render::gpu_memory::is_device_error(&error) { Refused::Device(error) } else { Refused::Cpu } + } +} diff --git a/crates/compose/src/fill_depth.rs b/crates/compose/src/fill_depth.rs index e77dc82df..179e22fdb 100644 --- a/crates/compose/src/fill_depth.rs +++ b/crates/compose/src/fill_depth.rs @@ -18,7 +18,7 @@ impl FillDepth { return ProjectorDepth::build(view, mesh).map(Self::Single); }; - // Share one grid's storage and raster budget across the copy views + // Share one grid's storage across the copy views let maps: Box<_> = ProjectorDepth::build_copies(view, mesh, &symmetry, center, radius).into_boxed_slice(); maps.iter().any(Option::is_some).then_some(Self::Copies(maps)) diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 8eda07841..f3b3d0b8b 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -101,5 +101,5 @@ pub mod distance_test_hooks { pub use crate::distance_envelope::DistanceEnvelope; pub use crate::shape_distance::{edge_distances, trail_distances}; } -pub use thumb::{THUMB_TEXELS, ThumbImage, ThumbTarget}; +pub use thumb::{THUMB_TEXELS, ThumbImage, ThumbOutput, ThumbPlan, ThumbTarget}; pub use tile_pattern::{TileLayout, prepare_tile_layout}; diff --git a/crates/compose/src/projector_depth.rs b/crates/compose/src/projector_depth.rs index 213ff7882..511640a21 100644 --- a/crates/compose/src/projector_depth.rs +++ b/crates/compose/src/projector_depth.rs @@ -28,14 +28,16 @@ pub struct ProjectorDepth { } /// The smallest grid cell across and up, so a flat view still divides -const MIN_CELL_SIZE: f32 = 1e-6; +pub const MIN_CELL_SIZE: f32 = 1e-6; /// A cell centre this close outside a triangle's edge (as a share of its area) still counts as inside, so shared edges leave no gaps -const EDGE_TOLERANCE: f32 = 1e-6; +pub const EDGE_TOLERANCE: f32 = 1e-6; mod depth_grid; +mod grid_setup; pub use depth_grid::DepthGrid; +pub use grid_setup::GridSetup; impl ProjectorDepth { /// The grid as `cover` reads it. @@ -54,13 +56,19 @@ impl ProjectorDepth { } /// The depth maps of a fill's symmetry copies (one per copy, None where a copy sees nothing), - /// sharing one grid's storage and raster budget as the CPU evaluator does. + /// sharing one grid's storage as the CPU evaluator does. pub fn build_copies(view: ProjectorView, mesh: &Mesh, symmetry: &FillSymmetry, center: Vec3, radius: f32) -> Vec> { let copies = FillCopies::new(symmetry, center, center, radius); let count = symmetry.copies() as usize; - let grid_side = (GRID_SIDE * GRID_SIDE / count).isqrt(); - let cell_budget = CELL_BUDGET / count; - (0..count).map(|index| Self::build_for_copy(view, mesh, Some(copies.copy(index as u32)), grid_side, cell_budget)).collect() + let grid_side = copy_grid_side(count); + (0..count).map(|index| Self::build_for_copy(view, mesh, Some(copies.copy(index as u32)), grid_side)).collect() + } + + /// What [`Self::build_copies`] rasterizes per copy, at its grid side + pub fn copy_setups(view: ProjectorView, mesh: &Mesh, symmetry: &FillSymmetry, center: Vec3, radius: f32) -> Vec> { + let copies = FillCopies::new(symmetry, center, center, radius); + let count = symmetry.copies() as usize; + (0..count).map(|index| GridSetup::new(view, mesh, Some(copies.copy(index as u32)), copy_grid_side(count))).collect() } /// Build the depth map of a borrowed mesh, if the projection uses depth culling. @@ -69,54 +77,35 @@ impl ProjectorDepth { Self::build(view, mesh).map(Arc::new) } - /// Rasterize the mesh in this view, using a coarser grid when the cell budget requires one. + /// Rasterize the mesh in this view on the full grid. pub fn build(view: ProjectorView, mesh: &Mesh) -> Option { - Self::build_for_copy(view, mesh, None, GRID_SIDE, CELL_BUDGET) + Self::build_for_copy(view, mesh, None, GRID_SIDE) } - /// [`Self::build`] for one copy of a fill (`copy` places the mesh), on a grid of at most `grid_side` cells across within `cell_budget` cell visits. - pub fn build_for_copy(view: ProjectorView, mesh: &Mesh, copy: Option, mut grid_side: usize, cell_budget: usize) -> Option { - let projected: Vec<_> = mesh.positions.iter().map(|&point| view.local(copy.map_or(point, |copy| copy.point(point)))).collect(); - let (min, max) = projected - .iter() - .flatten() - .fold((Vec2::splat(f32::MAX), Vec2::splat(f32::MIN)), |(lo, hi), view_point| (lo.min(view_point.truncate()), hi.max(view_point.truncate()))); - if min.x > max.x || min.y > max.y { + /// [`Self::build`] for one copy of a fill (`copy` places the mesh), on a grid of `grid_side` cells across. + pub fn build_for_copy(view: ProjectorView, mesh: &Mesh, copy: Option, grid_side: usize) -> Option { + if grid_side == 0 { return None; } - // The one-cell fallback can always afford one visit per triangle - let cell_budget = cell_budget.max(mesh.triangle_count()); - let nearness_unit = view.unit(); - while grid_side > 0 { - let cell = ((max - min) / grid_side as f32).max(Vec2::splat(MIN_CELL_SIZE)); - let front = vec![[f32::NEG_INFINITY, 0.0, 0.0]; grid_side * grid_side]; - let mut depth = ProjectorDepth { view, origin: min, grid_side, cell, nearness_unit, front }; - let mut remaining = cell_budget; - let mut triangles = mesh.indices.as_chunks::<3>().0.iter().filter_map(|indices| { - let [a, b, c] = indices.map(|index| projected.get(index as usize).copied().flatten()); - Some([a?, b?, c?]) - }); - - if triangles.all(|triangle| depth.raster(triangle, &mut remaining)) { - return Some(depth); - } - - // Discard any partial grid before retrying the whole mesh - grid_side /= 2; + let setup = GridSetup::new(view, mesh, copy, grid_side)?; + let front = vec![[f32::NEG_INFINITY, 0.0, 0.0]; grid_side * grid_side]; + let mut depth = ProjectorDepth { view, origin: setup.origin, grid_side, cell: setup.cell, nearness_unit: setup.nearness_unit, front }; + for triangle in setup.triangles(mesh) { + depth.raster(triangle); } - None + Some(depth) } - /// Keep `triangle` where it is nearer than what a cell holds; false once the cell budget runs out - fn raster(&mut self, triangle: [Vec3; 3], budget: &mut usize) -> bool { + /// Keep `triangle` where it is nearer than what a cell holds + fn raster(&mut self, triangle: [Vec3; 3]) { let [a, b, c] = triangle; let (edge_ab, edge_ac) = (b - a, c - a); let determinant = edge_ab.x * edge_ac.y - edge_ab.y * edge_ac.x; if !determinant.is_finite() || determinant.abs() < MIN_SCREEN_AREA { // An edge-on triangle covers no cells - return true; + return; } let slope = Vec2::new((edge_ab.z * edge_ac.y - edge_ac.z * edge_ab.y) / determinant, (edge_ab.x * edge_ac.z - edge_ac.x * edge_ab.z) / determinant) @@ -128,9 +117,6 @@ impl ProjectorDepth { let first_cell = |position: f32| (position - 0.5).ceil().clamp(0.0, self.grid_side as f32) as usize; let end_cell = |position: f32| ((position - 0.5).floor() + 1.0).clamp(0.0, self.grid_side as f32) as usize; let (x0, x1, y0, y1) = (first_cell(lo.x), end_cell(hi.x), first_cell(lo.y), end_cell(hi.y)); - let cells = x1.saturating_sub(x0).saturating_mul(y1.saturating_sub(y0)); - let Some(left) = budget.checked_sub(cells) else { return false }; - *budget = left; let area = edge(pa, pb, pc); for y in y0..y1 { @@ -151,8 +137,6 @@ impl ProjectorDepth { } } } - - true } /// How much depth culling with `hardness` leaves of a projection at world point `p`: 0 behind the surface nearest the projector, 1 on it or where nothing is in front @@ -196,23 +180,25 @@ fn edge(a: Vec2, b: Vec2, q: Vec2) -> f32 { /// Cells across and up the grid pub const GRID_SIDE: usize = 512; -/// A triangle flatter than this on screen is seen edge on -const MIN_SCREEN_AREA: f32 = 1e-12; +/// Cells across and up each copy's grid when `count` symmetry copies share one grid's storage +pub fn copy_grid_side(count: usize) -> usize { + (GRID_SIDE * GRID_SIDE / count.max(1)).isqrt() +} -/// Cell visits available at each resolution before large overlapping triangles require a coarser grid. -pub const CELL_BUDGET: usize = 256 * GRID_SIDE * GRID_SIDE; +/// A triangle flatter than this on screen is seen edge on +pub const MIN_SCREEN_AREA: f32 = 1e-12; /// Steepest surface slope kept, in nearness per view unit -const MAX_SLOPE: f32 = 1e4; +pub const MAX_SLOPE: f32 = 1e4; /// How far behind the nearest surface a point may sit and keep everything, in mesh radii -const BIAS: f32 = 0.002; +pub const BIAS: f32 = 0.002; /// Most the slope adds to the bias, in mesh radii -const MAX_SLOPE_BIAS: f32 = 0.05; +pub const MAX_SLOPE_BIAS: f32 = 0.05; /// How far behind the nearest surface culling fades out at hardness 0, in mesh radii -const FADE: f32 = 0.1; +pub const FADE: f32 = 0.1; #[cfg(test)] mod tests { @@ -305,22 +291,17 @@ mod tests { assert_eq!(depth.cover(Vec3::new(1.0, 1.0, -0.5), 1.0), 0.0); } + /// A mesh of many large overlapping triangles keeps the full grid, as the GPU raster does #[test] - fn raster_budget_fallback_accounts_for_the_last_triangle() { + fn many_overlapping_triangles_keep_the_full_grid() { let mut mesh = two_squares(0.5, -0.5); - let rear_triangles = [4, 5, 6, 4, 6, 7]; - let front_triangles = [0, 1, 2, 0, 2, 3]; - mesh.indices = rear_triangles.repeat(CELL_BUDGET / (GRID_SIDE * GRID_SIDE)); - mesh.indices.extend(front_triangles); - let projection = planar_z(true, 1.0); - let behind = Vec3::new(0.5, 0.3, -0.5); + mesh.indices = [4, 5, 6, 4, 6, 7].repeat(300); + mesh.indices.extend([0, 1, 2, 0, 2, 3]); - let front_last = ProjectorDepth::of(&mesh, mesh.bounds(), &projection).unwrap(); - mesh.indices.rotate_right(front_triangles.len()); - let front_first = ProjectorDepth::of(&mesh, mesh.bounds(), &projection).unwrap(); + let depth = ProjectorDepth::of(&mesh, mesh.bounds(), &planar_z(true, 1.0)).unwrap(); - assert_eq!(front_last.cover(behind, 1.0), 0.0); - assert_eq!(front_last.cover(behind, 1.0), front_first.cover(behind, 1.0)); + assert_eq!(depth.grid_side, GRID_SIDE); + assert_eq!(depth.cover(Vec3::new(0.5, 0.3, -0.5), 1.0), 0.0, "the front square drawn last still culls"); } #[test] diff --git a/crates/compose/src/projector_depth/grid_setup.rs b/crates/compose/src/projector_depth/grid_setup.rs new file mode 100644 index 000000000..d7990fee5 --- /dev/null +++ b/crates/compose/src/projector_depth/grid_setup.rs @@ -0,0 +1,53 @@ +use super::{FillCopy, MIN_CELL_SIZE, Mesh, ProjectorView, Vec2, Vec3}; + +/// What a projector depth grid rasterizes: the mesh's corners in the view and the grid laid over +/// them. The CPU raster ([`super::ProjectorDepth::build_for_copy`]) and the GPU compositor's +/// raster start from the same numbers. +#[derive(Clone, Debug)] +pub struct GridSetup { + /// Each mesh corner in the view (across, up, nearness), None where the view has no point for it + pub projected: Vec>, + /// The view point at the grid's lower corner + pub origin: Vec2, + /// One cell's size across and up in the view + pub cell: Vec2, + /// Cells across and up + pub grid_side: usize, + /// The mesh radius measured along the view's depth axis + pub nearness_unit: f32, + /// The view point at the grid's upper corner + upper: Vec2, +} + +impl GridSetup { + /// The setup of `mesh` (placed by `copy`) in `view` at `grid_side` cells across; None when the + /// view sees none of its corners. + pub fn new(view: ProjectorView, mesh: &Mesh, copy: Option, grid_side: usize) -> Option { + let projected: Vec<_> = mesh.positions.iter().map(|&point| view.local(copy.map_or(point, |copy| copy.point(point)))).collect(); + let (min, max) = projected + .iter() + .flatten() + .fold((Vec2::splat(f32::MAX), Vec2::splat(f32::MIN)), |(lo, hi), view_point| (lo.min(view_point.truncate()), hi.max(view_point.truncate()))); + if min.x > max.x || min.y > max.y { + return None; + } + + let mut setup = Self { projected, origin: min, cell: Vec2::ZERO, grid_side, nearness_unit: view.unit(), upper: max }; + setup.resize(grid_side); + Some(setup) + } + + /// The same grid at `grid_side` cells across + pub(super) fn resize(&mut self, grid_side: usize) { + self.grid_side = grid_side; + self.cell = ((self.upper - self.origin) / grid_side.max(1) as f32).max(Vec2::splat(MIN_CELL_SIZE)); + } + + /// The triangles whose three corners the view sees, in mesh order + pub fn triangles<'a>(&'a self, mesh: &'a Mesh) -> impl Iterator + 'a { + mesh.indices.as_chunks::<3>().0.iter().filter_map(|indices| { + let [a, b, c] = indices.map(|index| self.projected.get(index as usize).copied().flatten()); + Some([a?, b?, c?]) + }) + } +} diff --git a/crates/compose/src/thumb.rs b/crates/compose/src/thumb.rs index afa677d69..e10171824 100644 --- a/crates/compose/src/thumb.rs +++ b/crates/compose/src/thumb.rs @@ -37,6 +37,48 @@ pub struct ThumbImage { pub rgba: Vec, } +/// What a thumbnail reads of its cut project ([`ThumbPlan`]) +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ThumbOutput { + /// The enabled mask of `layer`, gray, opaque where the mesh covers the texture + Mask(LayerId), + /// The paint or fill layer's `channel` over nothing: straight value, coverage as alpha + Flat(Channel), + /// The folder's `channel` composited over the channel defaults, opaque where covered + Composite(Channel), +} + +/// The project a thumbnail composites (only the requested layer drawn, forced visible at +/// Normal / 100 %, its effects cut after the previewed one) and what it reads of it +pub struct ThumbPlan { + pub project: Project, + /// The layer drawn (the one asked for, or the owner of a previewed effect) + pub layer: LayerId, + pub output: ThumbOutput, +} + +impl ThumbPlan { + /// The plan of `target` in texture set `texture_set`. None for an unknown layer or effect, + /// a layer without that channel, or a mask that does not exist. + pub fn new(project: &Project, texture_set: usize, target: ThumbTarget) -> Option { + match target { + ThumbTarget::Content { layer, channel } => content_plan(project, texture_set, layer, channel, None), + ThumbTarget::Mask { layer } => mask_plan(project, texture_set, layer, None), + ThumbTarget::Stage { effect, channel } => { + let (owner, _) = project.effect(effect)?; + let in_mask = project.layers.get(&owner)?.mask.as_ref().is_some_and(|m| m.effects.iter().any(|e| e.id == effect)); + if in_mask { mask_plan(project, texture_set, owner, Some(effect)) } else { content_plan(project, texture_set, owner, channel, Some(effect)) } + } + } + } + + /// Whether the cut project draws only the requested layer (a layer reading the stack below + /// keeps the whole stack) + pub fn draws_alone(&self, texture_set: usize) -> bool { + self.project.texture_sets.get(texture_set).is_some_and(|set| set.stack == [self.layer]) + } +} + /// The thumbnail of `target`, computed at `inp.gbuf`'s size, which must be square (use a /// [`THUMB_TEXELS`] G-buffer; None otherwise). None for an unknown layer or effect, a layer without that channel, or a /// mask that does not exist. @@ -44,13 +86,18 @@ pub fn render(inp: &Inputs, target: ThumbTarget) -> Option { if inp.gbuf.width != inp.gbuf.height { return None; } - match target { - ThumbTarget::Content { layer, channel } => content(inp, layer, channel, None), - ThumbTarget::Mask { layer } => mask(inp, layer, None), - ThumbTarget::Stage { effect, channel } => { - let (owner, _) = inp.project.effect(effect)?; - let in_mask = inp.project.layers.get(&owner)?.mask.as_ref().is_some_and(|m| m.effects.iter().any(|e| e.id == effect)); - if in_mask { mask(inp, owner, Some(effect)) } else { content(inp, owner, channel, Some(effect)) } + let plan = ThumbPlan::new(inp.project, inp.ts, target)?; + let cut_inputs = Inputs { project: &plan.project, preview: None, block_scales: inp.block_scales.clone(), ..*inp }; + let (width, height) = (inp.gbuf.width, inp.gbuf.height); + match plan.output { + ThumbOutput::Mask(layer) => mask(&cut_inputs, layer), + ThumbOutput::Flat(channel) => { + let flat = flatten_layer(&cut_inputs, plan.layer, &all_tiles(width, height))?; + Some(encode_flat(&flat, channel, width, height)) + } + ThumbOutput::Composite(channel) => { + let comp = crate::eval::thumbnail::composite_layer(&cut_inputs, plan.layer, channel)?; + Some(encode_channel(&comp, channel, inp)) } } } @@ -85,14 +132,14 @@ fn truncate_after(list: &mut Vec, last: LayerId) -> b } } -fn content(inputs: &Inputs, layer: LayerId, channel: Channel, through_effect: Option) -> Option { - let set = inputs.project.texture_set(inputs.ts).ok()?; +fn content_plan(project: &Project, texture_set: usize, layer: LayerId, channel: Channel, through_effect: Option) -> Option { + let set = project.texture_set(texture_set).ok()?; if !set.channel_list().contains(&channel) { return None; } // An instance draws its source's effects - let mut cut = solo(inputs.project, inputs.ts, layer, Some(channel))?; + let mut cut = solo(project, texture_set, layer, Some(channel))?; let owner = cut.content_layer(layer)?.id; for id in [layer, owner] { let content = cut.layers.get_mut(&id)?; @@ -106,17 +153,9 @@ fn content(inputs: &Inputs, layer: LayerId, channel: Channel, through_effect: Op return None; } - let cut_inputs = Inputs { project: &cut, preview: None, block_scales: inputs.block_scales.clone(), ..*inputs }; - let (width, height) = (inputs.gbuf.width, inputs.gbuf.height); - // Paint and fill previews retain coverage; folders composite over channel defaults - if !cut.layers.get(&owner)?.is_group() { - let flat = flatten_layer(&cut_inputs, layer, &all_tiles(width, height))?; - return Some(encode_flat(&flat, channel, width, height)); - } - - let comp = crate::eval::thumbnail::composite_layer(&cut_inputs, layer, channel)?; - Some(encode_channel(&comp, channel, inputs)) + let output = if cut.layers.get(&owner)?.is_group() { ThumbOutput::Composite(channel) } else { ThumbOutput::Flat(channel) }; + Some(ThumbPlan { project: cut, layer, output }) } /// Encode the flattened (premultiplied value, coverage) tiles of `channel`: alpha is coverage. @@ -159,8 +198,8 @@ fn display(channel: Channel, v: [f32; 3]) -> [u8; 3] { } } -fn mask(inputs: &Inputs, layer: LayerId, through_effect: Option) -> Option { - let mut cut = solo(inputs.project, inputs.ts, layer, None)?; +fn mask_plan(project: &Project, texture_set: usize, layer: LayerId, through_effect: Option) -> Option { + let mut cut = solo(project, texture_set, layer, None)?; let owner = cut.mask_owner(layer); let mask = cut.layers.get_mut(&owner)?.mask.as_mut()?; mask.enabled = true; @@ -170,9 +209,13 @@ fn mask(inputs: &Inputs, layer: LayerId, through_effect: Option) -> Opt return None; } - let cut_inputs = Inputs { project: &cut, preview: None, block_scales: inputs.block_scales.clone(), ..*inputs }; + Some(ThumbPlan { project: cut, layer, output: ThumbOutput::Mask(layer) }) +} + +/// The gray mask of `layer` in the cut project of `inputs` +fn mask(inputs: &Inputs, layer: LayerId) -> Option { let (width, height) = (inputs.gbuf.width, inputs.gbuf.height); - let gray = mask_image(&cut_inputs, layer, width)?; + let gray = mask_image(inputs, layer, width)?; let mut rgba = Vec::with_capacity((width * height) as usize * 4); for y in 0..height { for x in 0..width { diff --git a/crates/core/src/block_scales.rs b/crates/core/src/block_scales.rs index e65e82216..fc73283c4 100644 --- a/crates/core/src/block_scales.rs +++ b/crates/core/src/block_scales.rs @@ -54,6 +54,12 @@ impl BlockScales { Some([(origin[0] + local[0]) * block / working_size.0 as f32, (origin[1] + local[1]) * block / working_size.1 as f32]) } + /// The block side in texels, the blocks across and each block's scale in row order (no + /// scales when every tile fills its block), for samplers outside this crate + pub fn layout(&self) -> (u32, u32, &[f32]) { + (self.block, self.cols, &self.scales) + } + /// The scale at atlas texel (x, y) pub fn at(&self, x: u32, y: u32) -> f32 { let (bx, by) = (x / self.block.max(1), y / self.block.max(1)); diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 3f1f05f80..d1250d61d 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -10,6 +10,7 @@ workspace = true [dependencies] chrono = { workspace = true } +half = { workspace = true } texturecraft-core = { workspace = true } texturecraft-texel = { workspace = true } texturecraft-geom = { workspace = true } diff --git a/crates/engine/src/brush_device.rs b/crates/engine/src/brush_device.rs index b533152f2..25c0fcb70 100644 --- a/crates/engine/src/brush_device.rs +++ b/crates/engine/src/brush_device.rs @@ -25,13 +25,28 @@ pub use brush_surface::BrushSurface; pub use device_stroke_preview::DeviceStrokePreview; pub trait BrushDevice: Send + Sync { - fn start(&self, surface: BrushSurface) -> std::result::Result, String>; + /// A stroke on the device. A refusal paints the stroke on the CPU; a device error fails it. + fn start(&self, surface: BrushSurface) -> std::result::Result, crate::gpu_failure::GpuFailure>; } pub trait DeviceStroke: Send + Sync { - fn append_world(&mut self, stamps: &[Stamp]) -> std::result::Result; + /// World dabs; without `use_view` they skip the camera's visibility test and backface + /// culling (a 3D path's surface samples, as the CPU paints them) + fn append_world(&mut self, stamps: &[Stamp], use_view: bool) -> std::result::Result; fn append_uv(&mut self, stamps: &[UvStamp]) -> std::result::Result; fn read_alpha(&self, tiles: &BrushTiles) -> std::result::Result; fn read_projection(&self, tiles: &BrushTiles) -> std::result::Result; + /// A clone's or smudge's stroke alpha and carried values (straight, encoded) of `tiles` + fn read_carried(&self, _tiles: &BrushTiles) -> std::result::Result<(TileImage, BTreeMap), String> { + Err("This brush device carries no values.".into()) + } + /// Each carried channel's own stroke alpha of `tiles`, for a source with per-channel coverage + fn read_channel_alphas(&self, _tiles: &BrushTiles) -> std::result::Result, String> { + Err("This brush device carries no per-channel alphas.".into()) + } + /// A smudge's trails so far, for a CPU stroke that continues it + fn read_smudge_lanes(&self, _tiles: &BrushTiles) -> std::result::Result, String> { + Err("This brush device carries no values.".into()) + } fn as_any(&self) -> &dyn Any; } diff --git a/crates/engine/src/brush_device/brush_surface.rs b/crates/engine/src/brush_device/brush_surface.rs index 0b4f9d4fa..e0898facf 100644 --- a/crates/engine/src/brush_device/brush_surface.rs +++ b/crates/engine/src/brush_device/brush_surface.rs @@ -1,5 +1,6 @@ use super::{Arc, BrushSettings, Bvh, EyeDepth, ImageRes, Mesh, Stencil, TileImage, UvGBuffer}; +#[derive(Clone)] pub struct BrushSurface { pub mesh: Arc, pub bvh: Arc, @@ -10,4 +11,8 @@ pub struct BrushSurface { pub alpha_image: Option>, pub stencil: Option, pub limit: Option<(TileImage, bool)>, + /// A clone stroke paints only where its source is read + pub clone: Option, + /// A smudge stroke drags its source's values stamp by stamp on the device + pub smudge: Option, } diff --git a/crates/engine/src/brush_device/device_stroke_preview.rs b/crates/engine/src/brush_device/device_stroke_preview.rs index 707ba1596..2580b4301 100644 --- a/crates/engine/src/brush_device/device_stroke_preview.rs +++ b/crates/engine/src/brush_device/device_stroke_preview.rs @@ -10,5 +10,8 @@ pub struct DeviceStrokePreview<'a> { pub opacity: f32, /// The Eraser: the stroke scales the target's paint and coverage down instead of painting. pub erase: bool, + /// A clone or smudge: the stroke paints the values its device carries in place of `values` + /// or the mask gray. + pub pickup: bool, pub stroke: &'a dyn DeviceStroke, } diff --git a/crates/engine/src/composite_device.rs b/crates/engine/src/composite_device.rs new file mode 100644 index 000000000..59fd590ee --- /dev/null +++ b/crates/engine/src/composite_device.rs @@ -0,0 +1,206 @@ +//! A renderer can composite small material pictures (shelf and orb previews, layer thumbnails, +//! the material overview) on the GPU without the engine depending on wgpu. + +use std::sync::Arc; +use std::sync::atomic::AtomicBool; + +use texturecraft_compose::{BakedMaps, DisplayKind, ImageStore, PixelStore, ThumbImage, ThumbOutput}; +use texturecraft_core::Project; +use texturecraft_geom::{Mesh, UvGBuffer}; +use texturecraft_texel::srgb_to_linear; + +use crate::gpu_failure::GpuFailure; +use crate::preview::Sample; + +/// Texture set `ts` of `project` on `mesh`, with `gbuf` at the set's size, composited at the +/// set's size halved `shift` times (every 2^shift-th texel); display maps pad UV islands from +/// `padding` (coverage and radius in set texels) when given. The device stops before its next +/// composite once `cancel` is set (and answers a device error nobody waits for). +pub struct CompositeJob<'a> { + pub project: &'a Project, + pub ts: usize, + pub pixels: &'a PixelStore, + pub mesh: &'a Arc, + pub gbuf: &'a Arc, + pub baked: &'a BakedMaps, + pub images: &'a ImageStore, + pub shift: u32, + pub padding: Option<(&'a Arc, u32)>, + pub cancel: Option<&'a AtomicBool>, +} + +/// The display maps' size and each map's bytes +pub type DisplayMaps = ((u32, u32), Vec>); + +pub trait CompositeDevice: Send + Sync { + /// The display maps `kinds` of `job` and their size (the set's size halved by the job's + /// shift, or more where the device's textures cannot hold it), row-major and packed as + /// [`texturecraft_compose::tile_bytes`] packs them. A refusal composites on the CPU; a + /// device error is returned to the caller, not redone on the CPU. + fn display_maps(&self, job: &CompositeJob, kinds: &[DisplayKind]) -> Result; + + /// The layer thumbnail `output` of `job` (whose project is cut to the layer, + /// [`texturecraft_compose::ThumbPlan`]) at the job's display size, encoded as the CPU + /// thumbnails are ([`ThumbImage`]). Refusals and errors as in [`Self::display_maps`]. + fn thumbnail(&self, job: &CompositeJob, output: ThumbOutput) -> Result; +} + +/// The material values at `texels` composited by `device`: None without a device or when it +/// refuses the material (the caller composites on the CPU); its error when it reports one. +/// Values come from the 8-bit display maps; roughness is the displayed one (1 − glossiness on +/// specular/glossiness sets). Maps smaller than the set (a device whose textures cannot hold it) +/// are read at the matching texel. +pub(crate) fn samples(device: Option<&dyn CompositeDevice>, job: &CompositeJob, texels: &[(u32, u32)]) -> Result>, String> { + let Some(device) = device else { return Ok(None) }; + let set = (job.gbuf.width, job.gbuf.height); + let (size, maps) = match device.display_maps(job, &[DisplayKind::BaseColor, DisplayKind::Orm, DisplayKind::Height]) { + Ok((size, _)) if size.0 == 0 || size.1 == 0 || size.0 > set.0 || size.1 > set.1 => { + return Err("the GPU returned display maps of the wrong size".into()); + } + Ok(answer) => answer, + Err(GpuFailure::Refused(_)) => return Ok(None), + Err(GpuFailure::Device(error)) => return Err(error), + }; + let width = size.0 as usize; + let texels_in_set = width * size.1 as usize; + let [base, orm, height] = maps.as_slice() else { return Err("the GPU returned the wrong display maps".into()) }; + if base.len() != texels_in_set * 4 || orm.len() != texels_in_set * 4 || height.len() != texels_in_set * 8 { + return Err("the GPU returned display maps of the wrong size".into()); + } + let byte = |map: &[u8], texel: usize, k: usize| map.get(texel * 4 + k).map_or(0.0, |&value| f32::from(value) / 255.0); + let samples = texels + .iter() + .map(|&(x, y)| { + let (x, y) = (u64::from(x) * u64::from(size.0) / u64::from(set.0), u64::from(y) * u64::from(size.1) / u64::from(set.1)); + let texel = y as usize * width + x as usize; + let height = height.get(texel * 8..texel * 8 + 2).map_or(0.0, |h| half::f16::from_le_bytes([h[0], h[1]]).to_f32()); + Sample { base: [0, 1, 2].map(|k| srgb_to_linear(byte(base, texel, k))), metallic: byte(orm, texel, 2), roughness: byte(orm, texel, 1), height } + }) + .collect(); + Ok(Some(samples)) +} + +#[cfg(test)] +mod tests { + use std::sync::atomic::{AtomicUsize, Ordering}; + + use super::*; + use crate::orb_preview::OrbPreview; + + /// Answers every composite with `failure`, or with mid-gray base color, metallic 1, + /// roughness 0 and height 0.25 everywhere; counts its composites + struct FakeDevice { + failure: Option, + composites: AtomicUsize, + /// Halvings past the job's shift (a device whose textures cannot hold the set) + reduced: u32, + } + + impl CompositeDevice for FakeDevice { + fn display_maps(&self, job: &CompositeJob, kinds: &[DisplayKind]) -> Result { + self.composites.fetch_add(1, Ordering::Relaxed); + if let Some(failure) = &self.failure { + return Err(failure.clone()); + } + + let size = (job.gbuf.width >> (job.shift + self.reduced), job.gbuf.height >> (job.shift + self.reduced)); + let texels = (size.0 * size.1) as usize; + let height = half::f16::from_f32(0.25).to_le_bytes(); + let maps = kinds + .iter() + .map(|kind| match kind { + DisplayKind::Orm => [255, 0, 255, 128].repeat(texels), + DisplayKind::Height => [height[0], height[1], 0, 0, 0, 0, 0, 0].repeat(texels), + _ => [188, 188, 188, 255].repeat(texels), + }) + .collect(); + Ok((size, maps)) + } + + fn thumbnail(&self, job: &CompositeJob, _output: ThumbOutput) -> Result { + self.composites.fetch_add(1, Ordering::Relaxed); + if let Some(failure) = &self.failure { + return Err(failure.clone()); + } + + let (width, height) = (job.gbuf.width >> job.shift, job.gbuf.height >> job.shift); + Ok(ThumbImage { width, height, rgba: [1, 2, 3, 4].repeat((width * height) as usize) }) + } + } + + fn device(failure: Option) -> FakeDevice { + FakeDevice { failure, composites: AtomicUsize::new(0), reduced: 0 } + } + + /// The material overview composites on the device at the overview's step; a device error is + /// returned without a CPU overview, a refusal composites on the CPU + #[test] + fn the_material_overview_composites_on_the_device() { + let session = crate::Session::new_project("overview", texturecraft_geom::primitives::plane(1.0, 1), "builtin:plane", None, 1024).unwrap(); + let snapshot = session.overview_snapshot(0, 128).unwrap(); + + let fake = device(None); + let overview = snapshot.render(Some(&fake), None).unwrap(); + assert_eq!(overview.size, (128, 128)); + assert!( + fake.composites.load(Ordering::Relaxed) == 1 + && overview.maps.iter().any(|(kind, map)| *kind == DisplayKind::BaseColor && map[..4] == [188, 188, 188, 255]) + ); + + let error = GpuFailure::Device("The GPU reported an error in a test".into()); + assert_eq!(snapshot.render(Some(&device(Some(error.clone()))), None).err(), Some(error.to_string())); + let refused = snapshot.render(Some(&device(Some(GpuFailure::Refused("a test refusal".into())))), None).unwrap(); + let on_cpu = session.material_overview(0, 128).unwrap(); + assert_eq!((refused.size, refused.maps), (on_cpu.size, on_cpu.maps)); + + // A cancelled overview composites nowhere, the CPU included + let cancelled = std::sync::atomic::AtomicBool::new(true); + assert_eq!(snapshot.render(None, Some(&cancelled)).err().as_deref(), Some("the overview was cancelled")); + } + + /// A device whose textures cannot hold the set returns smaller maps: the preview reads each + /// texel's value from the matching texel instead of failing + #[test] + fn a_preview_reads_reduced_display_maps() { + let reduced = FakeDevice { reduced: 1, ..device(None) }; + let filter = crate::preview::filter("levels", 8, Some(&reduced)).unwrap().unwrap(); + let samples: Vec<_> = filter.iter().flatten().copied().collect(); + assert!(!samples.is_empty() && samples.iter().all(|sample| sample.metallic == 1.0 && sample.height == 0.25), "{samples:?}"); + } + + /// The shelf's filter preview and the orb's material preview take their values from the device + #[test] + fn material_previews_composite_on_the_device() { + let fake = device(None); + let filter = crate::preview::filter("levels", 8, Some(&fake)).unwrap().unwrap(); + let mut orb = OrbPreview::new().unwrap(); + orb.set_composite_device(Some(Arc::new(device(None)))); + let material = orb.material("steel_painted_worn", 8).unwrap().unwrap(); + + let samples = filter.iter().flatten().copied().chain(material.iter().flatten().map(|pixel| pixel.sample)); + let mut seen = 0; + for sample in samples { + assert!((sample.base[0] - srgb_to_linear(188.0 / 255.0)).abs() < 1e-5 && sample.metallic == 1.0 && sample.roughness == 0.0, "{sample:?}"); + assert_eq!(sample.height, 0.25); + seen += 1; + } + assert!(seen > 0 && fake.composites.load(Ordering::Relaxed) == 1); + } + + /// A device error is returned, not composited on the CPU; a refusal composites on the CPU + #[test] + fn a_device_error_fails_the_preview_and_a_refusal_composites_on_the_cpu() { + let error = GpuFailure::Device("The GPU reported an error in a test".into()); + assert_eq!(crate::preview::filter("levels", 8, Some(&device(Some(error.clone())))).unwrap_err(), error.to_string()); + let mut orb = OrbPreview::new().unwrap(); + orb.set_composite_device(Some(Arc::new(device(Some(error.clone()))))); + assert_eq!(orb.material("steel", 8).unwrap_err(), error.to_string()); + + let refused = device(Some(GpuFailure::Refused("a test refusal".into()))); + assert_eq!(crate::preview::filter("levels", 8, Some(&refused)).unwrap(), crate::preview::filter("levels", 8, None).unwrap()); + orb.set_composite_device(Some(Arc::new(device(Some(GpuFailure::Refused("a test refusal".into())))))); + let on_cpu = orb.material("steel", 8).unwrap(); + orb.set_composite_device(None); + assert_eq!(on_cpu, orb.material("steel", 8).unwrap()); + } +} diff --git a/crates/engine/src/depth_device.rs b/crates/engine/src/depth_device.rs new file mode 100644 index 000000000..e7fab00bb --- /dev/null +++ b/crates/engine/src/depth_device.rs @@ -0,0 +1,99 @@ +//! A renderer can rasterize the paint camera's depth on the GPU without the engine depending on wgpu. + +use texturecraft_geom::{Mesh, OrbitCamera}; +use texturecraft_paint::EyeDepth; + +pub trait DepthDevice: Send + Sync { + /// [`EyeDepth::rasterize`] of `mesh` seen by `camera` at `size` (width, height): only the + /// triangles `include` accepts, and the nearest triangle per pixel when `record_triangles`. + /// The device's error when it reports one or cannot take the raster (a limit). + fn eye_depth( + &self, + mesh: &Mesh, + camera: &OrbitCamera, + size: (u32, u32), + record_triangles: bool, + include: &dyn Fn(usize) -> bool, + ) -> Result; +} + +/// The camera's depth from `device`, or from the software raster without one (GPU compositing +/// off, or no GPU). The device's error is returned, not redone in software. +pub(crate) fn eye_depth( + device: Option<&dyn DepthDevice>, + mesh: &Mesh, + camera: &OrbitCamera, + (width, height): (u32, u32), + record_triangles: bool, + include: &dyn Fn(usize) -> bool, +) -> Result { + match device { + Some(device) => device.eye_depth(mesh, camera, (width, height), record_triangles, include), + None => Ok(EyeDepth::rasterize(mesh, camera, width, height, record_triangles, include)), + } +} + +#[cfg(test)] +mod tests { + use std::collections::BTreeSet; + use std::sync::Arc; + use std::sync::atomic::{AtomicUsize, Ordering}; + + use texturecraft_geom::glam::Vec2; + use texturecraft_geom::{Bvh, primitives}; + + use super::*; + use crate::stroke_view::StrokeView; + + /// Counts its rasters and hands back the software raster + struct CountingDevice(AtomicUsize); + + /// Reports a GPU error for every raster + struct FailingDevice; + + impl DepthDevice for FailingDevice { + fn eye_depth(&self, _: &Mesh, _: &OrbitCamera, _: (u32, u32), _: bool, _: &dyn Fn(usize) -> bool) -> Result { + Err("The GPU reported an error in a test".into()) + } + } + + /// A device error reaches the caller: the software raster does not stand in for the GPU + #[test] + fn a_depth_device_error_is_returned_not_rasterized_in_software() { + let mesh = primitives::sphere(1.0, 16, 8); + let bvh = Arc::new(Bvh::new(&mesh)); + let view = StrokeView::with_hidden_materials(OrbitCamera::default(), Vec2::new(64.0, 64.0), BTreeSet::new()); + + let result = view.visibility(&mesh, &bvh, None, Some(&FailingDevice)); + + assert_eq!(result.err().as_deref(), Some("The GPU reported an error in a test")); + } + + impl DepthDevice for CountingDevice { + fn eye_depth( + &self, + mesh: &Mesh, + camera: &OrbitCamera, + size: (u32, u32), + record_triangles: bool, + include: &dyn Fn(usize) -> bool, + ) -> Result { + self.0.fetch_add(1, Ordering::Relaxed); + Ok(EyeDepth::rasterize(mesh, camera, size.0, size.1, record_triangles, include)) + } + } + + /// A stroke's visibility asks the depth device for the camera's depth, with and without + /// hidden materials + #[test] + fn stroke_visibility_rasterizes_on_the_depth_device() { + let mesh = primitives::sphere(1.0, 16, 8); + let bvh = Arc::new(Bvh::new(&mesh)); + let device = CountingDevice(AtomicUsize::new(0)); + for hidden in [BTreeSet::new(), BTreeSet::from([3])] { + let view = StrokeView::with_hidden_materials(OrbitCamera::default(), Vec2::new(256.0, 256.0), hidden); + view.visibility(&mesh, &bvh, None, Some(&device)).unwrap(); + } + assert_eq!(device.0.load(Ordering::Relaxed), 2); + } +} diff --git a/crates/engine/src/gpu_failure.rs b/crates/engine/src/gpu_failure.rs new file mode 100644 index 000000000..6fb691615 --- /dev/null +++ b/crates/engine/src/gpu_failure.rs @@ -0,0 +1,20 @@ +//! Why a GPU device did not do the work the engine handed it. + +use std::fmt; + +/// A refusal sends the work to the CPU; a device error is shown and nothing is computed on the CPU. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum GpuFailure { + /// The device cannot take this work (an adapter limit or an input it does not support) + Refused(String), + /// The GPU reported an error, after the device's one retry when it ran out of memory + Device(String), +} + +impl fmt::Display for GpuFailure { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + GpuFailure::Refused(reason) | GpuFailure::Device(reason) => f.write_str(reason), + } + } +} diff --git a/crates/engine/src/id_mask_view.rs b/crates/engine/src/id_mask_view.rs index 7b14a9a62..1ea1bb6d2 100644 --- a/crates/engine/src/id_mask_view.rs +++ b/crates/engine/src/id_mask_view.rs @@ -17,27 +17,28 @@ impl Session { Some((texture_set, image)) } - /// RGBA8 of [`Session::id_mask_image`] on its texture set at `size²`, the stored values unconverted like the ID mesh map's view - pub fn id_mask_view_rgba(&self, effect: LayerId, size: u32) -> Option> { + /// RGBA8 of [`Session::id_mask_image`] on its texture set at `extent` (width, height), the + /// stored values unconverted like the ID mesh map's view. Where layers composite on the GPU, + /// the renderer draws this view itself (`AuxSource::IdMask`). + pub fn id_mask_view_rgba(&self, effect: LayerId, extent: (u32, u32)) -> Option> { let (texture_set, image) = self.id_mask_image(effect)?; let (width, height) = self.doc.project.texture_sets.get(texture_set)?.size(); - let size = size.max(1); + let (columns, rows) = (extent.0.max(1), extent.1.max(1)); // Each view pixel shows the color its texture set texel reads, sampled at that texel's centre as the mask and a pick do - let texel_centre = |pixel: u32, extent: u32| { + let texel_centre = |pixel: u32, count: u32, extent: u32| { let extent = extent.max(1); - let texel = ((pixel as f32 + 0.5) / size as f32 * extent as f32).floor().min((extent - 1) as f32); + let texel = ((pixel as f32 + 0.5) / count as f32 * extent as f32).floor().min((extent - 1) as f32); (texel + 0.5) / extent as f32 }; - let side = size as usize; - let byte_count = side.checked_mul(side)?.checked_mul(4)?; + let byte_count = (columns as usize).checked_mul(rows as usize)?.checked_mul(4)?; let mut rgba = Vec::new(); rgba.try_reserve_exact(byte_count).ok()?; - for y in 0..size { - let v = texel_centre(y, height); - for x in 0..size { - let color = image.sample_nearest(texel_centre(x, width), v); + for y in 0..rows { + let v = texel_centre(y, rows, height); + for x in 0..columns { + let color = image.sample_nearest(texel_centre(x, columns, width), v); rgba.extend(color[..3].iter().map(|value| (value.clamp(0.0, 1.0) * 255.0 + 0.5) as u8)); rgba.push(u8::MAX); } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 8d904f053..40715932e 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -18,7 +18,9 @@ pub mod brush_preset_cmds; pub mod camera_cmds; pub mod color_selection_cmds; pub mod commands; +pub mod composite_device; pub mod decal_cmds; +pub mod depth_device; pub mod distance_params; pub mod effect_blending_cmds; pub mod effect_clipboard; @@ -35,6 +37,7 @@ pub mod folder_cmds; mod frame_target; mod generator_input; pub mod generator_pick; +pub mod gpu_failure; pub mod id_mask_view; pub mod inspect; pub mod instance_cmds; @@ -53,7 +56,7 @@ mod mask_owner; mod mask_preview_pixel; pub mod material_lib; mod material_overview; -pub use material_overview::MaterialOverview; +pub use material_overview::{MaterialOverview, OverviewSnapshot}; mod material_preview_pixel; pub mod materials; pub mod materialx_cmds; diff --git a/crates/engine/src/material_overview.rs b/crates/engine/src/material_overview.rs index fbc227561..989bac5b8 100644 --- a/crates/engine/src/material_overview.rs +++ b/crates/engine/src/material_overview.rs @@ -1,12 +1,15 @@ //! A bounded, disposable material image for a viewport with a cold composite. use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; -use texturecraft_compose::{BakedMaps, Composite, DisplayKind, Inputs, all_tiles, composite_tiles, kinds_for, tile_bytes}; -use texturecraft_core::{AoMixing, Channel}; -use texturecraft_geom::UvGBuffer; +use texturecraft_compose::{BakedMaps, Composite, DisplayKind, ImageStore, Inputs, PixelStore, all_tiles, composite_tiles, kinds_for, tile_bytes}; +use texturecraft_core::{AoMixing, Channel, Project}; +use texturecraft_geom::{Mesh, UvGBuffer}; use texturecraft_texel::TILE; use crate::Session; +use crate::composite_device::{CompositeDevice, CompositeJob}; +use crate::gpu_failure::GpuFailure; /// Packed display maps, sampled across the entire atlas before full-size tiles arrive. pub struct MaterialOverview { @@ -14,20 +17,109 @@ pub struct MaterialOverview { pub maps: Vec<(DisplayKind, Vec)>, } +/// An owned copy of what one texture set's overview reads, so it can be made off the UI thread +/// ([`OverviewSnapshot::render`]) +pub struct OverviewSnapshot { + ts: usize, + /// The set's size halved this many times (the overview's step is 2^shift texels) + shift: u32, + /// The project as the viewport shows it (a soloed layer alone) + project: Project, + pixels: PixelStore, + baked: BakedMaps, + images: ImageStore, + mesh: Arc, + /// The set's G-buffer at its full size + gbuf: Arc, + /// The coverage the viewport pads UV islands from, when it pads from one + padding: Option>, +} + impl Session { /// Evaluate the ordinary material stack on a small UV grid, sharing its source pixels, /// images and bakes. This never enters a paint, undo or export cache. pub fn material_overview(&self, ts: usize, max_edge: u32) -> Option { + self.overview_snapshot(ts, max_edge)?.on_cpu() + } + + /// What [`Self::material_overview`] reads, owned: render it on another thread + pub fn overview_snapshot(&self, ts: usize, max_edge: u32) -> Option { let set = self.doc.project.texture_sets.get(ts)?; let (w, h) = set.size(); let limit = max_edge.clamp(TILE, 256); - let mut step = 1; - while w.max(h) / step > limit { - step *= 2; + let mut shift = 0; + while w.max(h) >> shift > limit { + shift += 1; } - let (width, height) = ((w / step).max(1), (h / step).max(1)); let cache = self.caches.get(ts)?; - let source = &cache.gbuf; + Some(OverviewSnapshot { + ts, + shift, + project: self.solo_view().unwrap_or_else(|| self.doc.project.clone()), + pixels: self.doc.pixels.clone(), + baked: self.doc.baked.get(&ts).cloned().unwrap_or_default(), + images: self.images.clone(), + mesh: self.mesh.clone(), + gbuf: cache.gbuf.clone(), + padding: cache.dilation.mixed_coverage(), + }) + } +} + +impl OverviewSnapshot { + /// The overview composited on `device` when given (at the set's size halved by the + /// overview's step, reading every step-th texel); without a device, or when it refuses the + /// material, on the CPU. A device error is returned, not redone on the CPU. Once `cancel` + /// is set the device stops before its next composite and nothing composites on the CPU. + pub fn render(&self, device: Option<&dyn CompositeDevice>, cancel: Option<&AtomicBool>) -> Result { + if let Some(device) = device { + match self.on_device(device, cancel) { + Ok(overview) => return Ok(overview), + Err(GpuFailure::Refused(_)) if cancel.is_some_and(|cancel| cancel.load(Ordering::Acquire)) => return Err("the overview was cancelled".into()), + Err(GpuFailure::Refused(_)) => {} + Err(GpuFailure::Device(error)) => return Err(error), + } + } + + if cancel.is_some_and(|cancel| cancel.load(Ordering::Acquire)) { + return Err("the overview was cancelled".into()); + } + self.on_cpu().ok_or_else(|| "the texture set no longer exists".to_string()) + } + + fn on_device(&self, device: &dyn CompositeDevice, cancel: Option<&AtomicBool>) -> Result { + let set = self.project.texture_sets.get(self.ts).ok_or_else(|| GpuFailure::Refused("the texture set no longer exists".into()))?; + let job = CompositeJob { + project: &self.project, + ts: self.ts, + pixels: &self.pixels, + mesh: &self.mesh, + gbuf: &self.gbuf, + baked: &self.baked, + images: &self.images, + shift: self.shift, + padding: self.padding.as_ref().map(|coverage| (coverage, crate::session::DISPLAY_PADDING)), + cancel, + }; + let kinds: Vec = kinds_for(&set.channel_list()).collect(); + let (size, maps) = device.display_maps(&job, &kinds)?; + + // The renderer may halve beyond the overview's step for its texture limit; the viewport + // seeds an overview of at most 256 texels a side + if size.0 == 0 || size.1 == 0 || size.0.max(size.1) > 256 || maps.len() != kinds.len() { + return Err(GpuFailure::Refused("the GPU overview is not the overview's size".into())); + } + Ok(MaterialOverview { size, maps: kinds.into_iter().zip(maps).collect() }) + } + + /// The overview on the CPU: the set's G-buffer sampled at block centres, composited with the + /// reduced block scales and padded as the viewport pads + fn on_cpu(&self) -> Option { + let set = self.project.texture_sets.get(self.ts)?; + let (w, h) = set.size(); + let step = 1 << self.shift; + let (width, height) = ((w / step).max(1), (h / step).max(1)); + let source = &self.gbuf; // Reuse the full UV raster to avoid traversing the mesh again for an overview let positions = (0..height).flat_map(|y| { @@ -40,18 +132,15 @@ impl Session { let (tri, bary) = positions.map(|i| (source.tri.get(i).copied().unwrap_or(texturecraft_geom::NO_TRI), source.bary.get(i).copied().unwrap_or_default())).unzip(); let gbuf = Arc::new(UvGBuffer { width, height, tri, bary, overlaps: 0, shared_surfaces: false }); - let empty = BakedMaps::default(); - let baked = self.doc.baked.get(&ts).unwrap_or(&empty); let channels = set.channel_list(); - let project = self.solo_view(); let scales = set.block_scales().at_reduced_resolution(step); let inputs = Inputs { - project: project.as_ref().unwrap_or(&self.doc.project), - ts, + project: &self.project, + ts: self.ts, mesh: &self.mesh, gbuf: &gbuf, - pixels: &self.doc.pixels, - baked, + pixels: &self.pixels, + baked: &self.baked, block_scales: scales.clone(), preview: None, images: &self.images, @@ -65,7 +154,7 @@ impl Session { let has_coverage = gbuf.tri.iter().any(|&triangle| triangle != texturecraft_geom::NO_TRI); let padding = crate::session::DisplayPadding::new(&self.mesh, set, &gbuf, has_coverage, block); padding.apply_to_tiles(&mut composite, &tiles); - let maps = pack_overview(&composite, baked, set.ao_mixing, &channels, &tiles); + let maps = pack_overview(&composite, &self.baked, set.ao_mixing, &channels, &tiles); Some(MaterialOverview { size: (width, height), maps }) } } diff --git a/crates/engine/src/orb_preview.rs b/crates/engine/src/orb_preview.rs index 55e12298f..c522864b8 100644 --- a/crates/engine/src/orb_preview.rs +++ b/crates/engine/src/orb_preview.rs @@ -5,7 +5,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; use serde_json::json; -use texturecraft_compose::ImageRes; +use texturecraft_compose::{BakedMaps, ImageRes}; use texturecraft_core::{ BakeResolution, BakedMap, BlendMode, Channel, CurvatureMethod, EffectKind, Generator, GeneratorKind, KindControls, LayerId, MaskBackground, Procedural, ProceduralKind, Source, @@ -14,6 +14,7 @@ use texturecraft_geom::glam::Vec3; use texturecraft_geom::primitives; use texturecraft_texel::TILE; +use crate::composite_device::{CompositeDevice, CompositeJob}; pub use crate::mask_preview_pixel::MaskPreviewPixel; pub use crate::material_preview_pixel::MaterialPreviewPixel; use crate::orb_camera::OrbCamera; @@ -155,11 +156,17 @@ impl OrbPreview { Some(pixels) } + /// Composite the material previews on `device` (the GPU), or on the CPU with None + pub fn set_composite_device(&mut self, device: Option>) { + self.session.composite_device = device; + } + /// Row-major `size²` pixels of built-in material `id`, with None outside the shape - /// Returns None for unknown materials or sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`] - pub fn material(&mut self, id: &str, size: usize) -> Option>> { + /// Returns None for unknown materials or sizes outside 1..=[`MAX_PREVIEW_SIZE_PX`], and the + /// composite device's error when it reports one (the CPU does not composite it instead) + pub fn material(&mut self, id: &str, size: usize) -> std::result::Result>>, String> { if !valid_size(size) { - return None; + return Ok(None); } // Each material goes on the bare shape, not over the previous one @@ -167,10 +174,12 @@ impl OrbPreview { let applied = materials::apply(&mut self.session, id); // Previews need no undo history; retaining snapshots grows memory across materials self.session.undo.clear(); - applied.ok()?; + if applied.is_err() { + return Ok(None); + } - let camera = camera_for(&mut self.cameras, &self.session, size)?; - let values = material_at(&self.session, &camera.texels)?; + let Some(camera) = camera_for(&mut self.cameras, &self.session, size) else { return Ok(None) }; + let Some(values) = material_at(&self.session, &camera.texels)? else { return Ok(None) }; let sub_pixels = (SUPERSAMPLE * SUPERSAMPLE) as f32; let pixels = (0..size * size) @@ -199,7 +208,7 @@ impl OrbPreview { }) }) .collect(); - Some(pixels) + Ok(Some(pixels)) } } @@ -218,12 +227,33 @@ fn pixel_hits(camera: &OrbCamera, size: usize, pixel: usize) -> impl Iterator Option> { +/// The material values at `texels`: on the session's composite device unless it refuses the +/// material, else on the CPU compositing only the tiles that hold them. The device's error is +/// returned, not redone on the CPU. +fn material_at(session: &Session, texels: &[(u32, u32)]) -> std::result::Result>, String> { + if let Some(cache) = session.caches.get(SET) { + let empty = BakedMaps::default(); + let job = CompositeJob { + project: &session.doc.project, + ts: SET, + pixels: &session.doc.pixels, + mesh: &session.mesh, + gbuf: &cache.gbuf, + baked: session.doc.baked.get(&SET).unwrap_or(&empty), + images: &session.images, + shift: 0, + padding: None, + cancel: None, + }; + if let Some(samples) = crate::composite_device::samples(session.composite_device.as_deref(), &job, texels)? { + return Ok(Some(samples)); + } + } + let tiles: BTreeSet<(u32, u32)> = texels.iter().map(|(x, y)| (x / TILE, y / TILE)).collect(); let tiles: Vec<(u32, u32)> = tiles.into_iter().collect(); - session.with_inputs(SET, |inputs| { + Ok(session.with_inputs(SET, |inputs| { let mut composite = texturecraft_compose::Composite::new(&MATERIAL_CHANNELS, TEXTURE_PX); texturecraft_compose::composite_tiles(inputs, &mut composite, &tiles); @@ -235,7 +265,7 @@ fn material_at(session: &Session, texels: &[(u32, u32)]) -> Option> }) .collect(); Some(samples) - }) + })) } /// Cache one camera per preview size, evicting the least recently used view @@ -295,7 +325,7 @@ mod tests { let stack_size = preview.session.doc.project.texture_set(SET).unwrap().stack.len(); for size in [0, MAX_PREVIEW_SIZE_PX + 1, usize::MAX / 2 + 1, usize::MAX] { assert!(preview.mask("edges_sharp", size).is_none(), "size {size} should be rejected before rendering"); - assert!(preview.material("steel_painted_worn", size).is_none(), "size {size} should be rejected before rendering"); + assert!(preview.material("steel_painted_worn", size).unwrap().is_none(), "size {size} should be rejected before rendering"); assert!(preview.cameras.is_empty(), "invalid sizes must not allocate a camera"); assert!(preview.session.doc.project.layer(layer).unwrap().mask.is_none(), "invalid sizes must not apply a mask"); assert_eq!(preview.session.doc.project.texture_set(SET).unwrap().stack.len(), stack_size, "invalid sizes must not apply a material"); @@ -376,7 +406,7 @@ mod tests { let mut preview = OrbPreview::new().unwrap(); for material in materials::MATERIALS.iter().filter(|material| material.smart) { let id = material.id; - let pixels = preview.material(id, size).unwrap_or_else(|| panic!("{id}")); + let pixels = preview.material(id, size).unwrap().unwrap_or_else(|| panic!("{id}")); assert_eq!(pixels.len(), size * size, "{id}"); assert!(pixels[0].is_none(), "{id}: the corners are outside the shape"); @@ -387,10 +417,10 @@ mod tests { assert!(pixel.normal.is_finite() && pixel.coverage > 0.0, "{id}: {pixel:?}"); } } - assert!(preview.material("nope", size).is_none()); + assert!(preview.material("nope", size).unwrap().is_none()); // Paint chipped at the edges shows the steel under it: the smart material is not its base - let (worn, steel) = (preview.material("steel_painted_worn", size).unwrap(), preview.material("steel", size).unwrap()); + let (worn, steel) = (preview.material("steel_painted_worn", size).unwrap().unwrap(), preview.material("steel", size).unwrap().unwrap()); let metallic_pixels = |pixels: &[Option]| pixels.iter().flatten().filter(|pixel| pixel.sample.metallic > 0.5).count(); let (worn_metallic, steel_metallic) = (metallic_pixels(&worn), metallic_pixels(&steel)); assert!(worn_metallic > 0 && worn_metallic < steel_metallic / 2, "bare steel only at the worn edges: {worn_metallic} of {steel_metallic}"); @@ -399,7 +429,7 @@ mod tests { assert_ne!(base_colors(&worn), base_colors(&steel)); // Each material starts from the bare orb: rendering another one in between changes nothing - preview.material("iron_rusted", size).unwrap(); - assert_eq!(preview.material("steel_painted_worn", size).unwrap(), worn); + preview.material("iron_rusted", size).unwrap().unwrap(); + assert_eq!(preview.material("steel_painted_worn", size).unwrap().unwrap(), worn); } } diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index d734b9d36..2cc166ef0 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -9,7 +9,7 @@ use texturecraft_core::{BlendMode, Channel, Effect, EffectKind, LayerId, LayerKi use texturecraft_geom::glam::Vec2; use texturecraft_paint::{ CommitSource, PickCtx, Pickup, PickupMode, RasterCtx, Shape, Staging, Stamp, Stroke, StrokeCanvas, SurfaceHit, commit_layer, commit_mask, pick, - pick_filtered, rasterize, + pick_filtered, }; use texturecraft_texel::{TILE, TILE_AREA}; @@ -19,7 +19,7 @@ use crate::session::{ ActiveStroke, CloneFrom, DisplayStrokeEnd, QUICK_MASK_STROKE_LABEL, ReleasedDab, Session, StackTarget, Tool, history_label, next_mesh_id, stroke_template, }; use crate::stroke_replay::{PaintPlacement, RecordedPaint, StrokeReplays, WorldPaint, record_sample, record_uv_dabs}; -use crate::uv_stroke_state::{UV_STAMP_BATCH, UvStrokeState}; +use crate::uv_stroke_state::UvStrokeState; use crate::uv_symmetry::UvMirror; use crate::{EngineError, Result}; @@ -173,7 +173,7 @@ impl Session { let snapshot = texturecraft_paint::pickup::PickupSnapshot { project, ts: 0, - target: PaintTarget::Layer(layer_id), + target: Some(PaintTarget::Layer(layer_id)), mesh: self.mesh.clone(), bounds: self.mesh.bounds(), pixels: Default::default(), @@ -280,7 +280,14 @@ impl Session { let (bvh, depth) = if uv_mode { (self.bvh.clone(), None) } else { - let (bvh, depth) = self.stroke_visibility(viewport); + // A GPU depth error ends the stroke with that error; no software depth replaces it + let (bvh, depth) = match self.stroke_visibility(viewport) { + Ok(visibility) => visibility, + Err(error) => { + self.doc = before; + return Err(EngineError::Other(error)); + } + }; (bvh, Some(depth)) }; let stroke = Stroke::new(&self.tool.brush, &self.mesh); @@ -308,15 +315,20 @@ impl Session { baked: before.baked.get(&ts).cloned().unwrap_or_default(), images: self.images.clone(), }; + + // A smudge or clone for the GPU brush leaves its source to the GPU compositor: the CPU + // evaluates source tiles only if the stroke paints on the CPU + let device_pickup = matches!(tool, Tool::Smudge | Tool::Clone) && allow_device && self.brush_device.is_some(); let mut pickup = match (&layer_source, mask_owner, smudge_target) { // On a mask the stroke reads the mask's own values - (_, Some(owner), _) => Pickup::from_snapshot(mode, snapshot(PaintTarget::Mask(owner)), cache.gbuf.clone(), []), + (_, Some(owner), _) => Pickup::from_snapshot(mode, snapshot(Some(PaintTarget::Mask(owner))), cache.gbuf.clone(), []), (Some(flat), None, _) => Pickup::from_layer(mode, flat, size, cache.gbuf.clone(), values.keys().copied()), (None, None, Some(id)) => { let pixels: BTreeMap<_, _> = values.keys().filter_map(|&channel| before.pixels.layer(id, channel).map(|image| (channel, image.clone()))).collect(); Pickup::from_paint(mode, pixels, cache.gbuf.clone(), values.keys().copied()) } + (None, None, None) if device_pickup => Pickup::from_snapshot(mode, snapshot(None), cache.gbuf.clone(), values.keys().copied()), (None, None, None) => Pickup::new( mode, self.document_composite(ts, &cache.covered_tiles).ok_or_else(|| EngineError::Other("texture set not ready".into()))?.into_owned(), @@ -350,7 +362,6 @@ impl Session { let settings = &stroke.settings; let image_alpha = settings.alpha_image.as_ref().and_then(|name| self.images.get(name)).cloned(); - let library_alpha = if image_alpha.is_none() { settings.library_alpha_image() } else { None }; // Resolved once: staging, both previews and the commit paint this gray let mask_gray = self.mask_gray(); @@ -375,16 +386,24 @@ impl Session { }; // Paths rasterize their outlines through the brush backend - let gpu_tool = matches!(tool, Tool::Paint | Tool::Eraser | Tool::Projection | Tool::Path); - - // The world shader only evaluates the surface that owns each texel + let gpu_tool = matches!(tool, Tool::Paint | Tool::Eraser | Tool::Projection | Tool::Path | Tool::Clone | Tool::Smudge); + + // A clone's carried values are the source's at a fixed offset (the brush material's + // pattern at none): the device paints the alpha and reads the source there. A smudge + // drags its source on the device stamp by stamp. The pickup keeps what it read back. + let clone = canvas.pickup.as_ref().filter(|_| allow_device && self.brush_device.is_some()).and_then(Pickup::clone_source); + let smudge = canvas.pickup.as_ref().filter(|_| allow_device && self.brush_device.is_some()).and_then(texturecraft_paint::Pickup::smudge_source); + // A source with per-channel coverage keeps an alpha per channel on the device + let mut channel_alphas = smudge.as_ref().is_some_and(|source| source.coverage.is_some()); + + // On shared UVs the world shader paints every surface of a texel, but a stencil is + // sampled at the owner only (the CPU keeps the strongest surface's sample) let device = if allow_device && gpu_tool - && canvas.pickup.is_none() - && stencil.as_ref().is_none_or(|stencil| stencil.colors) + && (canvas.pickup.is_none() || clone.is_some() || smudge.is_some()) && let Some(backend) = &self.brush_device && let Some(cache) = self.caches.get(ts) - && (uv_mode || !cache.gbuf.shared_surfaces) + && (uv_mode || !cache.gbuf.shared_surfaces || stencil.is_none()) && backend.surface.ptr_eq(&std::sync::Arc::downgrade(&cache.gbuf)) { let surface = crate::brush_device::BrushSurface { @@ -397,17 +416,64 @@ impl Session { alpha_image: image_alpha.clone(), stencil: stencil.clone(), limit: canvas.limit.clone(), + clone, + smudge, }; - match backend.device.start(surface) { - Ok(device) => Some(device), - Err(error) => { - self.log.performance(format!("GPU brush could not start: {error}")); + let brush = backend.device.clone(); + let composited = surface.smudge.as_ref().is_some_and(|source| source.composited.is_some()) + || surface.clone.as_ref().is_some_and(|source| source.composited.is_some()); + let mut started = brush.start(surface.clone()); + + // A material the GPU compositor refuses: the CPU composite (or the mask's values, or + // the brush material's fill) is the source, the GPU brush still paints the stroke + if composited + && let Err(crate::gpu_failure::GpuFailure::Refused(reason)) = &started + && reason.starts_with(texturecraft_paint::PICKUP_SOURCE_REFUSED) + && let Some(pickup) = canvas.pickup.as_mut() + { + self.log.performance(format!("GPU clone or smudge source composited on the CPU: {reason}")); + self.read_whole_pickup_source(ts, pickup)?; + pickup.evaluate_whole(); + let (smudge, clone) = (pickup.smudge_source(), pickup.clone_source()); + channel_alphas = smudge.as_ref().is_some_and(|source| source.coverage.is_some()); + started = if smudge.is_none() && clone.is_none() { + Err(crate::gpu_failure::GpuFailure::Refused("the evaluated source's channels differ in coverage".into())) + } else { + brush.start(crate::brush_device::BrushSurface { smudge, clone, ..surface }) + }; + } + match started { + Ok(device) => { + // The device paints one stroke alpha that every carried channel shares, or + // with per-channel coverage each channel's own + if let Some(pickup) = canvas.pickup.as_mut().filter(|_| !channel_alphas) { + pickup.use_stroke_alpha(); + } + Some(device) + } + Err(crate::gpu_failure::GpuFailure::Refused(reason)) => { + self.log.performance(format!("GPU brush could not start: {reason}")); None } + + // A device error fails the stroke: the CPU does not paint it instead + Err(crate::gpu_failure::GpuFailure::Device(error)) => { + self.doc = before; + return Err(self.fail_stroke(format!("GPU brush could not start: {error}"))); + } } } else { None }; + // A CPU clone or smudge reads the document's composite whole (the cache's, when it is current) + if device.is_none() + && let Some(pickup) = canvas.pickup.as_mut() + { + self.read_whole_pickup_source(ts, pickup)?; + } + + // The device generates library tips itself: only a CPU stroke renders the CPU image + let library_alpha = if device.is_none() && image_alpha.is_none() { settings.library_alpha_image() } else { None }; if device.is_some() { let detail = if stencil.is_some() { "stroke coverage, stencil sampling and live paint" } else { "stroke coverage and live paint" }; self.log.performance(format!("Brush: GPU ({detail})")); @@ -435,12 +501,22 @@ impl Session { label, staging: Staging::default(), device, - device_uv_stamps: Vec::new(), + device_error: None, replay, }); Ok(()) } + /// A clone or smudge evaluating the document's composite lazily reads it whole instead + fn read_whole_pickup_source(&self, ts: usize, pickup: &mut Pickup) -> Result<()> { + if pickup.composites_lazily() { + let cache = self.caches.get(ts).ok_or_else(|| EngineError::Other("texture set not ready".into()))?; + let whole = self.document_composite(ts, &cache.covered_tiles).ok_or_else(|| EngineError::Other("texture set not ready".into()))?; + pickup.read_whole(whole.into_owned()); + } + Ok(()) + } + /// A Pass through paint layer can smear the stack without blending it twice. /// `id` is the resolved stroke target, including the source of an instance. fn smudge_reads_stack(&self, id: LayerId, values: &BTreeMap) -> bool { @@ -567,7 +643,6 @@ impl Session { } } if let Some(device) = &mut active.device { - active.device_uv_stamps.extend(batch.iter().copied()); match device.append_uv(batch) { Ok(tiles) => { active.display_tiles.extend(&tiles); @@ -575,14 +650,10 @@ impl Session { } Err(error) => { active.device = None; - active.display_tiles.append(&mut active.canvas.dirty); - self.log.performance(format!("GPU brush switched to CPU: {error}")); - for stamps in std::mem::take(&mut active.device_uv_stamps).chunks(UV_STAMP_BATCH) { - texturecraft_paint::rasterize_uv(&mut active.canvas, &cache.gbuf, shape, stamps); - } + active.device_error = Some(format!("GPU brush failed: {error}")); } } - } else { + } else if active.device_error.is_none() { texturecraft_paint::rasterize_uv(&mut active.canvas, &cache.gbuf, shape, batch); } }); @@ -625,7 +696,7 @@ impl Session { }; if let Some(device) = &mut active.device { - match device.append_world(&stamps) { + match device.append_world(&stamps, use_view) { Ok(tiles) => { active.display_tiles.extend(&tiles); active.canvas.dirty.extend(tiles); @@ -637,11 +708,12 @@ impl Session { Err(error) => { active.device = None; - active.display_tiles.append(&mut active.canvas.dirty); - self.log.performance(format!("GPU brush switched to CPU: {error}")); - rasterize(&mut active.canvas, &raster_context, &active.stroke.stamps); + active.device_error = Some(format!("GPU brush failed: {error}")); + return hit; } } + } else if active.device_error.is_some() { + return hit; } else { texturecraft_paint::raster::rasterize_with_stencil(&mut active.canvas, &raster_context, &stamps, active.stencil.as_mut()); } @@ -708,6 +780,7 @@ impl Session { mask_image: stroke.mask_gray.image_name(), opacity: stroke.stroke.settings.opacity, erase: stroke.erase, + pickup: stroke.canvas.pickup.is_some(), stroke: stroke.device.as_deref()?, }) } @@ -720,43 +793,46 @@ impl Session { fn take_device_stroke(&mut self, preview_fallback: Option<&str>) -> Option> { let stroke = self.stroke.as_mut()?; let device = stroke.device.take()?; - let valid = match device.read_alpha(&stroke.canvas.dirty) { + // A clone's or smudge's carried values come back once, with the alpha, for the commit or + // the CPU that continues the stroke + let read = match stroke.canvas.pickup.as_mut() { + Some(pickup) => device.read_carried(&stroke.canvas.dirty).and_then(|(alpha, values)| { + pickup.carry_device_values(values); + + // A source with per-channel coverage: each channel's own alpha comes back too + if pickup.channel_alphas().is_some() { + pickup.carry_device_alphas(device.read_channel_alphas(&stroke.canvas.dirty)?); + } + Ok(alpha) + }), + None => device.read_alpha(&stroke.canvas.dirty), + }; + let valid = match read { Ok(alpha) => { stroke.canvas.dirty = alpha.allocated().collect(); stroke.canvas.alpha = alpha; true } Err(error) => { - stroke.display_tiles.append(&mut stroke.canvas.dirty); - self.log.performance(format!("GPU stroke readback failed, replaying stroke on CPU: {error}")); - let cache = self.caches.get(stroke.ts)?; - let settings = &stroke.stroke.settings; - let shape = Shape::new(settings.alpha, stroke.image_alpha.as_deref(), stroke.library_alpha.as_deref(), settings.alpha_params); - if stroke.uv.is_some() { - for stamps in stroke.device_uv_stamps.chunks(UV_STAMP_BATCH) { - texturecraft_paint::rasterize_uv(&mut stroke.canvas, &cache.gbuf, shape, stamps); - } - } else { - let context = RasterCtx { - mesh: &self.mesh, - bvh: &stroke.bvh, - gbuf: &cache.gbuf, - material: self.doc.project.texture_sets.get(stroke.ts).map_or(0, |set| set.material), - depth: stroke.depth.as_deref(), - eye: stroke.camera.eye(), - backface_culling: stroke.stroke.settings.backface_culling, - angle_fade: stroke.stroke.settings.angle_fade, - shape, - }; - rasterize(&mut stroke.canvas, &context, &stroke.stroke.stamps); - } + stroke.device_error = Some(format!("GPU stroke readback failed: {error}")); false } }; - stroke.device_uv_stamps.clear(); stroke.display_tiles.extend(&stroke.canvas.dirty); stroke.canvas.recent.extend(&stroke.canvas.dirty); if let Some(reason) = preview_fallback { + // A smudge continues the device's trails: each copy's previous center and own deposits + if let Some(pickup) = stroke.canvas.pickup.as_mut().filter(|pickup| matches!(pickup.mode, PickupMode::Smudge { .. })) { + match device.read_smudge_lanes(&stroke.canvas.dirty) { + Ok(lanes) => pickup.resume_smudge(lanes), + Err(error) => stroke.device_error = Some(format!("GPU stroke readback failed: {error}")), + } + } + + // The rest of the stroke rasterizes on the CPU, which needs the library tip's image + if stroke.image_alpha.is_none() { + stroke.library_alpha = stroke.stroke.settings.library_alpha_image(); + } self.log.performance(format!("Brush: CPU ({reason})")); self.stroke_painted(); } @@ -764,8 +840,9 @@ impl Session { } /// Identity and tiles of a supported live stroke since the display last drew it, on its own - /// texture set or another one it feeds. A pickup (clone, smudge, brush material) shows - /// through [`Session::display_stroke_pixels`]. + /// texture set or another one it feeds. A pickup (clone, smudge, brush material) on the GPU + /// brush shows from the device's carried values, a CPU one through + /// [`Session::display_stroke_pixels`]. pub fn pending_display_stroke(&self, ts: usize) -> Option<(u64, &BTreeSet<(u32, u32)>)> { let stroke = self.stroke.as_ref()?; let tiles = &stroke.display_tiles; @@ -854,6 +931,16 @@ impl Session { /// Commit the active stroke (one undo step). pub fn end_stroke(&mut self) -> Result<()> { let device = self.take_device_stroke(None); + self.end_stroke_with(device) + } + + /// Commit the active stroke whose device coverage was read back (`device`: the GPU brush that + /// still answers a stencil's projection readback) + fn end_stroke_with(&mut self, device: Option>) -> Result<()> { + if let Some(error) = self.stroke.as_ref().and_then(|stroke| stroke.device_error.clone()) { + return Err(self.fail_stroke(error)); + } + let brush_tile = self.tile_demand(None).brush; let Some(mut stroke) = self.stroke.take() else { return Ok(()) }; @@ -896,23 +983,24 @@ impl Session { }; if let Some(device) = device.as_deref().filter(|_| stroke.stencil.is_some()) { let tiles: Vec<_> = stroke.canvas.dirty.iter().copied().collect(); - let mut gpu_readback = Some(device); for batch in tiles.chunks(PROJECTION_READBACK_BATCH) { let tiles: BrushTiles = batch.iter().copied().collect(); - let projection = gpu_readback.and_then(|device| match device.read_projection(&tiles) { - Ok(samples) if tiles.iter().all(|tile| samples.get(tile).is_some_and(|data| data.len() == TILE_AREA)) => Some(samples), - Ok(_) => { - self.log.performance("GPU stencil readback missed tiles, sampling remaining tiles on CPU"); - gpu_readback = None; - None - } + let projection = match device.read_projection(&tiles) { + Ok(samples) if tiles.iter().all(|tile| samples.get(tile).is_some_and(|data| data.len() == TILE_AREA)) => Ok(samples), + Ok(_) => Err("The GPU stencil readback missed tiles.".to_string()), + Err(error) => Err(error), + } + .map_err(|error| format!("GPU stencil readback failed: {error}")); + match projection { + Ok(projection) => commit(&tiles, Some(&projection)), Err(error) => { - self.log.performance(format!("GPU stencil readback failed, sampling remaining tiles on CPU: {error}")); - gpu_readback = None; - None + // The stroke's earlier batches are in the document: the cancel restores it + drop(commit); + stroke.staging = staging; + self.stroke = Some(stroke); + return Err(self.fail_stroke(error)); } - }); - commit(&tiles, projection.as_ref()); + } } } else { commit(&stroke.canvas.dirty, None); @@ -991,6 +1079,14 @@ impl Session { } } + /// Cancel the active stroke after a GPU brush error, which the commit returns: the CPU does not + /// redo the GPU's work. + fn fail_stroke(&mut self, error: String) -> EngineError { + self.log.error("brush", format!("The stroke was not applied: {error}")); + self.cancel_stroke(); + EngineError::Other(format!("The stroke was not applied: {error}")) + } + /// Abandon the active stroke (Esc). pub fn cancel_stroke(&mut self) { if let Some(st) = self.stroke.take() { @@ -1030,11 +1126,12 @@ impl Session { } /// Paint a 3D path in one stroke, using camera visibility only for screen-space samples. - pub(crate) fn stroke_surface_points(&mut self, samples: impl Iterator, viewport: Vec2, all_visible: bool) -> Result { + pub(crate) fn stroke_surface_points(&mut self, samples: impl Iterator, viewport: Vec2) -> Result { self.cancel_stroke(); - // A mixed stroke needs one CPU canvas because the device applies view tests to every dab - self.start_stroke(viewport, false, None, all_visible)?; + // Surface samples (points hidden from the camera) paint without the view test, on the + // device as on the CPU + self.start_stroke(viewport, false, None, true)?; let mut stamp_count = 0usize; for sample in samples { match sample { @@ -1073,9 +1170,10 @@ impl Session { for q in points.iter().skip(1) { self.continue_stroke_uv(*q, 1.0); } - self.materialize_device_stroke(None); + // The device stays until the commit, which reads a stencil's projection from it + let device = self.take_device_stroke(None); let tiles = self.stroke_tiles(); - self.end_stroke()?; + self.end_stroke_with(device)?; Ok(tiles) } @@ -1226,7 +1324,10 @@ fn with_commit_source( let tile = projection.get(&(x / TILE, y / TILE))?; let offset = ((y % TILE) * TILE + x % TILE) as usize; let &[red, green, blue, alpha] = tile.get(offset)?; - return Some((Some([red, green, blue]), alpha)); + + // A mask stencil's sample carries its factor in alpha and no pigment + let colors = stroke.stencil.as_ref().is_some_and(|stencil| stencil.colors); + return Some((colors.then_some([red, green, blue]), alpha)); } stroke.stencil.as_ref()?.paint_texel(x, y, || { @@ -1259,6 +1360,213 @@ mod tests { use crate::{Session, StackTarget, execute}; + /// Starts every stroke and paints nothing + struct IdleBrush; + + struct IdleStroke; + + impl crate::brush_device::BrushDevice for IdleBrush { + fn start(&self, _: crate::brush_device::BrushSurface) -> Result, crate::gpu_failure::GpuFailure> { + Ok(Box::new(IdleStroke)) + } + } + + impl crate::brush_device::DeviceStroke for IdleStroke { + fn append_world(&mut self, _: &[texturecraft_paint::Stamp], _: bool) -> Result { + Ok(Default::default()) + } + + fn append_uv(&mut self, _: &[texturecraft_paint::UvStamp]) -> Result { + Ok(Default::default()) + } + + fn read_alpha(&self, _: &crate::brush_device::BrushTiles) -> Result { + Err("nothing painted".into()) + } + + fn read_projection(&self, _: &crate::brush_device::BrushTiles) -> Result { + Err("nothing projected".into()) + } + + fn as_any(&self) -> &dyn std::any::Any { + self + } + } + + /// Starts an idle stroke and notes whether each start's clone or smudge source was left to the + /// GPU compositor; refuses those when `refuse` (a material the GPU compositor cannot take) + struct PickupSourceRecorder { + refuse: bool, + composited: std::sync::Mutex>, + } + + impl crate::brush_device::BrushDevice for PickupSourceRecorder { + fn start(&self, surface: crate::brush_device::BrushSurface) -> Result, crate::gpu_failure::GpuFailure> { + let composited = surface.smudge.as_ref().is_some_and(|source| source.composited.is_some()) + || surface.clone.as_ref().is_some_and(|source| source.composited.is_some()); + self.composited.lock().unwrap().push(composited); + if composited && self.refuse { + return Err(crate::gpu_failure::GpuFailure::Refused(format!("{}a test material", texturecraft_paint::PICKUP_SOURCE_REFUSED))); + } + Ok(Box::new(IdleStroke)) + } + } + + /// A GPU smudge or clone leaves its source to the GPU compositor (the CPU composites none of + /// it): a smudge on a Pass through layer (it smears the stack) and on a mask, a clone of the + /// composite and a brush material's pattern; when the device refuses to composite the + /// material, the CPU evaluates the source and the GPU brush still paints the stroke. A smudge + /// of a layer's own paint deposits per channel where the layer has it: the device takes its + /// per-channel coverage + #[test] + fn a_gpu_pickup_leaves_its_source_to_the_gpu_compositor() { + for kind in ["smudge", "mask smudge", "clone", "pattern", "own paint smudge"] { + let mut s = Session::new_project("t", texturecraft_geom::primitives::plane(1.0, 1), "builtin:plane", None, 256).unwrap(); + if kind == "mask smudge" { + execute(&mut s, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0]})).unwrap(); + execute(&mut s, "mask.add.black", &json!({})).unwrap(); + } else { + execute(&mut s, "layer.add.paint", &Value::Null).unwrap(); + } + if kind == "smudge" { + execute(&mut s, "layer.blend", &json!({"channel": "all", "mode": "passthrough"})).unwrap(); + } + match kind { + "clone" => { + execute(&mut s, "tool.clone", &json!({})).unwrap(); + s.tool.clone_source = Some(crate::session::CloneSource { uv: [0.3, 0.5], offset: None }); + } + "pattern" => { + execute(&mut s, "tool.paint", &json!({})).unwrap(); + execute(&mut s, "tool.material", &json!({"material": "cobblestone"})).unwrap(); + } + _ => { + execute(&mut s, "tool.smudge", &json!({})).unwrap(); + } + } + s.update(); + + for refuse in [false, true] { + let recorder = std::sync::Arc::new(PickupSourceRecorder { refuse, composited: Default::default() }); + s.brush_device = Some(crate::brush_device::BrushBackend { device: recorder.clone(), surface: std::sync::Arc::downgrade(&s.caches[0].gbuf) }); + s.begin_stroke_uv(Vec2::splat(0.5), 1.0).unwrap(); + if kind == "own paint smudge" { + // The device drags the layer's own paint with its per-channel coverage + assert_eq!(*recorder.composited.lock().unwrap(), vec![false], "the device starts for a smudge of the layer's own paint"); + let source = s.stroke.as_ref().and_then(|stroke| stroke.canvas.pickup.as_ref()).and_then(texturecraft_paint::Pickup::smudge_source); + assert!(source.is_some_and(|source| source.coverage.is_some()), "with its per-channel coverage"); + assert!(s.stroke.as_ref().is_some_and(|stroke| stroke.device.is_some())); + assert!(!s.log.entries().iter().any(|entry| entry.message.starts_with("Brush: CPU"))); + s.cancel_stroke(); + continue; + } + let expected = if refuse { vec![true, false] } else { vec![true] }; + assert_eq!(*recorder.composited.lock().unwrap(), expected, "{kind}, refused {refuse}"); + let refused = s.log.entries().iter().any(|entry| entry.message.starts_with("GPU brush could not start")); + assert!(!refused, "{kind}, refused {refuse}: the GPU brush paints it"); + s.cancel_stroke(); + } + } + } + + /// Paints one tile per batch and counts the readbacks of its carried values + struct CountingStroke { + appends: std::sync::Arc, + reads: std::sync::Arc, + } + + struct CountingBrush(std::sync::Arc, std::sync::Arc); + + impl crate::brush_device::BrushDevice for CountingBrush { + fn start(&self, _: crate::brush_device::BrushSurface) -> Result, crate::gpu_failure::GpuFailure> { + Ok(Box::new(CountingStroke { appends: self.0.clone(), reads: self.1.clone() })) + } + } + + impl crate::brush_device::DeviceStroke for CountingStroke { + fn append_world(&mut self, _: &[texturecraft_paint::Stamp], _: bool) -> Result { + self.appends.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + Ok([(0, 0)].into()) + } + + fn append_uv(&mut self, _: &[texturecraft_paint::UvStamp]) -> Result { + self.appends.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + Ok([(0, 0)].into()) + } + + fn read_alpha(&self, _: &crate::brush_device::BrushTiles) -> Result { + Err("a pickup reads its alpha with its values".into()) + } + + fn read_projection(&self, _: &crate::brush_device::BrushTiles) -> Result { + Err("nothing projected".into()) + } + + fn read_carried( + &self, + _: &crate::brush_device::BrushTiles, + ) -> Result<(texturecraft_texel::TileImage, std::collections::BTreeMap), String> { + self.reads.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let mut alpha = texturecraft_texel::TileImage::new(256, 256, 1); + alpha.set(1, 1, &[u16::MAX]); + Ok((alpha, Default::default())) + } + + fn as_any(&self) -> &dyn std::any::Any { + self + } + } + + /// A GPU smudge or clone reads its carried values back once, when it commits, not after + /// every batch of dabs (the live compositor reads them on the device) + #[test] + fn a_device_pickup_reads_its_values_back_only_at_the_commit() { + for tool in ["tool.smudge", "tool.clone"] { + let mut s = Session::new_project("t", texturecraft_geom::primitives::plane(1.0, 1), "builtin:plane", None, 256).unwrap(); + execute(&mut s, "layer.add.paint", &Value::Null).unwrap(); + // A Pass through layer's smudge smears the stack, which the device carries + execute(&mut s, "layer.blend", &json!({"channel": "all", "mode": "passthrough"})).unwrap(); + execute(&mut s, tool, &json!({})).unwrap(); + s.tool.clone_source = Some(crate::session::CloneSource { uv: [0.3, 0.5], offset: None }); + s.update(); + let (appends, reads) = (std::sync::Arc::default(), std::sync::Arc::::default()); + let device = std::sync::Arc::new(CountingBrush(std::sync::Arc::clone(&appends), std::sync::Arc::clone(&reads))); + s.brush_device = Some(crate::brush_device::BrushBackend { device, surface: std::sync::Arc::downgrade(&s.caches[0].gbuf) }); + s.begin_stroke_uv(Vec2::new(0.5, 0.5), 1.0).unwrap(); + for step in 1..8 { + s.continue_stroke_uv(Vec2::new(0.5 + step as f32 * 0.03, 0.5), 1.0); + } + let load = |count: &std::sync::atomic::AtomicUsize| count.load(std::sync::atomic::Ordering::Relaxed); + assert!(load(&appends) > 1, "{tool}: the stroke paints several batches on the device"); + assert_eq!(load(&reads), 0, "{tool}: no readback while the stroke paints"); + s.end_stroke().unwrap(); + assert_eq!(load(&reads), 1, "{tool}: one readback at the commit"); + } + } + + /// A GPU stroke with a library alpha leaves the tip to the device; a CPU stroke renders it + #[test] + fn only_a_cpu_stroke_renders_the_library_alpha_image() { + let mut s = Session::new_project("t", texturecraft_geom::primitives::plane(1.0, 1), "builtin:plane", None, 256).unwrap(); + execute(&mut s, "layer.add.paint", &Value::Null).unwrap(); + s.tool.brush.alpha_library = texturecraft_paint::alphas::library().first().map(|alpha| alpha.id.clone()); + s.update(); + + for device in [true, false] { + s.brush_device = device + .then(|| crate::brush_device::BrushBackend { device: std::sync::Arc::new(IdleBrush), surface: std::sync::Arc::downgrade(&s.caches[0].gbuf) }); + s.begin_stroke_uv(Vec2::splat(0.5), 1.0).unwrap(); + let stroke = s.stroke.as_ref().unwrap(); + assert_eq!(stroke.device.is_some(), device); + assert_eq!(stroke.library_alpha.is_some(), !device, "device stroke: {device}"); + + // A stroke the viewport moves to the CPU mid-way gets the image for its remaining dabs + s.materialize_device_stroke(Some("a test")); + assert!(s.stroke.as_ref().unwrap().library_alpha.is_some(), "device stroke: {device}"); + s.cancel_stroke(); + } + } + /// A mask stroke the stencil rejects rolls its new paint effect back; the paint margin cached /// for that effect must go too, since the ID is handed out again on another layer #[test] diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index 15165bf43..ef77c8431 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -1330,7 +1330,7 @@ impl Session { let path = SurfacePath::new(context, &points, &corners, closed, &hidden_materials); let samples = path.first().into_iter().chain(path.segments(STEP_PX).flat_map(|(_, samples)| samples)); - return Ok(json!({ "stamps": self.stroke_surface_points(samples, viewport, path.all_visible())? })); + return Ok(json!({ "stamps": self.stroke_surface_points(samples, viewport)? })); } let (points, corners): (Vec, Vec) = diff --git a/crates/engine/src/polygon_fill.rs b/crates/engine/src/polygon_fill.rs index 4729d4b39..705728237 100644 --- a/crates/engine/src/polygon_fill.rs +++ b/crates/engine/src/polygon_fill.rs @@ -119,7 +119,7 @@ impl Session { if drag.ts == ts && drag.target == target && drag.viewport == viewport && drag.quick_mask_before.is_some() == quick_mask { // A camera move (a wheel zoom mid-drag) keeps the drag, which then sees the mesh from the new camera if drag.camera != self.camera { - let (points, depth) = self.box_space(viewport); + let (points, depth) = self.box_space(viewport)?; if let Some(drag) = self.polygon_fill_drag.as_mut() { (drag.points, drag.depth, drag.camera, drag.last_box) = (points, depth, self.camera, None); } @@ -132,7 +132,7 @@ impl Session { } let material = self.fill_material()?; - let (points, depth) = self.box_space(viewport); + let (points, depth) = self.box_space(viewport)?; let polygons = match self.tool.fill_mode { FillMode::Triangle | FillMode::Polygon => None, FillMode::UvIsland | FillMode::Mesh => Some(TrianglePartition::new(&self.mesh, material, polygon_edges)), @@ -156,13 +156,20 @@ impl Session { } /// Each vertex where a box sees it (viewport pixels for a 3D view of size `viewport`, else texture coordinates) and, for visible polygons only in 3D, what the camera sees - fn box_space(&self, viewport: Option) -> (Vec>, Option) { - let Some(size) = viewport else { return (self.mesh.uvs.iter().copied().map(Some).collect(), None) }; + fn box_space(&self, viewport: Option) -> Result<(Vec>, Option)> { + let Some(size) = viewport else { return Ok((self.mesh.uvs.iter().copied().map(Some).collect(), None)) }; let view_proj = self.camera.view_proj(size.x / size.y); let points = self.mesh.positions.iter().map(|position| screen_point(view_proj, *position, size)).collect(); - let depth = self.tool.fill_visible_only.then(|| EyeDepth::render_with_triangles(&self.shown_mesh(), &self.camera, size.x as u32, size.y as u32)); - (points, depth) + let depth = self + .tool + .fill_visible_only + .then(|| { + crate::depth_device::eye_depth(self.depth_device.as_deref(), &self.shown_mesh(), &self.camera, (size.x as u32, size.y as u32), true, &|_| true) + }) + .transpose() + .map_err(EngineError::Other)?; + Ok((points, depth)) } /// The mesh material of the texture set being painted diff --git a/crates/engine/src/preview.rs b/crates/engine/src/preview.rs index c44dce36c..6fee9978b 100644 --- a/crates/engine/src/preview.rs +++ b/crates/engine/src/preview.rs @@ -1,5 +1,7 @@ //! Cheap shelf previews on a unit sphere: plain materials and library filters (smart ones use [`crate::orb_preview`]) +use std::sync::Arc; + use rayon::prelude::*; use texturecraft_compose::pattern::{Coords, procedural}; use texturecraft_core::{ @@ -8,6 +10,7 @@ use texturecraft_core::{ }; use texturecraft_geom::glam::{Vec2, Vec3}; +use crate::composite_device::{CompositeDevice, CompositeJob}; use crate::materials::{Builder, build}; /// Linear material values of one preview pixel. @@ -107,10 +110,13 @@ fn magnified(f: Filter, k: f32) -> Filter { /// Preview of library filter `id` (see [`crate::filter_lib`]): a sample material (colorful /// clouds, checker roughness, cell bumps) with the filter on its content, composited by the -/// compositor on a plane and laid over the sphere (None for an unknown id). -pub fn filter(id: &str, size: usize) -> Option>> { - let res = u32::try_from(size).ok()?.max(1); - let kind = match crate::filter_lib::build(id, &serde_json::Value::Null).ok()? { +/// compositor on a plane and laid over the sphere (None for an unknown id). `device` composites +/// on the GPU unless it refuses the material; its error is returned, not redone on the CPU. +pub fn filter(id: &str, size: usize, device: Option<&dyn CompositeDevice>) -> Result>>, String> { + let Ok(res) = u32::try_from(size) else { return Ok(None) }; + let res = res.max(1); + let Ok(kind) = crate::filter_lib::build(id, &serde_json::Value::Null) else { return Ok(None) }; + let kind = match kind { // Transform changes nothing as the library adds it: its picture shows it scaled and turned EffectKind::Filter(Filter::Transform(transform)) => { EffectKind::Filter(Filter::Transform(TileTransform { scaling: [2.0, 2.0], rotation: 30.0, ..transform })) @@ -121,12 +127,18 @@ pub fn filter(id: &str, size: usize) -> Option>> { // The filters that shape a mask's edge read where values cross 0.5: they get black and white shapes, where the clouds would leave them black let shapes = matches!(kind, EffectKind::Filter(Filter::BevelSmooth(_) | Filter::DirectionalDistance(_))); - render_filter_preview(kind, size, res, shapes) + render_filter_preview(kind, size, res, shapes, device) } -fn render_filter_preview(kind: EffectKind, size: usize, res: u32, shapes: bool) -> Option>> { - let mesh = texturecraft_geom::primitives::plane(2.0, 2); - let gbuf = texturecraft_geom::UvGBuffer::new(&mesh, 0, res, res); +fn render_filter_preview( + kind: EffectKind, + size: usize, + res: u32, + shapes: bool, + device: Option<&dyn CompositeDevice>, +) -> Result>>, String> { + let mesh = Arc::new(texturecraft_geom::primitives::plane(2.0, 2)); + let gbuf = Arc::new(texturecraft_geom::UvGBuffer::new(&mesh, 0, res, res)); let mut p = Project::new("preview", ""); p.texture_sets.push(TextureSet::new("preview", 0, res)); let procedural = @@ -142,33 +154,49 @@ fn render_filter_preview(kind: EffectKind, size: usize, res: u32, shapes: bool) fill.sources.insert(Channel::Height, procedural(ProceduralKind::Cells, 3.0, [-0.12; 3], [0.12; 3])); let mut layer = Layer::new(p.alloc_id(), "sample", LayerKind::Fill(fill), &CHANNELS); layer.content_effects.push(Effect::new(p.alloc_id(), kind)); - p.insert_layer(0, layer, None, false).ok()?; + if p.insert_layer(0, layer, None, false).is_err() { + return Ok(None); + } let (pixels, baked, images) = (Default::default(), Default::default(), Default::default()); + let texels: Vec<(u32, u32)> = (0..res).flat_map(|y| (0..res).map(move |x| (x, y))).collect(); + let job = + CompositeJob { project: &p, ts: 0, pixels: &pixels, mesh: &mesh, gbuf: &gbuf, baked: &baked, images: &images, shift: 0, padding: None, cancel: None }; + let samples = match crate::composite_device::samples(device, &job, &texels)? { + Some(samples) => samples, + None => cpu_samples(&p, &mesh, &gbuf, (&pixels, &baked, &images), res), + }; + Ok(Some(sphere_normals(size).enumerate().map(|(i, n)| n.and_then(|_| samples.get((i / size) * res as usize + i % size).copied())).collect())) +} + +/// The preview material's values at every texel, composited on the CPU +fn cpu_samples( + p: &Project, + mesh: &texturecraft_geom::Mesh, + gbuf: &texturecraft_geom::UvGBuffer, + (pixels, baked, images): (&texturecraft_compose::PixelStore, &texturecraft_compose::BakedMaps, &texturecraft_compose::ImageStore), + res: u32, +) -> Vec { let inp = texturecraft_compose::Inputs { - project: &p, + project: p, ts: 0, - mesh: &mesh, - gbuf: &gbuf, - pixels: &pixels, - baked: &baked, + mesh, + gbuf, + pixels, + baked, block_scales: p.texture_set(0).map(|set| set.block_scales()).unwrap_or_default(), preview: None, - images: &images, + images, bounds: mesh.bounds(), }; let mut out = texturecraft_compose::Composite::new(&CHANNELS, res); texturecraft_compose::composite_tiles(&inp, &mut out, &texturecraft_compose::all_tiles(res, res)); - Some( - sphere_normals(size) - .enumerate() - .map(|(i, n)| { - n?; - let (x, y) = ((i % size) as u32, (i / size) as u32); - let [base, metal, rough, height] = CHANNELS.map(|c| out.value(c, x, y)); - Some(Sample { base, metallic: metal[0], roughness: rough[0], height: height[0] }) - }) - .collect(), - ) + (0..res) + .flat_map(|y| (0..res).map(move |x| (x, y))) + .map(|(x, y)| { + let [base, metal, rough, height] = CHANNELS.map(|c| out.value(c, x, y)); + Sample { base, metallic: metal[0], roughness: rough[0], height: height[0] } + }) + .collect() } #[cfg(test)] @@ -199,16 +227,16 @@ mod tests { assert!(finite(¢er), "{id}"); assert!(pixels[0].is_none(), "corners are outside the sphere"); } - assert!(material("nope", size).is_none() && filter("nope", size).is_none()); + assert!(material("nope", size).is_none() && filter("nope", size, None).unwrap().is_none()); let size = 24; for library_filter in crate::filter_lib::FILTERS { let id = library_filter.id; - let pixels = filter(id, size).unwrap_or_else(|| panic!("{id}")); + let pixels = filter(id, size, None).unwrap().unwrap_or_else(|| panic!("{id}")); let center = pixels[size / 2 * size + size / 2].unwrap_or_else(|| panic!("{id}")); assert!(finite(¢er), "{id}"); } - let (plain, warped) = (filter("levels", size).unwrap(), filter("warp", size).unwrap()); + let (plain, warped) = (filter("levels", size, None).unwrap().unwrap(), filter("warp", size, None).unwrap().unwrap()); assert!(plain != warped, "the warp shows in its preview"); } @@ -218,9 +246,9 @@ mod tests { let size = SIDE_PX as usize; // Use the same checker input with an inactive filter - let checker = render_filter_preview(EffectKind::Filter(Filter::InvertOff), size, SIDE_PX, true).unwrap(); + let checker = render_filter_preview(EffectKind::Filter(Filter::InvertOff), size, SIDE_PX, true, None).unwrap().unwrap(); for id in ["bevelSmooth", "directionalDistance"] { - let pixels = filter(id, size).unwrap(); + let pixels = filter(id, size, None).unwrap().unwrap(); assert!(pixels != checker, "{id}: the preview shows the unchanged checker"); let lit: Vec = pixels.into_iter().flatten().map(|sample| sample.base.iter().sum::() / 3.0).collect(); let bright = lit.iter().filter(|value| **value > 0.25).count(); diff --git a/crates/engine/src/quick_mask.rs b/crates/engine/src/quick_mask.rs index 8d1689671..a53abbe21 100644 --- a/crates/engine/src/quick_mask.rs +++ b/crates/engine/src/quick_mask.rs @@ -119,24 +119,24 @@ impl Session { Some(QuickMaskStroke { alpha: &stroke.canvas.alpha, device: stroke.device.as_deref(), opacity: stroke.stroke.settings.opacity, erase: stroke.erase }) } - /// RGBA8 overlay of texture set `ts` while editing the quick mask (`size²` stretched over - /// the set, display-encoded): the base color, tinted red where painting is blocked. - /// Includes the stroke in progress. - pub fn quick_mask_rgba(&self, ts: usize, size: u32) -> Option> { + /// RGBA8 overlay of texture set `ts` while editing the quick mask (at `extent`, width and + /// height, stretched over the set, display-encoded): the base color, tinted red where + /// painting is blocked. Includes the stroke in progress. + pub fn quick_mask_rgba(&self, ts: usize, extent: (u32, u32)) -> Option> { let cache = self.caches.get(ts)?; let (width, height) = cache.size; - let size = size.clamp(1, width.max(height)); + let (columns, rows) = (extent.0.clamp(1, width.max(1)), extent.1.clamp(1, height.max(1))); let mask = self.quick_mask_image(ts, cache.size); let live = self.stroke.as_ref().filter(|s| s.ts == ts && s.target.is_none()).map(|s| (&s.canvas.alpha, s.stroke.settings.opacity, s.erase)); let base = cache.composite.channels.get(&Channel::BaseColor); let srgb = srgb_lut(); let inverted = self.quick_mask.inverted; - let mut out = vec![255u8; size as usize * size as usize * 4]; + let mut out = vec![255u8; columns as usize * rows as usize * 4]; - out.par_chunks_mut(size as usize * 4).enumerate().for_each(|(y, row)| { - let ty = (y as u64 * u64::from(height) / u64::from(size)) as u32; + out.par_chunks_mut(columns as usize * 4).enumerate().for_each(|(y, row)| { + let ty = (y as u64 * u64::from(height) / u64::from(rows)) as u32; for (x, pixel) in row.as_chunks_mut::<4>().0.iter_mut().enumerate() { - let tx = (x as u64 * u64::from(width) / u64::from(size)) as u32; + let tx = (x as u64 * u64::from(width) / u64::from(columns)) as u32; let mut coverage = from_u16(mask.get(tx, ty)[0]); if let Some((alpha, opacity, erase)) = live { let stroke_coverage = from_u16(alpha.get(tx, ty)[0]) * opacity; diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 1bbab3f1c..2bd9b9ef4 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -516,7 +516,9 @@ pub(crate) struct ActiveStroke { /// The commit's destination tiles, copied as the stroke reaches them. pub staging: texturecraft_paint::Staging, pub device: Option>, - pub device_uv_stamps: Vec, + /// The GPU brush's error: the stroke paints nothing more and its commit fails with it + /// (the CPU does not redo GPU work). + pub device_error: Option, pub(crate) replay: Option, } @@ -564,6 +566,10 @@ pub fn stroke_template(tool: Tool, on_mask: bool) -> &'static str { pub struct Session { pub brush_device: Option, + /// Rasterizes the paint camera's depth on the GPU (None: in software) + pub depth_device: Option>, + /// Composites the orb previews on the GPU (None: on the CPU) + pub composite_device: Option>, pub doc: Document, pub mesh: Arc, /// Unique per loaded mesh and UV layout (GPU caches compare it). @@ -690,6 +696,8 @@ impl Session { Ok(Session { brush_device: None, + depth_device: None, + composite_device: None, doc, mesh_id: next_mesh_id(), project_id: next_mesh_id(), @@ -1618,28 +1626,29 @@ impl Session { Some(gray.iter().flat_map(|g| [*g, *g, *g, 255]).collect()) } - /// The image resource of the "Other..." view as `size` x `size` RGBA8 pixels over the UV square (stretched, bilinear, - /// values as stored; HDR values clamp to 1). Returns None for a missing image, excessive - /// resolution or allocation failure. - pub fn image_view_rgba(&self, size: u32) -> Option> { - if size > texturecraft_core::MAX_RESOLUTION { + /// The image resource of the "Other..." view as RGBA8 pixels at `extent` (width, height) over + /// the UV square (stretched, bilinear, values as stored; HDR values clamp to 1). Returns None + /// for a missing image, excessive resolution or allocation failure. Where layers composite on + /// the GPU, the renderer draws this view itself (`AuxSource::Image`). + pub fn image_view_rgba(&self, extent: (u32, u32)) -> Option> { + if extent.0.max(extent.1) > texturecraft_core::MAX_RESOLUTION { return None; } let image = self.images.get(self.view_image.as_deref()?)?; let (width, height) = (image.width.max(1) as usize, image.height.max(1) as usize); width.checked_mul(height)?; - let size = size.max(1) as usize; + let (columns, rows) = (extent.0.max(1) as usize, extent.1.max(1) as usize); let fallback = [0.0, 0.0, 0.0, 1.0]; let texel = |x: usize, y: usize| image.rgba.get(y.min(height - 1) * width + x.min(width - 1)).copied().unwrap_or(fallback); let mut out = Vec::new(); - out.try_reserve_exact(size * size * 4).ok()?; + out.try_reserve_exact(columns * rows * 4).ok()?; - for y in 0..size { - let v = ((y as f32 + 0.5) / size as f32 * height as f32 - 0.5).max(0.0); + for y in 0..rows { + let v = ((y as f32 + 0.5) / rows as f32 * height as f32 - 0.5).max(0.0); let (y0, fy) = (v.floor() as usize, v.fract()); - for x in 0..size { - let u = ((x as f32 + 0.5) / size as f32 * width as f32 - 0.5).max(0.0); + for x in 0..columns { + let u = ((x as f32 + 0.5) / columns as f32 * width as f32 - 0.5).max(0.0); let (x0, fx) = (u.floor() as usize, u.fract()); let (a, b, c, d) = (texel(x0, y0), texel(x0 + 1, y0), texel(x0, y0 + 1), texel(x0 + 1, y0 + 1)); for k in 0..3 { diff --git a/crates/engine/src/set_cmds.rs b/crates/engine/src/set_cmds.rs index 91a7527c5..9f2c7cd84 100644 --- a/crates/engine/src/set_cmds.rs +++ b/crates/engine/src/set_cmds.rs @@ -157,6 +157,9 @@ pub struct ResizeTask { project_id: u64, /// The revision and mesh used to calculate this result. from: (u64, u64), + /// The session's brush and depth devices: recorded strokes repaint on the GPU when present + brush: Option>, + depth: Option>, } /// What [`ResizeTask::run`] computed. @@ -170,9 +173,18 @@ pub struct ResizeOutput { log: crate::log::SessionLog, project_id: u64, from: (u64, u64), + /// The task's brush device, kept for a rerun when edits arrived while it ran + brush: Option>, } impl ResizeTask { + /// Repaint recorded strokes on `brush` (the app's GPU brush, also outside paint views); None + /// repaints them on the CPU + pub fn with_brush_device(mut self, brush: Option>) -> Self { + self.brush = brush; + self + } + /// Repaint recorded strokes at the new size, resample the other images, and build the set's /// caches. Progress goes from 0 to 1. pub fn run(self, progress: &texturecraft_bake::Progress) -> Result { @@ -187,7 +199,7 @@ impl ResizeTask { mut accelerate: impl FnMut(&texturecraft_texel::TileImage, (u32, u32), &[u16]) -> Option>, ) -> Result { let start = Instant::now(); - let ResizeTask { ts, resolution, height, mut doc, mesh, bvh, project_id, from } = self; + let ResizeTask { ts, resolution, height, mut doc, mesh, bvh, project_id, from, brush, depth } = self; let set = doc.project.texture_set_mut(ts)?; let old = set.clone(); set.set_size(resolution, height); @@ -197,7 +209,8 @@ impl ResizeTask { crate::session::check_size(set)?; let size = set.size(); - let scene = ReplayScene { mesh: &mesh, bvh: &bvh, material: set.material }; + let scene = ReplayScene { mesh: &mesh, bvh: &bvh, material: set.material, brush: brush.as_deref(), depth: depth.as_deref() }; + let kept_brush = brush.clone(); let mut log = crate::log::SessionLog::new(); let mut gpu_ms = 0; let mut gpu_images = 0; @@ -284,7 +297,7 @@ impl ResizeTask { gpu_ms, if cache.is_some() { format!("{} ms", cache_built.duration_since(resampled).as_millis()) } else { "rebuilt on apply".into() } )); - Ok(ResizeOutput { ts, resolution, height, doc, cache, log, project_id, from }) + Ok(ResizeOutput { ts, resolution, height, doc, cache, log, project_id, from, brush: kept_brush }) } } @@ -319,6 +332,8 @@ impl Session { bvh: self.bvh.clone(), project_id: self.project_id, from: (self.revision, self.mesh_id), + brush: self.brush_device.as_ref().map(|backend| backend.device.clone()), + depth: self.depth_device.clone(), }) } @@ -333,8 +348,9 @@ impl Session { let (ts, width, height) = (out.ts, out.resolution, out.height); // Release the stale pixels and cache before building their replacement + let brush = out.brush.take(); drop(out); - out = self.resize_task_to(ts, width, height)?.run(&texturecraft_bake::Progress::new())?; + out = self.resize_task_to(ts, width, height)?.with_brush_device(brush).run(&texturecraft_bake::Progress::new())?; } let ResizeOutput { ts, resolution, height, doc, cache, log, .. } = out; diff --git a/crates/engine/src/stroke_replay.rs b/crates/engine/src/stroke_replay.rs index 4b357d9f0..52634b76a 100644 --- a/crates/engine/src/stroke_replay.rs +++ b/crates/engine/src/stroke_replay.rs @@ -110,6 +110,83 @@ mod tests { use crate::{Session, execute}; + /// Full coverage on the tile under each texture-space dab, or a GPU error for every append + struct TileBrush { + fail: bool, + } + + struct TileStroke { + size: (u32, u32), + fail: bool, + } + + impl crate::brush_device::BrushDevice for TileBrush { + fn start(&self, surface: crate::brush_device::BrushSurface) -> Result, crate::gpu_failure::GpuFailure> { + Ok(Box::new(TileStroke { size: (surface.uv.width, surface.uv.height), fail: self.fail })) + } + } + + impl crate::brush_device::DeviceStroke for TileStroke { + fn append_world(&mut self, _: &[texturecraft_paint::Stamp], _: bool) -> Result { + Err("texture-space strokes only".into()) + } + + fn append_uv(&mut self, stamps: &[texturecraft_paint::UvStamp]) -> Result { + use texturecraft_texel::TILE; + if self.fail { + return Err("The GPU reported an error in a test".into()); + } + + Ok(stamps.iter().map(|stamp| ((stamp.center.x * self.size.0 as f32) as u32 / TILE, (stamp.center.y * self.size.1 as f32) as u32 / TILE)).collect()) + } + + fn read_alpha(&self, tiles: &crate::brush_device::BrushTiles) -> Result { + let mut alpha = texturecraft_texel::TileImage::new(self.size.0, self.size.1, 1); + for &(x, y) in tiles { + alpha.set_tile(x, y, Some(std::sync::Arc::new(vec![u16::MAX; texturecraft_texel::TILE_AREA]))); + } + Ok(alpha) + } + + fn read_projection(&self, _: &crate::brush_device::BrushTiles) -> Result { + Err("no projection".into()) + } + + fn as_any(&self) -> &dyn std::any::Any { + self + } + } + + /// A resize repaints recorded strokes through the brush device; its error fails the resize + /// (no CPU repaint), and without a device the CPU repaints them + #[test] + fn recorded_strokes_repaint_through_the_brush_device() { + for device in [None, Some(false), Some(true)] { + let mut session = Session::new_project("Device replay", primitives::plane(1.0, 1), "builtin:plane", None, 128).unwrap(); + execute(&mut session, "layer.add.paint", &json!({})).unwrap(); + execute(&mut session, "tool.material", &json!({"channel": "baseColor", "solo": true, "color": [1.0, 0.0, 0.0]})).unwrap(); + session.begin_stroke_uv(Vec2::new(0.25, 0.5), 1.0).unwrap(); + session.continue_stroke_uv(Vec2::new(0.3, 0.5), 1.0); + session.end_stroke().unwrap(); + let layer = session.selected_layer().unwrap(); + session.brush_device = + device.map(|fail| crate::brush_device::BrushBackend { device: std::sync::Arc::new(TileBrush { fail }), surface: std::sync::Weak::new() }); + + let resized = session.resize_task(0, 256).unwrap().run(&texturecraft_bake::Progress::new()); + + if device == Some(true) { + let error = resized.err().map(|error| error.to_string()).unwrap_or_default(); + assert!(error.contains("The GPU reported an error in a test"), "{error}"); + continue; + } + session.apply_resize(resized.unwrap()).unwrap(); + + // The tile corner lies beyond the brush: only the device's full tile paints it + let corner = session.doc.pixels.layer(layer, Channel::BaseColor).unwrap().get(126, 190); + assert_eq!(corner.iter().any(|&value| value != 0), device.is_some(), "device {device:?}: {corner:?}"); + } + } + #[test] fn a_mask_stroke_painting_a_mask_image_is_not_recorded() { let mut session = Session::new_project("Mask image replay", primitives::plane(1.0, 1), "builtin:plane", None, 128).unwrap(); diff --git a/crates/engine/src/stroke_replay/recorded_paint.rs b/crates/engine/src/stroke_replay/recorded_paint.rs index 7c6b26b7a..cf4f8f78b 100644 --- a/crates/engine/src/stroke_replay/recorded_paint.rs +++ b/crates/engine/src/stroke_replay/recorded_paint.rs @@ -9,7 +9,12 @@ use texturecraft_bake::Progress; use texturecraft_compose::{MaskGray, PaintTarget, PixelStore}; use texturecraft_core::Channel; use texturecraft_geom::{UvGBuffer, glam::Vec2}; -use texturecraft_paint::{BrushSettings, CommitSource, RasterCtx, Shape, Staging, StrokeCanvas, commit_layer, commit_mask, rasterize, rasterize_uv}; +use texturecraft_paint::{ + BrushSettings, CommitSource, RasterCtx, Shape, Staging, Stamp, StrokeCanvas, UvStamp, commit_layer, commit_mask, rasterize, rasterize_uv, +}; + +use crate::brush_device::{BrushSurface, BrushTiles}; +use crate::gpu_failure::GpuFailure; #[derive(Debug, Serialize, Deserialize)] pub(crate) struct RecordedPaint { @@ -35,71 +40,46 @@ impl RecordedPaint { &self, target: PaintTarget, pixels: &mut PixelStore, - gbuf: &UvGBuffer, + gbuf: &Arc, scene: &ReplayScene<'_>, visibility: &mut Option, progress: &Progress, ) -> Result<()> { let size = (gbuf.width, gbuf.height); let mut canvas = StrokeCanvas::new(size.0, size.1).with_stamp_blending(self.settings.stamp_blending); - let library = self.settings.library_alpha_image(); - let shape = Shape::new(self.settings.alpha, None, library.as_deref(), self.settings.alpha_params); - match &self.placement { - PaintPlacement::Uv { dabs: Some(dabs), .. } => { - for dab in dabs { - if progress.cancel.load(Relaxed) { - break; - } - - rasterize_uv(&mut canvas, gbuf, shape, &[dab.stamp()]); - } - } + let cancelled = || progress.cancel.load(Relaxed); + let dabs = match &self.placement { + PaintPlacement::Uv { dabs: Some(dabs), .. } => ReplayDabs::Uv(dabs.iter().map(|dab| dab.stamp()).collect()), PaintPlacement::Uv { samples, .. } => { let mut stroke = UvStrokeState::default(); + let mut dabs = Vec::new(); for &[u, v, pressure] in samples { - if progress.cancel.load(Relaxed) { + if cancelled() { break; } - stroke.sample(&self.settings, Vec2::new(u, v), pressure, |dabs| { - for dab in dabs { - if progress.cancel.load(Relaxed) { - break; - } - - rasterize_uv(&mut canvas, gbuf, shape, std::slice::from_ref(dab)); - } - }); + stroke.sample(&self.settings, Vec2::new(u, v), pressure, |batch| dabs.extend_from_slice(batch)); } + ReplayDabs::Uv(dabs) } PaintPlacement::World { world } => { if visibility.as_ref().is_none_or(|cached| cached.view != world.view) { // Release the old depth buffer before rendering the new view let previous = visibility.take().map(|cached| (cached.view, cached.bvh)); - let (bvh, depth) = world.view.visibility(scene.mesh, scene.bvh, previous.as_ref().map(|(view, bvh)| (view.as_ref(), bvh))); - *visibility = Some(ReplayVisibility { view: world.view.clone(), bvh, depth }); + let (bvh, depth) = world + .view + .visibility(scene.mesh, scene.bvh, previous.as_ref().map(|(view, bvh)| (view.as_ref(), bvh)), scene.depth) + .map_err(EngineError::Other)?; + *visibility = Some(ReplayVisibility { view: world.view.clone(), bvh, depth: Arc::new(depth) }); } - let cached = visibility.as_ref().ok_or_else(|| EngineError::Other("World paint visibility could not be recreated".into()))?; - let context = RasterCtx { - mesh: scene.mesh, - bvh: &cached.bvh, - gbuf, - material: scene.material, - depth: Some(&cached.depth), - eye: world.view.camera.eye(), - backface_culling: self.settings.backface_culling, - angle_fade: self.settings.angle_fade, - shape, - }; - for dab in &world.dabs { - if progress.cancel.load(Relaxed) { - break; - } - - rasterize(&mut canvas, &context, std::slice::from_ref(dab)); - } + ReplayDabs::World(&world.dabs) } + }; + + let cached = visibility.as_ref().filter(|_| matches!(dabs, ReplayDabs::World(_))); + if !self.replay_on_device(&mut canvas, &dabs, gbuf, scene, cached, &cancelled)? { + self.replay_on_cpu(&mut canvas, &dabs, gbuf, scene, cached, &cancelled)?; } if progress.cancel.load(Relaxed) { return Err(EngineError::Other("Texture set resize was cancelled".into())); @@ -124,4 +104,124 @@ impl RecordedPaint { } Ok(()) } + + /// Repaint the dabs through the brush device. False when there is none or it refuses the + /// stroke (the CPU repaints it); a GPU error fails the replay: the CPU does not repaint it. + fn replay_on_device( + &self, + canvas: &mut StrokeCanvas, + dabs: &ReplayDabs<'_>, + gbuf: &Arc, + scene: &ReplayScene<'_>, + visibility: Option<&ReplayVisibility>, + cancelled: &dyn Fn() -> bool, + ) -> Result { + // Dabs per GPU submission, so a cancel stops between them + const DABS_PER_BATCH: usize = 4096; + + let Some(brush) = scene.brush else { return Ok(false) }; + let surface = BrushSurface { + mesh: scene.mesh.clone(), + bvh: visibility.map_or_else(|| scene.bvh.clone(), |cached| cached.bvh.clone()), + uv: gbuf.clone(), + material: scene.material, + depth: visibility.map(|cached| cached.depth.clone()), + settings: (*self.settings).clone(), + alpha_image: None, + stencil: None, + limit: None, + clone: None, + smudge: None, + }; + let failed = |error: String| EngineError::Other(format!("The recorded strokes could not be repainted on the GPU: {error}")); + let mut stroke = match brush.start(surface) { + Ok(stroke) => stroke, + Err(GpuFailure::Refused(_)) => return Ok(false), + Err(GpuFailure::Device(error)) => return Err(failed(error)), + }; + + let mut tiles = BrushTiles::new(); + match dabs { + ReplayDabs::Uv(dabs) => { + for batch in dabs.chunks(DABS_PER_BATCH) { + if cancelled() { + break; + } + + tiles.extend(stroke.append_uv(batch).map_err(failed)?); + } + } + ReplayDabs::World(dabs) => { + for batch in dabs.chunks(DABS_PER_BATCH) { + if cancelled() { + break; + } + + tiles.extend(stroke.append_world(batch, true).map_err(failed)?); + } + } + } + if cancelled() { + return Ok(true); + } + + let alpha = stroke.read_alpha(&tiles).map_err(failed)?; + canvas.dirty = alpha.allocated().collect(); + canvas.alpha = alpha; + Ok(true) + } + + /// Repaint the dabs on the CPU, one at a time (GPU off or absent, or a refused stroke) + fn replay_on_cpu( + &self, + canvas: &mut StrokeCanvas, + dabs: &ReplayDabs<'_>, + gbuf: &UvGBuffer, + scene: &ReplayScene<'_>, + visibility: Option<&ReplayVisibility>, + cancelled: &dyn Fn() -> bool, + ) -> Result<()> { + let library = self.settings.library_alpha_image(); + let shape = Shape::new(self.settings.alpha, None, library.as_deref(), self.settings.alpha_params); + match dabs { + ReplayDabs::Uv(dabs) => { + for dab in dabs { + if cancelled() { + break; + } + + rasterize_uv(canvas, gbuf, shape, std::slice::from_ref(dab)); + } + } + ReplayDabs::World(dabs) => { + let cached = visibility.ok_or_else(|| EngineError::Other("World paint visibility could not be recreated".into()))?; + let PaintPlacement::World { world } = &self.placement else { return Ok(()) }; + let context = RasterCtx { + mesh: scene.mesh, + bvh: &cached.bvh, + gbuf, + material: scene.material, + depth: Some(&cached.depth), + eye: world.view.camera.eye(), + backface_culling: self.settings.backface_culling, + angle_fade: self.settings.angle_fade, + shape, + }; + for dab in *dabs { + if cancelled() { + break; + } + + rasterize(canvas, &context, std::slice::from_ref(dab)); + } + } + } + Ok(()) + } +} + +/// The dabs a recorded stroke repaints: texture-space dabs, or world dabs seen from its view +enum ReplayDabs<'a> { + Uv(Vec), + World(&'a [Stamp]), } diff --git a/crates/engine/src/stroke_replay/replay_scene.rs b/crates/engine/src/stroke_replay/replay_scene.rs index a0784d1f3..24e823b31 100644 --- a/crates/engine/src/stroke_replay/replay_scene.rs +++ b/crates/engine/src/stroke_replay/replay_scene.rs @@ -6,4 +6,8 @@ pub(crate) struct ReplayScene<'a> { pub(crate) mesh: &'a Arc, pub(crate) bvh: &'a Arc, pub(crate) material: usize, + /// Repaints the strokes on the GPU; None (GPU off or absent) repaints them on the CPU + pub(crate) brush: Option<&'a dyn crate::brush_device::BrushDevice>, + /// Renders the replay's camera depth; None renders it in software + pub(crate) depth: Option<&'a dyn crate::depth_device::DepthDevice>, } diff --git a/crates/engine/src/stroke_replay/replay_visibility.rs b/crates/engine/src/stroke_replay/replay_visibility.rs index 948081641..58126a978 100644 --- a/crates/engine/src/stroke_replay/replay_visibility.rs +++ b/crates/engine/src/stroke_replay/replay_visibility.rs @@ -8,5 +8,5 @@ use crate::stroke_view::StrokeView; pub(super) struct ReplayVisibility { pub(super) view: Arc, pub(super) bvh: Arc, - pub(super) depth: EyeDepth, + pub(super) depth: Arc, } diff --git a/crates/engine/src/stroke_replay/resize_replays.rs b/crates/engine/src/stroke_replay/resize_replays.rs index ae279785c..2f940e602 100644 --- a/crates/engine/src/stroke_replay/resize_replays.rs +++ b/crates/engine/src/stroke_replay/resize_replays.rs @@ -42,7 +42,7 @@ impl ResizeReplays { self, pixels: &mut PixelStore, replays: &mut StrokeReplays, - gbuf: &UvGBuffer, + gbuf: &Arc, scene: &ReplayScene<'_>, progress: &Progress, ) -> Result { diff --git a/crates/engine/src/stroke_view.rs b/crates/engine/src/stroke_view.rs index 77a834e1d..6d6ec5b5e 100644 --- a/crates/engine/src/stroke_view.rs +++ b/crates/engine/src/stroke_view.rs @@ -60,17 +60,23 @@ impl StrokeView { hidden_materials } - /// Identical triangle selection for cursor rays, exact occlusion and camera depth. - pub(crate) fn visibility(&self, mesh: &Mesh, full_bvh: &Arc, previous: Option<(&Self, &Arc)>) -> (Arc, EyeDepth) { - let (width, height) = self.size; + /// Identical triangle selection for cursor rays, exact occlusion and camera depth, the depth + /// rasterized by `device` when there is one. + pub(crate) fn visibility( + &self, + mesh: &Mesh, + full_bvh: &Arc, + previous: Option<(&Self, &Arc)>, + device: Option<&dyn crate::depth_device::DepthDevice>, + ) -> Result<(Arc, EyeDepth), String> { if self.hidden_materials.is_empty() { - (full_bvh.clone(), EyeDepth::render(mesh, &self.camera, width, height)) + Ok((full_bvh.clone(), crate::depth_device::eye_depth(device, mesh, &self.camera, self.size, false, &|_| true)?)) } else { let shown = visible_triangle_mask(mesh, &self.hidden_materials); - let include = |triangle| shown.get(triangle).copied().unwrap_or(false); + let include = |triangle: usize| shown.get(triangle).copied().unwrap_or(false); let existing = previous.filter(|(view, _)| self.hidden_materials == view.hidden_materials); let bvh = existing.map_or_else(|| Arc::new(Bvh::new_filtered(mesh, include)), |(_, bvh)| bvh.clone()); - (bvh, EyeDepth::render_filtered(mesh, &self.camera, width, height, include)) + Ok((bvh, crate::depth_device::eye_depth(device, mesh, &self.camera, self.size, false, &include)?)) } } } diff --git a/crates/engine/src/stroke_visibility.rs b/crates/engine/src/stroke_visibility.rs index 02f4c9656..2baf10dd2 100644 --- a/crates/engine/src/stroke_visibility.rs +++ b/crates/engine/src/stroke_visibility.rs @@ -10,23 +10,71 @@ pub(crate) struct StrokeVisibility { pub(crate) view: StrokeView, bvh: Arc, depth: Arc, + /// The depth device that rasterized `depth` (None: the CPU) + device: Option>, +} + +/// Whether two depth backends are the same (both the CPU, or one device) +fn same_device(a: Option<&Arc>, b: Option<&Arc>) -> bool { + match (a, b) { + (Some(a), Some(b)) => std::ptr::addr_eq(Arc::as_ptr(a), Arc::as_ptr(b)), + (None, None) => true, + _ => false, + } } impl Session { - pub(crate) fn stroke_visibility(&mut self, viewport: Vec2) -> (Arc, Arc) { + /// The stroke view's BVH and camera depth; the depth device's error when it reports one. + pub(crate) fn stroke_visibility(&mut self, viewport: Vec2) -> Result<(Arc, Arc), String> { let view = if self.painting_paths { StrokeView::with_hidden_materials(self.camera, viewport, self.path_hidden_materials.clone()) } else { StrokeView::capture(self.camera, viewport, &self.doc.project.texture_sets) }; let cached = self.stroke_visibility.as_ref().filter(|scene| scene.mesh_id == self.mesh_id); - if let Some(scene) = cached.filter(|scene| scene.view == view) { - return (scene.bvh.clone(), scene.depth.clone()); + // The camera depth is reused on the backend that rasterized it; the BVH on any + if let Some(scene) = cached.filter(|scene| scene.view == view && same_device(scene.device.as_ref(), self.depth_device.as_ref())) { + return Ok((scene.bvh.clone(), scene.depth.clone())); } - let (bvh, depth) = view.visibility(&self.mesh, &self.bvh, cached.map(|scene| (&scene.view, &scene.bvh))); + let (bvh, depth) = view.visibility(&self.mesh, &self.bvh, cached.map(|scene| (&scene.view, &scene.bvh)), self.depth_device.as_deref())?; let depth = Arc::new(depth); - self.stroke_visibility = Some(StrokeVisibility { mesh_id: self.mesh_id, view, bvh: bvh.clone(), depth: depth.clone() }); - (bvh, depth) + let device = self.depth_device.clone(); + self.stroke_visibility = Some(StrokeVisibility { mesh_id: self.mesh_id, view, bvh: bvh.clone(), depth: depth.clone(), device }); + Ok((bvh, depth)) + } +} + +#[cfg(test)] +mod tests { + use std::sync::atomic::{AtomicUsize, Ordering}; + + use texturecraft_geom::{Mesh, OrbitCamera, primitives}; + + use super::*; + use crate::depth_device::DepthDevice; + + /// Counts its rasters and hands back the software raster + struct CountingDevice(AtomicUsize); + + impl DepthDevice for CountingDevice { + fn eye_depth(&self, mesh: &Mesh, camera: &OrbitCamera, size: (u32, u32), record: bool, include: &dyn Fn(usize) -> bool) -> Result { + self.0.fetch_add(1, Ordering::Relaxed); + Ok(EyeDepth::rasterize(mesh, camera, size.0, size.1, record, include)) + } + } + + /// Turning GPU compositing on between two strokes of one view rasterizes the camera depth on + /// the device instead of reusing the CPU's + #[test] + fn a_new_depth_backend_rasterizes_the_view_again() { + let mut session = Session::new_project("depth", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap(); + let viewport = Vec2::new(128.0, 128.0); + session.stroke_visibility(viewport).unwrap(); + let device = Arc::new(CountingDevice(AtomicUsize::new(0))); + session.depth_device = Some(device.clone()); + session.stroke_visibility(viewport).unwrap(); + session.stroke_visibility(viewport).unwrap(); + assert_eq!(device.0.load(Ordering::Relaxed), 1, "rasterized once on the new device, then reused"); } } diff --git a/crates/engine/src/thumbs.rs b/crates/engine/src/thumbs.rs index be41a0080..967c1769e 100644 --- a/crates/engine/src/thumbs.rs +++ b/crates/engine/src/thumbs.rs @@ -7,9 +7,12 @@ //! project, copy-on-write pixel tiles, baked maps, images and the mesh) plus a 64 px G-buffer. //! It is rebuilt only when the document really changed, at most every [`DEBOUNCE`] seconds //! (a slider drag renders at that pace, not once per frame). -//! * A **worker thread** evaluates one target at a time from a snapshot with -//! [`texturecraft_compose::thumb::render`]. On wasm32 (no threads) one job runs per -//! [`ThumbService::poll`] instead. +//! * A **worker thread** evaluates one target at a time from a snapshot: on the GPU through the +//! [`CompositeDevice`] when the app gives one ([`ThumbService::set_composite_device`]), at a +//! reduced display size of the set; otherwise, or where the GPU compositor refuses the layer, +//! with [`texturecraft_compose::thumb::render`]. A GPU error leaves the thumbnail empty and +//! is reported ([`ThumbService::take_errors`]), not redone on the CPU. On wasm32 (no threads) +//! one job runs per [`ThumbService::poll`] instead. //! * Results are kept in a small LRU **cache** ([`CACHE_ENTRIES`]). A result computed from an //! older snapshot than the current one is dropped, so a slow job can never overwrite a newer //! thumbnail. An entry that is out of date keeps showing until its replacement arrives. @@ -18,13 +21,16 @@ use std::collections::{HashMap, HashSet, VecDeque}; use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; -use texturecraft_compose::{BakedMaps, ImageStore, Inputs, PixelStore, THUMB_TEXELS, ThumbImage, ThumbTarget, thumb}; +use texturecraft_compose::{BakedMaps, ImageStore, Inputs, PixelStore, THUMB_TEXELS, ThumbImage, ThumbOutput, ThumbPlan, ThumbTarget, thumb}; use texturecraft_core::Project; use texturecraft_geom::glam::Vec3; use texturecraft_geom::{Mesh, UvGBuffer}; use crate::Session; +use crate::composite_device::{CompositeDevice, CompositeJob}; +use crate::gpu_failure::GpuFailure; /// Thumbnails kept. pub const CACHE_ENTRIES: usize = 96; @@ -44,11 +50,18 @@ pub struct ThumbSnapshot { mesh: Arc, gbuf: Arc, bounds: (Vec3, Vec3), + /// The set's own G-buffer, which the GPU composites read at every 2^shift-th texel + set_gbuf: Option>, + device: Option>, + /// Set when the app changes the composite device: the snapshot's jobs stop before their + /// next attempt and free the worker for the new device's pictures + cancel: Arc, } impl ThumbSnapshot { - /// Snapshot texture set `ts` of `s`, with the G-buffer from `gbufs` (built on a miss). - pub fn new(s: &Session, ts: usize, gbufs: &mut GbufCache) -> Option { + /// Snapshot texture set `ts` of `s`, with the G-buffer from `gbufs` (built on a miss), + /// rendering on `device` when given. + pub fn new(s: &Session, ts: usize, gbufs: &mut GbufCache, device: Option>) -> Option { let material = s.doc.project.texture_set(ts).ok()?.material; let gbuf = gbufs.get(&s.mesh, s.mesh_id, material); Some(ThumbSnapshot { @@ -61,6 +74,9 @@ impl ThumbSnapshot { mesh: s.mesh.clone(), gbuf, bounds: s.mesh.bounds(), + set_gbuf: s.caches.get(ts).map(|cache| cache.gbuf.clone()), + device, + cancel: Arc::new(AtomicBool::new(false)), }) } @@ -87,8 +103,20 @@ impl ThumbSnapshot { && self.images.iter().all(|(key, image)| session.images.get(key).is_some_and(|current| Arc::ptr_eq(current, image))) } - /// Render `target`: the work of one job. - pub fn render(&self, target: ThumbTarget) -> Option { + /// Render `target`: the work of one job. On the device when the snapshot has one (a refusal + /// renders on the CPU); its error is returned. + pub fn render(&self, target: ThumbTarget) -> Result, String> { + if let (Some(device), Some(set_gbuf)) = (&self.device, &self.set_gbuf) { + match self.render_on(device.as_ref(), set_gbuf, target) { + Ok(Some(image)) => return Ok(image), + Ok(None) => {} + Err(error) => return Err(error), + } + } + if self.cancel.load(Ordering::Acquire) { + return Err("the thumbnail was cancelled".into()); + } + let inp = Inputs { project: &self.project, ts: self.ts, @@ -101,7 +129,38 @@ impl ThumbSnapshot { images: &self.images, bounds: self.bounds, }; - thumb::render(&inp, target) + Ok(thumb::render(&inp, target)) + } + + /// `target` composited on `device` (None when it refuses the layer): at the set's size + /// halved down to at least [`THUMB_TEXELS`] per side, picked to a [`THUMB_TEXELS`] square + fn render_on(&self, device: &dyn CompositeDevice, set_gbuf: &Arc, target: ThumbTarget) -> Result>, String> { + let Some(plan) = ThumbPlan::new(&self.project, self.ts, target) else { return Ok(Some(None)) }; + + // A layer kept with the stack it reads draws among the other layers: the CPU cuts it out + if !matches!(plan.output, ThumbOutput::Mask(_)) && !plan.draws_alone(self.ts) { + return Ok(None); + } + + let side = set_gbuf.width.min(set_gbuf.height); + let shift = (side / THUMB_TEXELS).checked_ilog2().unwrap_or(0); + let job = CompositeJob { + project: &plan.project, + ts: self.ts, + pixels: &self.pixels, + mesh: &self.mesh, + gbuf: set_gbuf, + baked: &self.baked, + images: &self.images, + shift, + padding: None, + cancel: Some(&self.cancel), + }; + match device.thumbnail(&job, plan.output) { + Ok(image) => Ok(Some(Some(square(&image, THUMB_TEXELS)))), + Err(GpuFailure::Refused(_)) => Ok(None), + Err(GpuFailure::Device(error)) => Err(error), + } } /// Whether the layer or effect `target` shows still exists in the snapshot's project. @@ -110,6 +169,23 @@ impl ThumbSnapshot { } } +/// `image` picked to a `side` square at the nearest texels (the CPU thumbnails are square) +fn square(image: &ThumbImage, side: u32) -> ThumbImage { + if (image.width, image.height) == (side, side) { + return image.clone(); + } + + let pick = |at: u32, length: u32| (u64::from(2 * at + 1) * u64::from(length) / u64::from(2 * side)) as u32; + let mut rgba = Vec::with_capacity((side * side) as usize * 4); + for y in 0..side { + for x in 0..side { + let offset = (pick(y, image.height) * image.width + pick(x, image.width)) as usize * 4; + rgba.extend_from_slice(image.rgba.get(offset..offset + 4).unwrap_or(&[0; 4])); + } + } + ThumbImage { width: side, height: side, rgba } +} + fn has_target(p: &Project, target: ThumbTarget) -> bool { match target { ThumbTarget::Content { layer, .. } | ThumbTarget::Mask { layer } => p.layers.contains_key(&layer), @@ -162,7 +238,8 @@ struct Job { struct Done { generation: u64, target: ThumbTarget, - image: Option, + /// The picture, or the GPU's error (the entry stays empty) + image: Result, String>, } #[cfg(not(target_arch = "wasm32"))] @@ -216,6 +293,11 @@ pub struct ThumbService { inline: VecDeque, /// Pictures computed (tests, benchmarks). pub rendered: u64, + device: Option>, + /// GPU errors of finished jobs, for the app to report + errors: Vec, + /// The last error reported: the same error of the next pictures is not repeated + last_error: Option, } impl Default for ThumbService { @@ -240,6 +322,9 @@ impl Default for ThumbService { spawned: false, inline: VecDeque::new(), rendered: 0, + device: None, + errors: Vec::new(), + last_error: None, } } } @@ -249,6 +334,31 @@ impl ThumbService { ThumbService::default() } + /// Render the next pictures on `device` (None: GPU compositing off or no GPU, the CPU + /// renders them). A change redraws every picture on the new device. + pub fn set_composite_device(&mut self, device: Option>) { + let same = match (&self.device, &device) { + (Some(a), Some(b)) => Arc::ptr_eq(a, b), + (None, None) => true, + _ => false, + }; + if !same { + // Jobs of the old device stop, and its errors are reported again on the new one + if let Some(snapshot) = &self.snapshot { + snapshot.cancel.store(true, Ordering::Release); + } + self.device = device; + self.snapshot = None; + self.seen = None; + self.last_error = None; + } + } + + /// The GPU errors of thumbnails finished since the last call + pub fn take_errors(&mut self) -> Vec { + std::mem::take(&mut self.errors) + } + /// Start of a frame: forget what the last frame asked for (but what it asked for after its poll) and notice document changes pub fn begin_frame(&mut self, session: &Session, now: f64) { self.wanted = std::mem::take(&mut self.late); @@ -271,7 +381,7 @@ impl ThumbService { return; } - self.snapshot = ThumbSnapshot::new(session, texture_set, &mut self.gbufs).map(Arc::new); + self.snapshot = ThumbSnapshot::new(session, texture_set, &mut self.gbufs, self.device.clone()).map(Arc::new); self.seen = Some(session.revision); self.generation = self.generation.wrapping_add(1); @@ -414,8 +524,17 @@ impl ThumbService { continue; } + // A GPU error is reported once and leaves the picture empty until the document changes + let image = result.image.unwrap_or_else(|error| { + let message = format!("The layer thumbnail failed on the GPU: {error}"); + if self.last_error.as_ref() != Some(&message) { + self.last_error = Some(message.clone()); + self.errors.push(message); + } + None + }); self.versions = self.versions.wrapping_add(1); - let entry = Entry { image: result.image.map(Arc::new), generation: result.generation, version: self.versions, used: self.tick }; + let entry = Entry { image: image.map(Arc::new), generation: result.generation, version: self.versions, used: self.tick }; self.cache.insert(result.target, entry); changed = true; } @@ -469,7 +588,7 @@ mod tests { let baked = session.doc.baked.entry(0).or_default(); baked.resolution = 1; baked.maps.insert(texturecraft_core::BakedMap::Height, Arc::new(vec![f32::NAN])); - let snapshot = ThumbSnapshot::new(&session, 0, &mut GbufCache::default()).unwrap(); + let snapshot = ThumbSnapshot::new(&session, 0, &mut GbufCache::default(), None).unwrap(); assert!(snapshot.matches(&session, 0), "unchanged shared data must not invalidate every frame"); @@ -486,7 +605,7 @@ mod tests { baked.resolution = 4096; baked.maps.insert(texturecraft_core::BakedMap::Normal, Arc::new(vec![0.5; 4096 * 4096 * 3])); baked.maps.insert(texturecraft_core::BakedMap::AmbientOcclusion, Arc::new(vec![0.5; 4096 * 4096])); - let snapshot = ThumbSnapshot::new(&session, 0, &mut GbufCache::default()).unwrap(); + let snapshot = ThumbSnapshot::new(&session, 0, &mut GbufCache::default(), None).unwrap(); let start = std::time::Instant::now(); for _ in 0..20 { @@ -496,6 +615,99 @@ mod tests { eprintln!("20 unchanged snapshot comparisons, 4K normal + AO (256 MiB): {:?}", start.elapsed()); } + /// Answers every thumbnail with `failure`, or with one color at the job's display size + struct ThumbDevice(Option); + + impl CompositeDevice for ThumbDevice { + fn display_maps(&self, _job: &CompositeJob, _kinds: &[texturecraft_compose::DisplayKind]) -> Result { + Err(GpuFailure::Refused("thumbnails only".into())) + } + + fn thumbnail(&self, job: &CompositeJob, _output: ThumbOutput) -> Result { + if job.cancel.is_some_and(|cancel| cancel.load(Ordering::Acquire)) { + return Err(GpuFailure::Device("the preview was cancelled".into())); + } + if let Some(failure) = &self.0 { + return Err(failure.clone()); + } + + let (width, height) = (job.gbuf.width >> job.shift, job.gbuf.height >> job.shift); + Ok(ThumbImage { width, height, rgba: [9, 8, 7, 6].repeat((width * height) as usize) }) + } + } + + /// A job dispatched for one device stops once the app switches devices, instead of keeping + /// the worker busy with a picture nobody shows + #[test] + fn a_device_change_cancels_the_old_devices_jobs() { + let session = test_session().unwrap(); + let target = ThumbTarget::Content { layer: session.selected_layer().unwrap(), channel: Channel::BaseColor }; + let (mut service, jobs, _results) = held_worker(); + service.set_composite_device(Some(Arc::new(ThumbDevice(None)))); + service.begin_frame(&session, 0.0); + service.get(&session, target); + service.poll(&session); + let job = jobs.try_recv().unwrap(); + + service.set_composite_device(None); + assert!(job.snapshot.render(target).is_err(), "the old device's job stops"); + } + + /// The same GPU error on a new device is reported again + #[test] + fn a_device_change_reports_the_same_error_again() { + let session = test_session().unwrap(); + let target = ThumbTarget::Content { layer: session.selected_layer().unwrap(), channel: Channel::BaseColor }; + let error = GpuFailure::Device("Not enough GPU memory for a test".into()); + let (mut service, jobs, results) = held_worker(); + let mut reported = Vec::new(); + for frame in 0..2 { + service.set_composite_device(Some(Arc::new(ThumbDevice(Some(error.clone()))))); + service.begin_frame(&session, f64::from(frame)); + service.get(&session, target); + service.poll(&session); + let job = jobs.try_recv().unwrap(); + results.send(Done { generation: job.generation, target, image: job.snapshot.render(target) }).unwrap(); + service.begin_frame(&session, f64::from(frame) + 0.5); + service.get(&session, target); + service.poll(&session); + reported.push(service.take_errors().len()); + } + assert_eq!(reported, [1, 1], "each device reports its error"); + } + + /// A layer thumbnail comes from the device as a square of the thumbnail size; a device error + /// is reported once and leaves the picture empty; a refusal renders on the CPU + #[test] + fn layer_thumbnails_render_on_the_device_and_report_its_errors() { + let session = test_session().unwrap(); + let target = ThumbTarget::Content { layer: session.selected_layer().unwrap(), channel: Channel::BaseColor }; + let snapshot = |device: Option| ThumbSnapshot::new(&session, 0, &mut GbufCache::default(), Some(Arc::new(ThumbDevice(device)))).unwrap(); + + let image = snapshot(None).render(target).unwrap().unwrap(); + assert_eq!((image.width, image.height), (THUMB_TEXELS, THUMB_TEXELS)); + assert!(image.rgba.as_chunks::<4>().0.iter().all(|pixel| *pixel == [9, 8, 7, 6])); + let error = "The GPU reported an error in a test".to_string(); + assert_eq!(snapshot(Some(GpuFailure::Device(error.clone()))).render(target), Err(error.clone())); + let on_cpu = ThumbSnapshot::new(&session, 0, &mut GbufCache::default(), None).unwrap().render(target); + assert_eq!(snapshot(Some(GpuFailure::Refused("a test refusal".into()))).render(target), on_cpu); + + let (mut service, jobs, results) = held_worker(); + service.set_composite_device(Some(Arc::new(ThumbDevice(Some(GpuFailure::Device(error)))))); + service.begin_frame(&session, 0.0); + service.get(&session, target); + service.poll(&session); + let job = jobs.try_recv().unwrap(); + results.send(Done { generation: job.generation, target, image: job.snapshot.render(target) }).unwrap(); + service.begin_frame(&session, 0.1); + service.get(&session, target); + service.poll(&session); + + assert_eq!(service.take_errors().len(), 1); + assert!(service.is_fresh(target) && service.get(&session, target).image.is_none(), "the failed picture is not queued again"); + assert!(jobs.try_recv().is_err()); + } + #[test] fn a_target_the_document_lacks_is_not_rendered() { let session = test_session().unwrap(); @@ -622,7 +834,7 @@ mod tests { // Finishing stale work frees a slot for the newest document, without caching old results for job in queued { - results.send(Done { generation: job.generation, target: job.target, image: None }).unwrap(); + results.send(Done { generation: job.generation, target: job.target, image: Ok(None) }).unwrap(); } assert_eq!(snapshots.iter().filter(|snapshot| snapshot.strong_count() > 0).count(), 1, "completed jobs release stale snapshots"); diff --git a/crates/engine/src/view_cmds.rs b/crates/engine/src/view_cmds.rs index 352571fb2..5651f35b9 100644 --- a/crates/engine/src/view_cmds.rs +++ b/crates/engine/src/view_cmds.rs @@ -565,7 +565,7 @@ mod tests { assert!(execute(&mut s, "viewport.view", &json!({"mode": "image"})).is_err(), "the image is required"); assert!(execute(&mut s, "viewport.view", &json!({"mode": "image", "image": "stone.png"})).is_err(), "unknown resources are rejected"); assert_eq!(s.view, ViewMode::Material); - assert!(s.image_view_rgba(8).is_none(), "no image is chosen"); + assert!(s.image_view_rgba((8, 8)).is_none(), "no image is chosen"); let mut png = Vec::new(); let img = image::RgbaImage::from_fn(2, 2, |x, y| image::Rgba([if x == 0 { 255 } else { 0 }, if y == 0 { 255 } else { 0 }, 0, 255])); @@ -575,14 +575,14 @@ mod tests { assert_eq!((s.view, s.view_image.as_deref()), (ViewMode::Image, Some(name.as_str()))); // The 2x2 image is stretched over the UV square: each quadrant keeps its texel's color - let rgba = s.image_view_rgba(8).unwrap(); + let rgba = s.image_view_rgba((8, 8)).unwrap(); assert_eq!(rgba.len(), 8 * 8 * 4); let at = |x: usize, y: usize| rgba[(y * 8 + x) * 4..(y * 8 + x) * 4 + 3].to_vec(); assert_eq!(at(0, 0), [255, 255, 0], "top left: red and green"); assert_eq!(at(7, 0), [0, 255, 0], "top right: green"); assert_eq!(at(0, 7), [255, 0, 0], "bottom left: red"); assert_eq!(at(7, 7), [0, 0, 0], "bottom right: black"); - assert!(s.image_view_rgba(u32::MAX).is_none(), "reject an oversized raster before allocating it"); + assert!(s.image_view_rgba((u32::MAX, 1)).is_none(), "reject an oversized raster before allocating it"); } #[test] diff --git a/crates/engine/tests/it/color_selection.rs b/crates/engine/tests/it/color_selection.rs index 976c07392..5728d9bb6 100644 --- a/crates/engine/tests/it/color_selection.rs +++ b/crates/engine/tests/it/color_selection.rs @@ -397,14 +397,14 @@ fn output_hardness_and_background_shape_the_mask_in_one_undo_step_each() { fn the_id_mask_view_shows_the_chosen_image_where_the_mask_reads_it() { let mut session = session(); let (_, effect) = masked_layer(&mut session, false); - assert!(session.id_mask_view_rgba(effect, 16).is_none(), "the ID mesh map is no image"); + assert!(session.id_mask_view_rgba(effect, (16, 16)).is_none(), "the ID mesh map is no image"); let image = session.import_resource_bytes("parts.png", id_map_png()).unwrap(); execute(&mut session, "effect.set", &json!({"effect": effect.0, "idMap": image})).unwrap(); assert_eq!(session.id_mask_image(effect).map(|(texture_set, _)| texture_set), Some(0)); - let rgba = session.id_mask_view_rgba(effect, 16).unwrap(); + let rgba = session.id_mask_view_rgba(effect, (16, 16)).unwrap(); assert_eq!(rgba.len(), 16 * 16 * 4); diff --git a/crates/engine/tests/it/perf.rs b/crates/engine/tests/it/perf.rs index 814c3a51f..95450c4ec 100644 --- a/crates/engine/tests/it/perf.rs +++ b/crates/engine/tests/it/perf.rs @@ -476,10 +476,10 @@ fn bench_layer_thumbs_4k() { let ts = s.ts(); let mut gbufs = GbufCache::default(); let t = Instant::now(); - let snap = ThumbSnapshot::new(&s, ts, &mut gbufs).unwrap(); + let snap = ThumbSnapshot::new(&s, ts, &mut gbufs, None).unwrap(); let first = t.elapsed(); let t = Instant::now(); - let _again = ThumbSnapshot::new(&s, ts, &mut gbufs).unwrap(); + let _again = ThumbSnapshot::new(&s, ts, &mut gbufs, None).unwrap(); let cached = t.elapsed(); let p = &s.doc.project; let mut targets = Vec::new(); diff --git a/crates/engine/tests/it/shared_uv_parts.rs b/crates/engine/tests/it/shared_uv_parts.rs index ceef0d97f..b35a4c87a 100644 --- a/crates/engine/tests/it/shared_uv_parts.rs +++ b/crates/engine/tests/it/shared_uv_parts.rs @@ -79,7 +79,7 @@ fn a_stroke_on_either_part_sharing_uvs_paints_the_shared_texels() { } #[test] -fn overlapping_world_strokes_use_the_cpu_even_when_a_brush_device_is_available() { +fn overlapping_world_strokes_start_the_brush_device() { let mut session = session(two_walls_sharing_uvs()); let device_starts = Arc::new(AtomicUsize::new(0)); session.brush_device = Some(BrushBackend { device: Arc::new(BrushStartCounter(device_starts.clone())), surface: Arc::downgrade(&session.caches[0].gbuf) }); @@ -89,12 +89,12 @@ fn overlapping_world_strokes_use_the_cpu_even_when_a_brush_device_is_available() execute(&mut session, "tool.stroke", &json!({"points": [[pixel.x, pixel.y]]})).unwrap(); session.update(); - assert_eq!(device_starts.load(Ordering::Relaxed), 0, "the owner-only device must not start a shared-UV world stroke"); - assert!(red_at_uv(&session, wall_uv(other_wall))); + assert_eq!(device_starts.load(Ordering::Relaxed), 1, "the device paints every surface sharing a texel, so it starts a shared-UV world stroke"); + assert!(red_at_uv(&session, wall_uv(other_wall)), "the refusing test device leaves the stroke to the CPU"); execute(&mut session, "tool.strokeUv", &json!({"points": [[0.5, 0.5]]})).unwrap(); - assert_eq!(device_starts.load(Ordering::Relaxed), 1, "texture-space strokes can still use the device"); + assert_eq!(device_starts.load(Ordering::Relaxed), 2, "texture-space strokes use the device too"); } /// The UV a wall point maps to: wall UVs run (x + 1) / 2 on the first wall, (x - 3) / 2 on the @@ -193,9 +193,15 @@ fn a_world_stencil_samples_the_hit_wall_for_preview_and_commit() { execute(&mut session, "tool.material", &json!({"channel": "baseColor", "color": [0.0, 1.0, 0.0]})).unwrap(); } execute(&mut session, "tool.stencil", &json!({"image": name, "scale": 1.0, "tile": false})).unwrap(); + let device_starts = Arc::new(AtomicUsize::new(0)); + session.brush_device = + Some(BrushBackend { device: Arc::new(BrushStartCounter(device_starts.clone())), surface: Arc::downgrade(&session.caches[0].gbuf) }); session.begin_stroke(pixel, session.viewport, 1.0).unwrap(); session.update(); + // The device samples a stencil at the owner surface only + assert_eq!(device_starts.load(Ordering::Relaxed), 0, "a shared-UV stencil stroke stays on the CPU, projection={projection}"); + assert!(red_at_uv(&session, hit.uv), "live preview on the hit wall, projection={projection}"); session.end_stroke().unwrap(); @@ -206,7 +212,7 @@ fn a_world_stencil_samples_the_hit_wall_for_preview_and_commit() { } #[test] -fn only_screen_space_path_strokes_start_the_brush_device() { +fn a_path_with_a_hidden_point_starts_the_brush_device() { let mut session = session(primitives::sphere(1.0, 48, 24)); assert!(!session.caches[0].gbuf.shared_surfaces); let device_starts = Arc::new(AtomicUsize::new(0)); @@ -219,8 +225,9 @@ fn only_screen_space_path_strokes_start_the_brush_device() { session.tool.path.points = vec![far_point]; execute(&mut session, "tool.path", &json!({"commit": true})).unwrap(); - assert_eq!(device_starts.load(Ordering::Relaxed), visible_starts, "the device would cull the hidden point"); + // The device skips the view test for the hidden point's surface samples, as the CPU does + assert_eq!(device_starts.load(Ordering::Relaxed), visible_starts + 1, "a path with a hidden point starts the brush device"); session.camera.set_angles(std::f32::consts::PI, 0.0); let hit = session.pick(screen(&session, far_point), session.viewport).unwrap(); - assert!(red_at_uv(&session, hit.uv), "the CPU stroke paints the far point"); + assert!(red_at_uv(&session, hit.uv), "the stroke the refusing test device leaves to the CPU paints the far point"); } diff --git a/crates/engine/tests/it/shared_uv_parts/brush_start_counter.rs b/crates/engine/tests/it/shared_uv_parts/brush_start_counter.rs index 15963c4b4..9b8c415af 100644 --- a/crates/engine/tests/it/shared_uv_parts/brush_start_counter.rs +++ b/crates/engine/tests/it/shared_uv_parts/brush_start_counter.rs @@ -2,12 +2,13 @@ use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; use texturecraft_engine::brush_device::{BrushDevice, BrushSurface, DeviceStroke}; +use texturecraft_engine::gpu_failure::GpuFailure; pub(super) struct BrushStartCounter(pub(super) Arc); impl BrushDevice for BrushStartCounter { - fn start(&self, _: BrushSurface) -> Result, String> { + fn start(&self, _: BrushSurface) -> Result, GpuFailure> { self.0.fetch_add(1, Ordering::Relaxed); - Err("test brush does not rasterize".into()) + Err(GpuFailure::Refused("test brush does not rasterize".into())) } } diff --git a/crates/engine/tests/it/thumbs.rs b/crates/engine/tests/it/thumbs.rs index f5f32a5e1..de73a5cf3 100644 --- a/crates/engine/tests/it/thumbs.rs +++ b/crates/engine/tests/it/thumbs.rs @@ -352,11 +352,11 @@ fn instances_preview_the_source_content_and_inherited_mask() { let mut session = session(); let stack = stack(&mut session); let instance = id(execute(&mut session, "layer.instance", &json!({"layer": stack.layer.0})).unwrap(), "layer"); - let snapshot = ThumbSnapshot::new(&session, 0, &mut GbufCache::default()).unwrap(); + let snapshot = ThumbSnapshot::new(&session, 0, &mut GbufCache::default(), None).unwrap(); for channel in [Channel::BaseColor, Channel::Roughness] { - let source = snapshot.render(ThumbTarget::Content { layer: stack.layer, channel }).unwrap(); - let preview = snapshot.render(ThumbTarget::Content { layer: instance, channel }); + let source = snapshot.render(ThumbTarget::Content { layer: stack.layer, channel }).unwrap().unwrap(); + let preview = snapshot.render(ThumbTarget::Content { layer: instance, channel }).unwrap(); assert!(preview == Some(source), "the instance inherits {channel:?} from its source"); } @@ -381,14 +381,14 @@ fn thumbnails_keep_anchor_inputs_from_lower_layers() { execute(&mut session, "layer.fill.set", &json!({"channel": "roughness", "anchor": anchor.0, "anchorChannel": "height"})).unwrap(); execute(&mut session, "mask.add.black", &Value::Null).unwrap(); let mask_effect = id(execute(&mut session, "effect.add.fill", &json!({"anchor": anchor.0, "anchorChannel": "height"})).unwrap(), "effect"); - let snapshot = ThumbSnapshot::new(&session, 0, &mut GbufCache::default()).unwrap(); + let snapshot = ThumbSnapshot::new(&session, 0, &mut GbufCache::default(), None).unwrap(); for target in [ ThumbTarget::Content { layer, channel: Channel::Roughness }, ThumbTarget::Mask { layer }, ThumbTarget::Stage { effect: mask_effect, channel: Channel::BaseColor }, ] { - let image = snapshot.render(target).unwrap(); + let image = snapshot.render(target).unwrap().unwrap(); let pixel = image.rgba.as_chunks::<4>().0.iter().find(|pixel| pixel[3] == 255).unwrap(); assert!((i32::from(pixel[0]) - 64).abs() <= 1, "{target:?} must read the lower anchor's 0.25, got {pixel:?}"); @@ -402,9 +402,9 @@ fn folder_thumbnails_keep_anchors_outside_the_folder() { let (mut session, anchor, layer) = anchor_stack(); execute(&mut session, "layer.fill.set", &json!({"channel": "roughness", "anchor": anchor.0, "anchorChannel": "height"})).unwrap(); let folder = id(execute(&mut session, "layer.group", &json!({"layer": layer.0})).unwrap(), "layer"); - let snapshot = ThumbSnapshot::new(&session, 0, &mut GbufCache::default()).unwrap(); + let snapshot = ThumbSnapshot::new(&session, 0, &mut GbufCache::default(), None).unwrap(); - let image = snapshot.render(ThumbTarget::Content { layer: folder, channel: Channel::Roughness }).unwrap(); + let image = snapshot.render(ThumbTarget::Content { layer: folder, channel: Channel::Roughness }).unwrap().unwrap(); let pixel = image.rgba.as_chunks::<4>().0.iter().find(|pixel| pixel[3] == 255).unwrap(); assert!((i32::from(pixel[0]) - 64).abs() <= 1, "the folder must read the external anchor's 0.25, got {pixel:?}"); @@ -427,10 +427,10 @@ fn effect_only_anchor_reads_keep_the_lower_stack() { execute(&mut session, "effect.set", &json!({"effect": effect.0, "anchor": anchor.0, "anchorChannel": "height"})).unwrap(); } let target = if target_kind == "content" { ThumbTarget::Content { layer, channel: Channel::Roughness } } else { ThumbTarget::Mask { layer } }; - let snapshot = ThumbSnapshot::new(&session, 0, &mut GbufCache::default()).unwrap(); + let snapshot = ThumbSnapshot::new(&session, 0, &mut GbufCache::default(), None).unwrap(); for target in [target, ThumbTarget::Stage { effect, channel: Channel::Roughness }] { - let image = snapshot.render(target).unwrap(); + let image = snapshot.render(target).unwrap().unwrap(); let pixel = image.rgba.as_chunks::<4>().0.iter().find(|pixel| pixel[3] == 255).unwrap(); assert!((i32::from(pixel[0]) - 64).abs() <= 1, "{target_kind} {target:?} must read the lower anchor's 0.25, got {pixel:?}"); diff --git a/crates/engine/tests/it/tools.rs b/crates/engine/tests/it/tools.rs index 3bf340bcd..676309407 100644 --- a/crates/engine/tests/it/tools.rs +++ b/crates/engine/tests/it/tools.rs @@ -259,7 +259,10 @@ fn quick_mask_limits_painting() { assert_eq!(session.history_labels().len(), undo, "mask strokes stay out of the history"); let overlay_size: u32 = 64; let rgba_bytes = (overlay_size * overlay_size * 4) as usize; - assert!(session.quick_mask_rgba(0, overlay_size).is_some_and(|pixels| pixels.len() == rgba_bytes), "an RGBA8 overlay of the requested size"); + assert!( + session.quick_mask_rgba(0, (overlay_size, overlay_size)).is_some_and(|pixels| pixels.len() == rgba_bytes), + "an RGBA8 overlay of the requested size" + ); execute(&mut session, "viewport.quickMask.edit", &Value::Null).unwrap(); execute(&mut session, "tool.brush", &json!({"size": 6})).unwrap(); diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 4229da6b2..f84e8d92a 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -975,6 +975,164 @@ fn the_eraser_erases_only_through_the_stencils_gray() { assert_ne!(base_color_at(&session, WHITE_DAB_X), right_painted, "white stencil lets the eraser through"); } +/// A GPU brush covering every tile, whose stroke readback or stencil readback fails +struct FailingReadback { + alpha: bool, +} + +struct FailingReadbackStroke { + alpha: bool, + size: (u32, u32), +} + +impl texturecraft_engine::brush_device::BrushDevice for FailingReadback { + fn start( + &self, + surface: texturecraft_engine::brush_device::BrushSurface, + ) -> Result, texturecraft_engine::gpu_failure::GpuFailure> { + Ok(Box::new(FailingReadbackStroke { alpha: self.alpha, size: (surface.uv.width, surface.uv.height) })) + } +} + +impl FailingReadbackStroke { + fn tiles(&self) -> texturecraft_engine::brush_device::BrushTiles { + use texturecraft_engine::texel::TILE; + (0..self.size.1 / TILE).flat_map(|y| (0..self.size.0 / TILE).map(move |x| (x, y))).collect() + } +} + +impl texturecraft_engine::brush_device::DeviceStroke for FailingReadbackStroke { + fn append_world(&mut self, _: &[texturecraft_engine::paint::Stamp], _: bool) -> Result { + Ok(self.tiles()) + } + + fn append_uv(&mut self, _: &[texturecraft_engine::paint::UvStamp]) -> Result { + Ok(self.tiles()) + } + + fn read_alpha(&self, tiles: &texturecraft_engine::brush_device::BrushTiles) -> Result { + use texturecraft_engine::texel::{TILE_AREA, TileImage}; + if self.alpha { + return Err("The GPU reported an error in a test".into()); + } + + let mut alpha = TileImage::new(self.size.0, self.size.1, 1); + for &(x, y) in tiles { + alpha.set_tile(x, y, Some(std::sync::Arc::new(vec![u16::MAX; TILE_AREA]))); + } + Ok(alpha) + } + + fn read_projection(&self, _: &texturecraft_engine::brush_device::BrushTiles) -> Result { + Err("The GPU reported an error in a test".into()) + } + + fn as_any(&self) -> &dyn std::any::Any { + self + } +} + +/// A GPU brush that does not start, with `failure` +struct NotStarting(texturecraft_engine::gpu_failure::GpuFailure); + +impl texturecraft_engine::brush_device::BrushDevice for NotStarting { + fn start( + &self, + _: texturecraft_engine::brush_device::BrushSurface, + ) -> Result, texturecraft_engine::gpu_failure::GpuFailure> { + Err(self.0.clone()) + } +} + +/// A device error at the GPU brush start fails the stroke; only a refusal paints on the CPU +#[test] +fn a_gpu_brush_start_error_fails_the_stroke_and_a_refusal_paints_on_the_cpu() { + use texturecraft_engine::gpu_failure::GpuFailure; + + for failure in [GpuFailure::Device("The GPU reported an error in a test".into()), GpuFailure::Refused("adapter limits in a test".into())] { + let mut session = session_at(TEXTURE_SIZE); + execute(&mut session, "tool.paint", &Value::Null).unwrap(); + execute(&mut session, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); + session.brush_device = Some(texturecraft_engine::brush_device::BrushBackend { + device: std::sync::Arc::new(NotStarting(failure.clone())), + surface: std::sync::Arc::downgrade(&session.caches[0].gbuf), + }); + let before = session.doc.clone(); + let history = session.history_labels(); + + let started = session.begin_stroke(Vec2::new(WHITE_DAB_X, DAB_Y), session.viewport, 1.0); + + match failure { + GpuFailure::Device(_) => { + let error = started.unwrap_err().to_string(); + assert!(error.contains("The GPU reported an error in a test"), "{error}"); + assert!(!session.stroke_active(), "no CPU stroke stands in for the GPU"); + assert!(same_document(&session.doc, &before)); + assert_eq!(session.history_labels(), history); + } + GpuFailure::Refused(_) => { + started.unwrap(); + assert!(session.device_stroke().is_none()); + session.end_stroke().unwrap(); + assert!(!same_document(&session.doc, &before), "a refused GPU brush paints on the CPU"); + } + } + } +} + +/// A failed GPU stroke or stencil readback fails the stroke: the CPU does not repaint it +#[test] +fn a_failed_gpu_brush_readback_is_returned_not_painted_on_the_cpu() { + for (tool, alpha) in [("tool.paint", true), ("tool.projection", false)] { + let mut session = session_at(TEXTURE_SIZE); + let name = half_black_stencil(&mut session); + execute(&mut session, tool, &Value::Null).unwrap(); + if !alpha { + execute(&mut session, "tool.stencil", &json!({"image": name, "scale": 1.0, "tile": true})).unwrap(); + } + execute(&mut session, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); + session.brush_device = Some(texturecraft_engine::brush_device::BrushBackend { + device: std::sync::Arc::new(FailingReadback { alpha }), + surface: std::sync::Arc::downgrade(&session.caches[0].gbuf), + }); + let before = session.doc.clone(); + let history = session.history_labels(); + + session.begin_stroke(Vec2::new(WHITE_DAB_X, DAB_Y), session.viewport, 1.0).unwrap(); + session.continue_stroke(Vec2::new(WHITE_DAB_X + 10.0, DAB_Y), 1.0); + assert!(session.device_stroke().is_some(), "{tool}: the stroke runs on the device"); + let error = session.end_stroke().unwrap_err().to_string(); + + assert!(error.contains("The GPU reported an error in a test"), "{tool}: {error}"); + assert!(same_document(&session.doc, &before), "{tool}: the document keeps no paint"); + assert_eq!(session.history_labels(), history, "{tool}"); + assert!(!session.stroke_active()); + } +} + +/// A whole 2D stroke keeps its GPU brush until the commit: a failed stencil readback fails it, +/// the CPU does not sample the stencil instead +#[test] +fn a_whole_uv_stroke_reads_its_stencil_from_the_device() { + let mut session = session_at(TEXTURE_SIZE); + let name = half_black_stencil(&mut session); + execute(&mut session, "tool.projection", &Value::Null).unwrap(); + execute(&mut session, "tool.stencil", &json!({"image": name, "scale": 1.0, "tile": true})).unwrap(); + execute(&mut session, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); + session.brush_device = Some(texturecraft_engine::brush_device::BrushBackend { + device: std::sync::Arc::new(FailingReadback { alpha: false }), + surface: std::sync::Arc::downgrade(&session.caches[0].gbuf), + }); + let before = session.doc.clone(); + let history = session.history_labels(); + + let error = session.stroke_uv_points(&[Vec2::new(0.4, 0.5), Vec2::new(0.6, 0.5)]).unwrap_err().to_string(); + + assert!(error.contains("GPU stencil readback failed"), "{error}"); + assert!(same_document(&session.doc, &before), "the document keeps no paint"); + assert_eq!(session.history_labels(), history); +} + #[test] fn a_mask_stroke_shows_through_the_stencil_while_painting_as_it_commits() { let mut session = session_at(TEXTURE_SIZE); diff --git a/crates/paint/src/alphas.rs b/crates/paint/src/alphas.rs index 6001a80c9..540d07e89 100644 --- a/crates/paint/src/alphas.rs +++ b/crates/paint/src/alphas.rs @@ -1,7 +1,9 @@ -//! The built-in alpha library: brush stamp shapes generated in code (no image files). Each alpha -//! is rendered once, on first use, into a mip-mapped grayscale image that strokes sample -//! bilinearly at the level matching the stamp size, so a library alpha costs no more per texel -//! than a procedural one and nothing is allocated per stamp. +//! The built-in alpha library: brush stamp shapes generated in code (no image files). The GPU +//! brush generates each alpha on the GPU at the size the texture set needs (the generators +//! ported to WGSL, [`LibraryAlpha::gpu_spec`]). Without a GPU, each alpha is rendered once on the +//! CPU, on first use, into a mip-mapped grayscale image of [`BASE`] texels a side that strokes +//! sample bilinearly at the level matching the stamp size; the CPU generators are also the GPU's +//! oracle. use std::collections::{BTreeMap, VecDeque}; use std::f32::consts::{PI, TAU}; @@ -15,12 +17,14 @@ pub use crate::alpha_option::AlphaOption; use crate::brush::smoothstep; -/// Size in pixels of the finest mip level. +/// Size in pixels of the CPU image's finest mip level (GPU compositing off) and of the picture a +/// library alpha saves into a project as a fill source. pub const BASE: usize = 512; /// Size of the coarsest mip level. -const MIN_LEVEL: usize = 4; -/// Edge anti-aliasing width in stamp units (about 1.5 base pixels; the stamp spans −1..1). -const AA: f32 = 3.0 / BASE as f32; +pub const MIN_LEVEL: usize = 4; +/// Edge anti-aliasing width in stamp units (the stamp spans −1..1): a property of the shapes, the +/// same at every rendered size. +pub const AA: f32 = 3.0 / 512.0; const SEED: u32 = 0x7C0A; /// A shape over the stamp square: local coordinates −1..1 (y up) → coverage 0..1. @@ -59,10 +63,26 @@ pub struct LibraryAlpha { /// Shelf group ("Basic", "Grunge", …). pub category: &'static str, maker: Maker, + /// The generator's number in the GPU shader: its place in [`SHAPES`], [`GLYPH_KIND`] for letters + kind: u32, options: &'static [AlphaOption], image: OnceLock>, } +/// What the GPU generator needs to draw one library alpha with its settings: the generator +/// (`kind`), its seed, its scalar settings and its items (lines, drops, strands or glyph strokes +/// as vec4s), each laid out as `alpha_gen.wgsl` reads them +#[derive(Clone, Debug, PartialEq)] +pub struct AlphaSpec { + pub kind: u32, + pub seed: u32, + pub values: [f32; 8], + pub items: Vec<[f32; 4]>, +} + +/// The GPU generator number of the stencil letters +pub const GLYPH_KIND: u32 = SHAPES.len() as u32; + /// Bound the pixel buffer and supersampling work for a single alpha render const MAX_RENDER_SIDE: usize = 4096; const MAX_SAMPLES_PER_AXIS: usize = 4; @@ -72,6 +92,85 @@ impl LibraryAlpha { self.options } + /// The GPU generator's input for this alpha with `params` (the CPU generator's settings, + /// derived the same way; `alpha_gen.wgsl` evaluates the shape) + pub fn gpu_spec(&self, params: &LibraryAlphaParams) -> AlphaSpec { + let mut values = Vec::new(); + let mut items = Vec::new(); + let thickness = THICKNESS.value(params); + let softness = SOFTNESS.value(params); + let scale = SCALE.value(params); + let density = DENSITY.value(params); + let breakup = BREAKUP.value(params); + match self.maker { + Maker::Glyph(strokes) => { + values.push(thickness); + items.extend(glyph_segments(strokes).into_iter().map(|(a, b)| [a[0], a[1], b[0], b[1]])); + } + Maker::Shape(_) => match self.id.as_str() { + "ring" => values.push(0.2 * thickness), + "cross" => values.push(0.22 * thickness), + "star_5" => values.push((0.4 * thickness).min(0.9)), + "star_4" => values.push((0.1 * thickness).min(0.9)), + "star_6" => values.push((0.55 * thickness).min(0.9)), + "arrow" => values.push(0.16 * thickness), + "dots_grid" => { + let count = DOT_ROWS.value(params); + let step = 1.8 / count; + let radius = (0.14 * thickness).min(step * 0.48); + let offset = if count == DOT_ROWS.default { 0.675 } else { 0.9 - step * 0.5 }; + values.extend([count, step, radius, offset]); + } + "scratches" => { + for (a, b, width, intensity) in scratch_lines(params) { + items.extend([[a[0], a[1], b[0], b[1]], [width, intensity, 0.0, 0.0]]); + } + } + "chips" => values.extend([scale, density, CHIP_DETAIL.value(params).trunc(), breakup]), + "splatter" => { + values.push(breakup); + items.extend(splatter_drops(params).into_iter().map(|[x, y, radius]| [x, y, radius, 0.0])); + } + "sponge" => values.extend([scale, density, breakup]), + "grunge_spots" => values.extend([scale, density, SPOT_DETAIL.value(params).trunc()]), + "cracks" => values.extend([scale, thickness, breakup]), + "speckle" => values.extend([40.0 * scale, 0.78 - 0.15 * (density - 1.0)]), + "fur" => { + for (p, width, bounds) in fur_strands(params) { + items.extend([[p[0][0], p[0][1], p[1][0], p[1][1]], [p[2][0], p[2][1], p[3][0], p[3][1]], bounds, [width, 0.0, 0.0, 0.0]]); + } + } + "leaf" => { + let (sin, cos) = (PI / 6.0).sin_cos(); + values.extend([VEIN_COUNT.value(params), thickness, sin, cos]); + } + "wood_knot" => values.extend([30.0 * scale, breakup]), + "bolt_head" => values.extend([BOLT_SIDES.value(params).trunc(), softness]), + "screw_slot" | "screw_cross" => values.push(0.08 * thickness), + "stitches" => { + let count = STITCH_COUNT.value(params).trunc(); + let step = 1.5 / (count - 1.0).max(1.0); + let offset = if count == 1.0 { 0.0 } else { -0.75 }; + values.extend([count, step, (0.05 * thickness).min(step * 0.45), offset]); + } + "vent" => { + let count = VENT_COUNT.value(params).trunc(); + let step = 1.2 / (count - 1.0).max(1.0); + let offset = if count == 1.0 { 0.0 } else { -0.6 }; + values.extend([count, step, (0.07 * thickness).min(step * 0.45), offset]); + } + "fabric" => values.push(7.0 * scale), + "bricks" => values.extend([1.6 * scale, 3.2 * scale, thickness]), + _ => values.push(softness), + }, + } + let mut packed = [0.0; 8]; + for (slot, value) in packed.iter_mut().zip(values) { + *slot = value; + } + AlphaSpec { kind: self.kind, seed: random_seed(params), values: packed, items } + } + /// Keep only this alpha's valid non-default settings. pub fn sanitized_parameters(&self, params: &LibraryAlphaParams) -> LibraryAlphaParams { self.options @@ -212,11 +311,12 @@ impl AlphaImage { } static LIBRARY: LazyLock> = LazyLock::new(|| { - let entry = |id: String, label: String, category, options, maker| LibraryAlpha { id, label, category, maker, options, image: OnceLock::new() }; - let shapes = SHAPES.iter().map(|&(id, label, cat, options, make)| entry(id.into(), label.into(), cat, options, Maker::Shape(make))); - let glyphs = GLYPHS - .iter() - .map(|&(c, strokes)| entry(format!("letter_{}", c.to_ascii_lowercase()), format!("Stencil {c}"), LETTERS, &[THICKNESS], Maker::Glyph(strokes))); + let entry = |id: String, label: String, category, options, maker, kind| LibraryAlpha { id, label, category, maker, kind, options, image: OnceLock::new() }; + let shapes = + SHAPES.iter().enumerate().map(|(kind, &(id, label, cat, options, make))| entry(id.into(), label.into(), cat, options, Maker::Shape(make), kind as u32)); + let glyphs = GLYPHS.iter().map(|&(c, strokes)| { + entry(format!("letter_{}", c.to_ascii_lowercase()), format!("Stencil {c}"), LETTERS, &[THICKNESS], Maker::Glyph(strokes), GLYPH_KIND) + }); shapes.chain(glyphs).collect() }); @@ -417,14 +517,13 @@ fn dots_grid(params: &LibraryAlphaParams) -> Gen { // --------------------------------------------------------------------------------------------- // Grunge -fn scratches(params: &LibraryAlphaParams) -> Gen { +/// [a, b, half width, intensity] of the scratches' thin lines along a dominant direction +fn scratch_lines(params: &LibraryAlphaParams) -> Vec<([f32; 2], [f32; 2], f32, f32)> { let seed = random_seed(params); let count = SCRATCH_COUNT.value(params) as u32; let width = THICKNESS.value(params); let breakup = BREAKUP.value(params); - - // [a, b, half width, intensity] of thin lines along a dominant direction - let lines: Vec<([f32; 2], [f32; 2], f32, f32)> = (0..count) + (0..count) .map(|i| { let (cx, cy) = (rnd(i, 0, seed) * 1.2 - 0.6, rnd(i, 1, seed) * 1.2 - 0.6); let ang = 0.5 + (rnd(i, 2, seed) - 0.5) * 0.6 * breakup; @@ -432,7 +531,11 @@ fn scratches(params: &LibraryAlphaParams) -> Gen { let (dx, dy) = (ang.cos() * half, ang.sin() * half); ([cx - dx, cy - dy], [cx + dx, cy + dy], (0.004 + rnd(i, 4, seed) * 0.012) * width, 0.5 + rnd(i, 5, seed) * 0.5) }) - .collect(); + .collect() +} + +fn scratches(params: &LibraryAlphaParams) -> Gen { + let lines = scratch_lines(params); Box::new(move |x, y| { let m = lines.iter().fold(0.0f32, |m, &(a, b, w, k)| { let (d, t) = seg(x, y, a, b); @@ -463,19 +566,23 @@ fn chips(params: &LibraryAlphaParams) -> Gen { }) } -fn splatter(params: &LibraryAlphaParams) -> Gen { +/// The splatter's droplets [x, y, radius] around a ragged central blob +fn splatter_drops(params: &LibraryAlphaParams) -> Vec<[f32; 3]> { let seed = random_seed(params); let count = SPLAT_COUNT.value(params) as u32; let thickness = THICKNESS.value(params); - let breakup = BREAKUP.value(params); - - // Droplets [x, y, radius] around a ragged central blob - let drops: Vec<[f32; 3]> = (0..count) + (0..count) .map(|i| { let (a, d) = (rnd(i, 0, seed) * TAU, 0.42 + rnd(i, 1, seed).powf(0.7) * 0.45); [a.cos() * d, a.sin() * d, (0.015 + rnd(i, 2, seed).powi(2) * 0.07) * thickness] }) - .collect(); + .collect() +} + +fn splatter(params: &LibraryAlphaParams) -> Gen { + let seed = random_seed(params); + let breakup = BREAKUP.value(params); + let drops = splatter_drops(params); Box::new(move |x, y| { let a = y.atan2(x); let edge = 0.36 + 0.3 * (fbm(a.cos() * 1.5 + 4.0, a.sin() * 1.5, 0.0, 3, seed) - 0.5) * breakup; @@ -536,13 +643,12 @@ fn speckle(params: &LibraryAlphaParams) -> Gen { // --------------------------------------------------------------------------------------------- // Organic -fn fur(params: &LibraryAlphaParams) -> Gen { +/// Fur strands rising from the bottom and bending sideways: 4 points, half width, bounding box +fn fur_strands(params: &LibraryAlphaParams) -> Vec<([[f32; 2]; 4], f32, [f32; 4])> { let seed = random_seed(params); let count = FUR_COUNT.value(params) as u32; let thickness = THICKNESS.value(params); - - // Strands rising from the bottom and bending sideways: 4 points, half width, bounding box - let strands: Vec<([[f32; 2]; 4], f32, [f32; 4])> = (0..count) + (0..count) .map(|i| { let (x0, y0) = (rnd(i, 0, seed) * 1.4 - 0.7, -0.85 + rnd(i, 1, seed) * 0.3); let (length, bend) = (0.8 + rnd(i, 2, seed) * 0.7, (rnd(i, 3, seed) - 0.5) * 0.9); @@ -554,7 +660,11 @@ fn fur(params: &LibraryAlphaParams) -> Gen { let bb = p.iter().fold([f32::MAX, f32::MAX, f32::MIN, f32::MIN], |b, q| [b[0].min(q[0]), b[1].min(q[1]), b[2].max(q[0]), b[3].max(q[1])]); (p, w, [bb[0] - w, bb[1] - w, bb[2] + w, bb[3] + w]) }) - .collect(); + .collect() +} + +fn fur(params: &LibraryAlphaParams) -> Gen { + let strands = fur_strands(params); Box::new(move |x, y| { let mut m = 0.0f32; for (p, w, bb) in &strands { @@ -728,19 +838,24 @@ const GLYPHS: [(char, &str); 36] = [ /// A glyph from [`GLYPHS`] strokes, drawn with round caps. fn glyph(strokes: &str, thickness: f32) -> Gen { + let segs = glyph_segments(strokes); + Box::new(move |x, y| fill(segs.iter().map(|&(a, b)| seg(x, y, a, b).0).fold(f32::MAX, f32::min) - 0.11 * thickness)) +} + +/// The straight segments of a glyph's strokes, in stamp units +fn glyph_segments(strokes: &str) -> Vec<([f32; 2], [f32; 2])> { const UNIT: f32 = 0.27; let point = |p: &[u8]| match p { [x, y] => Some([(x.wrapping_sub(b'0') as f32 - 2.0) * UNIT, (3.0 - y.wrapping_sub(b'0') as f32) * UNIT]), _ => None, }; - let segs: Vec<([f32; 2], [f32; 2])> = strokes + strokes .split_whitespace() .flat_map(|run| { let pts: Vec<[f32; 2]> = run.as_bytes().chunks(2).filter_map(point).collect(); pts.windows(2).filter_map(|w| if let [a, b] = w { Some((*a, *b)) } else { None }).collect::>() }) - .collect(); - Box::new(move |x, y| fill(segs.iter().map(|&(a, b)| seg(x, y, a, b).0).fold(f32::MAX, f32::min) - 0.11 * thickness)) + .collect() } #[cfg(test)] diff --git a/crates/paint/src/lib.rs b/crates/paint/src/lib.rs index 217db9b7f..a5c4cac27 100644 --- a/crates/paint/src/lib.rs +++ b/crates/paint/src/lib.rs @@ -31,8 +31,10 @@ pub use alpha_params::AlphaParams; pub use brush::{Alignment, BrushAlpha, BrushSettings, FULL_TURN_DEGREES, MAX_RADIAL_COPIES, Shape, StampBlending, Symmetry, image_alpha}; pub use commit::{CommitSource, Staging, TexelFn, commit_coverage, commit_layer, commit_mask}; pub use path::{Lasso, spline, spline_segments, spline_segments_3d_stream, spline_segments_stream, spline_segments_with_corners, spline_with_corners}; -pub use pickup::{Pickup, PickupMode}; -pub use raster::{RasterCtx, StrokeCanvas, UvStamp, fill_coverage, fill_coverage_surfaces, fill_triangle_surfaces, fill_triangles, rasterize, rasterize_uv}; +pub use pickup::{CloneSource, PICKUP_SOURCE_REFUSED, Pickup, PickupMode, SmudgeLane, SmudgeSource}; +pub use raster::{ + RasterCtx, StrokeCanvas, UvStamp, fill_coverage, fill_coverage_surfaces, fill_triangle_surfaces, fill_triangles, non_owner_covers, rasterize, rasterize_uv, +}; pub use stamp_source::StampSource; pub use stroke::{PickCtx, Stamp, Stroke, SurfaceHit, nearest_surface_filtered, pick, pick_filtered}; -pub use visibility::{EyeDepth, screen_point}; +pub use visibility::{DepthRaster, EyeDepth, screen_point}; diff --git a/crates/paint/src/pickup.rs b/crates/paint/src/pickup.rs index 9bd061871..9ce2a2171 100644 --- a/crates/paint/src/pickup.rs +++ b/crates/paint/src/pickup.rs @@ -20,9 +20,15 @@ mod pickup_snapshot; pub use pickup_snapshot::PickupSnapshot; +/// How a refusal to composite a clone or smudge source on the GPU starts (the CPU then evaluates it) +pub const PICKUP_SOURCE_REFUSED: &str = "The GPU compositor cannot write the clone or smudge source: "; + use lane::Lane; use pickup_reads::PickupReads; +/// Per carried channel the source's straight values, and per channel its coverage +type ChannelCoverage = (Vec<(Channel, TileImage)>, Vec); + /// How a pickup stroke finds the values it deposits. #[derive(Clone, Copy, Debug, PartialEq)] pub enum PickupMode { @@ -33,6 +39,55 @@ pub enum PickupMode { Smudge { strength: f32 }, } +/// Where a clone stroke reads, for a GPU brush that weighs each dab by it and carries the source's +/// values at the offset: the texel offset and, when the stroke clones one layer, that layer's +/// coverage (None reads every covered texel fully). +#[derive(Clone, Debug)] +pub struct CloneSource { + pub offset: [i64; 2], + pub coverage: Option, + /// Per carried channel (in the order of [`Pickup::values`]) the source as encoded values, + /// every tile with covered texels present (absent ones hold the channel's default) + pub channels: Vec<(Channel, TileImage)>, + /// A source the GPU composites itself from these inputs (the document's composite, a mask's + /// values or the brush material's fill): `channels` then only name the channels, their images + /// hold no tiles + pub composited: Option>, +} + +/// What a smudge stroke reads, for a GPU brush that drags it stamp by stamp: the strength, whether +/// every symmetry copy drags its own trail ([`Pickup::isolate_copies`]), and per carried channel (in +/// the order of [`Pickup::values`]) the source as encoded values, every tile with covered texels +/// present (absent ones hold the channel's default). +#[derive(Clone, Debug)] +pub struct SmudgeSource { + pub strength: f32, + pub isolated: bool, + pub channels: Vec<(Channel, TileImage)>, + /// A source the GPU composites itself from these inputs (the document's composite or a + /// mask's values): `channels` then only name the channels, their images hold no tiles + pub composited: Option>, + /// A layer's own paint or a cloned layer: per carried channel (in the order of `channels`) + /// the source's coverage, which weighs that channel's deposits, each channel keeping its own + /// stroke alpha (None: every channel reads fully and shares the stroke alpha) + pub coverage: Option>, + /// A clone whose channels differ in coverage, painted stamp by stamp: it reads the source + /// this many texels away and never what the stroke deposited (None: a smudge) + pub clone_offset: Option<[i64; 2]>, +} + +/// One symmetry copy's trail of a smudge a GPU brush painted so far (the stroke's only trail +/// unless copies drag their own): its previous stamp center and, for an isolated copy, its own +/// alpha and carried values, for a CPU stroke that continues it. +#[derive(Clone, Debug)] +pub struct SmudgeLane { + pub source: Option, + pub previous: Option<[f32; 2]>, + pub carried: Option<(TileImage, BTreeMap)>, + /// With per-channel coverage ([`SmudgeSource::coverage`]): the copy's alpha per channel + pub alphas: BTreeMap, +} + /// The values a clone or smudge stroke carries. #[derive(Clone, Debug)] pub struct Pickup { @@ -187,12 +242,13 @@ impl Pickup { /// Evaluate only the source tiles read by this stroke, sharing each tile across its stamps. pub fn from_snapshot(mode: PickupMode, snapshot: PickupSnapshot, gbuf: Arc, channels: impl IntoIterator) -> Self { - let mask = matches!(snapshot.target, PaintTarget::Mask(_)); + let mask = matches!(snapshot.target, Some(PaintTarget::Mask(_))); let channels = if mask { vec![MASK_CHANNEL] } else { channels.into_iter().collect() }; let source = Composite::with_size(&channels, gbuf.width, gbuf.height); let size = (gbuf.width, gbuf.height); let mut pickup = Self::new(mode, source, gbuf, channels); - if !mask { + // A layer weighs by its coverage per channel; the document's composite covers everything + if matches!(snapshot.target, Some(PaintTarget::Layer(_))) { pickup.enable_channel_alphas(size); pickup.coverage = Some(pickup.alphas.clone()); } @@ -246,7 +302,11 @@ impl Pickup { missing.push(tile); } } + self.evaluate(&missing); + } + /// Evaluate the source tiles `missing` from the snapshot, or resample them from the paint + fn evaluate(&mut self, missing: &[(u32, u32)]) { if missing.is_empty() { return; } @@ -256,7 +316,7 @@ impl Pickup { let Some(output) = self.source.channels.get_mut(&channel) else { continue }; let empty = [enc(channel.kind(), 0.0); 3]; - for &(tile_x, tile_y) in &missing { + for &(tile_x, tile_y) in missing { if let Some(data) = image.resampled_tile(output.width(), output.height(), tile_x, tile_y, &empty[..channel.components()]) { output.set_tile(tile_x, tile_y, Some(Arc::new(data))); } @@ -270,16 +330,17 @@ impl Pickup { let Some(inputs) = snapshot.inputs(&self.gbuf) else { return }; match snapshot.target { - PaintTarget::Layer(id) => { - if let Some(flat) = texturecraft_compose::flatten_layer(&inputs, id, &missing) { + Some(PaintTarget::Layer(id)) => { + if let Some(flat) = texturecraft_compose::flatten_layer(&inputs, id, missing) { self.add_layer_tiles(&flat); } } - PaintTarget::Mask(owner) => { + Some(PaintTarget::Mask(owner)) => { if let Some(output) = self.source.channels.get_mut(&MASK_CHANNEL) { - texturecraft_compose::eval::mask_values_into(&inputs, owner, &missing, output); + texturecraft_compose::eval::mask_values_into(&inputs, owner, missing, output); } } + None => texturecraft_compose::composite_tiles(&inputs, &mut self.source, missing), } } @@ -388,6 +449,265 @@ impl Pickup { self.put_back(lane, painted) } + /// A clone stroke's source for a GPU brush (None for smudge). A pickup evaluating its source + /// lazily (the document's composite, a mask, or the brush material's fill, which covers every + /// texel it reaches) leaves it to the GPU compositor and reads every covered texel fully; a + /// cloned layer supplies its flattened values and weighs by its coverage. + pub fn clone_source(&self) -> Option { + let PickupMode::Clone { offset } = self.mode else { return None }; + Some(match &self.snapshot { + Some(snapshot) => CloneSource { offset, coverage: None, channels: self.channel_names(), composited: Some(snapshot.clone()) }, + None => CloneSource { offset, coverage: self.shared_coverage()?, channels: self.loaded_channels(), composited: None }, + }) + } + + /// The one coverage every carried channel shares (None: no coverage, every texel reads + /// fully); refused (outer None) when the channels' coverages differ, which the GPU brush's + /// single stroke alpha cannot carry. + fn shared_coverage(&self) -> Option> { + let Some(coverages) = &self.coverage else { return Some(None) }; + let mut images = self.values.keys().map(|channel| coverages.get(channel)); + let first = images.next().flatten()?; + images.all(|image| image.is_some_and(|image| same_texels(image, first))).then(|| Some(first.clone())) + } + + /// A GPU clone painting one stroke alpha for every channel (its channels share their + /// coverage, [`Pickup::clone_source`]) drops the per-channel alphas once the device takes the + /// stroke, so the commit, the preview and a CPU continuation use the stroke alpha. A source + /// with per-channel coverage ([`SmudgeSource::coverage`]) keeps them: the device paints them. + pub fn use_stroke_alpha(&mut self) { + self.alphas.clear(); + } + + /// A GPU stroke's alpha per channel (read back with its carried values), for a pickup whose + /// device source has per-channel coverage + pub fn carry_device_alphas(&mut self, alphas: BTreeMap) { + for (channel, carried) in alphas { + let Some(image) = self.alphas.get_mut(&channel) else { continue }; + for (tile_x, tile_y) in carried.allocated() { + image.set_tile(tile_x, tile_y, carried.tile_handle(tile_x, tile_y).cloned()); + } + } + } + + /// A smudge stroke's source for a GPU brush, or a clone's whose channels differ in coverage + /// (painted stamp by stamp like a smudge); None for any other clone. The document's composite + /// or a mask's values evaluated lazily are composited by the GPU from their snapshot. A + /// layer's own paint or a cloned layer supplies its straight values and per-channel coverage. + pub fn smudge_source(&self) -> Option { + let (strength, clone_offset) = match self.mode { + PickupMode::Smudge { strength } => (strength, None), + PickupMode::Clone { offset } if self.snapshot.is_none() && self.clone_source().is_none() => (1.0, Some(offset)), + PickupMode::Clone { .. } => return None, + }; + let strength = strength.clamp(0.0, 1.0); + + // One layer's own paint (or its flattening) deposits per channel where the layer has it + if !self.alphas.is_empty() || self.paint_to_resample.is_some() { + if self.snapshot.is_some() { + return None; + } + let (channels, coverage) = self.channel_coverage()?; + return Some(SmudgeSource { strength, isolated: self.isolated, channels, composited: None, coverage: Some(coverage), clone_offset }); + } + let Some(snapshot) = &self.snapshot else { return self.loaded_smudge_source(strength) }; + if matches!(snapshot.target, Some(PaintTarget::Layer(_))) { + return None; + } + + Some(SmudgeSource { + strength, + isolated: self.isolated, + channels: self.channel_names(), + composited: Some(snapshot.clone()), + coverage: None, + clone_offset: None, + }) + } + + /// Per carried channel the source's straight values (encoded, every covered tile present) and + /// its coverage, for a pickup reading one layer's paint (`from_paint`, resampled where the + /// paint has another size) or a layer's flattening (`from_layer`) + fn channel_coverage(&self) -> Option { + let tiles = covered_tiles(&self.gbuf); + let (width, height) = (self.source.resolution, self.source.height); + let mut channels = Vec::new(); + let mut coverages = Vec::new(); + for &channel in self.values.keys() { + let (components, kind) = (channel.components(), channel.kind()); + let mut values = TileImage::new(width, height, components); + let mut coverage = TileImage::new(width, height, 1); + let default: Vec = channel.default_value().iter().take(components).map(|value| enc(kind, *value)).collect(); + for &(tile_x, tile_y) in &tiles { + let mut straight: Vec = default.iter().copied().cycle().take(TILE_AREA * components).collect(); + let mut amounts = vec![0u16; TILE_AREA]; + match &self.paint_to_resample { + // Premultiplied paint with its coverage as the last component + Some(resample) => { + let stored = match (resample.get(&channel), self.source.channels.get(&channel)) { + (Some(image), _) => { + let empty = [enc(kind, 0.0); 3]; + image.resampled_tile(width, height, tile_x, tile_y, &empty[..components]).map(Arc::new) + } + (None, Some(image)) => image.tile_handle(tile_x, tile_y).cloned(), + (None, None) => None, + }; + if let Some(stored) = stored { + for (texel, data) in stored.chunks_exact(components + 1).enumerate().take(TILE_AREA) { + let alpha = data[components]; + amounts[texel] = alpha; + if alpha == 0 { + continue; + } + let inverse = 1.0 / from_u16(alpha); + for component in 0..components { + straight[texel * components + component] = enc(kind, (dec(kind, data[component]) * inverse).clamp(-1.0, 1.0)); + } + } + } + } + + // A flattened layer: straight values and the coverage per channel + None => { + let image = self.source.channels.get(&channel).filter(|image| image.comps() == components); + if let Some(data) = image.and_then(|image| image.tile(tile_x, tile_y)) { + straight.copy_from_slice(&data[..TILE_AREA * components]); + } + let covered = self.coverage.as_ref().and_then(|coverages| coverages.get(&channel)); + if let Some(data) = covered.and_then(|image| image.tile(tile_x, tile_y)) { + amounts.copy_from_slice(&data[..TILE_AREA]); + } + } + } + values.set_tile(tile_x, tile_y, Some(Arc::new(straight))); + if amounts.iter().any(|&amount| amount != 0) { + coverage.set_tile(tile_x, tile_y, Some(Arc::new(amounts))); + } + } + channels.push((channel, values)); + coverages.push(coverage); + } + Some((channels, coverages)) + } + + /// The carried channels, each with an image holding no tiles + fn channel_names(&self) -> Vec<(Channel, TileImage)> { + self.values.iter().map(|(channel, image)| (*channel, TileImage::new(image.width(), image.height(), channel.components()))).collect() + } + + /// Whether the pickup evaluates the document's composite lazily from its snapshot + pub fn composites_lazily(&self) -> bool { + self.snapshot.as_ref().is_some_and(|snapshot| snapshot.target.is_none()) + } + + /// A pickup evaluating the document's composite lazily reads `whole` (the composite of every + /// covered tile) instead: a smudge whose source the GPU compositor does not write. + pub fn read_whole(&mut self, whole: Composite) { + if self.composites_lazily() { + self.source = whole; + self.snapshot = None; + self.loaded.clear(); + } + } + + /// A pickup evaluating a mask's values or a layer lazily evaluates every covered tile now: a + /// clone or smudge whose source the GPU compositor does not write reads them whole. The + /// document's composite is read whole from the cache instead ([`Pickup::read_whole`]). + pub fn evaluate_whole(&mut self) { + if !self.snapshot.as_ref().is_some_and(|snapshot| snapshot.target.is_some()) { + return; + } + + let missing: Vec<(u32, u32)> = covered_tiles(&self.gbuf).into_iter().filter(|tile| !self.loaded.contains(tile)).collect(); + self.evaluate(&missing); + self.snapshot = None; + self.loaded.clear(); + } + + /// The smudge source from the values loaded so far + fn loaded_smudge_source(&self, strength: f32) -> Option { + Some(SmudgeSource { strength, isolated: self.isolated, channels: self.loaded_channels(), composited: None, coverage: None, clone_offset: None }) + } + + /// The source values loaded so far per carried channel, every tile with covered texels present + fn loaded_channels(&self) -> Vec<(Channel, TileImage)> { + let tiles = covered_tiles(&self.gbuf); + self.values + .keys() + .map(|channel| { + let (components, kind) = (channel.components(), channel.kind()); + let mut image = self + .source + .channels + .get(channel) + .filter(|image| image.comps() == components) + .cloned() + .unwrap_or_else(|| TileImage::new(self.source.resolution, self.source.height, components)); + let default: Vec = channel.default_value().iter().take(components).map(|value| enc(kind, *value)).collect(); + let default_tile = Arc::new(default.iter().copied().cycle().take(TILE_AREA * components).collect::>()); + for &(tile_x, tile_y) in &tiles { + if !image.is_allocated(tile_x, tile_y) { + image.set_tile(tile_x, tile_y, Some(default_tile.clone())); + } + } + (*channel, image) + }) + .collect() + } + + /// A GPU clone's or smudge's carried values (straight, encoded), read back once when the + /// device stroke ends or the CPU takes it over: kept in [`Pickup::values`] for the commit. + /// The live compositor reads them on the device. + pub fn carry_device_values(&mut self, values: BTreeMap) { + for (channel, carried) in values { + let Some(image) = self.values.get_mut(&channel) else { continue }; + if carried.comps() != channel.components() { + continue; + } + + for (tile_x, tile_y) in carried.allocated() { + image.set_tile(tile_x, tile_y, carried.tile_handle(tile_x, tile_y).cloned()); + } + } + } + + /// Continue a GPU smudge on the CPU from its `lanes` ([`SmudgeLane`]); the carried values + /// themselves were kept by [`Pickup::carry_device_values`]. + pub fn resume_smudge(&mut self, lanes: Vec) { + if !self.isolated { + self.prev = lanes.into_iter().next().and_then(|lane| lane.previous); + return; + } + + self.lanes = lanes + .into_iter() + .map(|lane| { + let (alpha, values) = lane.carried.unwrap_or_else(|| (TileImage::new(self.source.resolution, self.source.height, 1), BTreeMap::new())); + let values = self + .values + .iter() + .map(|(channel, image)| { + let carried = values.get(channel).cloned().unwrap_or_else(|| TileImage::new(image.width(), image.height(), channel.components())); + (*channel, carried) + }) + .collect(); + // Per-channel coverage: each channel's own alpha, no shared one (as `take_lane`) + let per_channel = !self.alphas.is_empty(); + let alphas = if per_channel { + self.alphas + .iter() + .map(|(channel, image)| { + (*channel, lane.alphas.get(channel).cloned().unwrap_or_else(|| TileImage::new(image.width(), image.height(), 1))) + }) + .collect() + } else { + BTreeMap::new() + }; + Lane { source: lane.source, prev: lane.previous, alpha: (!per_channel).then_some(alpha), alphas, values } + }) + .collect(); + } + /// Actual deposits of the last successful stamp, in footprint order. pub(crate) fn deposits(&self) -> &[(u32, u32, f32)] { &self.reads @@ -413,6 +733,31 @@ impl Pickup { } } +/// Tiles with texels on the UV islands, the only ones a clone or smudge reads +fn covered_tiles(gbuf: &UvGBuffer) -> Vec<(u32, u32)> { + let (tiles_x, tiles_y) = (gbuf.width.div_ceil(TILE), gbuf.height.div_ceil(TILE)); + let mut covered = vec![false; (tiles_x * tiles_y) as usize]; + for (texel, triangle) in gbuf.tri.iter().enumerate() { + if *triangle != NO_TRI { + let (x, y) = (texel as u32 % gbuf.width, texel as u32 / gbuf.width); + covered[((y / TILE) * tiles_x + x / TILE) as usize] = true; + } + } + covered.iter().enumerate().filter(|(_, covered)| **covered).map(|(index, _)| (index as u32 % tiles_x, index as u32 / tiles_x)).collect() +} + +/// Whether two images hold the same texels (an absent tile reads zero) +fn same_texels(a: &TileImage, b: &TileImage) -> bool { + fn tile(image: &TileImage, x: u32, y: u32) -> Option<&[u16]> { + image.tile(x, y).filter(|data| data.iter().any(|&value| value != 0)) + } + (a.width(), a.height(), a.comps()) == (b.width(), b.height(), b.comps()) + && a.allocated().chain(b.allocated()).all(|(x, y)| match (a.tile_handle(x, y), b.tile_handle(x, y)) { + (Some(left), Some(right)) if Arc::ptr_eq(left, right) => true, + _ => tile(a, x, y) == tile(b, x, y), + }) +} + fn covered(gbuf: &UvGBuffer, x: u32, y: u32) -> bool { if x >= gbuf.width || y >= gbuf.height { return false; @@ -466,7 +811,7 @@ mod tests { } #[test] - fn layer_and_mask_pickups_only_evaluate_the_shifted_tiles_the_stroke_reads() { + fn lazy_pickups_only_evaluate_the_shifted_tiles_the_stroke_reads() { use texturecraft_core::{Fill, Layer, LayerKind, Mask, MaskBackground, Project, Source, TextureSet}; let size = 4 * TILE; @@ -486,7 +831,7 @@ mod tests { layer.mask = Some(Mask::new(MaskBackground::White)); project.insert_layer(0, layer, None, false).unwrap(); - for (target, expected) in [(PaintTarget::Layer(id), 0.25), (PaintTarget::Mask(id), 1.0)] { + for (target, expected) in [(Some(PaintTarget::Layer(id)), 0.25), (Some(PaintTarget::Mask(id)), 1.0), (None, 0.25)] { let snapshot = PickupSnapshot { project: project.clone(), ts: 0, @@ -506,7 +851,7 @@ mod tests { assert!(pickup.stamp(&mut alpha, &[(x, 8, 1.0)], [x as f32, 8.0], None, StampBlending::Normal)); let image = &pickup.values[&Channel::Roughness]; assert!((from_u16(image.get(x, 8)[0]) - expected).abs() < 1e-4); - assert_eq!(pickup.mask_values().is_some(), matches!(target, PaintTarget::Mask(_))); + assert_eq!(pickup.mask_values().is_some(), matches!(target, Some(PaintTarget::Mask(_)))); } assert_eq!(pickup.loaded, [(1, 0), (2, 0)].into()); @@ -569,6 +914,38 @@ mod tests { assert!(!q.stamp(&mut TileImage::new(TILE, TILE, 1), &disc(20, 32, 3), [20.0, 32.0], None, StampBlending::Normal), "the source is the empty half"); } + /// A layer clone reaches the GPU brush (one stroke alpha) only when its channels share one + /// coverage; once the device takes it, the commit uses the stroke alpha + #[test] + fn a_layer_clone_whose_channels_differ_in_coverage_goes_to_the_gpu_stamp_by_stamp() { + let (_, gbuffer) = setup(|_| 0.0); + let half = to_u16(0.5); + let channels = [Channel::Roughness, Channel::Height]; + let texels = [to_u16(0.25), half].repeat(TILE_AREA); + let clone = |tiles: &[(Channel, (u32, u32), Vec)]| { + Pickup::from_layer(PickupMode::Clone { offset: [0; 2] }, tiles, (TILE, TILE), gbuffer.clone(), channels) + }; + + // Height has no coverage where Roughness has some: one stroke alpha cannot carry it, the + // device paints it stamp by stamp with each channel's coverage + let unequal = clone(&[(Channel::Roughness, (0, 0), texels.clone())]); + assert!(unequal.clone_source().is_none()); + let source = unequal.smudge_source().expect("a clone with per-channel coverage"); + assert_eq!(source.clone_offset, Some([0; 2])); + let coverage = source.coverage.expect("per channel"); + let at = |channel| source.channels.iter().position(|(carried, _)| *carried == channel).unwrap(); + let (roughness, height) = (at(Channel::Roughness), at(Channel::Height)); + assert_eq!((coverage[roughness].get(8, 8)[0], coverage[height].get(8, 8)[0]), (half, 0)); + assert_eq!(source.channels[roughness].1.get(8, 8)[0], to_u16(0.5), "straight values: 0.25 over coverage 0.5"); + + let mut shared = clone(&[(Channel::Roughness, (0, 0), texels.clone()), (Channel::Height, (0, 0), texels)]); + let source = shared.clone_source().expect("both channels share one coverage"); + assert_eq!(source.coverage.map(|coverage| coverage.get(8, 8)[0]), Some(half)); + assert!(shared.channel_alphas().is_some()); + shared.use_stroke_alpha(); + assert!(shared.channel_alphas().is_none()); + } + #[test] fn layer_pickup_accumulates_channels_using_the_brush_blending_mode() { let (_, gbuffer) = setup(|_| 0.0); diff --git a/crates/paint/src/pickup/pickup_snapshot.rs b/crates/paint/src/pickup/pickup_snapshot.rs index 5fa4e7c9b..4635b20ed 100644 --- a/crates/paint/src/pickup/pickup_snapshot.rs +++ b/crates/paint/src/pickup/pickup_snapshot.rs @@ -4,12 +4,13 @@ use texturecraft_compose::{BakedMaps, ImageStore, Inputs, PaintTarget, PixelStor use texturecraft_core::Project; use texturecraft_geom::{Mesh, UvGBuffer}; -/// Compositor inputs frozen at stroke start. A mask target identifies the layer that owns it. +/// Compositor inputs frozen at stroke start. A mask target identifies the layer that owns it; +/// no target reads the document's composite. #[derive(Clone, Debug)] pub struct PickupSnapshot { pub project: Project, pub ts: usize, - pub target: PaintTarget, + pub target: Option, pub mesh: Arc, pub bounds: (texturecraft_geom::glam::Vec3, texturecraft_geom::glam::Vec3), pub pixels: PixelStore, diff --git a/crates/paint/src/raster.rs b/crates/paint/src/raster.rs index cddb0ae40..2b5b7b2e1 100644 --- a/crates/paint/src/raster.rs +++ b/crates/paint/src/raster.rs @@ -247,13 +247,9 @@ pub fn rasterize_with_stencil(canvas: &mut StrokeCanvas, context: &RasterCtx, st }); // The footprint texel nearest the stamp center supplies the pickup's center - let mut center = ([0.0f32; 2], f32::MAX); + let center = Nearest::center(parts.iter().map(|(_, nearest, _)| nearest), context.gbuf.width); let mut has_non_owner_coverage = false; - for (texels, nearest, non_owner_coverage) in parts { - if nearest.1 < center.1 { - center = nearest; - } - + for (texels, _, non_owner_coverage) in parts { has_non_owner_coverage |= non_owner_coverage; canvas.texels.extend(texels); } @@ -264,7 +260,7 @@ pub fn rasterize_with_stencil(canvas: &mut StrokeCanvas, context: &RasterCtx, st canvas.texels.dedup_by_key(|t| (t.0, t.1)); } - canvas.add_stamp(center.0, stamp.source); + canvas.add_stamp(center, stamp.source); } } @@ -286,7 +282,7 @@ fn add_projected_stamp( parts: Vec>, source: Option, ) { - let center = parts.iter().map(|(_, nearest, _)| nearest).min_by(|a, b| a.1.total_cmp(&b.1)).map_or([0.0; 2], |nearest| nearest.0); + let center = Nearest::center(parts.iter().map(|(_, nearest, _)| nearest), context.gbuf.width); let shared = parts.iter().any(|(_, _, non_owner)| *non_owner); if !shared && stencil.surface_samples.is_none() { // The owner can be sampled on demand throughout preview and commit @@ -341,10 +337,49 @@ fn add_projected_stamp( }); } -/// Texels of one triangle a stamp covers, and the one nearest the stamp center. +/// Texels of one triangle a stamp covers, and those nearest the stamp center. /// The flag is set when some painted texels are owned by another triangle in the G-buffer /// (the mesh has parts sharing UVs). -type TriTexels = (Vec<(u32, u32, T)>, ([f32; 2], f32), bool); +type TriTexels = (Vec<(u32, u32, T)>, Nearest, bool); + +/// How close (in squared texels of the triangle) a texel's squared distance to a stamp center may +/// come to the nearest one and still count as tied with it. Of tied texels the first row-major is +/// the center, so a stamp centered on a texel edge or corner picks the same texel whatever the +/// rounding there (the GPU smudge finds the same one; distances near the allowance's edge may +/// still round apart, far rarer than at a texel edge). +const CENTER_TIE: f32 = 1.0 / 16.0; + +/// The footprint texels nearest a stamp center in one triangle's volume: the nearest squared +/// distance, and the texels (row-major index) that may tie with the nearest of all triangles, +/// with their squared distance less the tie allowance. +#[derive(Debug)] +struct Nearest { + distance: f32, + candidates: Vec<(u64, f32)>, +} + +impl Nearest { + fn new() -> Self { + Nearest { distance: f32::MAX, candidates: Vec::new() } + } + + fn add(&mut self, index: u64, distance: f32, tie: f32) { + self.distance = self.distance.min(distance); + + // A texel beyond this triangle's nearest by more than its allowance never ties + if distance - tie <= self.distance { + self.candidates.push((index, distance - tie)); + } + } + + /// The texel center (in texels) of the first row-major texel tied with the nearest of + /// `parts`; the origin when no texel lies in the volume + fn center<'a>(parts: impl Iterator + Clone, width: u32) -> [f32; 2] { + let nearest = parts.clone().map(|part| part.distance).fold(f32::MAX, f32::min); + let first = parts.flat_map(|part| &part.candidates).filter(|(_, reach)| *reach <= nearest).map(|(index, _)| *index).min(); + first.map_or([0.0; 2], |index| [(index % u64::from(width)) as f32 + 0.5, (index / u64::from(width)) as f32 + 0.5]) + } +} /// A texel-space triangle with less double area than this (texels squared) has no usable barycentrics. const MIN_UV_TRIANGLE_AREA: f32 = 1e-12; @@ -377,13 +412,16 @@ fn scan_triangle( let world_area = world_cross.length(); let shape = context.shape.at_radius(stamp.radius * (uv_area / world_area).sqrt()); + // The center's tie allowance in squared world units + let tie = if uv_area > 0.0 { CENTER_TIE * world_area / uv_area } else { 0.0 }; + // Layouts without UV overlaps only scan texels owned by this triangle let shared_uvs = context.gbuf.shared_surfaces; let texel_size = Vec2::new(width as f32, height as f32); let uv_texels = [*uv_a * texel_size, *uv_b * texel_size, *uv_c * texel_size]; let mut texels = Vec::new(); - let mut center = ([0.0f32; 2], f32::MAX); + let mut center = Nearest::new(); let mut has_non_owner_coverage = false; for y in top..bottom { @@ -416,10 +454,7 @@ fn scan_triangle( continue; } - let distance_squared = offset.length_squared(); - if distance_squared < center.1 { - center = ([x as f32 + 0.5, y as f32 + 0.5], distance_squared); - } + center.add(u64::from(y) * u64::from(width) + u64::from(x), offset.length_squared(), tie); let normal = (*normal_a * b0 + *normal_b * b1 + *normal_c * b2).try_normalize().unwrap_or(stamp.normal); if normal.dot(stamp.normal) <= 0.0 { @@ -454,7 +489,7 @@ fn scan_triangle( } } - (center.1 < f32::MAX || !texels.is_empty()).then_some((texels, center, has_non_owner_coverage)) + (center.distance < f32::MAX || !texels.is_empty()).then_some((texels, center, has_non_owner_coverage)) } /// Whether this cover sits on the indexed edge shared with the G-buffer owner. @@ -613,36 +648,57 @@ fn fill_overlapping_texels( canvas.add_stamp([0.0; 2], None); } -/// Non-owner covers beyond the indexed edges shared with their owners. -#[cfg(test)] -fn non_owner_covers(mesh: &Mesh, material: usize, gbuf: &UvGBuffer) -> Vec<(usize, u32, [f32; 2])> { - let mut covers = Vec::new(); - for index in mesh.triangles_of(material).map(|index| index as u32) { - let Some(triangle) = FillTriangle::new(mesh, index, gbuf.width, gbuf.height) else { continue }; - - let vertices = mesh.tri(index as usize).unwrap(); - for y in triangle.rows { - for x in triangle.columns.clone() { - let texel = (y * gbuf.width + x) as usize; - let owner = gbuf.tri[texel]; - if owner == NO_TRI || owner == index { - continue; - } +/// Non-owner covers beyond the indexed edges shared with their owners, in triangle order: +/// (texel index, covering triangle, barycentric weights of its vertices 1 and 2 at the texel +/// centre). The GPU brush evaluates these surfaces next to each texel's owner. +pub fn non_owner_covers(mesh: &Mesh, material: usize, gbuf: &UvGBuffer) -> Vec<(usize, u32, [f32; 2])> { + let triangles: Vec<_> = mesh.triangles_of(material).filter_map(|index| FillTriangle::new(mesh, index as u32, gbuf.width, gbuf.height)).collect(); + triangles + .par_iter() + .flat_map_iter(|triangle| { + let mut covers = Vec::new(); + let Some(vertices) = mesh.tri(triangle.index as usize) else { return covers }; + + for y in triangle.rows.clone() { + for x in triangle.columns.clone() { + let texel = (y * gbuf.width + x) as usize; + let owner = gbuf.tri[texel]; + if owner == NO_TRI || owner == triangle.index { + continue; + } - let Some(bary) = uv_bary(triangle.texel_uvs, [x as f32 + 0.5, y as f32 + 0.5]) else { continue }; + let Some(bary) = uv_bary(triangle.texel_uvs, [x as f32 + 0.5, y as f32 + 0.5]) else { continue }; - if !shares_texel_edge(mesh, owner, vertices, bary) { - covers.push((texel, index, bary)); + if !shares_texel_edge(mesh, owner, vertices, bary) { + covers.push((texel, triangle.index, bary)); + } } } - } - } - - covers + covers + }) + .collect() } #[cfg(test)] mod tests { + /// A stamp centered on a texel corner ties four texels: the first row-major one is the + /// center, from whichever triangle it comes; a nearer texel beyond the allowance wins alone + #[test] + fn tied_stamp_centers_pick_the_first_row_major_texel() { + let mut first = super::Nearest::new(); + let mut second = super::Nearest::new(); + let width = 8; + let tie = super::CENTER_TIE; + second.add(3 * 8 + 3, 0.5, tie); + second.add(3 * 8 + 4, 0.5 + 1e-6, tie); + first.add(4 * 8 + 3, 0.5 - 1e-6, tie); + first.add(4 * 8 + 4, 0.5, tie); + assert_eq!(super::Nearest::center([&first, &second].into_iter(), width), [3.5, 3.5]); + + first.add(5 * 8 + 5, 0.5 - 2.0 * tie, tie); + assert_eq!(super::Nearest::center([&first, &second].into_iter(), width), [5.5, 5.5]); + } + use super::*; use texturecraft_geom::primitives; diff --git a/crates/paint/src/visibility.rs b/crates/paint/src/visibility.rs index d4c6d829c..19ef7d18d 100644 --- a/crates/paint/src/visibility.rs +++ b/crates/paint/src/visibility.rs @@ -1,5 +1,7 @@ -//! Which surface points the paint camera can see: a software-rasterized eye-distance buffer, -//! rendered once at the start of a stroke. +//! Which surface points the paint camera can see: an eye-distance buffer rendered once at the +//! start of a stroke, on the GPU (`texturecraft_render::gpu_eye_depth`) or here in software. + +use std::ops::RangeInclusive; use rayon::prelude::*; use texturecraft_geom::glam::{Mat4, Vec2, Vec3, Vec4}; @@ -7,14 +9,11 @@ use texturecraft_geom::{Mesh, NO_TRI, OrbitCamera}; const BAND: usize = 16; -/// Largest buffer side in pixels. -const MAX_SIZE: u32 = 4096; - /// Clip-space w below which a vertex counts as behind the camera. pub const MIN_CLIP_W: f32 = 1e-5; /// Screen area (pixels squared) below which a triangle is skipped as degenerate. -const MIN_SCREEN_AREA: f32 = 1e-9; +pub const MIN_SCREEN_AREA: f32 = 1e-9; /// How far outside a triangle (in barycentric weight) a pixel center may lie and still count, closing seams between neighbours. const EDGE_TOLERANCE: f32 = 1e-4; @@ -50,8 +49,87 @@ pub fn screen_point(view_proj: Mat4, position: Vec3, size: Vec2) -> Option (clip.w > MIN_CLIP_W).then(|| Vec2::new(clip.x / clip.w * 0.5 + 0.5, 0.5 - clip.y / clip.w * 0.5) * size) } +/// What rasterizing a camera's depth starts from, shared by the software raster here and the +/// GPU's (`texturecraft_render::gpu_eye_depth`), which must give the same buffer. +pub struct DepthRaster { + pub width: u32, + pub height: u32, + /// Each vertex on screen (pixels, origin top-left), None behind the camera + pub screen: Vec>, + /// Each vertex's depth key, smaller nearer: view depth in an orthographic view, minus the + /// inverse view depth in a perspective one (affine on screen, without the precision loss of + /// normalized clip depth) + pub vertex_depth: Vec, + /// The depth keys between the camera's near and far planes + pub depth_range: RangeInclusive, + /// How far outside a triangle (in barycentric weight) a pixel centre still counts: none when + /// recording triangles, where it could expose hidden faces at silhouettes + pub edge_tolerance: f32, + /// The projection's horizontal and vertical scale, for [`DepthRaster::distance`] + pub scale: Vec2, + pub ortho: bool, + view_proj: Mat4, + eye: Vec3, + orthographic_to_eye: Option, + bias: f32, +} + +impl DepthRaster { + /// Rasterizing `mesh` seen by `camera` into a `width × height` buffer. + pub fn new(mesh: &Mesh, camera: &OrbitCamera, width: u32, height: u32, record_triangles: bool) -> Self { + let (width, height) = (width.max(1), height.max(1)); + let projection = camera.proj(width as f32 / height as f32); + let view = camera.view(); + let view_proj = projection * view; + let depth_key = |view_depth: f32| if camera.ortho { view_depth } else { -view_depth.recip() }; + let inverse_projection = projection.inverse(); + let clip_depth = |z: f32| { + let point = inverse_projection * Vec4::new(0.0, 0.0, z, 1.0); + depth_key(-point.z / point.w) + }; + let size = Vec2::new(width as f32, height as f32); + DepthRaster { + width, + height, + screen: mesh.positions.iter().map(|position| screen_point(view_proj, *position, size)).collect(), + vertex_depth: mesh.positions.iter().map(|position| depth_key(-(view * position.extend(1.0)).z)).collect(), + depth_range: clip_depth(0.0)..=clip_depth(1.0), + edge_tolerance: if record_triangles { 0.0 } else { EDGE_TOLERANCE }, + scale: Vec2::new(projection.x_axis.x, projection.y_axis.y), + ortho: camera.ortho, + view_proj, + eye: camera.eye(), + orthographic_to_eye: camera.ortho.then(|| -camera.forward()), + bias: mesh.radius() * BIAS_PER_RADIUS, + } + } + + /// The eye distance of the surface whose depth key at pixel (`column`, `row`) is `depth`. + pub fn distance(&self, column: usize, row: usize, depth: f32) -> f32 { + let view_x = ((column as f32 + 0.5) / self.width as f32 * 2.0 - 1.0) / self.scale.x; + let view_y = (1.0 - (row as f32 + 0.5) / self.height as f32 * 2.0) / self.scale.y; + let radial_squared = view_x * view_x + view_y * view_y; + if self.ortho { (radial_squared + depth * depth).sqrt() } else { (radial_squared + 1.0).sqrt() / -depth } + } + + /// The buffer from its eye distances (f32::MAX where empty) and nearest triangles (empty + /// unless recorded). + pub fn finish(self, dist: Vec, triangle: Vec) -> EyeDepth { + EyeDepth { + width: self.width, + height: self.height, + view_proj: self.view_proj, + eye: self.eye, + orthographic_to_eye: self.orthographic_to_eye, + dist, + triangle, + bias: self.bias, + } + } +} + impl EyeDepth { - /// Rasterize `mesh` seen by `camera` into a `width × height` buffer (sizes capped at [`MAX_SIZE`]), without [`EyeDepth::triangle`]. + /// Rasterize `mesh` seen by `camera` into a `width × height` buffer in software, without [`EyeDepth::triangle`]. pub fn render(mesh: &Mesh, camera: &OrbitCamera, width: u32, height: u32) -> EyeDepth { Self::render_filtered(mesh, camera, width, height, |_| true) } @@ -67,29 +145,11 @@ impl EyeDepth { } /// The eye-distance buffer, plus the nearest triangle per pixel when `record_triangles` is set. - fn rasterize(mesh: &Mesh, camera: &OrbitCamera, width: u32, height: u32, record_triangles: bool, include: impl Fn(usize) -> bool) -> EyeDepth { - // Capping storage dimensions must not change the camera's projection - let projection = camera.proj(width.max(1) as f32 / height.max(1) as f32); - let view = camera.view(); - let view_proj = projection * view; - let depth_key = |view_depth: f32| if camera.ortho { view_depth } else { -view_depth.recip() }; - let inverse_projection = projection.inverse(); - let clip_depth = |z: f32| { - let point = inverse_projection * Vec4::new(0.0, 0.0, z, 1.0); - depth_key(-point.z / point.w) - }; - let depth_range = clip_depth(0.0)..=clip_depth(1.0); - let (width, height) = (width.clamp(1, MAX_SIZE), height.clamp(1, MAX_SIZE)); + pub fn rasterize(mesh: &Mesh, camera: &OrbitCamera, width: u32, height: u32, record_triangles: bool, include: impl Fn(usize) -> bool) -> EyeDepth { + let raster = DepthRaster::new(mesh, camera, width, height, record_triangles); + let (width, height) = (raster.width, raster.height); let size = Vec2::new(width as f32, height as f32); - let eye = camera.eye(); - - // Brush depth closes seams, but expanding triangle IDs can expose hidden faces at silhouettes - let edge_tolerance = if record_triangles { 0.0 } else { EDGE_TOLERANCE }; - - let screen: Vec> = mesh.positions.iter().map(|position| screen_point(view_proj, *position, size)).collect(); - - // Inverse view depth is affine in perspective and avoids the precision loss of normalized clip depth - let vertex_depth: Vec = mesh.positions.iter().map(|position| depth_key(-(view * position.extend(1.0)).z)).collect(); + let (screen, vertex_depth, depth_range, edge_tolerance) = (&raster.screen, &raster.vertex_depth, &raster.depth_range, raster.edge_tolerance); // Bin each triangle into the bands of rows it covers let mut bands: Vec> = vec![Vec::new(); (height as usize).div_ceil(BAND)]; @@ -113,8 +173,9 @@ impl EyeDepth { } } - let mut dist = vec![f32::MAX; (width * height) as usize]; - let mut triangle = if record_triangles { vec![NO_TRI; (width * height) as usize] } else { Vec::new() }; + let pixels = width as usize * height as usize; + let mut dist = vec![f32::MAX; pixels]; + let mut triangle = if record_triangles { vec![NO_TRI; pixels] } else { Vec::new() }; let band_len = BAND * width as usize; let mut triangle_bands: Vec> = triangle.chunks_mut(band_len).map(Some).collect(); triangle_bands.resize_with(dist.len().div_ceil(band_len), || None); @@ -166,25 +227,13 @@ impl EyeDepth { // Convert only the winning depths to eye distances for brush visibility queries for (row, distances) in band_dist.chunks_mut(width as usize).enumerate() { - let view_y = (1.0 - (first_row as f32 + row as f32 + 0.5) / size.y * 2.0) / projection.y_axis.y; for (column, distance) in distances.iter_mut().enumerate().filter(|(_, distance)| **distance != f32::MAX) { - let view_x = ((column as f32 + 0.5) / size.x * 2.0 - 1.0) / projection.x_axis.x; - let radial_squared = view_x * view_x + view_y * view_y; - *distance = if camera.ortho { (radial_squared + *distance * *distance).sqrt() } else { (radial_squared + 1.0).sqrt() / -*distance }; + *distance = raster.distance(column, first_row + row, *distance); } } }); - EyeDepth { - width, - height, - view_proj, - eye, - orthographic_to_eye: camera.ortho.then(|| -camera.forward()), - dist, - triangle, - bias: mesh.radius() * BIAS_PER_RADIUS, - } + raster.finish(dist, triangle) } /// Whether a world point is visible (not hidden behind other geometry, inside the view). diff --git a/crates/paint/tests/visibility.rs b/crates/paint/tests/visibility.rs index 2c4cd77e7..7573922e8 100644 --- a/crates/paint/tests/visibility.rs +++ b/crates/paint/tests/visibility.rs @@ -71,16 +71,17 @@ fn perspective_depth_matches_ray_intersections() { } #[test] -fn capped_buffers_keep_the_requested_viewport_aspect() { +fn wide_buffers_keep_their_requested_size_and_aspect() { let positions = vec![Vec3::new(4.0, -1.0, 0.0), Vec3::new(7.0, -1.0, 0.0), Vec3::new(5.5, 1.0, 0.0)]; let mesh = Mesh::from_parts(positions, None, vec![Vec2::ZERO; 3], vec![0, 1, 2], "m").unwrap(); let camera = OrbitCamera { pitch: 0.0, ..Default::default() }; let depth = EyeDepth::render_with_triangles(&mesh, &camera, 8192, 1024); + assert_eq!((depth.width, depth.height), (8192, 1024), "no side is capped"); let point = camera.project(Vec3::new(5.5, 0.0, 0.0), 8.0).unwrap(); let x = ((point.x * 0.5 + 0.5) * depth.width as f32) as usize; let y = ((0.5 - point.y * 0.5) * depth.height as f32) as usize; - assert_eq!(depth.triangle[y * depth.width as usize + x], 0, "the triangle stays under its viewport position after the buffer is capped"); + assert_eq!(depth.triangle[y * depth.width as usize + x], 0, "the triangle stays under its viewport position"); } #[test] diff --git a/crates/render/src/composite_package/shader_flags.rs b/crates/render/src/composite_package/shader_flags.rs index 1fd1becd3..7028cc08d 100644 --- a/crates/render/src/composite_package/shader_flags.rs +++ b/crates/render/src/composite_package/shader_flags.rs @@ -26,6 +26,11 @@ impl ShaderFlags { } } + /// These flags with the full brush package (a live clone or smudge stroke's variant) + pub(in super::super) fn with_brush(self) -> Self { + Self { brush: true, ..self } + } + #[cfg(all(test, not(target_arch = "wasm32")))] pub(in super::super) const ALL: Self = Self { projection: true, projection_uv_images: false, point: true, stack: true, lighting: true, brush: true, udim: true }; diff --git a/crates/render/src/composite_pipeline/composite_pipelines.rs b/crates/render/src/composite_pipeline/composite_pipelines.rs index a91b5066d..da82f8ba1 100644 --- a/crates/render/src/composite_pipeline/composite_pipelines.rs +++ b/crates/render/src/composite_pipeline/composite_pipelines.rs @@ -14,6 +14,8 @@ pub(in crate::gpu_composite) struct CompositePipelines { pub(super) supports_id: bool, pub(super) supports_fields: bool, variants: BTreeMap, + /// The features and grouping of each texture set's last viewport program + composited: BTreeMap, } /// The pipelines a compositor uses: its own, or when `shared` (a compositor on the device tests @@ -40,7 +42,7 @@ pub(in crate::gpu_composite) fn shared(shared: bool, supports_curvature: bool, s fn compile_checked(device: &wgpu::Device, label: &str, compile: impl FnOnce() -> wgpu::ComputePipeline) -> Result { let scoped = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| crate::gpu_trace::scoped(device, label, compile))); match scoped { - Ok(result) => result.map_err(|error| format!("GPU pipeline {label} failed to compile: {error}")), + Ok(result) => result.map_err(|error| compile_error(label, error)), Err(panic) => { let message = panic.downcast_ref::().cloned().or_else(|| panic.downcast_ref::<&str>().map(|text| text.to_string())); Err(format!("GPU pipeline {label} failed to compile: {}", message.unwrap_or_default())) @@ -48,9 +50,16 @@ fn compile_checked(device: &wgpu::Device, label: &str, compile: impl FnOnce() -> } } +/// A compile's error as the caller sees it: a lack of GPU memory stays as the device reported it, +/// so callers free their caches and retry; other errors name the pipeline. +#[cfg(not(target_arch = "wasm32"))] +fn compile_error(label: &str, error: String) -> String { + if crate::gpu_memory::is_out_of_memory(&error) { error } else { format!("GPU pipeline {label} failed to compile: {error}") } +} + impl CompositePipelines { pub(in crate::gpu_composite) fn new(supports_curvature: bool, supports_id: bool, supports_fields: bool) -> Self { - Self { supports_curvature, supports_id, supports_fields, variants: BTreeMap::new() } + Self { supports_curvature, supports_id, supports_fields, variants: BTreeMap::new(), composited: BTreeMap::new() } } /// Start compiling `program`'s pipelines without waiting (`get` returns them once ready). @@ -58,6 +67,31 @@ impl CompositePipelines { let _ = self.get(device, layout, program, !cfg!(target_arch = "wasm32")); } + /// Remember the variant of texture set `ts`'s viewport program `program` + pub(in crate::gpu_composite) fn remember(&mut self, ts: usize, program: &CompositeProgram) { + self.composited.insert(ts, (PipelineFeatures::of(program), program.groups.depth != 0)); + } + + /// Forget the remembered variants of all sets + pub(in crate::gpu_composite) fn forget(&mut self) { + self.composited.clear(); + } + + /// Start compiling, without waiting, the variant a live clone or smudge stroke on texture + /// set `ts` composites with: its last viewport program's with the full brush package. True + /// once it is compiled. + pub(in crate::gpu_composite) fn prewarm_pickup(&mut self, device: &wgpu::Device, layout: &wgpu::PipelineLayout, ts: usize) -> bool { + let Some(&(features, grouped)) = self.composited.get(&ts) else { return false }; + matches!(self.variant(device, layout, features.with_brush(), grouped, !cfg!(target_arch = "wasm32")), Ok(Some(_))) + } + + /// Whether the live clone or smudge variant of texture set `ts`'s last viewport program has + /// started compiling + #[cfg(all(test, not(target_arch = "wasm32")))] + pub(in crate::gpu_composite) fn has_pickup_variant(&self, ts: usize) -> bool { + self.composited.get(&ts).is_some_and(|(features, _)| self.variants.contains_key(&features.with_brush())) + } + /// The program's compose and prepare pipelines; None while one still compiles (new ones /// compile on worker threads when `asynchronous`: the viewport keeps its last result), an /// error when a worker's compile failed. @@ -68,7 +102,17 @@ impl CompositePipelines { program: &CompositeProgram, asynchronous: bool, ) -> Result)>, String> { - let features = PipelineFeatures::of(program); + self.variant(device, layout, PipelineFeatures::of(program), program.groups.depth != 0, asynchronous) + } + + fn variant( + &mut self, + device: &wgpu::Device, + layout: &wgpu::PipelineLayout, + features: PipelineFeatures, + grouped: bool, + asynchronous: bool, + ) -> Result)>, String> { let supports_curvature = self.supports_curvature; let supports_id = self.supports_id; let supports_fields = self.supports_fields; @@ -113,7 +157,6 @@ impl CompositePipelines { PipelineSlot::Ready(compile()) }; - let grouped = program.groups.depth != 0; let render = variants.render[usize::from(grouped)].get_or_insert_with(|| pipeline("compose", "tc_gpu_composite", grouped)).ready(!asynchronous)?; // Only material anchors need the group structure in the prepare pass @@ -135,9 +178,19 @@ impl CompositePipelines { #[cfg(test)] #[cfg(not(target_arch = "wasm32"))] mod tests { - use super::compile_checked; + use super::{compile_checked, compile_error}; use crate::headless::Headless; + /// A compile that runs out of GPU memory keeps the device's error, so the renderer frees its + /// cached inputs and retries instead of treating it as a refusal. + #[test] + fn a_compile_out_of_memory_stays_an_out_of_memory_error() { + let oom = crate::gpu_memory::out_of_memory_error("tc_test_pipeline", "allocation failed"); + assert!(crate::gpu_memory::is_out_of_memory(&compile_error("tc_test_pipeline", oom))); + let other = compile_error("tc_test_pipeline", "validation".into()); + assert!(other.contains("tc_test_pipeline") && !crate::gpu_memory::is_out_of_memory(&other)); + } + /// A pipeline the device rejects (an entry point the module lacks) must come back from the /// worker-side compile as an error, even though the app's uncaptured-error handler only logs: /// without an error scope on the worker the slot would be Ready with an invalid pipeline. diff --git a/crates/render/src/composite_pipeline/mod.rs b/crates/render/src/composite_pipeline/mod.rs index b4ec00ccb..b31763a23 100644 --- a/crates/render/src/composite_pipeline/mod.rs +++ b/crates/render/src/composite_pipeline/mod.rs @@ -24,6 +24,7 @@ mod tests { }) .collect(); variants.push(PipelineFeatures { mask_preview: true, spatial: true, mask_effects: true, packages: ShaderFlags::ALL, ..PipelineFeatures::default() }); + variants.push(PipelineFeatures { thumb: 1, mask_effects: true, content_effects: true, ..PipelineFeatures::default() }); // Generators without authored images: Grayscale Conversion's image read is a stub variants.push(PipelineFeatures { generators: true, mask_effects: true, ..PipelineFeatures::default() }); @@ -35,6 +36,7 @@ mod tests { authored_images: true, built_in_image_fills: true, mask_preview: false, + thumb: 0, extended_blend_modes: true, generators: true, generator_controls: true, diff --git a/crates/render/src/composite_pipeline/pipeline_features.rs b/crates/render/src/composite_pipeline/pipeline_features.rs index 5d86d4f58..32d79ad78 100644 --- a/crates/render/src/composite_pipeline/pipeline_features.rs +++ b/crates/render/src/composite_pipeline/pipeline_features.rs @@ -13,6 +13,8 @@ pub(super) struct PipelineFeatures { pub(super) authored_images: bool, pub(super) built_in_image_fills: bool, pub(super) mask_preview: bool, + // A layer thumbnail's output mode (`CompositeProgram::set_thumbnail`), 0 for none + pub(super) thumb: u32, pub(super) extended_blend_modes: bool, pub(super) generators: bool, // P1: an operation on the wear, section or light controls @@ -37,11 +39,17 @@ pub(super) struct PipelineFeatures { } impl PipelineFeatures { + /// These features with the full brush package (`composite_brush.wgsl`) + pub(super) fn with_brush(self) -> Self { + Self { packages: self.packages.with_brush(), ..self } + } + pub(super) fn of(program: &CompositeProgram) -> Self { let mut features = Self { material_underlay: program.underlay.is_some(), authored_images: !program.material_images.is_empty(), mask_preview: program.is_mask_preview(), + thumb: program.thumb[0], spatial: !program.filters.stages.is_empty(), packages: ShaderFlags::of(program), capture: program.micro.is_capture(), @@ -211,7 +219,7 @@ impl PipelineFeatures { .join("\n") } - pub(super) fn constants(self, grouped: bool) -> [(&'static str, f64); 9] { + pub(super) fn constants(self, grouped: bool) -> [(&'static str, f64); 10] { [ ("enable_authored_images", f64::from(u8::from(self.built_in_image_fills))), ("enable_generators", f64::from(u8::from(self.generators))), @@ -222,6 +230,7 @@ impl PipelineFeatures { ("composite_mask_preview", f64::from(u8::from(self.mask_preview))), ("enable_extended_blend_modes", f64::from(u8::from(self.extended_blend_modes))), ("composite_capture", f64::from(u8::from(self.capture))), + ("composite_thumb", f64::from(self.thumb)), ] } } diff --git a/crates/render/src/gpu_alpha.rs b/crates/render/src/gpu_alpha.rs new file mode 100644 index 000000000..5fbd3b9d2 --- /dev/null +++ b/crates/render/src/gpu_alpha.rs @@ -0,0 +1,193 @@ +//! The built-in library alphas generated on the GPU (`shaders/alpha_gen.wgsl`) at the size a +//! brush needs, with their mip chain: the brush's tip texture. The CPU generators in +//! `texturecraft_paint::alphas` stay the GPU-off path and the oracle. + +use texturecraft_paint::alphas::{AA, AlphaSpec, MIN_LEVEL}; +use wgpu::util::DeviceExt; + +/// Texels one submission of the generator draws: larger tips split into bands of rows (the tests +/// split their tips too) +const BAND_TEXELS: u32 = if cfg!(test) { 1 << 18 } else { 1 << 22 }; + +/// The generator's compiled passes, created on first use +pub(crate) struct AlphaGenerator { + generate: wgpu::ComputePipeline, + downsample: wgpu::ComputePipeline, +} + +/// Mip levels of a square alpha of `side` texels: halved down to [`MIN_LEVEL`], as the CPU image +pub(crate) fn alpha_levels(side: u32) -> u32 { + let mut levels = 1; + while side >> levels >= MIN_LEVEL as u32 { + levels += 1; + } + levels +} + +impl AlphaGenerator { + pub(crate) fn new(device: &wgpu::Device) -> AlphaGenerator { + let source = [include_str!("shaders/noise.wgsl"), include_str!("shaders/alpha_gen.wgsl")].join("\n"); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("tc_alpha_gen"), source: wgpu::ShaderSource::Wgsl(source.into()) }); + let pipeline = |entry: &str| { + device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("tc_alpha_gen"), + layout: None, + module: &module, + entry_point: Some(entry), + compilation_options: Default::default(), + cache: None, + }) + }; + AlphaGenerator { generate: pipeline("generate"), downsample: pipeline("downsample") } + } + + /// `spec` drawn at `side` texels a side (one sample per texel centre) into a new R32Float + /// texture with its mip chain (each level the mean of 2×2 texels of the one above) + pub(crate) fn generate(&self, device: &wgpu::Device, queue: &wgpu::Queue, spec: &AlphaSpec, side: u32) -> wgpu::Texture { + let levels = alpha_levels(side); + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("tc_library_alpha"), + size: wgpu::Extent3d { width: side, height: side, depth_or_array_layers: 1 }, + mip_level_count: levels, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::R32Float, + usage: wgpu::TextureUsages::STORAGE_BINDING | wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC, + view_formats: &[], + }); + let level = |mip: u32| texture.create_view(&wgpu::TextureViewDescriptor { base_mip_level: mip, mip_level_count: Some(1), ..Default::default() }); + + let mut words = [0u32; 16]; + words[..4].copy_from_slice(&[spec.kind, side, spec.seed, spec.items.len() as u32]); + for (word, value) in words[4..12].iter_mut().zip(spec.values) { + *word = value.to_bits(); + } + words[12] = AA.to_bits(); + + // A storage binding is never empty + let items: Vec<[f32; 4]> = if spec.items.is_empty() { vec![[0.0; 4]] } else { spec.items.clone() }; + let items = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("tc_library_alpha_items"), + contents: bytemuck::cast_slice(&items), + usage: wgpu::BufferUsages::STORAGE, + }); + let top_level = level(0); + + // Large tips generate in bands of rows (the first row in word 13), each its own + // submission, so no single dispatch runs long + let band_rows = ((BAND_TEXELS / side).max(8) & !7).min(side); + for top in (0..side).step_by(band_rows as usize) { + words[13] = top; + let uniform = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("tc_library_alpha_spec"), + contents: bytemuck::cast_slice(&words), + usage: wgpu::BufferUsages::UNIFORM, + }); + let entries = [ + wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 1, resource: items.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(&top_level) }, + ]; + let bind_group = + device.create_bind_group(&wgpu::BindGroupDescriptor { label: None, layout: &self.generate.get_bind_group_layout(0), entries: &entries }); + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_library_alpha") }); + let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("tc_library_alpha"), timestamp_writes: None }); + pass.set_pipeline(&self.generate); + pass.set_bind_group(0, &bind_group, &[]); + pass.dispatch_workgroups(side.div_ceil(8), band_rows.min(side - top).div_ceil(8), 1); + drop(pass); + queue.submit([encoder.finish()]); + } + + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_library_alpha") }); + for mip in 1..levels { + let (above, below) = (level(mip - 1), level(mip)); + let entries = [ + wgpu::BindGroupEntry { binding: 2, resource: wgpu::BindingResource::TextureView(&below) }, + wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(&above) }, + ]; + let bind_group = + device.create_bind_group(&wgpu::BindGroupDescriptor { label: None, layout: &self.downsample.get_bind_group_layout(0), entries: &entries }); + dispatch(&mut encoder, &self.downsample, &bind_group, side >> mip); + } + queue.submit([encoder.finish()]); + texture + } +} + +fn dispatch(encoder: &mut wgpu::CommandEncoder, pipeline: &wgpu::ComputePipeline, bind_group: &wgpu::BindGroup, side: u32) { + let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("tc_library_alpha"), timestamp_writes: None }); + pass.set_pipeline(pipeline); + pass.set_bind_group(0, bind_group, &[]); + let groups = side.div_ceil(8); + pass.dispatch_workgroups(groups, groups, 1); +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + + use texturecraft_paint::alphas::{LibraryAlphaParams, library}; + + use super::*; + use crate::headless::Headless; + use crate::readback::Readback; + + /// Every library alpha of `category` generated on the GPU at a side past the CPU image's + /// 512 texels matches the CPU generator rendered at that side (one sample per texel), with + /// its first mip level the mean of the finest level's 2×2 blocks + fn family_matches_the_cpu(category: &str) { + let Some(gpu) = Headless::for_required_tests() else { return }; + let generator = AlphaGenerator::new(&gpu.device); + let side = 1024; + let alphas: Vec<_> = library().iter().filter(|alpha| alpha.category == category).collect(); + assert!(!alphas.is_empty(), "{category}"); + for alpha in alphas { + // The defaults, then every setting halfway through its range + let halfway: LibraryAlphaParams = alpha.options().iter().map(|option| (option.control, (option.minimum + option.maximum) * 0.5)).collect(); + for params in [LibraryAlphaParams::new(), halfway] { + let texture = generator.generate(&gpu.device, &gpu.queue, &alpha.gpu_spec(¶ms), side); + let (width, height, bytes) = Readback::blocking(&gpu.device, &gpu.queue, &texture).unwrap(); + assert_eq!((width, height), (side, side)); + let on_gpu: Vec = bytemuck::pod_collect_to_vec(&bytes); + let on_cpu = alpha.render_configured(side as usize, 1, ¶ms); + let differing = on_gpu.iter().zip(&on_cpu).filter(|(g, c)| (*g - *c).abs() > 0.02).count(); + assert!(differing * 200 <= on_cpu.len(), "{} {params:?}: {differing} texels differ", alpha.id); + + let (half, _, bytes) = Readback::blocking_level(&gpu.device, &gpu.queue, &texture, 1).unwrap(); + let level: Vec = bytemuck::pod_collect_to_vec(&bytes); + let at = |x: u32, y: u32| on_gpu[(y * side + x) as usize]; + for (texel, value) in level.iter().enumerate() { + let (x, y) = (texel as u32 % half, texel as u32 / half); + let mean = (at(2 * x, 2 * y) + at(2 * x + 1, 2 * y) + at(2 * x, 2 * y + 1) + at(2 * x + 1, 2 * y + 1)) * 0.25; + assert!((value - mean).abs() < 1e-5, "{}: mip", alpha.id); + } + } + } + } + + #[test] + fn basic_alphas_generate_on_the_gpu_as_on_the_cpu() { + family_matches_the_cpu("Basic"); + } + + #[test] + fn grunge_alphas_generate_on_the_gpu_as_on_the_cpu() { + family_matches_the_cpu("Grunge"); + } + + #[test] + fn organic_alphas_generate_on_the_gpu_as_on_the_cpu() { + family_matches_the_cpu("Organic"); + } + + #[test] + fn hard_surface_alphas_generate_on_the_gpu_as_on_the_cpu() { + family_matches_the_cpu("Hard surface"); + } + + #[test] + fn stencil_letters_generate_on_the_gpu_as_on_the_cpu() { + family_matches_the_cpu("Stencil letters"); + } +} diff --git a/crates/render/src/gpu_aux_view.rs b/crates/render/src/gpu_aux_view.rs new file mode 100644 index 000000000..c3cfc9028 --- /dev/null +++ b/crates/render/src/gpu_aux_view.rs @@ -0,0 +1,80 @@ +//! The aux views drawn on the GPU: the mesh-map, image and ID-mask views and their flat fills, +//! sampled from their source texels into a texture set's aux texture at its display size, as +//! their CPU producers ([`crate::mesh_maps::mesh_map_rgba`], `Session::image_view_rgba`, +//! `Session::id_mask_view_rgba`) do where layers composite on the CPU. + +mod aux_source; +mod aux_view_gpu; +mod source_owner; + +pub use aux_source::AuxSource; +pub(crate) use aux_view_gpu::AuxViewGpu; + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + #![allow(clippy::unwrap_used)] + + use std::sync::Arc; + + use texturecraft_compose::BakedMaps; + use texturecraft_core::{BakedMap, TextureSet}; + + use super::AuxSource; + use crate::headless::Headless; + use crate::readback::Readback; + + /// The largest difference of any channel between two RGBA8 images of the same size + fn max_difference(a: &[u8], b: &[u8]) -> u8 { + assert_eq!(a.len(), b.len()); + a.iter().zip(b).map(|(a, b)| a.abs_diff(*b)).max().unwrap_or(0) + } + + /// A map with more floats than the device's widest texture holds in rows wraps into layers + #[test] + fn source_texels_past_the_texture_side_wrap_into_layers() { + let Ok(mut h) = Headless::for_tests_with_limits(|adapter| wgpu::Limits { max_texture_dimension_2d: 512, ..adapter.limits() }) else { return }; + let set = TextureSet::new("Small", 0, 512); + let (size, scales) = (set.size(), set.block_scales()); + h.renderer.set_texture_sets(&h.device, &h.queue, &[(size, 0)], 1); + let normal: Vec = (0..512 * 512 * 3).map(|i| ((i * 7) % 255) as f32 / 255.0).collect(); + let baked = BakedMaps { resolution: 512, maps: [(BakedMap::Normal, Arc::new(normal))].into() }; + + h.renderer.draw_aux_view(&h.device, &h.queue, 0, &AuxSource::mesh_map(Some(&baked), BakedMap::Normal, &scales)).unwrap(); + + let (_, _, gpu) = Readback::blocking(&h.device, &h.queue, h.renderer.aux_texture(0).unwrap()).unwrap(); + let cpu = crate::mesh_maps::mesh_map_rgba(Some(&baked), BakedMap::Normal, crate::aux_extent(size, 0), size, &scales); + assert!(max_difference(&gpu, &cpu) <= 1, "786432 floats in 512-wide rows take 3 layers of 512 rows"); + } + + #[test] + fn the_gpu_draws_mesh_maps_at_the_display_size_as_the_cpu_samples_them() { + let Some(mut h) = Headless::for_required_tests() else { return }; + + // Two UV tiles side by side, the second at half resolution: a wide set with block scales + let mut set = TextureSet::new("Tiles", 0, 256); + set.uv_tiles = vec![1001, 1002]; + set.tile_resolutions.insert(1002, 128); + let (size, scales) = (set.size(), set.block_scales()); + h.renderer.set_texture_sets(&h.device, &h.queue, &[(size, 0)], 1); + let occlusion: Vec = (0..128 * 256).map(|i| ((i % 256) + i / 256) as f32 / 400.0).collect(); + let normal: Vec = (0..128 * 256 * 3).map(|i| (i % 7) as f32 / 6.0 + if i % 3 == 0 { 0.4 } else { 0.0 }).collect(); + let baked = BakedMaps { resolution: 256, maps: [(BakedMap::AmbientOcclusion, Arc::new(occlusion)), (BakedMap::Normal, Arc::new(normal))].into() }; + let extent = crate::aux_extent(size, 0); + + for map in [BakedMap::AmbientOcclusion, BakedMap::Normal, BakedMap::Curvature] { + h.renderer.draw_aux_view(&h.device, &h.queue, 0, &AuxSource::mesh_map(Some(&baked), map, &scales)).unwrap(); + let (width, height, gpu) = Readback::blocking(&h.device, &h.queue, h.renderer.aux_texture(0).unwrap()).unwrap(); + let cpu = crate::mesh_maps::mesh_map_rgba(Some(&baked), map, extent, size, &scales); + + assert_eq!((width, height), extent, "{map:?}: the set's display size, not a square"); + assert!(width > height); + assert!( + max_difference(&gpu, &cpu) <= 1, + "{map:?}: GPU and CPU views differ by {} ({:?} vs {:?})", + max_difference(&gpu, &cpu), + &gpu[..8], + &cpu[..8] + ); + } + } +} diff --git a/crates/render/src/gpu_aux_view/aux_source.rs b/crates/render/src/gpu_aux_view/aux_source.rs new file mode 100644 index 000000000..7a60ad660 --- /dev/null +++ b/crates/render/src/gpu_aux_view/aux_source.rs @@ -0,0 +1,42 @@ +use std::sync::Arc; + +use texturecraft_compose::{BakedMaps, ImageRes}; +use texturecraft_core::{BakedMap, BlockScales}; + +/// What [`crate::Renderer::draw_aux_view`] draws into a texture set's aux texture. +#[derive(Clone, Debug)] +pub enum AuxSource { + /// One display-encoded RGBA8 color everywhere: a blank view, or a map not baked yet + Fill([u8; 4]), + /// A baked map's texels (`components` floats each, `width` texels a row) placed over the + /// texture set through its block scales, as [`crate::mesh_maps::mesh_map_rgba`] places them + MeshMap { data: Arc>, components: usize, width: u32, block_scales: BlockScales }, + /// An image stretched over the texture set, bilinear (the "Other..." image view) + Image(Arc), + /// An image a color selection reads as its ID mask: each view texel shows the image texel + /// nearest its texture set texel's centre + IdMask(Arc), +} + +/// Mid gray: what the mesh-map view shows where a map is not baked (alpha as `mesh_map_rgba` leaves it) +const NOT_BAKED: [u8; 4] = [128; 4]; + +impl AuxSource { + /// Baked map `map` of `baked` on a texture set with `block_scales`, mid gray where not baked. + pub fn mesh_map(baked: Option<&BakedMaps>, map: BakedMap, block_scales: &BlockScales) -> AuxSource { + let Some((baked, data)) = baked.and_then(|baked| baked.maps.get(&map).map(|data| (baked, data))) else { return AuxSource::Fill(NOT_BAKED) }; + if baked.resolution == 0 || baked.height(map) == 0 { + return AuxSource::Fill(NOT_BAKED); + } + + AuxSource::MeshMap { data: data.clone(), components: map.components(), width: baked.resolution, block_scales: block_scales.clone() } + } + + /// The neutral value of map `m` everywhere (a map not baked yet during a bake), encoded as + /// [`crate::mesh_maps::neutral_rgba`] encodes it. + pub fn neutral(map: BakedMap) -> AuxSource { + let value = map.neutral(); + let [r, g, b] = [0, 1, 2].map(|k| (value[k].clamp(0.0, 1.0) * 255.0 + 0.5) as u8); + AuxSource::Fill([r, g, b, 255]) + } +} diff --git a/crates/render/src/gpu_aux_view/aux_view_gpu.rs b/crates/render/src/gpu_aux_view/aux_view_gpu.rs new file mode 100644 index 000000000..1bf4fd6a5 --- /dev/null +++ b/crates/render/src/gpu_aux_view/aux_view_gpu.rs @@ -0,0 +1,192 @@ +use std::sync::Arc; + +use wgpu::util::DeviceExt; + +use super::AuxSource; +use super::source_owner::SourceOwner; + +/// The aux view pipeline and the source texels it uploaded, kept while their owners live +pub(crate) struct AuxViewGpu { + pub(crate) pipeline: wgpu::RenderPipeline, + sources: Vec<(SourceOwner, wgpu::Texture)>, +} + +/// Mode words of `aux_view.wgsl` +const MESH_MAP: u32 = 0; +const IMAGE: u32 = 1; +const ID_MASK: u32 = 2; + +impl AuxViewGpu { + pub(crate) fn new(device: &wgpu::Device) -> Self { + let texture_entry = |binding, view_dimension| wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Texture { sample_type: wgpu::TextureSampleType::Float { filterable: false }, view_dimension, multisampled: false }, + count: None, + }; + let bindings = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("tc_aux_view"), + entries: &[ + texture_entry(0, wgpu::TextureViewDimension::D2Array), + texture_entry(1, wgpu::TextureViewDimension::D2), + wgpu::BindGroupLayoutEntry { + binding: 2, + visibility: wgpu::ShaderStages::FRAGMENT, + ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None }, + count: None, + }, + ], + }); + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("tc_aux_view"), + bind_group_layouts: &[Some(&bindings)], + immediate_size: 0, + }); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("tc_aux_view"), + source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/aux_view.wgsl").into()), + }); + let pipeline = device.create_render_pipeline(&wgpu::RenderPipelineDescriptor { + label: Some("tc_aux_view"), + layout: Some(&layout), + vertex: wgpu::VertexState { module: &module, entry_point: Some("vs"), compilation_options: Default::default(), buffers: &[] }, + fragment: Some(wgpu::FragmentState { + module: &module, + entry_point: Some("fs"), + compilation_options: Default::default(), + targets: &[Some(wgpu::TextureFormat::Rgba8Unorm.into())], + }), + primitive: Default::default(), + depth_stencil: None, + multisample: Default::default(), + multiview_mask: None, + cache: None, + }); + Self { pipeline, sources: Vec::new() } + } + + /// Drop every uploaded source (the aux view changed, or memory ran out). + pub(crate) fn release_sources(&mut self) { + self.sources.clear(); + } + + /// The bind group drawing `source` into an aux texture of `extent` on a texture set of + /// `working` texels; None for a flat fill (a clear draws it). + pub(crate) fn bindings( + &mut self, + (device, queue): (&wgpu::Device, &wgpu::Queue), + source: &AuxSource, + extent: (u32, u32), + working: (u32, u32), + ) -> Option { + self.sources.retain(|(owner, _)| owner.alive()); + let (mode, components, size, values) = match source { + AuxSource::Fill(_) => return None, + AuxSource::MeshMap { data, components, width, .. } => { + let height = (data.len() / (*width as usize * components).max(1)) as u32; + let values = self.values(device, queue, SourceOwner::Map(Arc::downgrade(data)), &data[..(*width as usize) * (height as usize) * components]); + (MESH_MAP, *components as u32, (*width, height), values) + } + AuxSource::Image(image) | AuxSource::IdMask(image) => { + let mode = if matches!(source, AuxSource::Image(_)) { IMAGE } else { ID_MASK }; + let texels = &image.rgba[..(image.width as usize * image.height as usize).min(image.rgba.len())]; + let values = self.values(device, queue, SourceOwner::Image(Arc::downgrade(image)), bytemuck::cast_slice(texels)); + (mode, 4, (image.width, image.height), values) + } + }; + + let (block, columns, scales) = match source { + AuxSource::MeshMap { block_scales, .. } => block_scales.layout(), + _ => (0, 0, &[][..]), + }; + let (block, scales) = if scales.is_empty() { (0, &[1.0][..]) } else { (block.max(1), scales) }; + let scale_texture = device.create_texture_with_data( + queue, + &wgpu::TextureDescriptor { + label: Some("tc_aux_view_scales"), + size: wgpu::Extent3d { width: scales.len() as u32, height: 1, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::R32Float, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }, + wgpu::util::TextureDataOrder::LayerMajor, + bytemuck::cast_slice(scales), + ); + let params = [mode, components, block, columns, extent.0, extent.1, working.0, working.1, size.0, size.1, scales.len() as u32, 0]; + let uniforms = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("tc_aux_view_params"), + contents: bytemuck::cast_slice(¶ms), + usage: wgpu::BufferUsages::UNIFORM, + }); + let values = values.create_view(&wgpu::TextureViewDescriptor { dimension: Some(wgpu::TextureViewDimension::D2Array), ..Default::default() }); + let scales = scale_texture.create_view(&Default::default()); + Some(device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("tc_aux_view"), + layout: &self.pipeline.get_bind_group_layout(0), + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: wgpu::BindingResource::TextureView(&values) }, + wgpu::BindGroupEntry { binding: 1, resource: wgpu::BindingResource::TextureView(&scales) }, + wgpu::BindGroupEntry { binding: 2, resource: uniforms.as_entire_binding() }, + ], + })) + } + + /// The texture holding `values` for `owner`, uploaded on first use: one float per texel, + /// wrapped across the rows of the device's widest texture and, past its tallest, its layers. + fn values(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, owner: SourceOwner, values: &[f32]) -> wgpu::Texture { + if let Some((_, texture)) = self.sources.iter().find(|(entry, _)| entry.same(&owner)) { + return texture.clone(); + } + + let side = device.limits().max_texture_dimension_2d.max(1) as usize; + let count = values.len().max(1); + let width = count.min(side); + let rows = count.div_ceil(width); + let height = rows.min(side); + // GL picks a texture's target from its layers: at least two keep it an array (six of a square, a cube) + let layers = match rows.div_ceil(height).max(2) { + 6 if width == height => 7, + layers => layers, + }; + let texture = device.create_texture(&wgpu::TextureDescriptor { + label: Some("tc_aux_view_values"), + size: wgpu::Extent3d { width: width as u32, height: height as u32, depth_or_array_layers: layers as u32 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::R32Float, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }); + + // Whole rows of each layer, then the last row's start + let write = |first: usize, texels: &[f32]| { + let (layer, row) = (first / width / height, first / width % height); + queue.write_texture( + wgpu::TexelCopyTextureInfo { + texture: &texture, + mip_level: 0, + origin: wgpu::Origin3d { x: 0, y: row as u32, z: layer as u32 }, + aspect: wgpu::TextureAspect::All, + }, + bytemuck::cast_slice(texels), + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(width as u32 * 4), rows_per_image: None }, + wgpu::Extent3d { width: texels.len().min(width) as u32, height: texels.len().div_ceil(width) as u32, depth_or_array_layers: 1 }, + ); + }; + for (index, layer) in values.chunks(width * height).enumerate() { + let whole = layer.len() / width * width; + if whole > 0 { + write(index * width * height, &layer[..whole]); + } + if layer.len() > whole { + write(index * width * height + whole, &layer[whole..]); + } + } + self.sources.push((owner, texture.clone())); + texture + } +} diff --git a/crates/render/src/gpu_aux_view/source_owner.rs b/crates/render/src/gpu_aux_view/source_owner.rs new file mode 100644 index 000000000..64f21a5b1 --- /dev/null +++ b/crates/render/src/gpu_aux_view/source_owner.rs @@ -0,0 +1,28 @@ +use std::sync::Weak; + +use texturecraft_compose::ImageRes; + +/// Who owns uploaded aux view texels: a weak reference keeps the address from being reused while +/// the entry lives +pub(super) enum SourceOwner { + Map(Weak>), + Image(Weak), +} + +impl SourceOwner { + pub(super) fn alive(&self) -> bool { + match self { + SourceOwner::Map(map) => map.strong_count() > 0, + SourceOwner::Image(image) => image.strong_count() > 0, + } + } + + /// Whether both name the same owner + pub(super) fn same(&self, other: &SourceOwner) -> bool { + match (self, other) { + (SourceOwner::Map(a), SourceOwner::Map(b)) => a.ptr_eq(b), + (SourceOwner::Image(a), SourceOwner::Image(b)) => a.ptr_eq(b), + _ => false, + } + } +} diff --git a/crates/render/src/gpu_brush.rs b/crates/render/src/gpu_brush.rs index 10a740f6c..c72b3c98d 100644 --- a/crates/render/src/gpu_brush.rs +++ b/crates/render/src/gpu_brush.rs @@ -9,7 +9,7 @@ use texturecraft_geom::{ Bvh, Mesh, UvGBuffer, glam::{Mat4, Vec2}, }; -use texturecraft_paint::{BrushAlpha, BrushSettings, EyeDepth, Stamp, UvStamp, alphas::AlphaImage}; +use texturecraft_paint::{BrushAlpha, BrushSettings, CloneSource, EyeDepth, SmudgeSource, Stamp, UvStamp}; use texturecraft_texel::{TILE, TileImage}; use wgpu::util::DeviceExt; @@ -31,16 +31,21 @@ const PROJECTION_READBACK_TILES: usize = 64; mod brush_input; mod brush_pipeline; +mod clone_source; mod dab; mod gpu_brush_stroke; mod parameters; +mod pickup_source; +mod smudge; mod visibility; pub use brush_input::BrushInput; pub(crate) use brush_pipeline::BrushPipeline; +use brush_pipeline::SurfaceCovers; use dab::Dab; pub use gpu_brush_stroke::GpuBrushStroke; use parameters::Parameters; +pub(crate) use pickup_source::composite_pickup_source; use visibility::Visibility; // Clip the triangle to the dab's enclosing volume before binning its projected texels @@ -170,6 +175,8 @@ mod tests { alpha_image: None, stencil: Some(stencil.clone()), limit: None, + clone: None, + smudge: None, }; let mut stroke = gpu.renderer.start_gpu_brush(&gpu.device, &gpu.queue, input).unwrap(); let dab = UvStamp { center: Vec2::splat(0.5), radius: 0.41, angle: 0.0, flow: 0.8, hardness: 0.7, seed: 5, source: None }; @@ -226,6 +233,8 @@ mod tests { alpha_image: None, stencil: None, limit: None, + clone: None, + smudge: None, }; assert!(gpu.renderer.start_gpu_brush(&gpu.device, &gpu.queue, input).is_err()); } @@ -245,6 +254,8 @@ mod tests { alpha_image: None, stencil: None, limit: None, + clone: None, + smudge: None, }; let stroke = gpu.renderer.start_gpu_brush(&gpu.device, &gpu.queue, input).unwrap(); @@ -273,6 +284,8 @@ mod tests { alpha_image: None, stencil: None, limit: None, + clone: None, + smudge: None, }; let dab = |center: Vec2| UvStamp { center, radius: 0.1, angle: 0.0, flow: 0.9, hardness: 0.8, seed: 0, source: None }; let mut first = gpu.renderer.start_gpu_brush(&gpu.device, &gpu.queue, input()).unwrap(); @@ -320,6 +333,8 @@ mod tests { alpha_image: None, stencil: None, limit: None, + clone: None, + smudge: None, }; let uv_dab = UvStamp { center: Vec2::splat(0.48), radius: 0.29, angle: 35.0, flow: 0.8, hardness: 0.6, seed, source: None }; @@ -412,7 +427,7 @@ mod tests { let mut cpu = StrokeCanvas::new(size, size); rasterize(&mut cpu, &context, dabs); - let input = BrushInput { mesh, bvh, uv, material: 0, depth, settings, alpha_image, stencil: None, limit: None }; + let input = BrushInput { mesh, bvh, uv, material: 0, depth, settings, alpha_image, stencil: None, limit: None, clone: None, smudge: None }; let mut stroke = gpu.renderer.start_gpu_brush(&gpu.device, &gpu.queue, input).unwrap(); let tiles = stroke.append_world(dabs).unwrap(); (cpu.alpha, stroke.read_alpha(&tiles).unwrap()) @@ -552,6 +567,80 @@ mod tests { assert!(actual.get(64, 64)[0] > 0, "the copy paints the visible texel"); } + /// A library alpha is generated on the GPU at the texture set's side (past the CPU image's + /// 512 texels), not at a fixed size + #[test] + fn a_library_tip_is_generated_at_the_sets_side() { + let Some(mut gpu) = Headless::for_required_tests() else { return }; + let size = 2048; + let mesh = Arc::new(primitives::plane(1.0, 1)); + let bvh = Arc::new(Bvh::new(&mesh)); + let uv = Arc::new(UvGBuffer::new(&mesh, 0, size, size)); + let settings = BrushSettings { alpha_library: Some("scratches".into()), size: 0.5, ..Default::default() }; + let input = || BrushInput { + mesh: mesh.clone(), + bvh: bvh.clone(), + uv: uv.clone(), + material: 0, + depth: None, + settings: settings.clone(), + alpha_image: None, + stencil: None, + limit: None, + clone: None, + smudge: None, + }; + + // A failed start keeps no tip its error may have left invalid: the retry generates it + gpu.renderer.fail_next_gpu_attempts(1); + assert!(gpu.renderer.start_gpu_brush(&gpu.device, &gpu.queue, input()).is_err()); + assert_eq!(gpu.renderer.library_tip_side(), None); + gpu.renderer.start_gpu_brush(&gpu.device, &gpu.queue, input()).unwrap(); + + assert_eq!(gpu.renderer.library_tip_side(), Some(size.min(gpu.device.limits().max_texture_dimension_2d))); + assert_eq!(brush_pipeline::library_tip_side(0.05, (size, size), u32::MAX), 512, "a small brush keeps the CPU image's side"); + assert_eq!(brush_pipeline::library_tip_side(0.5, (8192, 4096), 4096), 4096, "the device's texture side bounds the tip"); + } + + /// A failed start drops the surface covers it allocated: the retry allocates them again + #[test] + fn a_failed_start_keeps_no_surface_covers() { + let Some(mut gpu) = Headless::for_required_tests() else { return }; + let wall = |shift: f32| [(-1.0, -1.0), (1.0, -1.0), (-1.0, 1.0), (1.0, 1.0)].map(|(x, y)| Vec3::new(x + shift, y, 0.0)); + let uvs = [(0.1, 0.9), (0.9, 0.9), (0.1, 0.1), (0.9, 0.1)].map(|(u, v)| Vec2::new(u, v)); + let mesh = Arc::new( + Mesh::from_parts( + wall(0.0).into_iter().chain(wall(4.0)).collect(), + None, + uvs.into_iter().chain(uvs).collect(), + vec![0, 1, 2, 2, 1, 3, 4, 5, 6, 6, 5, 7], + "Walls", + ) + .unwrap(), + ); + let (bvh, uv) = (Arc::new(Bvh::new(&mesh)), Arc::new(UvGBuffer::new(&mesh, 0, 64, 64))); + assert!(uv.shared_surfaces); + let input = || BrushInput { + mesh: mesh.clone(), + bvh: bvh.clone(), + uv: uv.clone(), + material: 0, + depth: None, + settings: BrushSettings::default(), + alpha_image: None, + stencil: None, + limit: None, + clone: None, + smudge: None, + }; + + gpu.renderer.fail_next_gpu_attempts(1); + assert!(gpu.renderer.start_gpu_brush(&gpu.device, &gpu.queue, input()).is_err()); + assert!(!gpu.renderer.has_brush_covers(), "the failed start's covers are dropped"); + gpu.renderer.start_gpu_brush(&gpu.device, &gpu.queue, input()).unwrap(); + assert!(gpu.renderer.has_brush_covers(), "a started brush keeps its covers for the next stroke"); + } + #[test] fn symmetry_copies_paint_library_and_image_tips_like_the_cpu() { use texturecraft_geom::glam::Mat3; @@ -583,6 +672,47 @@ mod tests { assert_coverage_matches(&cpu, &actual, "mirrored image tip"); } + /// Two walls 4 apart with the same UVs: a dab on either wall paints the texels it covers, + /// whichever wall owns them in the G-buffer, as the CPU raster does. + #[test] + fn world_dabs_paint_every_surface_sharing_the_texels() { + let Some(mut gpu) = Headless::for_required_tests() else { return }; + let wall = |shift: f32| [(-1.0, -1.0), (1.0, -1.0), (-1.0, 1.0), (1.0, 1.0)].map(|(x, y)| Vec3::new(x + shift, y, 0.0)); + let uvs = [(0.1, 0.9), (0.9, 0.9), (0.1, 0.1), (0.9, 0.1)].map(|(u, v)| Vec2::new(u, v)); + let mesh = Mesh::from_parts( + wall(0.0).into_iter().chain(wall(4.0)).collect(), + Some(vec![Vec3::Z; 8]), + uvs.into_iter().chain(uvs).collect(), + vec![0, 1, 2, 2, 1, 3, 4, 5, 6, 6, 5, 7], + "Walls sharing UVs", + ) + .unwrap(); + assert!(UvGBuffer::new(&mesh, 0, 128, 128).shared_surfaces); + + let dab = |center: Vec3| Stamp { + center, + normal: Vec3::Z, + tangent: Vec3::X, + bitangent: Vec3::Y, + radius: 0.3, + flow: 0.8, + hardness: 0.5, + depth: 1.0, + seed: 0, + source: None, + }; + let settings = BrushSettings { backface_culling: false, ..Default::default() }; + let (cpu, actual) = world_brush_coverage(&mut gpu, mesh, settings, None, &[dab(Vec3::new(-0.5, 0.3, 0.0)), dab(Vec3::new(4.5, -0.3, 0.0))]); + + // One of the two spots lies on texels the other wall owns + for (x, y) in [(38, 48), (89, 79)] { + let expected = cpu.get(x, y)[0]; + assert!(expected > 0, "the CPU paints the spot at texel ({x}, {y})"); + assert!(actual.get(x, y)[0].abs_diff(expected) <= 257, "GPU {} vs CPU {expected} at texel ({x}, {y})", actual.get(x, y)[0]); + } + assert_coverage_matches(&cpu, &actual, "walls sharing UVs"); + } + #[test] fn world_stroke_stamp_blending_paints_both_sides_of_a_uv_seam() { let Ok(mut gpu) = Headless::new() else { return }; @@ -626,6 +756,8 @@ mod tests { alpha_image: None, stencil: None, limit: None, + clone: None, + smudge: None, }; let mut stroke = gpu.renderer.start_gpu_brush(&gpu.device, &gpu.queue, input).unwrap(); let tiles = stroke.append_world(&[dab]).unwrap(); diff --git a/crates/render/src/gpu_brush/brush_input.rs b/crates/render/src/gpu_brush/brush_input.rs index ef2ddd912..811aa679d 100644 --- a/crates/render/src/gpu_brush/brush_input.rs +++ b/crates/render/src/gpu_brush/brush_input.rs @@ -1,5 +1,5 @@ use super::ImageRes; -use super::{Arc, BrushSettings, Bvh, EyeDepth, Mesh, Stencil, TileImage, UvGBuffer}; +use super::{Arc, BrushSettings, Bvh, CloneSource, EyeDepth, Mesh, SmudgeSource, Stencil, TileImage, UvGBuffer}; pub struct BrushInput { pub mesh: Arc, @@ -11,4 +11,8 @@ pub struct BrushInput { pub alpha_image: Option>, pub stencil: Option, pub limit: Option<(TileImage, bool)>, + /// A clone stroke paints only where its source is read, weighed by the source's coverage + pub clone: Option, + /// A smudge stroke drags its source's values stamp by stamp + pub smudge: Option, } diff --git a/crates/render/src/gpu_brush/brush_pipeline.rs b/crates/render/src/gpu_brush/brush_pipeline.rs index c50bc42e7..761a9589c 100644 --- a/crates/render/src/gpu_brush/brush_pipeline.rs +++ b/crates/render/src/gpu_brush/brush_pipeline.rs @@ -1,28 +1,55 @@ -use super::{AlphaImage, IMAGE_ALPHA_KIND, LIBRARY_ALPHA_KIND}; +use super::smudge::{GpuSmudge, SmudgePipelines}; use super::{ - Arc, BTreeMap, BrushAlpha, BrushInput, Bvh, EyeDepth, GpuBrushStroke, GpuStencil, ImageRes, Mat4, Parameters, SpareAlpha, TILE, Tiles, Visibility, Weak, - clear_tiles, extent, gpu_stencil, storage, texture, + Arc, BTreeMap, BrushAlpha, BrushInput, Bvh, EyeDepth, GpuBrushStroke, GpuStencil, ImageRes, Mat4, Parameters, SpareAlpha, TILE, Tiles, UvGBuffer, + Visibility, Weak, clear_tiles, extent, gpu_stencil, storage, texture, }; +use super::{IMAGE_ALPHA_KIND, LIBRARY_ALPHA_KIND}; +use crate::gpu_alpha::AlphaGenerator; +use rayon::slice::ParallelSliceMut; +use texturecraft_paint::alphas::{LibraryAlpha, LibraryAlphaParams}; pub(crate) struct BrushPipeline { pub(super) shader: wgpu::ShaderModule, pub(super) layout: wgpu::PipelineLayout, - pub(super) pipelines: BTreeMap, + /// The kernel's inputs (group 0), shared by the smudge's measure + pub(super) inputs: wgpu::BindGroupLayout, + /// The smudge passes by alpha kind and shared surfaces, as `pipelines` + pub(super) smudge: BTreeMap<(u32, bool), SmudgePipelines>, + /// By alpha kind and whether the kernel evaluates the other surfaces sharing a texel's UVs + pub(super) pipelines: BTreeMap<(u32, bool), wgpu::ComputePipeline>, pub(super) rays: Option<(Weak, wgpu::Buffer, wgpu::Buffer)>, pub(super) depth: Option<(Weak, wgpu::TextureView)>, pub(super) stencil_image: Option<(Weak, wgpu::TextureView)>, - pub(super) library_tip: Option<(Weak, wgpu::TextureView)>, + /// The library alpha generated on the GPU: its id, settings and side, and its texture + pub(super) library_tip: Option<((String, LibraryAlphaParams, u32), wgpu::TextureView)>, + pub(super) alpha_generator: Option, pub(super) image_tip: Option<(Weak, wgpu::TextureView)>, pub(super) blank_tip: wgpu::TextureView, pub(super) projection_readback: Option, pub(super) spare_alpha: SpareAlpha, + /// The surfaces sharing UVs with each texel's owner, for the last G-buffer that has them + pub(super) covers: Option<(Weak, SurfaceCovers)>, + /// Bound when the set has no shared surfaces + pub(super) no_covers: SurfaceCovers, } +/// Per texel the first entry + 1 (0: none) in a list of covering triangles: each entry is the +/// triangle (high bit on the texel's last entry) and the bits of its weights of vertices 1 and 2 +#[derive(Clone)] +pub(super) struct SurfaceCovers { + pub(super) first: wgpu::TextureView, + pub(super) entries: wgpu::Buffer, +} + +/// Marks a texel's last covering triangle +const LAST_COVER: u32 = 1 << 31; + impl BrushPipeline { pub(crate) fn clear_visibility(&mut self) { self.rays = None; self.depth = None; self.stencil_image = None; + self.covers = None; } pub fn new(device: &wgpu::Device) -> Self { @@ -44,72 +71,110 @@ impl BrushPipeline { storage(8, true), storage(9, false), texture_entry(10, wgpu::TextureSampleType::Float { filterable: false }), + texture_entry(11, wgpu::TextureSampleType::Uint), + storage(12, true), ], }); let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { label: Some("tc_brush"), bind_group_layouts: &[Some(&inputs)], immediate_size: 0 }); - let source = concat!(include_str!("../shaders/rays.wgsl"), "\n", include_str!("../shaders/noise.wgsl"), "\n", include_str!("../shaders/brush.wgsl")); + let source = concat!( + include_str!("../shaders/rays.wgsl"), + "\n", + include_str!("../shaders/noise.wgsl"), + "\n", + include_str!("../shaders/brush.wgsl"), + "\n", + include_str!("../shaders/smudge.wgsl") + ); let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor { label: Some("tc_brush"), source: wgpu::ShaderSource::Wgsl(source.into()) }); let blank_tip = texture(device, [1, 1], wgpu::TextureFormat::R32Float).create_view(&Default::default()); + let no_covers = SurfaceCovers { + first: texture(device, [1, 1], wgpu::TextureFormat::R32Uint).create_view(&Default::default()), + entries: super::storage(device, "tc_brush_no_covers", &[0_u32; 3]), + }; Self { shader, layout, + inputs, + smudge: BTreeMap::new(), pipelines: BTreeMap::new(), rays: None, depth: None, stencil_image: None, library_tip: None, + alpha_generator: None, image_tip: None, blank_tip, projection_readback: None, spare_alpha: SpareAlpha::default(), + covers: None, + no_covers, } } - pub(super) fn pipeline(&mut self, device: &wgpu::Device, alpha_kind: u32) -> wgpu::ComputePipeline { - // Specialize by shape so the simple brushes keep their smaller GPU kernels + pub(super) fn pipeline(&mut self, device: &wgpu::Device, alpha_kind: u32, shared_surfaces: bool) -> wgpu::ComputePipeline { + // Specialize by shape and shared UVs so the simple brushes keep their smaller GPU kernels self.pipelines - .entry(alpha_kind) + .entry((alpha_kind, shared_surfaces)) .or_insert_with(|| { device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { label: Some("tc_brush"), layout: Some(&self.layout), module: &self.shader, entry_point: Some("brush"), - compilation_options: wgpu::PipelineCompilationOptions { constants: &[("alpha_kind", f64::from(alpha_kind))], ..Default::default() }, + compilation_options: wgpu::PipelineCompilationOptions { + constants: &[("alpha_kind", f64::from(alpha_kind)), ("shared_surfaces", f64::from(u8::from(shared_surfaces)))], + ..Default::default() + }, cache: None, }) }) .clone() } - fn library_tip(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, alpha: &Arc) -> wgpu::TextureView { - let key = Arc::downgrade(alpha); + /// Drop the generated library tip and the surface covers (a failed brush start may have + /// left them invalid, so the retry allocates them again) + pub(crate) fn forget_failed_start(&mut self) { + self.library_tip = None; + self.covers = None; + } + + /// Tests: whether surface covers are kept for a G-buffer + #[cfg(test)] + pub(crate) fn has_covers(&self) -> bool { + self.covers.is_some() + } + + /// Tests: the side of the library alpha the last brush generated + #[cfg(test)] + pub(crate) fn library_tip_side(&self) -> Option { + self.library_tip.as_ref().map(|((_, _, side), _)| *side) + } + + /// The library alpha `alpha` with `params`, generated on the GPU at `side` texels with its + /// mip chain (kept until another alpha, setting or side is asked for). A GPU error is + /// returned and nothing is kept, so the brush's memory retry generates it again. + fn library_tip( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + alpha: &LibraryAlpha, + params: &LibraryAlphaParams, + side: u32, + ) -> Result { + let key = (alpha.id.clone(), alpha.sanitized_parameters(params), side); if let Some((previous, view)) = &self.library_tip - && previous.ptr_eq(&key) + && *previous == key { - return view.clone(); + return Ok(view.clone()); } - let base = texturecraft_paint::alphas::BASE as u32; - let texture = device.create_texture(&wgpu::TextureDescriptor { - label: Some("tc_brush_library_tip"), - size: extent(base, base), - mip_level_count: alpha.levels() as u32, - sample_count: 1, - dimension: wgpu::TextureDimension::D2, - format: wgpu::TextureFormat::R32Float, - usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_DST, - view_formats: &[], - }); - for (level, (side, pixels)) in alpha.mip_pixels().enumerate() { - let destination = wgpu::TexelCopyTextureInfo { mip_level: level as u32, ..texture.as_image_copy() }; - let layout = wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(side * size_of::() as u32), rows_per_image: None }; - queue.write_texture(destination, bytemuck::cast_slice(pixels), layout, extent(side, side)); - } + self.library_tip = None; + let generator = self.alpha_generator.get_or_insert_with(|| AlphaGenerator::new(device)); + let texture = crate::gpu_trace::scoped(device, "library brush alpha", || generator.generate(device, queue, &alpha.gpu_spec(params), side))?; let view = texture.create_view(&Default::default()); self.library_tip = Some((key, view.clone())); - view + Ok(view) } fn brush_tip(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, input: &BrushInput) -> Result<(wgpu::TextureView, u32), String> { @@ -126,9 +191,14 @@ impl BrushPipeline { return Ok((view, IMAGE_ALPHA_KIND)); } - if let Some(alpha) = input.settings.library_alpha_image() { - return Ok((self.library_tip(device, queue, &alpha), LIBRARY_ALPHA_KIND)); + // A library alpha holds about one tip texel per set texel at the brush's full size (its + // radius is a fraction of the mesh's diagonal, taken as the set's side), never coarser + // than the CPU image, up to the device's texture side + if let Some(alpha) = input.settings.library_alpha() { + let side = library_tip_side(input.settings.size, (input.uv.width, input.uv.height), device.limits().max_texture_dimension_2d); + return Ok((self.library_tip(device, queue, alpha, &input.settings.alpha_library_params, side)?, LIBRARY_ALPHA_KIND)); } + self.library_tip = None; let kind = match input.settings.alpha { BrushAlpha::Round => 0, @@ -142,6 +212,56 @@ impl BrushPipeline { Ok((self.blank_tip.clone(), kind)) } + /// The surfaces sharing each texel's UVs with its owner (none when the set has no shared + /// surfaces), kept for the G-buffer until another one asks + fn surface_covers(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, input: &BrushInput) -> Result { + if !input.uv.shared_surfaces { + return Ok(self.no_covers.clone()); + } + + let key = Arc::downgrade(&input.uv); + if let Some((previous, covers)) = &self.covers + && previous.ptr_eq(&key) + { + return Ok(covers.clone()); + } + + self.covers = None; + let mut covers = texturecraft_paint::non_owner_covers(&input.mesh, input.material, &input.uv); + covers.par_sort_unstable_by_key(|&(texel, triangle, _)| (texel, triangle)); + let limits = device.limits(); + let bytes = (covers.len().max(1) * 3 * size_of::()) as u64; + if bytes > limits.max_storage_buffer_binding_size.min(limits.max_buffer_size) || covers.len() >= LAST_COVER as usize / 3 { + return Err("The surfaces sharing UVs exceed this adapter's buffer limits.".into()); + } + + let (width, height) = (input.uv.width, input.uv.height); + let mut first = vec![0_u32; width as usize * height as usize]; + let mut entries = Vec::with_capacity(covers.len().max(1) * 3); + for (index, &(texel, triangle, [second, third])) in covers.iter().enumerate() { + if first[texel] == 0 { + first[texel] = index as u32 + 1; + } + + let last = covers.get(index + 1).is_none_or(|next| next.0 != texel); + entries.extend([triangle | if last { LAST_COVER } else { 0 }, second.to_bits(), third.to_bits()]); + } + if entries.is_empty() { + entries.extend([0; 3]); + } + + let first_texture = texture(device, [width, height], wgpu::TextureFormat::R32Uint); + queue.write_texture( + first_texture.as_image_copy(), + bytemuck::cast_slice(&first), + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(width * 4), rows_per_image: None }, + extent(width, height), + ); + let covers = SurfaceCovers { first: first_texture.create_view(&Default::default()), entries: storage(device, "tc_brush_covers", &entries) }; + self.covers = Some((key, covers.clone())); + Ok(covers) + } + pub(super) fn visibility(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, input: &BrushInput) -> Result { let key = Arc::downgrade(&input.bvh); if self.rays.as_ref().is_none_or(|(last, ..)| !last.ptr_eq(&key)) { @@ -173,12 +293,14 @@ impl BrushPipeline { Ok(Visibility { nodes: nodes.clone(), triangles: triangles.clone(), depth }) } + /// `smudge_maps`: a smudge source the compositor already wrote (`smudge_source`) pub fn begin( &mut self, device: &wgpu::Device, queue: &wgpu::Queue, input: BrushInput, surface: (wgpu::TextureView, wgpu::Buffer), + mut source_maps: Option, ) -> Result { let size = [input.uv.width, input.uv.height]; if size.into_iter().any(|edge| !edge.is_multiple_of(TILE) || edge > device.limits().max_texture_dimension_2d) { @@ -189,6 +311,11 @@ impl BrushPipeline { return Err("The quick mask does not match the GPU brush texture size.".into()); } + let clone_coverage = input.clone.as_ref().and_then(|clone| clone.coverage.as_ref()); + if clone_coverage.is_some_and(|coverage| [coverage.width(), coverage.height()] != size || coverage.comps() != 1) { + return Err("The clone source does not match the GPU brush texture size.".into()); + } + let visibility = self.visibility(device, queue, &input)?; let spare = self.spare_alpha.lock().ok().and_then(|mut spare| spare.take()); let alpha = match spare { @@ -204,7 +331,6 @@ impl BrushPipeline { let radius = (hi - lo).length().mul_add(0.5, 0.0).max(1e-4); self.stencil_image.take_if(|(source, _)| source.strong_count() == 0); self.image_tip.take_if(|(source, _)| source.strong_count() == 0); - self.library_tip.take_if(|(source, _)| source.strong_count() == 0); let projection = if let Some(stencil) = &input.stencil { let key = Arc::downgrade(&stencil.image); if self.stencil_image.as_ref().is_none_or(|(previous, _)| !previous.ptr_eq(&key)) { @@ -220,7 +346,23 @@ impl BrushPipeline { }; let settings = &input.settings; let (tip, kind) = self.brush_tip(device, queue, &input)?; - let pipeline = self.pipeline(device, kind); + let covers = self.surface_covers(device, queue, &input)?; + let pipeline = self.pipeline(device, kind, input.uv.shared_surfaces); + let smudge = match &input.smudge { + Some(source) => { + let pipelines = self + .smudge + .entry((kind, input.uv.shared_surfaces)) + .or_insert_with(|| SmudgePipelines::new(device, &self.shader, &self.inputs, kind, input.uv.shared_surfaces)) + .clone(); + Some(GpuSmudge::new(device, queue, pipelines, size, source, source_maps.take())?) + } + None => None, + }; + let clone_source = match &input.clone { + Some(clone) => Some(super::clone_source::GpuClone::new(device, queue, size, clone, source_maps.take())?), + None => None, + }; let (sin, cos) = settings.alpha_params.rotation.to_radians().sin_cos(); let mut params = Parameters { camera: Mat4::IDENTITY.to_cols_array_2d(), @@ -237,7 +379,8 @@ impl BrushPipeline { input.limit.as_ref().map_or(0, |(_, invert)| 1 + u32::from(*invert)), ], stamp_blending: settings.stamp_blending as u32, - padding: [0; 3], + clone_offset: input.clone.as_ref().map_or([0; 2], |clone| clone_offset(clone.offset, size)), + clone_mode: input.clone.as_ref().map_or(0, |clone| if clone.coverage.is_some() { 2 } else { 1 }), }; if let Some(depth) = &input.depth { params.camera = depth.view_proj.to_cols_array_2d(); @@ -261,8 +404,27 @@ impl BrushPipeline { params, scratch: None, projection, + covers, written: Tiles::new(), spare_alpha: self.spare_alpha.clone(), + smudge, + clone_source, }) } } + +/// A clone offset in texels as the shader adds it: one beyond the set reads nothing either way +pub(super) fn clone_offset(offset: [i64; 2], size: [u32; 2]) -> [i32; 2] { + std::array::from_fn(|axis| { + let side = i64::from(size[axis]); + i32::try_from(offset[axis].clamp(-side, side)).unwrap_or(0) + }) +} + +/// The side of a library tip for a brush of `size` (radius as a fraction of the mesh diagonal) on +/// a set of `set` texels: the stamp's diameter in set texels as a power of two, at least the CPU +/// image's side, at most `max_side` +pub(super) fn library_tip_side(size: f32, set: (u32, u32), max_side: u32) -> u32 { + let diameter = (2.0 * size.max(0.0) * set.0.max(set.1) as f32).ceil().min(u32::MAX as f32) as u32; + diameter.max(texturecraft_paint::alphas::BASE as u32).checked_next_power_of_two().unwrap_or(u32::MAX).min(max_side.max(1)) +} diff --git a/crates/render/src/gpu_brush/clone_source.rs b/crates/render/src/gpu_brush/clone_source.rs new file mode 100644 index 000000000..def7ae684 --- /dev/null +++ b/crates/render/src/gpu_brush/clone_source.rs @@ -0,0 +1,245 @@ +//! A clone's source on the GPU: the source maps (composited by the GPU compositor, or uploaded +//! once from a cloned layer's CPU flattening) whose values at the clone offset are the stroke's +//! carried values. The CPU evaluates no source tile while the stroke paints. + +use std::collections::BTreeMap; + +use texturecraft_core::Channel; +use texturecraft_paint::CloneSource; +use texturecraft_texel::{TILE, TileImage}; + +use super::smudge::{SourceMaps, array_view, layer_copy, rows, source_layout, upload_source}; +use super::{CHUNK, GpuBrushStroke, ROW_BYTES, Tiles, buffer, extent, tile_copy}; +use crate::gpu_composite::{CarriedSlot, LiveCarried}; + +/// Bytes of one tile of a source layer (RGBA16 rows) +const LAYER_ROW_BYTES: u32 = TILE * 8; +const LAYER_TILE_BYTES: u64 = (TILE * LAYER_ROW_BYTES) as u64; +const ALPHA_TILE_BYTES: u64 = (TILE * ROW_BYTES) as u64; + +pub(super) struct GpuClone { + /// The carried channels with their layer in the scalar or the color maps + channels: Vec<(Channel, bool, u32)>, + source: SourceMaps, +} + +impl GpuClone { + /// The clone's source from `maps` (composited on the GPU) or uploaded from `clone`'s values + pub(super) fn new(device: &wgpu::Device, queue: &wgpu::Queue, size: [u32; 2], clone: &CloneSource, maps: Option) -> Result { + let channels = source_layout(device, size, &clone.channels)?; + let source = match maps { + Some(maps) => maps, + None if clone.composited.is_some() => return Err("The clone's composited source is missing.".into()), + None => upload_source(device, queue, size, &clone.channels, &channels), + }; + Ok(GpuClone { channels, source }) + } + + /// The source maps for the live compositor, read at the clone `offset`: scalar channels four + /// per RGBA16 layer, color channels one layer each + pub(super) fn live(&self, offset: [i32; 2]) -> LiveCarried { + let channels = self + .channels + .iter() + .map(|&(channel, color, layer)| { + let slot = if color { + CarriedSlot { color, layer, component: 0, alpha: None } + } else { + CarriedSlot { color, layer: layer / 4, component: layer % 4, alpha: None } + }; + (channel, slot) + }) + .collect(); + LiveCarried { scalars: array_view(&self.source.0), colors: array_view(&self.source.1), offset, channels } + } + + /// The source layers (scalar groups of four, then colors) + fn layers(&self) -> Vec<(&wgpu::Texture, u32)> { + let scalars = self.channels.iter().filter(|(_, color, _)| !*color).count() as u32; + let colors = self.channels.len() as u32 - scalars; + (0..scalars.div_ceil(4)).map(|layer| (&self.source.0, layer)).chain((0..colors).map(|layer| (&self.source.1, layer))).collect() + } +} + +impl GpuBrushStroke { + /// The stroke alpha and a clone's carried values of `tiles`: the source's values at the clone + /// offset (what `Pickup::stamp` reads; texels whose source lies beyond the set hold 0, the + /// stroke has no alpha there) + pub(super) fn read_clone(&self, clone: &GpuClone, tiles: &Tiles) -> Result<(TileImage, BTreeMap), String> { + self.validate_readback_tiles(tiles)?; + let (width, height) = (self.input.uv.width, self.input.uv.height); + let mut alpha = TileImage::new(width, height, 1); + let mut values: BTreeMap = + clone.channels.iter().map(|(channel, color, _)| (*channel, TileImage::new(width, height, if *color { 3 } else { 1 }))).collect(); + if tiles.is_empty() { + return Ok((alpha, values)); + } + + let layers = clone.layers(); + let tile_bytes = ALPHA_TILE_BYTES + LAYER_TILE_BYTES * layers.len() as u64; + // One readback of the whole stroke at its end: chunked as the alpha readback is + let per_chunk = ((self.device.limits().max_buffer_size / tile_bytes) as usize).clamp(1, CHUNK); + let offset = self.params.clone_offset.map(i64::from); + let scalar_layers = clone.channels.iter().filter(|(_, color, _)| !*color).count().div_ceil(4); + let (device, queue) = (&self.device, &self.queue); + let coordinates: Vec<_> = tiles.iter().copied().collect(); + for chunk in coordinates.chunks(per_chunk) { + let bytes = chunk.len() as u64 * tile_bytes; + let read = crate::gpu_trace::scoped(device, "GPU clone readback buffer", || { + buffer(device, "tc_clone_read", bytes, wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ) + })?; + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_clone_read") }); + for (index, &tile) in chunk.iter().enumerate() { + let base = index as u64 * tile_bytes; + encoder.copy_texture_to_buffer(tile_copy(&self.alpha, tile.0 * TILE, tile.1 * TILE), rows(&read, base, ROW_BYTES), extent(TILE, TILE)); + + // The source under the tile, clipped to the set (the rest stays 0) + let origin = [i64::from(tile.0 * TILE) + offset[0], i64::from(tile.1 * TILE) + offset[1]]; + let low = [origin[0].max(0), origin[1].max(0)]; + let high = [(origin[0] + i64::from(TILE)).min(i64::from(width)), (origin[1] + i64::from(TILE)).min(i64::from(height))]; + if high[0] <= low[0] || high[1] <= low[1] { + continue; + } + + let inside = (low[1] - origin[1]) as u64 * u64::from(LAYER_ROW_BYTES) + (low[0] - origin[0]) as u64 * 8; + for (k, &(texture, layer)) in layers.iter().enumerate() { + let at = base + ALPHA_TILE_BYTES + k as u64 * LAYER_TILE_BYTES + inside; + let source = wgpu::TexelCopyTextureInfo { + origin: wgpu::Origin3d { x: low[0] as u32, y: low[1] as u32, z: layer }, + ..layer_copy(texture, (0, 0), layer) + }; + encoder.copy_texture_to_buffer(source, rows(&read, at, LAYER_ROW_BYTES), extent((high[0] - low[0]) as u32, (high[1] - low[1]) as u32)); + } + } + let submitted = queue.submit([encoder.finish()]); + let (send, receive) = std::sync::mpsc::channel(); + read.slice(..).map_async(wgpu::MapMode::Read, move |result| { + let _ = send.send(result); + }); + device.poll(wgpu::PollType::Wait { submission_index: Some(submitted), timeout: None }).map_err(|e| e.to_string())?; + receive.recv().map_err(|e| e.to_string())?.map_err(|e| e.to_string())?; + { + let mapped = read.slice(..).get_mapped_range().map_err(|e| e.to_string())?; + let words: &[u16] = bytemuck::try_cast_slice(&mapped).map_err(|e| e.to_string())?; + let row_words = (ROW_BYTES / 2) as usize; + for (index, &(x, y)) in chunk.iter().enumerate() { + let at = index * (tile_bytes / 2) as usize; + let tile_alpha: Vec = (0..TILE as usize).flat_map(|row| words[at + row * row_words..][..TILE as usize].iter().copied()).collect(); + if tile_alpha.iter().any(|a| *a != 0) { + alpha.set_tile(x, y, Some(std::sync::Arc::new(tile_alpha))); + } + + // Four words per texel in every layer + let layer_at = |k: usize| at + ((ALPHA_TILE_BYTES + k as u64 * LAYER_TILE_BYTES) / 2) as usize; + for (channel, color, layer) in &clone.channels { + let data: Vec = if *color { + let texels = &words[layer_at(scalar_layers + *layer as usize)..][..(LAYER_TILE_BYTES / 2) as usize]; + texels.as_chunks::<4>().0.iter().flat_map(|&[red, green, blue, _]| [red, green, blue]).collect() + } else { + let texels = &words[layer_at(*layer as usize / 4)..][..(LAYER_TILE_BYTES / 2) as usize]; + texels.as_chunks::<4>().0.iter().map(|texel| texel[*layer as usize % 4]).collect() + }; + if let Some(image) = values.get_mut(channel) { + image.set_tile(x, y, Some(std::sync::Arc::new(data))); + } + } + } + } + read.unmap(); + } + Ok((alpha, values)) + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use texturecraft_compose::eval::Composite; + use texturecraft_core::Channel; + use texturecraft_geom::glam::Vec2; + use texturecraft_geom::{Bvh, UvGBuffer, primitives}; + use texturecraft_paint::{BrushAlpha, BrushSettings, Pickup, PickupMode, Shape, StrokeCanvas, UvStamp, rasterize_uv}; + use texturecraft_texel::to_u16; + + use crate::gpu_brush::BrushInput; + use crate::headless::Headless; + + const SIZE: u32 = 128; + + /// Five scalar channels (two packed source layers, a signed one among them) and base color + const CHANNELS: [Channel; 6] = [Channel::Roughness, Channel::Metallic, Channel::Height, Channel::Opacity, Channel::AmbientOcclusion, Channel::BaseColor]; + + /// A clone's carried values read back from the GPU source at the offset are the CPU clone's, + /// for every channel, also where the source runs past the set's edge + #[test] + fn clone_values_read_back_at_the_offset_as_the_cpu_clones() { + let Some(mut gpu) = Headless::for_required_tests() else { return }; + let mesh = Arc::new(primitives::plane(2.0, 4)); + let uv = Arc::new(UvGBuffer::new(&mesh, 0, SIZE, SIZE)); + let mut source = Composite::with_size(&CHANNELS, SIZE, SIZE); + for y in 0..SIZE { + for x in 0..SIZE { + for (index, channel) in CHANNELS[..5].iter().enumerate() { + let value = ((x * 3 + y * 5 + index as u32 * 17) % 97) as f32 / 96.0; + source.channels.get_mut(channel).unwrap().set(x, y, &[to_u16(value)]); + } + let color = [x as f32 / SIZE as f32, y as f32 / SIZE as f32, 0.5]; + source.channels.get_mut(&Channel::BaseColor).unwrap().set(x, y, &color.map(to_u16)); + } + } + let settings = BrushSettings { alpha: BrushAlpha::Round, backface_culling: false, ..Default::default() }; + let shape = Shape::new(settings.alpha, None, None, settings.alpha_params); + let stamps: Vec = (0..12) + .map(|i| UvStamp { + center: Vec2::new(0.1 + i as f32 * 0.07, 0.3 + i as f32 * 0.04), + radius: 0.06, + angle: 0.0, + flow: 0.9, + hardness: 0.6, + seed: 0, + source: None, + }) + .collect(); + let pickup = Pickup::new(PickupMode::Clone { offset: [-37, 30] }, source, uv.clone(), CHANNELS); + let input = BrushInput { + mesh: mesh.clone(), + bvh: Arc::new(Bvh::new(&mesh)), + uv: uv.clone(), + material: 0, + depth: None, + settings, + alpha_image: None, + stencil: None, + limit: None, + clone: pickup.clone_source(), + smudge: None, + }; + let mut cpu = StrokeCanvas::new(SIZE, SIZE); + cpu.pickup = Some(pickup); + rasterize_uv(&mut cpu, &uv, shape, &stamps); + let mut stroke = gpu.renderer.start_gpu_brush(&gpu.device, &gpu.queue, input).unwrap(); + let tiles = stroke.append_uv(&stamps).unwrap(); + let (alpha, values) = stroke.read_carried(&tiles).unwrap(); + let carried = &cpu.pickup.as_ref().unwrap().values; + let (mut covered, mut edge, mut alpha_differ) = (0, false, 0); + for y in 0..SIZE { + for x in 0..SIZE { + // Coverage first: a texel only one of them paints is a difference, not skipped + let (expected, actual) = (cpu.alpha.get(x, y)[0], alpha.get(x, y)[0]); + alpha_differ += usize::from(expected.abs_diff(actual) > 64); + if expected == 0 || actual == 0 { + continue; + } + + covered += 1; + edge |= y + 30 >= SIZE - 4; + for channel in CHANNELS { + assert_eq!(values[&channel].get(x, y), carried[&channel].get(x, y), "{channel:?} at ({x}, {y})"); + } + } + } + assert!(covered > 500 && edge, "the stroke clones ({covered} texels) up to the set's edge"); + assert!(alpha_differ * 200 <= covered, "{alpha_differ}/{covered} alpha texels differ"); + } +} diff --git a/crates/render/src/gpu_brush/gpu_brush_stroke.rs b/crates/render/src/gpu_brush/gpu_brush_stroke.rs index 7c72f4357..13f4cf086 100644 --- a/crates/render/src/gpu_brush/gpu_brush_stroke.rs +++ b/crates/render/src/gpu_brush/gpu_brush_stroke.rs @@ -1,7 +1,7 @@ use super::{ Arc, BTreeMap, BrushInput, CHUNK, Dab, DeviceExt, GpuStencil, PROJECTION_READBACK_TILES, PROJECTION_TILE_BYTES, Parameters, ProjectedTiles, ROW_BYTES, - SpareAlpha, Stamp, TILE, TILE_BYTES, TileDabs, TileImage, Tiles, UvStamp, Vec2, Visibility, buffer, buffer_copy, covered_tiles, extent, footprint, storage, - tile_copy, + SpareAlpha, Stamp, SurfaceCovers, TILE, TILE_BYTES, TileDabs, TileImage, Tiles, UvStamp, Vec2, Visibility, buffer, buffer_copy, covered_tiles, extent, + footprint, storage, tile_copy, }; pub struct GpuBrushStroke { @@ -17,9 +17,15 @@ pub struct GpuBrushStroke { pub(super) params: Parameters, pub(super) scratch: Option, pub(super) projection: Option<(GpuStencil, wgpu::ComputePipeline)>, + /// The other surfaces sharing a texel's UVs (an empty list on most meshes) + pub(super) covers: SurfaceCovers, /// The alpha tiles the stroke wrote, cleared when the next stroke reuses its map pub(super) written: Tiles, pub(super) spare_alpha: SpareAlpha, + /// A smudge stroke's source, carried values and lanes + pub(super) smudge: Option, + /// A clone stroke's source, read at the clone offset + pub(super) clone_source: Option, } impl Drop for GpuBrushStroke { @@ -39,11 +45,26 @@ impl GpuBrushStroke { self.projection.as_ref().map(|(stencil, _)| stencil.clone()) } + /// A clone's or smudge's carried values where the live compositor reads them (no readback) + pub fn carried(&self) -> Option { + if let Some(clone) = &self.clone_source { + return Some(clone.live(self.params.clone_offset)); + } + self.smudge.as_ref().map(super::smudge::GpuSmudge::live) + } + pub fn append_world(&mut self, stamps: &[Stamp]) -> Result { + self.append_world_with(stamps, true) + } + + /// World dabs; without `use_view` they skip the camera's visibility test and backface + /// culling, as the CPU paints a 3D path's surface samples + pub fn append_world_with(&mut self, stamps: &[Stamp], use_view: bool) -> Result { let mut bins = TileDabs::new(); let input = &self.input; let size = Vec2::new(input.uv.width as f32, input.uv.height as f32); let mut dabs = Vec::new(); + let mut stamped = Vec::new(); for stamp in stamps { if !stamp.radius.is_finite() || stamp.radius <= 0.0 || !stamp.center.is_finite() { continue; @@ -73,11 +94,26 @@ impl GpuBrushStroke { touched.extend(covered_tiles(lo * size, hi * size, size)); } }); + if self.smudge.is_some() { + stamped.push((touched.clone(), stamp.source)); + } for tile in touched { bins.entry(tile).or_default().push(index); } } - self.dispatch(&bins, &dabs, false)?; + let viewed = self.params; + if !use_view { + self.params.flags[1] = 0; + self.params.view_scale[3] = 0.0; + } + let painted = if self.smudge.is_some() { + let stamps = dabs.into_iter().zip(stamped).map(|(dab, (tiles, source))| (dab, tiles, source)).collect(); + self.smudge_stamps(stamps, false) + } else { + self.dispatch(&bins, &dabs, false) + }; + self.params = viewed; + painted?; Ok(bins.into_keys().collect()) } @@ -85,6 +121,7 @@ impl GpuBrushStroke { let mut bins = TileDabs::new(); let size = Vec2::new(self.input.uv.width as f32, self.input.uv.height as f32); let mut dabs = Vec::new(); + let mut stamped = Vec::new(); for stamp in stamps { if !stamp.radius.is_finite() || stamp.radius <= 0.0 || !stamp.center.is_finite() { continue; @@ -105,11 +142,20 @@ impl GpuBrushStroke { to_source: [[0.0; 4]; 3], }); let reach = Vec2::splat(radius * Stamp::PLANAR_RADIUS_SCALE); - for tile in covered_tiles(center - reach, center + reach, size) { + let touched: Tiles = covered_tiles(center - reach, center + reach, size).collect(); + if self.smudge.is_some() { + stamped.push((touched.clone(), stamp.source)); + } + for tile in touched { bins.entry(tile).or_default().push(index); } } - self.dispatch(&bins, &dabs, true)?; + if self.smudge.is_some() { + let stamps = dabs.into_iter().zip(stamped).map(|(dab, (tiles, source))| (dab, tiles, source)).collect(); + self.smudge_stamps(stamps, true)?; + } else { + self.dispatch(&bins, &dabs, true)?; + } Ok(bins.into_keys().collect()) } @@ -122,7 +168,7 @@ impl GpuBrushStroke { params.flags[0] = u32::from(uv); self.written.extend(tiles.keys()); let coordinates: Vec<_> = tiles.iter().collect(); - let (device, queue) = (&self.device, &self.queue); + let (device, queue) = (&self.device.clone(), &self.queue.clone()); crate::gpu_trace::scoped(device, "GPU brush dispatch", || { let uniform = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("tc_brush_parameters"), @@ -137,37 +183,9 @@ impl GpuBrushStroke { let scratch = self.scratch.as_ref().ok_or("brush scratch buffer missing")?; let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_brush") }); for chunk in coordinates.chunks(CHUNK) { - // Origins, dab offsets/counts and optional quick-mask offsets - let mut cells = vec![0; chunk.len() * 5]; - for (tile, (&(x, y), indices)) in chunk.iter().copied().enumerate() { - let first = cells.len() as u32; - cells.extend(indices); - let mask = self.input.limit.as_ref().and_then(|(mask, _)| mask.tile(x, y)); - let limit = mask.map_or(0, |mask| { - let offset = cells.len() as u32; - cells.extend(mask.as_chunks::<2>().0.iter().map(|&[lo, hi]| u32::from(lo) | (u32::from(hi) << 16))); - offset - }); - cells[tile * 5..tile * 5 + 5].copy_from_slice(&[x * TILE, y * TILE, first, indices.len() as u32, limit]); - } + let cells = self.tile_cells(chunk.iter().map(|&(&tile, indices)| (tile, indices.as_slice()))); let cells = storage(device, "tc_brush_tiles", &cells); - let bind = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("tc_brush_inputs"), - layout: &self.pipeline.get_bind_group_layout(0), - entries: &[ - wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() }, - wgpu::BindGroupEntry { binding: 1, resource: self.visibility.nodes.as_entire_binding() }, - wgpu::BindGroupEntry { binding: 2, resource: self.visibility.triangles.as_entire_binding() }, - wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(&self.surface.0) }, - wgpu::BindGroupEntry { binding: 4, resource: self.surface.1.as_entire_binding() }, - wgpu::BindGroupEntry { binding: 5, resource: wgpu::BindingResource::TextureView(&self.view) }, - wgpu::BindGroupEntry { binding: 6, resource: wgpu::BindingResource::TextureView(&self.visibility.depth) }, - wgpu::BindGroupEntry { binding: 7, resource: dabs.as_entire_binding() }, - wgpu::BindGroupEntry { binding: 8, resource: cells.as_entire_binding() }, - wgpu::BindGroupEntry { binding: 9, resource: scratch.as_entire_binding() }, - wgpu::BindGroupEntry { binding: 10, resource: wgpu::BindingResource::TextureView(&self.tip) }, - ], - }); + let bind = self.inputs_bind_group(&self.pipeline.get_bind_group_layout(0), &uniform, &dabs, &cells, scratch); { let mut pass = encoder.begin_compute_pass(&Default::default()); pass.set_pipeline(&self.pipeline); @@ -183,6 +201,59 @@ impl GpuBrushStroke { })? } + /// The kernel's tile list: per tile its origin, dab offset and count, quick-mask and + /// clone-coverage offsets (0: none), then the dab indices and packed coverage tiles + pub(super) fn tile_cells<'a>(&self, tiles: impl ExactSizeIterator) -> Vec { + let mut cells = vec![0; tiles.len() * 6]; + for (tile, ((x, y), indices)) in tiles.enumerate() { + let first = cells.len() as u32; + cells.extend(indices); + let mask = self.input.limit.as_ref().and_then(|(mask, _)| mask.tile(x, y)); + let limit = mask.map_or(0, |mask| { + let offset = cells.len() as u32; + cells.extend(mask.as_chunks::<2>().0.iter().map(|&[lo, hi]| u32::from(lo) | (u32::from(hi) << 16))); + offset + }); + let source = self.input.clone.as_ref().and_then(|clone| Some((clone.offset, clone.coverage.as_ref()?))).map_or(0, |(offset, coverage)| { + let offset_words = cells.len() as u32; + cells.extend(shifted_coverage(coverage, (x, y), offset).as_chunks::<2>().0.iter().map(|&[lo, hi]| u32::from(lo) | (u32::from(hi) << 16))); + offset_words + }); + cells[tile * 6..tile * 6 + 6].copy_from_slice(&[x * TILE, y * TILE, first, indices.len() as u32, limit, source]); + } + cells + } + + /// The brush kernel's inputs (group 0) for `layout` + pub(super) fn inputs_bind_group( + &self, + layout: &wgpu::BindGroupLayout, + uniform: &wgpu::Buffer, + dabs: &wgpu::Buffer, + cells: &wgpu::Buffer, + scratch: &wgpu::Buffer, + ) -> wgpu::BindGroup { + self.device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("tc_brush_inputs"), + layout, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 1, resource: self.visibility.nodes.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 2, resource: self.visibility.triangles.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(&self.surface.0) }, + wgpu::BindGroupEntry { binding: 4, resource: self.surface.1.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 5, resource: wgpu::BindingResource::TextureView(&self.view) }, + wgpu::BindGroupEntry { binding: 6, resource: wgpu::BindingResource::TextureView(&self.visibility.depth) }, + wgpu::BindGroupEntry { binding: 7, resource: dabs.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 8, resource: cells.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 9, resource: scratch.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 10, resource: wgpu::BindingResource::TextureView(&self.tip) }, + wgpu::BindGroupEntry { binding: 11, resource: wgpu::BindingResource::TextureView(&self.covers.first) }, + wgpu::BindGroupEntry { binding: 12, resource: self.covers.entries.as_entire_binding() }, + ], + }) + } + pub(super) fn validate_readback_tiles(&self, tiles: &Tiles) -> Result<(), String> { let width = self.input.uv.width / TILE; let height = self.input.uv.height / TILE; @@ -311,3 +382,18 @@ impl GpuBrushStroke { Ok(samples) } } + +/// A clone source's coverage under the destination tile `(tile_x, tile_y)`: the coverage +/// `offset` texels away, 0 beyond the set +fn shifted_coverage(coverage: &TileImage, (tile_x, tile_y): (u32, u32), offset: [i64; 2]) -> Vec { + (0..TILE * TILE) + .map(|index| { + let x = i64::from(tile_x * TILE + index % TILE).saturating_add(offset[0]); + let y = i64::from(tile_y * TILE + index / TILE).saturating_add(offset[1]); + match (u32::try_from(x), u32::try_from(y)) { + (Ok(x), Ok(y)) => coverage.get(x, y)[0], + _ => 0, + } + }) + .collect() +} diff --git a/crates/render/src/gpu_brush/parameters.rs b/crates/render/src/gpu_brush/parameters.rs index bc7d038e6..7e38d0acb 100644 --- a/crates/render/src/gpu_brush/parameters.rs +++ b/crates/render/src/gpu_brush/parameters.rs @@ -12,5 +12,7 @@ pub(super) struct Parameters { pub(super) alpha_rotation: [f32; 4], pub(super) flags: [u32; 4], pub(super) stamp_blending: u32, - pub(super) padding: [u32; 3], + /// A clone stroke's source offset in texels and its mode (`CLONE_*` in brush.wgsl) + pub(super) clone_offset: [i32; 2], + pub(super) clone_mode: u32, } diff --git a/crates/render/src/gpu_brush/pickup_source.rs b/crates/render/src/gpu_brush/pickup_source.rs new file mode 100644 index 000000000..2e97e3d5f --- /dev/null +++ b/crates/render/src/gpu_brush/pickup_source.rs @@ -0,0 +1,302 @@ +//! A smudge's or a clone's source composited on the GPU compositor straight into the brush's +//! source arrays: the CPU neither composites nor uploads it. + +use std::sync::Arc; + +use texturecraft_compose::PaintTarget; +use texturecraft_core::Channel; +use texturecraft_paint::PICKUP_SOURCE_REFUSED; +use texturecraft_paint::pickup::PickupSnapshot; + +use super::smudge::{SourceMaps, source_layout, source_maps}; +use super::{BrushInput, extent, texture}; +use crate::gpu_composite::{CompositeProgram, GpuCompositor}; + +/// The compositor's cache key for a brush material's own one-set document: no texture set index +/// reaches it, nor its micro captures' key (`usize::MAX - key`), so a pattern stroke leaves the +/// document's cached inputs alone +const BRUSH_MATERIAL_INPUTS: usize = usize::MAX / 2; + +/// The source maps of `input`'s smudge or clone when the GPU composites it (the document's +/// composite, a mask's values or the brush material's fill, [`texturecraft_paint::SmudgeSource::composited`] +/// and [`texturecraft_paint::CloneSource::composited`]): +/// one pass per color channel and per four scalar channels. None for a source the CPU supplies. A +/// material the compositor refuses is refused with [`PICKUP_SOURCE_REFUSED`] first (the CPU then +/// evaluates the source); adapter limits the smudge itself needs are refused before compositing +/// anything. +pub(crate) fn composite_pickup_source( + compositor: &mut GpuCompositor, + gpu: (&wgpu::Device, &wgpu::Queue), + input: &BrushInput, +) -> Result, String> { + let (channels, snapshot) = match (&input.smudge, &input.clone) { + (Some(source), _) => { + super::smudge::check_limits(gpu.0)?; + (&source.channels, source.composited.as_ref()) + } + (None, Some(clone)) => (&clone.channels, clone.composited.as_ref()), + (None, None) => return Ok(None), + }; + let Some(snapshot) = snapshot else { return Ok(None) }; + let size = [input.uv.width, input.uv.height]; + let layout = source_layout(gpu.0, size, channels)?; + compose_source(compositor, gpu, input, snapshot, &layout).map(Some).map_err(|error| { + if crate::gpu_memory::is_device_error(&error) || crate::gpu_memory::is_out_of_memory(&error) { + error + } else { + format!("{PICKUP_SOURCE_REFUSED}{error}") + } + }) +} + +fn compose_source( + compositor: &mut GpuCompositor, + (device, queue): (&wgpu::Device, &wgpu::Queue), + input: &BrushInput, + snapshot: &Arc, + layout: &[(Channel, bool, u32)], +) -> Result { + let size = [input.uv.width, input.uv.height]; + let maps = source_maps(device, size, layout); + let scalars: Vec = layout.iter().filter(|(_, color, _)| !*color).map(|(channel, ..)| *channel).collect(); + let passes = scalars + .chunks(4) + .enumerate() + .map(|(layer, channels)| (channels.to_vec(), &maps.0, layer as u32)) + .chain(layout.iter().filter(|(_, color, _)| *color).map(|&(channel, _, layer)| (vec![channel], &maps.1, layer))); + + // The brush material's own document keeps its cached inputs apart from the document's set + let key = match snapshot.target { + Some(PaintTarget::Layer(_)) => BRUSH_MATERIAL_INPUTS, + None | Some(PaintTarget::Mask(_)) => snapshot.ts, + }; + let target = texture(device, size, wgpu::TextureFormat::Rgba16Uint); + for (channels, maps, layer) in passes { + let first = *channels.first().ok_or("A pickup source pass has no channel.")?; + let mut program = match snapshot.target { + // A layer target is the brush material's fill alone in its own document: its + // composite is the fill's values, which cover every texel they reach + None | Some(PaintTarget::Layer(_)) => CompositeProgram::try_compile_thumbnail(&snapshot.project, &snapshot.pixels, snapshot.ts, first, false), + Some(PaintTarget::Mask(owner)) => CompositeProgram::try_compile_mask_preview(&snapshot.project, &snapshot.pixels, snapshot.ts, owner, None, None), + }?; + program.set_pickup_output(&channels)?; + program.set_surface_inputs(&input.mesh, &input.uv, Some(&snapshot.baked))?; + program.set_tile_images(&snapshot.images); + + // The output is the Normal map's slot (`set_pickup_output`) + compositor.make_room(key); + compositor.compose_now((device, queue), &program, (key, (size[0], size[1])), &[&target, &target, &target])?; + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_pickup_source") }); + encoder.copy_texture_to_texture( + target.as_image_copy(), + wgpu::TexelCopyTextureInfo { origin: wgpu::Origin3d { x: 0, y: 0, z: layer }, ..maps.as_image_copy() }, + extent(size[0], size[1]), + ); + queue.submit([encoder.finish()]); + } + compositor.make_room(key); + Ok(maps) +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + + use std::sync::Arc; + + use texturecraft_compose::{Composite, Inputs, PaintTarget, all_tiles, composite_tiles}; + use texturecraft_core::{ + Channel, ChannelFormat, Effect, EffectKind, Fill, Layer, LayerKind, Mask, MaskBackground, Procedural, ProceduralKind, Project, Source, TextureSet, + }; + use texturecraft_geom::{Bvh, UvGBuffer, primitives}; + use texturecraft_paint::pickup::PickupSnapshot; + use texturecraft_paint::{BrushSettings, SmudgeSource}; + use texturecraft_texel::{TILE, TileImage}; + + use super::*; + use crate::gpu_composite::GpuCompositor; + use crate::headless::Headless; + use crate::readback::Readback; + + const SIZE: u32 = 2 * TILE; + + fn clouds(scale: f32, high: [f32; 3]) -> Source { + Source::Procedural { pattern: Procedural { scale, ..Procedural::new(ProceduralKind::Clouds) }, low: [0.1, -0.4, 0.2], high, ramp: Vec::new() } + } + + /// Layer `layer` of `maps` (RGBA16) as 16-bit values per texel + fn read_layer(gpu: &Headless, maps: &wgpu::Texture, layer: u32) -> Vec<[u16; 4]> { + let flat = texture(&gpu.device, [SIZE, SIZE], wgpu::TextureFormat::Rgba16Uint); + let mut encoder = gpu.device.create_command_encoder(&Default::default()); + encoder.copy_texture_to_texture( + wgpu::TexelCopyTextureInfo { origin: wgpu::Origin3d { x: 0, y: 0, z: layer }, ..maps.as_image_copy() }, + flat.as_image_copy(), + extent(SIZE, SIZE), + ); + gpu.queue.submit([encoder.finish()]); + let (_, _, bytes) = Readback::blocking(&gpu.device, &gpu.queue, &flat).unwrap(); + bytemuck::cast_slice::(&bytes).as_chunks::<4>().0.to_vec() + } + + /// The GPU compositor writes a smudge's source as the CPU composites it: the document's color + /// and scalar channels (signed ones included, four scalars per layer) and a mask's values + #[test] + fn smudge_sources_composite_on_the_gpu_as_on_the_cpu() { + let Some(gpu) = Headless::for_required_tests() else { return }; + let mut project = Project::new("source", "builtin:plane"); + let mut set = TextureSet::new("set", 0, SIZE); + set.channels.extend([Channel::Opacity, Channel::AmbientOcclusion].map(|channel| (channel, ChannelFormat::default_for(channel)))); + project.texture_sets.push(set); + let channels = [Channel::BaseColor, Channel::Roughness, Channel::Metallic, Channel::Height, Channel::Opacity, Channel::AmbientOcclusion]; + let mut fill = Fill::default(); + for (index, channel) in channels.into_iter().enumerate() { + fill.sources.insert(channel, clouds(2.0 + index as f32, [0.9, 0.7 - 0.1 * index as f32, 0.4])); + } + let id = project.alloc_id(); + let mut layer = Layer::new(id, "clouds", LayerKind::Fill(fill), &channels); + let mut mask = Mask::new(MaskBackground::Black); + let effect = + Effect::new(project.alloc_id(), EffectKind::Fill { source: clouds(3.0, [0.8; 3]), projection: Default::default(), sampling: Default::default() }); + mask.effects.push(effect); + layer.mask = Some(mask); + project.insert_layer(0, layer, None, false).unwrap(); + + let mesh = Arc::new(primitives::plane(2.0, 4)); + let uv = Arc::new(UvGBuffer::new(&mesh, 0, SIZE, SIZE)); + let snapshot = |target| PickupSnapshot { + project: project.clone(), + ts: 0, + target, + mesh: mesh.clone(), + bounds: mesh.bounds(), + pixels: Default::default(), + baked: Default::default(), + images: Default::default(), + }; + let cpu_snapshot = snapshot(None); + let inputs = Inputs { + project: &project, + ts: 0, + mesh: &mesh, + gbuf: &uv, + pixels: &cpu_snapshot.pixels, + baked: &cpu_snapshot.baked, + block_scales: project.texture_sets[0].block_scales(), + preview: None, + images: &cpu_snapshot.images, + bounds: mesh.bounds(), + }; + let mut cpu = Composite::with_size(&channels, SIZE, SIZE); + composite_tiles(&inputs, &mut cpu, &all_tiles(SIZE, SIZE)); + let mut mask_values = TileImage::new(SIZE, SIZE, 1); + texturecraft_compose::eval::mask_values_into(&inputs, id, &all_tiles(SIZE, SIZE), &mut mask_values); + let mask_channel = texturecraft_compose::MASK_CHANNEL; + + let mut compositor = GpuCompositor::new(&gpu.device); + for (target, expected) in + [(None, channels.map(|channel| (channel, &cpu.channels[&channel])).to_vec()), (Some(PaintTarget::Mask(id)), vec![(mask_channel, &mask_values)])] + { + let source_channels = expected.iter().map(|(channel, _)| (*channel, TileImage::new(SIZE, SIZE, channel.components()))).collect(); + let source = SmudgeSource { + strength: 1.0, + isolated: false, + channels: source_channels, + composited: Some(Arc::new(snapshot(target))), + coverage: None, + clone_offset: None, + }; + let input = BrushInput { + mesh: mesh.clone(), + bvh: Arc::new(Bvh::new(&mesh)), + uv: uv.clone(), + material: 0, + depth: None, + settings: BrushSettings::default(), + alpha_image: None, + stencil: None, + limit: None, + clone: None, + smudge: Some(source), + }; + let maps = composite_pickup_source(&mut compositor, (&gpu.device, &gpu.queue), &input).unwrap().unwrap(); + + // Scalars four per layer in their order, colors one per layer + let (mut scalars, mut colors) = (0, 0); + for (channel, image) in expected { + let components = channel.components(); + let (layer, offset) = if components == 3 { (colors, 0) } else { (scalars / 4, scalars % 4) }; + let texels = read_layer(&gpu, if components == 3 { &maps.1 } else { &maps.0 }, layer); + if components == 3 { + colors += 1 + } else { + scalars += 1 + } + let mut differ = 0; + for (index, texel) in texels.iter().enumerate() { + let (x, y) = (index as u32 % SIZE, index as u32 / SIZE); + if !uv.covered(index) { + continue; + } + + let gpu_value = &texel[offset as usize..offset as usize + components]; + differ += usize::from(image.get(x, y).iter().zip(gpu_value).any(|(cpu, gpu)| cpu.abs_diff(*gpu) > 64)); + } + assert!(differ == 0, "{target:?} {channel:?}: {differ} texels differ"); + } + } + } + + /// A brush material's source composites under its own cache key: the document's cached + /// inputs of the same texture set index (its baked maps here) survive a pattern stroke start + #[test] + fn a_brush_material_source_keeps_the_documents_cached_inputs() { + let Some(gpu) = Headless::for_required_tests() else { return }; + let mut project = Project::new("source", "builtin:plane"); + project.texture_sets.push(TextureSet::new("set", 0, SIZE)); + let mut fill = Fill::default(); + fill.sources.insert(Channel::BaseColor, clouds(2.0, [0.9, 0.7, 0.4])); + let id = project.alloc_id(); + project.insert_layer(0, Layer::new(id, "clouds", LayerKind::Fill(fill), &[Channel::BaseColor]), None, false).unwrap(); + let mesh = Arc::new(primitives::plane(2.0, 4)); + let uv = Arc::new(UvGBuffer::new(&mesh, 0, SIZE, SIZE)); + let occlusion = Arc::new(vec![0.5; (SIZE * SIZE) as usize]); + let document_baked = texturecraft_compose::BakedMaps { + resolution: SIZE, + maps: std::collections::BTreeMap::from([(texturecraft_core::BakedMap::AmbientOcclusion, occlusion.clone())]), + }; + let mut compositor = GpuCompositor::new(&gpu.device); + for (target, baked) in [(None, document_baked), (Some(PaintTarget::Layer(id)), Default::default())] { + let snapshot = PickupSnapshot { + project: project.clone(), + ts: 0, + target, + mesh: mesh.clone(), + bounds: mesh.bounds(), + pixels: Default::default(), + baked, + images: Default::default(), + }; + let clone = texturecraft_paint::CloneSource { + offset: [0; 2], + coverage: None, + channels: vec![(Channel::BaseColor, TileImage::new(SIZE, SIZE, 3))], + composited: Some(Arc::new(snapshot)), + }; + let input = BrushInput { + mesh: mesh.clone(), + bvh: Arc::new(Bvh::new(&mesh)), + uv: uv.clone(), + material: 0, + depth: None, + settings: BrushSettings::default(), + alpha_image: None, + stencil: None, + limit: None, + clone: Some(clone), + smudge: None, + }; + composite_pickup_source(&mut compositor, (&gpu.device, &gpu.queue), &input).unwrap().unwrap(); + assert!(compositor.caches_baked_map(0, &occlusion), "{target:?}: the document's baked inputs stay cached"); + } + } +} diff --git a/crates/render/src/gpu_brush/smudge.rs b/crates/render/src/gpu_brush/smudge.rs new file mode 100644 index 000000000..05fda627d --- /dev/null +++ b/crates/render/src/gpu_brush/smudge.rs @@ -0,0 +1,1211 @@ +//! Smudge on the GPU brush: one measure, resolve and deposit per stamp (smudge.wgsl), the source +//! and the carried values in 16-bit textures, a lane per symmetry copy. + +use std::collections::BTreeMap; + +use texturecraft_core::Channel; +use texturecraft_paint::{SmudgeLane, SmudgeSource, StampSource}; +use texturecraft_texel::{TILE, TILE_AREA, TileImage}; +use wgpu::util::DeviceExt; + +use super::{CHUNK, Dab, GpuBrushStroke, ROW_BYTES, TILE_BYTES, Tiles, buffer, extent, storage, tile_copy}; +use crate::gpu_composite::{CarriedSlot, LiveCarried}; + +/// u32 words of one R16 tile (rows of 256 bytes) and of one RGBA16 tile (rows of 512 bytes) +const SCALAR_TILE_WORDS: u32 = TILE * ROW_BYTES / 4; +const COLOR_TILE_WORDS: u32 = TILE * TILE * 2; +const COLOR_ROW_BYTES: u32 = TILE * 8; +/// u32 words of one stamp's state (smudge.wgsl `stamp_state`) and of one lane's +const STAMP_WORDS: usize = 12; +const LANE_WORDS: u64 = 4; + +/// The smudge pipelines of one brush kernel (alpha kind, shared surfaces) +#[derive(Clone)] +pub(crate) struct SmudgePipelines { + pub(super) measure: wgpu::ComputePipeline, + pub(super) center: wgpu::ComputePipeline, + pub(super) resolve: wgpu::ComputePipeline, + pub(super) deposit: wgpu::ComputePipeline, +} + +impl SmudgePipelines { + pub(super) fn new(device: &wgpu::Device, shader: &wgpu::ShaderModule, inputs: &wgpu::BindGroupLayout, alpha_kind: u32, shared_surfaces: bool) -> Self { + let state = device + .create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("tc_smudge_state"), entries: &[crate::gpu_trace::storage(0, false)] }); + + // The measure reads the brush's non-filterable float textures (depth, tip): an explicit layout + let layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("tc_smudge_measure"), + bind_group_layouts: &[Some(inputs), Some(&state)], + immediate_size: 0, + }); + let constants = [("alpha_kind", f64::from(alpha_kind)), ("shared_surfaces", f64::from(u8::from(shared_surfaces)))]; + let pipeline = |entry: &str, layout: Option<&wgpu::PipelineLayout>| { + device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("tc_smudge"), + layout, + module: shader, + entry_point: Some(entry), + compilation_options: wgpu::PipelineCompilationOptions { constants: &constants, ..Default::default() }, + cache: None, + }) + }; + Self { + measure: pipeline("smudge_measure", Some(&layout)), + center: pipeline("smudge_center", Some(&layout)), + resolve: pipeline("smudge_resolve", None), + deposit: pipeline("smudge_deposit", None), + } + } +} + +#[repr(C)] +#[derive(Clone, Copy, bytemuck::Pod, bytemuck::Zeroable)] +struct SmudgeUniform { + strength: f32, + isolated: u32, + scalars: u32, + colors: u32, + tile_words: u32, + /// 1 when every channel weighs its deposits by its source coverage and keeps its own alpha + channel_alphas: u32, + /// 1 for a clone painted stamp by stamp: it reads the source at `clone_offset` + clone_mode: u32, + clone_offset: [i32; 2], + padding: [u32; 3], +} + +/// One symmetry copy's own alpha and carried values +struct Lane { + alpha: wgpu::Texture, + scalars: wgpu::Texture, + colors: wgpu::Texture, +} + +pub(super) struct GpuSmudge { + pipelines: SmudgePipelines, + uniform: wgpu::Buffer, + /// The carried channels with their layer in the scalar or the color textures + channels: Vec<(Channel, bool, u32)>, + /// Every channel keeps its own alpha: R16 layers after the scalar values in the carried and + /// the lanes' scalar maps (scalars first, then colors, see [`alpha_index`]) + channel_alphas: bool, + isolated: bool, + tile_words: u32, + source: (wgpu::Texture, wgpu::Texture), + carried: (wgpu::Texture, wgpu::Texture), + /// Lane by symmetry copy (isolated) or the stroke's one lane, and the lanes' state + sources: Vec>, + lanes: Vec, + lane_state: wgpu::Buffer, + /// Bound in place of lane textures when the copies share the stroke's + blank: Lane, + /// One deposit output per chunk position, reused by every stamp (a stamp's chunks need their + /// own, as all of them deposit before any copies back) + outputs: Vec, + /// Tests: fewer tiles per chunk than the device's limits allow + #[cfg(test)] + chunk_limit: Option, + /// Tests: how many deposit outputs the stroke allocated + #[cfg(test)] + output_allocations: usize, +} + +fn array_texture(device: &wgpu::Device, size: [u32; 2], layers: u32, format: wgpu::TextureFormat) -> wgpu::Texture { + device.create_texture(&wgpu::TextureDescriptor { + label: Some("tc_pickup_map"), + size: wgpu::Extent3d { width: size[0], height: size[1], depth_or_array_layers: layers.max(1) }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format, + usage: wgpu::TextureUsages::TEXTURE_BINDING | wgpu::TextureUsages::COPY_SRC | wgpu::TextureUsages::COPY_DST, + view_formats: &[], + }) +} + +pub(super) fn array_view(texture: &wgpu::Texture) -> wgpu::TextureView { + texture.create_view(&wgpu::TextureViewDescriptor { dimension: Some(wgpu::TextureViewDimension::D2Array), ..Default::default() }) +} + +pub(super) fn layer_copy(texture: &wgpu::Texture, (x, y): (u32, u32), layer: u32) -> wgpu::TexelCopyTextureInfo<'_> { + wgpu::TexelCopyTextureInfo { origin: wgpu::Origin3d { x: x * TILE, y: y * TILE, z: layer }, ..texture.as_image_copy() } +} + +pub(super) fn rows(buffer: &wgpu::Buffer, offset: u64, bytes_per_row: u32) -> wgpu::TexelCopyBufferInfo<'_> { + wgpu::TexelCopyBufferInfo { buffer, layout: wgpu::TexelCopyBufferLayout { offset, bytes_per_row: Some(bytes_per_row), rows_per_image: None } } +} + +/// Whether the adapter can run the smudge passes (one storage buffer more than the brush) +pub(crate) fn check_limits(device: &wgpu::Device) -> Result<(), String> { + if device.limits().max_storage_buffers_per_shader_stage < 8 { + return Err("adapter limits do not support the GPU smudge".into()); + } + Ok(()) +} + +/// A smudge's or a clone's source values: scalar channels four per RGBA16 layer, channels of +/// three components one per RGBA16 layer +pub(crate) type SourceMaps = (wgpu::Texture, wgpu::Texture); + +/// The carried channels of a source (`channels`, [`SmudgeSource::channels`]) with whether they +/// have three components and their layer (the index among the scalar or the color channels) +pub(crate) fn source_layout(device: &wgpu::Device, size: [u32; 2], source: &[(Channel, TileImage)]) -> Result, String> { + let mut channels = Vec::new(); + let (mut scalars, mut colors) = (0, 0); + for (channel, image) in source { + let color = match image.comps() { + 1 => false, + 3 => true, + _ => return Err("The GPU brush carries one or three components per channel.".into()), + }; + if [image.width(), image.height()] != size { + return Err("The clone or smudge source does not match the GPU brush texture size.".into()); + } + + let layer = if color { &mut colors } else { &mut scalars }; + channels.push((*channel, color, *layer)); + *layer += 1; + } + if scalars.max(colors) > device.limits().max_texture_array_layers { + return Err("The carried channels exceed the adapter's texture array layers.".into()); + } + Ok(channels) +} + +/// Source arrays for `layout` (zero) +pub(crate) fn source_maps(device: &wgpu::Device, size: [u32; 2], layout: &[(Channel, bool, u32)]) -> SourceMaps { + source_maps_with(device, size, layout, false) +} + +/// Source arrays for `layout`, with `coverage` the channels' coverages (four per RGBA16 layer, by +/// [`alpha_index`]) after the scalar layers +fn source_maps_with(device: &wgpu::Device, size: [u32; 2], layout: &[(Channel, bool, u32)], coverage: bool) -> SourceMaps { + let colors = layout.iter().filter(|(_, color, _)| *color).count() as u32; + let scalars = layout.len() as u32 - colors; + let coverage_layers = if coverage { (layout.len() as u32).div_ceil(4) } else { 0 }; + ( + array_texture(device, size, scalars.div_ceil(4) + coverage_layers, wgpu::TextureFormat::Rgba16Uint), + array_texture(device, size, colors, wgpu::TextureFormat::Rgba16Uint), + ) +} + +/// A channel's index among the per-channel alphas and coverages: the scalar channels by layer, +/// then the color channels (smudge.wgsl `channel_stamp`) +fn alpha_index(scalars: u32, color: bool, layer: u32) -> u32 { + if color { scalars + layer } else { layer } +} + +/// Write `coverage` (one image per channel of `layout`) into the source's scalar map after its +/// value layers, four channels per layer +fn upload_coverage(queue: &wgpu::Queue, maps: &SourceMaps, layout: &[(Channel, bool, u32)], coverage: &[TileImage]) { + let scalars = layout.iter().filter(|(_, color, _)| !*color).count() as u32; + let mut indexed: Vec<(u32, &TileImage)> = + layout.iter().zip(coverage).map(|((_, color, layer), image)| (alpha_index(scalars, *color, *layer), image)).collect(); + indexed.sort_by_key(|(index, _)| *index); + for group in indexed.chunks(4) { + let tiles: std::collections::BTreeSet<(u32, u32)> = group.iter().flat_map(|(_, image)| image.allocated()).collect(); + for tile in tiles { + let mut texels = vec![0u16; TILE_AREA * 4]; + for (index, image) in group { + let Some(data) = image.tile(tile.0, tile.1) else { continue }; + for (texel, &value) in data.iter().enumerate().take(TILE_AREA) { + texels[texel * 4 + (*index % 4) as usize] = value; + } + } + let layer = scalars.div_ceil(4) + group[0].0 / 4; + queue.write_texture(layer_copy(&maps.0, tile, layer), bytemuck::cast_slice(&texels), row_layout(COLOR_ROW_BYTES), extent(TILE, TILE)); + } + } +} + +/// The source of a clone or smudge whose values the CPU evaluated (`source`, laid out as `layout`) +pub(super) fn upload_source( + device: &wgpu::Device, + queue: &wgpu::Queue, + size: [u32; 2], + source: &[(Channel, TileImage)], + layout: &[(Channel, bool, u32)], +) -> SourceMaps { + upload_source_with(device, queue, size, source, layout, None) +} + +/// [`upload_source`] with the channels' `coverage` (see [`source_maps_with`]) +fn upload_source_with( + device: &wgpu::Device, + queue: &wgpu::Queue, + size: [u32; 2], + source: &[(Channel, TileImage)], + layout: &[(Channel, bool, u32)], + coverage: Option<&[TileImage]>, +) -> SourceMaps { + let maps = source_maps_with(device, size, layout, coverage.is_some()); + if let Some(coverage) = coverage { + upload_coverage(queue, &maps, layout, coverage); + } + let images: Vec<(bool, u32, &TileImage)> = layout.iter().zip(source).map(|((_, color, layer), (_, image))| (*color, *layer, image)).collect(); + for &(_, layer, image) in images.iter().filter(|(color, ..)| *color) { + for tile in image.allocated() { + let Some(data) = image.tile(tile.0, tile.1) else { continue }; + let bytes: Vec = data.as_chunks::<3>().0.iter().flat_map(|&[red, green, blue]| [red, green, blue, 0]).flat_map(u16::to_le_bytes).collect(); + queue.write_texture(layer_copy(&maps.1, tile, layer), &bytes, row_layout(COLOR_ROW_BYTES), extent(TILE, TILE)); + } + } + + // Four scalar channels share a layer: one texel holds a component of each + let scalars: Vec<(u32, &TileImage)> = images.iter().filter(|(color, ..)| !*color).map(|&(_, layer, image)| (layer, image)).collect(); + for group in scalars.chunks(4) { + let tiles: std::collections::BTreeSet<(u32, u32)> = group.iter().flat_map(|(_, image)| image.allocated()).collect(); + for tile in tiles { + let mut texels = vec![0u16; TILE_AREA * 4]; + for (component, (_, image)) in group.iter().enumerate() { + let Some(data) = image.tile(tile.0, tile.1) else { continue }; + for (texel, &value) in data.iter().enumerate().take(TILE_AREA) { + texels[texel * 4 + component] = value; + } + } + queue.write_texture(layer_copy(&maps.0, tile, group[0].0 / 4), bytemuck::cast_slice(&texels), row_layout(COLOR_ROW_BYTES), extent(TILE, TILE)); + } + } + maps +} + +fn row_layout(bytes_per_row: u32) -> wgpu::TexelCopyBufferLayout { + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(bytes_per_row), rows_per_image: None } +} + +impl GpuSmudge { + /// Allocate the stroke's carried values (zero) for `source`, taking its values from `maps` + /// (composited on the GPU, [`source_layout`]) or uploading them from `source`. + pub(super) fn new( + device: &wgpu::Device, + queue: &wgpu::Queue, + pipelines: SmudgePipelines, + size: [u32; 2], + source: &SmudgeSource, + maps: Option, + ) -> Result { + check_limits(device)?; + let channels = source_layout(device, size, &source.channels)?; + let scalars = channels.iter().filter(|(_, color, _)| !*color).count() as u32; + let colors = channels.len() as u32 - scalars; + let coverage = source.coverage.as_deref().filter(|coverage| coverage.len() == channels.len()); + if source.coverage.is_some() && coverage.is_none() { + return Err("The smudge source's coverage does not match its channels.".into()); + } + let channel_alphas = if coverage.is_some() { channels.len() as u32 } else { 0 }; + if scalars + channel_alphas > device.limits().max_texture_array_layers { + return Err("The carried channels exceed the adapter's texture array layers.".into()); + } + let source_maps = match maps { + Some(_) if coverage.is_some() => return Err("A composited smudge source has no per-channel coverage.".into()), + Some(maps) => maps, + None => upload_source_with(device, queue, size, &source.channels, &channels, coverage), + }; + let lanes_per_tile = 1 + u32::from(source.isolated); + let tile_words = lanes_per_tile * (SCALAR_TILE_WORDS * (1 + scalars + channel_alphas) + COLOR_TILE_WORDS * colors); + let clone_offset = source.clone_offset.map_or([0; 2], |offset| super::brush_pipeline::clone_offset(offset, size)); + let uniform = SmudgeUniform { + strength: source.strength, + isolated: u32::from(source.isolated), + scalars, + colors, + tile_words, + channel_alphas: u32::from(coverage.is_some()), + clone_mode: u32::from(source.clone_offset.is_some()), + clone_offset, + padding: [0; 3], + }; + Ok(GpuSmudge { + pipelines, + uniform: device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("tc_smudge"), + contents: bytemuck::bytes_of(&uniform), + usage: wgpu::BufferUsages::UNIFORM, + }), + channels, + channel_alphas: coverage.is_some(), + isolated: source.isolated, + tile_words, + source: source_maps, + carried: ( + array_texture(device, size, scalars + channel_alphas, wgpu::TextureFormat::R16Uint), + array_texture(device, size, colors, wgpu::TextureFormat::Rgba16Uint), + ), + sources: Vec::new(), + lanes: Vec::new(), + lane_state: buffer( + device, + "tc_smudge_lanes", + LANE_WORDS * 4 * 8, + wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST, + ), + blank: Lane { + alpha: super::texture(device, [1, 1], wgpu::TextureFormat::R16Uint), + scalars: array_texture(device, [1, 1], 1, wgpu::TextureFormat::R16Uint), + colors: array_texture(device, [1, 1], 1, wgpu::TextureFormat::Rgba16Uint), + }, + outputs: Vec::new(), + #[cfg(test)] + chunk_limit: None, + #[cfg(test)] + output_allocations: 0, + }) + } + + /// The lane of the copy `source` (the stroke's only lane unless isolated), its textures + /// allocated and its state slot zeroed when the copy first stamps + fn lane(&mut self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, size: [u32; 2], source: Option) -> u32 { + let source = source.filter(|_| self.isolated); + if let Some(index) = self.sources.iter().position(|known| *known == source) { + return index as u32; + } + + let index = self.sources.len(); + self.sources.push(source); + let needed = (index as u64 + 1) * LANE_WORDS * 4; + if needed > self.lane_state.size() { + let grown = + buffer(device, "tc_smudge_lanes", needed * 2, wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC | wgpu::BufferUsages::COPY_DST); + encoder.copy_buffer_to_buffer(&self.lane_state, 0, &grown, 0, Some(self.lane_state.size())); + self.lane_state = grown; + } + encoder.clear_buffer(&self.lane_state, index as u64 * LANE_WORDS * 4, Some(LANE_WORDS * 4)); + if self.isolated { + let (scalars, colors) = self.layers(); + self.lanes.push(Lane { + alpha: super::texture(device, size, wgpu::TextureFormat::R16Uint), + scalars: array_texture(device, size, scalars + self.alpha_layers(), wgpu::TextureFormat::R16Uint), + colors: array_texture(device, size, colors, wgpu::TextureFormat::Rgba16Uint), + }); + } + index as u32 + } + + /// The carried values for the live compositor: one R16 layer per scalar channel, one RGBA16 + /// layer per color channel, read in place + pub(super) fn live(&self) -> LiveCarried { + let channels = self + .channels + .iter() + .map(|&(channel, color, layer)| (channel, CarriedSlot { color, layer, component: 0, alpha: self.alpha_layer(color, layer) })) + .collect(); + LiveCarried { scalars: array_view(&self.carried.0), colors: array_view(&self.carried.1), offset: [0; 2], channels } + } + + fn layers(&self) -> (u32, u32) { + let colors = self.channels.iter().filter(|(_, color, _)| *color).count() as u32; + (self.channels.len() as u32 - colors, colors) + } + + /// The R16 layers of per-channel alphas after the scalar values (none without them) + fn alpha_layers(&self) -> u32 { + if self.channel_alphas { self.channels.len() as u32 } else { 0 } + } + + /// The scalar-map layer of a channel's own alpha + fn alpha_layer(&self, color: bool, layer: u32) -> Option { + let scalars = self.layers().0; + self.channel_alphas.then(|| scalars + alpha_index(scalars, color, layer)) + } +} + +/// One chunk of a stamp's tiles with its bind groups +struct StampChunk<'a> { + tiles: &'a [(u32, u32)], + inputs: wgpu::BindGroup, + stamp: wgpu::BindGroup, + deposit: (wgpu::BindGroup, wgpu::BindGroup), + output: &'a wgpu::Buffer, +} + +fn run(encoder: &mut wgpu::CommandEncoder, pipeline: &wgpu::ComputePipeline, groups: [&wgpu::BindGroup; 2], workgroups: [u32; 3]) { + let mut pass = encoder.begin_compute_pass(&Default::default()); + pass.set_pipeline(pipeline); + pass.set_bind_group(0, groups[0], &[]); + pass.set_bind_group(1, groups[1], &[]); + pass.dispatch_workgroups(workgroups[0], workgroups[1], workgroups[2]); +} + +impl GpuBrushStroke { + /// Paint smudge `stamps` (each dab with its tiles and symmetry copy) one after another. + pub(super) fn smudge_stamps(&mut self, stamps: Vec<(Dab, Tiles, Option)>, uv: bool) -> Result<(), String> { + let Some(mut smudge) = self.smudge.take() else { return Err("The stroke has no GPU smudge.".into()) }; + let device = self.device.clone(); + let result = crate::gpu_trace::scoped(&device, "GPU smudge", || self.smudge_with(&mut smudge, stamps, uv)).and_then(|result| result); + self.smudge = Some(smudge); + result + } + + fn smudge_with(&mut self, smudge: &mut GpuSmudge, stamps: Vec<(Dab, Tiles, Option)>, uv: bool) -> Result<(), String> { + let (device, queue) = (self.device.clone(), self.queue.clone()); + let size = [self.input.uv.width, self.input.uv.height]; + let limits = device.limits(); + let binding = limits.max_storage_buffer_binding_size.min(limits.max_buffer_size); + // The scratch holds each tile's opacity and distance per texel + let tile_bytes = (2 * TILE_BYTES).max(u64::from(smudge.tile_words) * 4); + let per_chunk = ((binding / tile_bytes) as usize).min(limits.max_compute_workgroups_per_dimension as usize); + #[cfg(test)] + let per_chunk = per_chunk.min(smudge.chunk_limit.unwrap_or(usize::MAX)); + if per_chunk == 0 { + return Err("One GPU smudge tile exceeds the adapter's buffer limits.".into()); + } + + let mut params = self.params; + params.flags[0] = u32::from(uv); + let uniform = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("tc_brush_parameters"), + contents: bytemuck::bytes_of(¶ms), + usage: wgpu::BufferUsages::UNIFORM, + }); + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_smudge") }); + for (dab, tiles, source) in stamps { + if tiles.is_empty() { + continue; + } + + self.written.extend(&tiles); + let lane = smudge.lane(&device, &mut encoder, size, source); + let mut state = [0_u32; STAMP_WORDS]; + state[..6].copy_from_slice(&[u32::MAX, u32::MAX, 0, 0, u32::MAX, u32::MAX]); + state[9] = lane; + state[10] = dab.center[0].to_bits(); + state[11] = dab.center[1].to_bits(); + let state = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("tc_smudge_stamp"), + contents: bytemuck::cast_slice(&state), + usage: wgpu::BufferUsages::STORAGE, + }); + let dabs = storage(&device, "tc_brush_dabs", &[dab]); + let tiles: Vec<(u32, u32)> = tiles.into_iter().collect(); + let chunk_tiles = tiles.len().min(per_chunk) as u64; + let scratch_bytes = 2 * chunk_tiles * TILE_BYTES; + if self.scratch.as_ref().is_none_or(|scratch| scratch.size() < scratch_bytes) { + let bytes = scratch_bytes.next_power_of_two().min(binding).max(scratch_bytes); + self.scratch = Some(buffer(&device, "tc_brush_scratch", bytes, wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC)); + } + + // Every chunk deposits before any copies back, so all reads see the state before the stamp + let output_bytes = chunk_tiles * u64::from(smudge.tile_words) * 4; + let chunk_count = tiles.len().div_ceil(per_chunk); + for position in 0..chunk_count { + if smudge.outputs.get(position).is_none_or(|output| output.size() < output_bytes) { + let bytes = output_bytes.next_power_of_two().min(binding).max(output_bytes); + let output = buffer(&device, "tc_smudge_output", bytes, wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC); + #[cfg(test)] + { + smudge.output_allocations += 1; + } + match smudge.outputs.get_mut(position) { + Some(slot) => *slot = output, + None => smudge.outputs.push(output), + } + } + } + let outputs = &smudge.outputs[..chunk_count]; + let scratch = self.scratch.as_ref().ok_or("brush scratch buffer missing")?; + let lane_textures = smudge.lanes.get(lane as usize).filter(|_| smudge.isolated).unwrap_or(&smudge.blank); + let lane_views = (lane_textures.alpha.create_view(&Default::default()), array_view(&lane_textures.scalars), array_view(&lane_textures.colors)); + let maps = [&smudge.source.0, &smudge.source.1, &smudge.carried.0, &smudge.carried.1].map(array_view); + let chunks: Vec = tiles + .chunks(per_chunk) + .zip(outputs) + .map(|(chunk, output)| { + let mut cells = self.tile_cells(chunk.iter().map(|&tile| (tile, &[0_u32][..]))); + for index in 0..chunk.len() { + cells[index * 6 + 5] = ((chunk.len() + index) * TILE_AREA) as u32; + } + let cells = storage(&device, "tc_brush_tiles", &cells); + let inputs = self.inputs_bind_group(&smudge.pipelines.measure.get_bind_group_layout(0), &uniform, &dabs, &cells, scratch); + let stamp = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("tc_smudge_stamp"), + layout: &smudge.pipelines.measure.get_bind_group_layout(1), + entries: &[wgpu::BindGroupEntry { binding: 0, resource: state.as_entire_binding() }], + }); + let deposit_inputs = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("tc_smudge_deposit_inputs"), + layout: &smudge.pipelines.deposit.get_bind_group_layout(0), + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(&self.surface.0) }, + wgpu::BindGroupEntry { binding: 5, resource: wgpu::BindingResource::TextureView(&self.view) }, + wgpu::BindGroupEntry { binding: 8, resource: cells.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 9, resource: scratch.as_entire_binding() }, + ], + }); + let view = wgpu::BindingResource::TextureView; + let deposit = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("tc_smudge_deposit"), + layout: &smudge.pipelines.deposit.get_bind_group_layout(1), + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: state.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 2, resource: smudge.uniform.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 3, resource: view(&lane_views.0) }, + wgpu::BindGroupEntry { binding: 4, resource: view(&maps[0]) }, + wgpu::BindGroupEntry { binding: 5, resource: view(&maps[1]) }, + wgpu::BindGroupEntry { binding: 6, resource: view(&maps[2]) }, + wgpu::BindGroupEntry { binding: 7, resource: view(&maps[3]) }, + wgpu::BindGroupEntry { binding: 8, resource: view(&lane_views.1) }, + wgpu::BindGroupEntry { binding: 9, resource: view(&lane_views.2) }, + wgpu::BindGroupEntry { binding: 10, resource: output.as_entire_binding() }, + ], + }); + StampChunk { tiles: chunk, inputs, stamp, deposit: (deposit_inputs, deposit), output } + }) + .collect(); + let resolve = ( + device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("tc_smudge_resolve_inputs"), + layout: &smudge.pipelines.resolve.get_bind_group_layout(0), + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 3, resource: wgpu::BindingResource::TextureView(&self.surface.0) }, + ], + }), + device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("tc_smudge_resolve"), + layout: &smudge.pipelines.resolve.get_bind_group_layout(1), + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: state.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 1, resource: smudge.lane_state.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 2, resource: smudge.uniform.as_entire_binding() }, + ], + }), + ); + + // Measure the whole stamp before it resolves; reads see the state before the stamp + let groups = |chunk: &StampChunk| [TILE / 16, TILE / 8, chunk.tiles.len() as u32]; + for chunk in &chunks { + run(&mut encoder, &smudge.pipelines.measure, [&chunk.inputs, &chunk.stamp], groups(chunk)); + } + if !uv { + for chunk in &chunks { + run(&mut encoder, &smudge.pipelines.center, [&chunk.inputs, &chunk.stamp], groups(chunk)); + } + } + run(&mut encoder, &smudge.pipelines.resolve, [&resolve.0, &resolve.1], [1, 1, 1]); + for chunk in &chunks { + // The scratch holds the last chunk's opacity: measure again when there are several + if chunks.len() > 1 { + run(&mut encoder, &smudge.pipelines.measure, [&chunk.inputs, &chunk.stamp], groups(chunk)); + } + run(&mut encoder, &smudge.pipelines.deposit, [&chunk.deposit.0, &chunk.deposit.1], groups(chunk)); + } + for chunk in &chunks { + let output = chunk.output; + for (index, &tile) in chunk.tiles.iter().enumerate() { + let mut offset = index as u64 * u64::from(smudge.tile_words) * 4; + let mut copy = |encoder: &mut wgpu::CommandEncoder, texture: &wgpu::Texture, layer: u32, color: bool| { + let (row, words) = if color { (COLOR_ROW_BYTES, COLOR_TILE_WORDS) } else { (ROW_BYTES, SCALAR_TILE_WORDS) }; + encoder.copy_buffer_to_texture(rows(output, offset, row), layer_copy(texture, tile, layer), extent(TILE, TILE)); + offset += u64::from(words) * 4; + }; + copy(&mut encoder, &self.alpha, 0, false); + let lane_maps = smudge.lanes.get(lane as usize).filter(|_| smudge.isolated); + if let Some(lane_maps) = lane_maps { + copy(&mut encoder, &lane_maps.alpha, 0, false); + } + for color in [false, true] { + for (_, _, layer) in smudge.channels.iter().filter(|(_, is_color, _)| *is_color == color) { + copy(&mut encoder, if color { &smudge.carried.1 } else { &smudge.carried.0 }, *layer, color); + if let Some(lane_maps) = lane_maps { + copy(&mut encoder, if color { &lane_maps.colors } else { &lane_maps.scalars }, *layer, color); + } + } + } + + // Then each channel's own alpha, in alpha index order + let scalars = smudge.layers().0; + for index in 0..smudge.alpha_layers() { + copy(&mut encoder, &smudge.carried.0, scalars + index, false); + if let Some(lane_maps) = lane_maps { + copy(&mut encoder, &lane_maps.scalars, scalars + index, false); + } + } + } + } + } + queue.submit([encoder.finish()]); + Ok(()) + } + + /// The stroke alpha and a clone's or smudge's carried values (straight, encoded) of `tiles`. + pub fn read_carried(&self, tiles: &Tiles) -> Result<(TileImage, BTreeMap), String> { + if let Some(clone) = &self.clone_source { + return self.read_clone(clone, tiles); + } + + let Some(smudge) = &self.smudge else { return Err("The stroke carries no values on the GPU.".into()) }; + self.read_maps(smudge, (&self.alpha, &smudge.carried.0, &smudge.carried.1), tiles) + } + + /// Each carried channel's own stroke alpha of `tiles` (a source with per-channel coverage; + /// empty otherwise) + pub fn read_channel_alphas(&self, tiles: &Tiles) -> Result, String> { + match &self.smudge { + Some(smudge) => self.read_alphas_of(smudge, &smudge.carried.0, tiles), + None => Ok(BTreeMap::new()), + } + } + + /// The per-channel alphas (R16 layers after the scalar values of `scalars`) of `tiles` + fn read_alphas_of(&self, smudge: &GpuSmudge, scalars: &wgpu::Texture, tiles: &Tiles) -> Result, String> { + if !smudge.channel_alphas { + return Ok(BTreeMap::new()); + } + + self.validate_readback_tiles(tiles)?; + let (width, height) = (self.input.uv.width, self.input.uv.height); + let layers: Vec<(Channel, u32)> = + smudge.channels.iter().filter_map(|&(channel, color, layer)| Some((channel, smudge.alpha_layer(color, layer)?))).collect(); + let mut alphas: BTreeMap = layers.iter().map(|(channel, _)| (*channel, TileImage::new(width, height, 1))).collect(); + if tiles.is_empty() || layers.is_empty() { + return Ok(alphas); + } + + let tile_bytes = u64::from(SCALAR_TILE_WORDS) * 4 * layers.len() as u64; + let per_chunk = ((self.device.limits().max_buffer_size / tile_bytes) as usize).clamp(1, CHUNK); + let (device, queue) = (&self.device, &self.queue); + let coordinates: Vec<_> = tiles.iter().copied().collect(); + for chunk in coordinates.chunks(per_chunk) { + let bytes = chunk.len() as u64 * tile_bytes; + let read = crate::gpu_trace::scoped(device, "GPU smudge alpha readback buffer", || { + buffer(device, "tc_smudge_read_alphas", bytes, wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ) + })?; + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_smudge_read_alphas") }); + for (index, &tile) in chunk.iter().enumerate() { + for (k, (_, layer)) in layers.iter().enumerate() { + let offset = index as u64 * tile_bytes + k as u64 * u64::from(SCALAR_TILE_WORDS) * 4; + encoder.copy_texture_to_buffer(layer_copy(scalars, tile, *layer), rows(&read, offset, ROW_BYTES), extent(TILE, TILE)); + } + } + let submitted = queue.submit([encoder.finish()]); + let (send, receive) = std::sync::mpsc::channel(); + read.slice(..).map_async(wgpu::MapMode::Read, move |result| { + let _ = send.send(result); + }); + device.poll(wgpu::PollType::Wait { submission_index: Some(submitted), timeout: None }).map_err(|e| e.to_string())?; + receive.recv().map_err(|e| e.to_string())?.map_err(|e| e.to_string())?; + { + let mapped = read.slice(..).get_mapped_range().map_err(|e| e.to_string())?; + let words: &[u16] = bytemuck::try_cast_slice(&mapped).map_err(|e| e.to_string())?; + for (index, &(x, y)) in chunk.iter().enumerate() { + for (k, (channel, _)) in layers.iter().enumerate() { + let at = index * (tile_bytes / 2) as usize + k * SCALAR_TILE_WORDS as usize * 2; + let data: Vec = (0..TILE as usize).flat_map(|row| words[at + row * 128..][..TILE as usize].iter().copied()).collect(); + if data.iter().any(|&a| a != 0) + && let Some(image) = alphas.get_mut(channel) + { + image.set_tile(x, y, Some(std::sync::Arc::new(data))); + } + } + } + } + read.unmap(); + } + Ok(alphas) + } + + /// Every lane of a smudge so far, for a CPU stroke that continues it: its symmetry copy, its + /// previous center and, when copies drag their own trails, its alpha and values of `tiles`. + pub fn read_smudge_lanes(&self, tiles: &Tiles) -> Result, String> { + let Some(smudge) = &self.smudge else { return Err("The stroke carries no values on the GPU.".into()) }; + if smudge.sources.is_empty() { + return Ok(Vec::new()); + } + + let (device, queue) = (&self.device, &self.queue); + let bytes = smudge.sources.len() as u64 * LANE_WORDS * 4; + let read = crate::gpu_trace::scoped(device, "GPU smudge lane readback buffer", || { + buffer(device, "tc_smudge_read_lanes", bytes, wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ) + })?; + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_smudge_read_lanes") }); + encoder.copy_buffer_to_buffer(&smudge.lane_state, 0, &read, 0, Some(bytes)); + let submitted = queue.submit([encoder.finish()]); + let (send, receive) = std::sync::mpsc::channel(); + read.slice(..).map_async(wgpu::MapMode::Read, move |result| { + let _ = send.send(result); + }); + device.poll(wgpu::PollType::Wait { submission_index: Some(submitted), timeout: None }).map_err(|e| e.to_string())?; + receive.recv().map_err(|e| e.to_string())?.map_err(|e| e.to_string())?; + let state: Vec = bytemuck::try_cast_slice(&read.slice(..).get_mapped_range().map_err(|e| e.to_string())?).map_err(|e| e.to_string())?.to_vec(); + read.unmap(); + let mut lanes = Vec::new(); + for (index, (source, words)) in smudge.sources.iter().zip(state.as_chunks::<{ LANE_WORDS as usize }>().0).enumerate() { + let previous = (words[0] != 0).then(|| [f32::from_bits(words[1]), f32::from_bits(words[2])]); + let (carried, alphas) = match smudge.lanes.get(index).filter(|_| smudge.isolated) { + Some(lane) => { + (Some(self.read_maps(smudge, (&lane.alpha, &lane.scalars, &lane.colors), tiles)?), self.read_alphas_of(smudge, &lane.scalars, tiles)?) + } + None => (None, BTreeMap::new()), + }; + lanes.push(SmudgeLane { source: *source, previous, carried, alphas }); + } + Ok(lanes) + } + + /// An alpha map and carried values (scalar and color layers) of `tiles` + fn read_maps( + &self, + smudge: &GpuSmudge, + maps: (&wgpu::Texture, &wgpu::Texture, &wgpu::Texture), + tiles: &Tiles, + ) -> Result<(TileImage, BTreeMap), String> { + self.validate_readback_tiles(tiles)?; + let (width, height) = (self.input.uv.width, self.input.uv.height); + let mut alpha = TileImage::new(width, height, 1); + let mut values: BTreeMap = + smudge.channels.iter().map(|(channel, color, _)| (*channel, TileImage::new(width, height, if *color { 3 } else { 1 }))).collect(); + if tiles.is_empty() { + return Ok((alpha, values)); + } + + let (scalars, colors) = smudge.layers(); + let tile_bytes = u64::from(SCALAR_TILE_WORDS * (1 + scalars) + COLOR_TILE_WORDS * colors) * 4; + let limits = self.device.limits(); + // One readback of the whole stroke at its end: chunked as the alpha readback is + let per_chunk = ((limits.max_buffer_size / tile_bytes) as usize).clamp(1, CHUNK); + let (device, queue) = (&self.device, &self.queue); + let coordinates: Vec<_> = tiles.iter().copied().collect(); + for chunk in coordinates.chunks(per_chunk) { + let bytes = chunk.len() as u64 * tile_bytes; + let read = crate::gpu_trace::scoped(device, "GPU smudge readback buffer", || { + buffer(device, "tc_smudge_read", bytes, wgpu::BufferUsages::COPY_DST | wgpu::BufferUsages::MAP_READ) + })?; + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_smudge_read") }); + for (index, &tile) in chunk.iter().enumerate() { + let mut offset = index as u64 * tile_bytes; + encoder.copy_texture_to_buffer(tile_copy(maps.0, tile.0 * TILE, tile.1 * TILE), rows(&read, offset, ROW_BYTES), extent(TILE, TILE)); + offset += u64::from(SCALAR_TILE_WORDS) * 4; + for (_, color, layer) in &smudge.channels { + let (texture, row, words) = if *color { (maps.2, COLOR_ROW_BYTES, COLOR_TILE_WORDS) } else { (maps.1, ROW_BYTES, SCALAR_TILE_WORDS) }; + encoder.copy_texture_to_buffer(layer_copy(texture, tile, *layer), rows(&read, offset, row), extent(TILE, TILE)); + offset += u64::from(words) * 4; + } + } + let submitted = queue.submit([encoder.finish()]); + let slice = read.slice(..); + let (send, receive) = std::sync::mpsc::channel(); + slice.map_async(wgpu::MapMode::Read, move |result| { + let _ = send.send(result); + }); + device.poll(wgpu::PollType::Wait { submission_index: Some(submitted), timeout: None }).map_err(|e| e.to_string())?; + receive.recv().map_err(|e| e.to_string())?.map_err(|e| e.to_string())?; + { + let mapped = read.slice(..).get_mapped_range().map_err(|e| e.to_string())?; + let words: &[u16] = bytemuck::try_cast_slice(&mapped).map_err(|e| e.to_string())?; + for (index, &(x, y)) in chunk.iter().enumerate() { + let mut at = index * (tile_bytes / 2) as usize; + let scalar = + |at: usize| -> Vec { (0..TILE as usize).flat_map(|row| words[at + row * 128..][..TILE as usize].iter().copied()).collect() }; + let tile_alpha = scalar(at); + at += SCALAR_TILE_WORDS as usize * 2; + if tile_alpha.iter().any(|a| *a != 0) { + alpha.set_tile(x, y, Some(std::sync::Arc::new(tile_alpha))); + } + for (channel, color, _) in &smudge.channels { + let data: Vec = if *color { + words[at..][..(COLOR_TILE_WORDS * 2) as usize] + .as_chunks::<4>() + .0 + .iter() + .flat_map(|&[red, green, blue, _]| [red, green, blue]) + .collect() + } else { + scalar(at) + }; + at += if *color { COLOR_TILE_WORDS as usize * 2 } else { SCALAR_TILE_WORDS as usize * 2 }; + if let Some(image) = values.get_mut(channel) { + image.set_tile(x, y, Some(std::sync::Arc::new(data))); + } + } + } + } + read.unmap(); + } + Ok((alpha, values)) + } +} + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use texturecraft_compose::eval::Composite; + use texturecraft_core::Channel; + use texturecraft_geom::glam::{Mat3, Vec2, Vec3}; + use texturecraft_geom::{Bvh, UvGBuffer, primitives}; + use texturecraft_paint::{ + BrushAlpha, BrushSettings, Pickup, PickupMode, RasterCtx, Shape, Stamp, StampSource, StrokeCanvas, UvStamp, rasterize, rasterize_uv, + }; + use texturecraft_texel::{TILE, TileImage, to_u16}; + + use crate::gpu_brush::BrushInput; + use crate::headless::Headless; + + const SIZE: u32 = 128; + + /// Five scalar channels (two source layers, a signed one among them) and base color with an + /// edge at x 48 to drag across + const CHANNELS: [Channel; 6] = [Channel::Roughness, Channel::Metallic, Channel::Height, Channel::Opacity, Channel::AmbientOcclusion, Channel::BaseColor]; + + fn source() -> Composite { + let mut composite = Composite::with_size(&CHANNELS, SIZE, SIZE); + for y in 0..SIZE { + for x in 0..SIZE { + let left = x < 48; + for (index, channel) in CHANNELS[..5].iter().enumerate() { + let value = if left { 0.9 - 0.1 * index as f32 } else { 0.1 + 0.05 * index as f32 }; + composite.channels.get_mut(channel).unwrap().set(x, y, &[to_u16(value)]); + } + let color = if left { [0.8, 0.2, 0.1] } else { [0.1, 0.3, 0.7] }; + composite.channels.get_mut(&Channel::BaseColor).unwrap().set(x, y, &color.map(to_u16)); + } + } + composite + } + + /// Texels whose 16-bit values differ by more than `step`, and the texels either side covers + fn differing(cpu: &TileImage, gpu: &TileImage, alpha: &TileImage, step: u16) -> (usize, usize) { + let (mut differ, mut covered) = (0, 0); + for y in 0..SIZE { + for x in 0..SIZE { + if alpha.get(x, y)[0] == 0 { + continue; + } + + covered += 1; + differ += usize::from(cpu.get(x, y).iter().zip(gpu.get(x, y)).any(|(a, b)| a.abs_diff(b) > step)); + } + } + (differ, covered) + } + + /// Texels the GPU paints (alpha above `step`) where the CPU leaves the stroke clear + fn extra_paint(cpu: &TileImage, gpu: &TileImage, step: u16) -> usize { + (0..SIZE).flat_map(|y| (0..SIZE).map(move |x| (x, y))).filter(|&(x, y)| cpu.get(x, y)[0] == 0 && gpu.get(x, y)[0] > step).count() + } + + /// Smudge stamps drag the source on the GPU as `Pickup::stamp` does: the first stamp only + /// picks up, a drag carries the edge along, a jump drags nothing, in the 2D and the 3D view, + /// and with symmetry each copy drags its own trail. + #[test] + fn smudge_drags_values_on_the_gpu_as_on_the_cpu() { + let Some(mut gpu) = Headless::for_required_tests() else { return }; + let mesh = Arc::new(primitives::plane(2.0, 4)); + let bvh = Arc::new(Bvh::new(&mesh)); + let uv = Arc::new(UvGBuffer::new(&mesh, 0, SIZE, SIZE)); + let settings = BrushSettings { alpha: BrushAlpha::Round, backface_culling: false, ..Default::default() }; + let copy = |x: f32| Some(StampSource { origin: Vec3::ZERO, to_source: Mat3::from_diagonal(Vec3::new(x, 1.0, 1.0)) }); + + // Dab centers in UV: a drag right across the edge, a jump, then a drag up; mirrored copies drag left + let mut path: Vec = (0..24).map(|i| Vec2::new(0.3 + i as f32 * 0.012, 0.5)).collect(); + path.extend((0..8).map(|i| Vec2::new(0.75, 0.6 - i as f32 * 0.01))); + // Last: one tile per chunk, every chunk reading what lies before the stamp + for (world, isolated, one_tile_chunks) in [(false, false, false), (true, false, false), (false, true, false), (true, true, false), (false, false, true)] + { + let case = format!("3D view {world}, copies {isolated}, one tile per chunk {one_tile_chunks}"); + let mut sources = vec![None]; + if isolated { + sources = vec![copy(1.0), copy(-1.0)]; + } + let centers: Vec<(Vec2, Option)> = path + .iter() + .flat_map(|center| { + sources.iter().map(move |source| (if *source == copy(-1.0) { Vec2::new(1.0 - center.x, center.y) } else { *center }, *source)) + }) + .collect(); + let pickup = || { + let mut pickup = Pickup::new(PickupMode::Smudge { strength: 0.8 }, source(), uv.clone(), CHANNELS); + if isolated { + pickup.isolate_copies(); + } + pickup + }; + let mut cpu = StrokeCanvas::new(SIZE, SIZE); + cpu.pickup = Some(pickup()); + let input = BrushInput { + mesh: mesh.clone(), + bvh: bvh.clone(), + uv: uv.clone(), + material: 0, + depth: None, + settings: settings.clone(), + alpha_image: None, + stencil: None, + limit: None, + clone: None, + smudge: pickup().smudge_source(), + }; + let mut stroke = gpu.renderer.start_gpu_brush(&gpu.device, &gpu.queue, input).unwrap(); + if one_tile_chunks { + stroke.smudge.as_mut().unwrap().chunk_limit = Some(1); + } + let shape = Shape::new(settings.alpha, None, None, settings.alpha_params); + let mut tiles = super::Tiles::new(); + if world { + let stamps: Vec = centers + .iter() + .map(|(center, source)| Stamp { + center: Vec3::new((center.x - 0.5) * 2.0, 0.0, (center.y - 0.5) * 2.0), + normal: Vec3::Y, + tangent: Vec3::X, + bitangent: Vec3::Z, + radius: 0.08, + flow: 0.9, + hardness: 0.6, + depth: 1.0, + seed: 0, + source: *source, + }) + .collect(); + let context = RasterCtx { + mesh: &mesh, + bvh: &bvh, + gbuf: &uv, + material: 0, + depth: None, + eye: Vec3::Y * 4.0, + backface_culling: false, + angle_fade: settings.angle_fade, + shape, + }; + + // Two batches: the lanes and the previous centers carry over between appends + for batch in stamps.chunks(stamps.len() / 2 + 1) { + rasterize(&mut cpu, &context, batch); + tiles.extend(stroke.append_world(batch).unwrap()); + } + } else { + let stamps: Vec = centers + .iter() + .map(|(center, source)| UvStamp { center: *center, radius: 0.04, angle: 0.0, flow: 0.9, hardness: 0.6, seed: 0, source: *source }) + .collect(); + for batch in stamps.chunks(stamps.len() / 2 + 1) { + rasterize_uv(&mut cpu, &uv, shape, batch); + tiles.extend(stroke.append_uv(batch).unwrap()); + } + } + if one_tile_chunks { + // Stamps reuse the deposit outputs of their chunk positions + let smudge = stroke.smudge.as_ref().unwrap(); + assert_eq!(smudge.output_allocations, smudge.outputs.len(), "{case}: one output per chunk position"); + } + let (alpha, values) = stroke.read_carried(&tiles).unwrap(); + let carried = &cpu.pickup.as_ref().unwrap().values; + let (alpha_differ, covered) = differing(&cpu.alpha, &alpha, &cpu.alpha, 64); + let alpha_differ = alpha_differ + extra_paint(&cpu.alpha, &alpha, 64); + assert!(covered > 500, "{case}: the stroke deposits ({covered} texels)"); + assert!(alpha_differ * 200 <= covered, "{case}: {alpha_differ}/{covered} alpha texels differ"); + for channel in CHANNELS { + let (differ, _) = differing(&carried[&channel], &values[&channel], &cpu.alpha, 64); + assert!(differ * 200 <= covered, "{case}: {differ}/{covered} {channel:?} texels differ"); + } + + // The drag carried the edge's left value right of it (the oracle must see a smudge) + let dragged = (52..80).any(|x| carried[&Channel::Roughness].get(x, SIZE / 2)[0] > to_u16(0.3)); + assert!(dragged, "{case}: the CPU smudge drags the edge"); + assert_eq!(tiles.iter().filter(|tile| tile.0 * TILE >= SIZE).count(), 0); + } + } + + /// Pickups with per-channel coverage paint each channel's own alpha on the GPU as the CPU + /// does: a smudge of a layer's own paint (channels painted in different places, one partly + /// covered), with mirrored copies dragging their own trails, and a clone of a layer whose + /// channels differ in coverage, stamp by stamp + #[test] + fn per_channel_pickups_match_the_cpu() { + use std::collections::BTreeMap; + + let Some(mut gpu) = Headless::for_required_tests() else { return }; + let mesh = Arc::new(primitives::plane(2.0, 4)); + let bvh = Arc::new(Bvh::new(&mesh)); + let uv = Arc::new(UvGBuffer::new(&mesh, 0, SIZE, SIZE)); + let settings = BrushSettings { alpha: BrushAlpha::Round, backface_culling: false, ..Default::default() }; + let channels = [Channel::Roughness, Channel::Metallic, Channel::BaseColor]; + + // Premultiplied paint with its coverage: Roughness left of x 48, Metallic half covered + // below y 70, Base Color in a band + let paint: BTreeMap = channels + .iter() + .map(|&channel| { + let components = channel.components(); + let mut image = TileImage::new(SIZE, SIZE, components + 1); + for y in 0..SIZE { + for x in 0..SIZE { + let (value, coverage) = match channel { + Channel::Roughness if x < 48 => (0.8, 1.0), + Channel::Metallic if y < 70 => (0.6 - x as f32 / 400.0, 0.5), + Channel::BaseColor if (40..90).contains(&x) => (0.3 + y as f32 / 300.0, 0.9), + _ => continue, + }; + let mut texel = vec![to_u16(value * coverage); components]; + texel.push(to_u16(coverage)); + image.set(x, y, &texel); + } + } + (channel, image) + }) + .collect(); + let flat: Vec<(Channel, (u32, u32), Vec)> = paint + .iter() + .flat_map(|(channel, image)| image.allocated().filter_map(|tile| Some((*channel, tile, image.tile(tile.0, tile.1)?.to_vec()))).collect::>()) + .collect(); + let copy = |x: f32| Some(StampSource { origin: Vec3::ZERO, to_source: Mat3::from_diagonal(Vec3::new(x, 1.0, 1.0)) }); + let path: Vec = (0..20).map(|i| Vec2::new(0.25 + i as f32 * 0.015, 0.5)).collect(); + + for case in ["own paint smudge", "own paint smudge with copies", "layer clone"] { + let isolated = case.ends_with("copies"); + let pickup = || { + let mut pickup = if case == "layer clone" { + Pickup::from_layer(PickupMode::Clone { offset: [-20, -9] }, &flat, (SIZE, SIZE), uv.clone(), channels) + } else { + Pickup::from_paint(PickupMode::Smudge { strength: 0.8 }, paint.clone(), uv.clone(), channels) + }; + if isolated { + pickup.isolate_copies(); + } + pickup + }; + let source = pickup().smudge_source().expect("a source with per-channel coverage"); + assert!(source.coverage.is_some(), "{case}"); + let sources = if isolated { vec![copy(1.0), copy(-1.0)] } else { vec![None] }; + let stamps: Vec = path + .iter() + .flat_map(|center| { + sources.iter().map(move |source| { + let center = if *source == copy(-1.0) { Vec2::new(1.0 - center.x, center.y) } else { *center }; + UvStamp { center, radius: 0.05, angle: 0.0, flow: 0.9, hardness: 0.6, seed: 0, source: *source } + }) + }) + .collect(); + + let mut cpu = StrokeCanvas::new(SIZE, SIZE); + cpu.pickup = Some(pickup()); + let shape = Shape::new(settings.alpha, None, None, settings.alpha_params); + let input = BrushInput { + mesh: mesh.clone(), + bvh: bvh.clone(), + uv: uv.clone(), + material: 0, + depth: None, + settings: settings.clone(), + alpha_image: None, + stencil: None, + limit: None, + clone: None, + smudge: Some(source), + }; + let mut stroke = gpu.renderer.start_gpu_brush(&gpu.device, &gpu.queue, input).unwrap(); + let mut tiles = super::Tiles::new(); + for batch in stamps.chunks(stamps.len() / 2 + 1) { + rasterize_uv(&mut cpu, &uv, shape, batch); + tiles.extend(stroke.append_uv(batch).unwrap()); + } + let (alpha, values) = stroke.read_carried(&tiles).unwrap(); + let alphas = stroke.read_channel_alphas(&tiles).unwrap(); + let pickup = cpu.pickup.as_ref().unwrap(); + let cpu_alphas = pickup.channel_alphas().expect("the CPU keeps an alpha per channel"); + + let (alpha_differ, covered) = differing(&cpu.alpha, &alpha, &cpu.alpha, 64); + let alpha_differ = alpha_differ + extra_paint(&cpu.alpha, &alpha, 64); + assert!(covered > 300, "{case}: the stroke deposits ({covered} texels)"); + assert!(alpha_differ * 200 <= covered, "{case}: {alpha_differ}/{covered} stroke alpha texels differ"); + for channel in channels { + let (expected, actual) = (&cpu_alphas[&channel], &alphas[&channel]); + let (differ, painted) = differing(expected, actual, expected, 64); + let differ = differ + extra_paint(expected, actual, 64); + assert!(differ * 200 <= covered, "{case}: {differ}/{painted} {channel:?} alpha texels differ"); + let (differ, _) = differing(&pickup.values[&channel], &values[&channel], expected, 64); + assert!(differ * 200 <= covered, "{case}: {differ}/{painted} {channel:?} texels differ"); + } + + // The channels' alphas differ: Metallic is half covered where Roughness is full + let (roughness, metallic) = (&cpu_alphas[&Channel::Roughness], &cpu_alphas[&Channel::Metallic]); + let unequal = (0..SIZE).flat_map(|y| (0..SIZE).map(move |x| (x, y))).any(|(x, y)| roughness.get(x, y)[0].abs_diff(metallic.get(x, y)[0]) > 4096); + assert!(unequal, "{case}: the channels deposit by their own coverage"); + } + } + + /// Two walls 4 apart sharing their UVs, a smudge dragged on the wall that does not own the + /// texels in the G-buffer, exactly along a texel edge: every stamp's center is a tie between + /// two rows, and the GPU picks the same center as the CPU (the first row-major of the tied + /// texels, distances of the surface each texel's dab reaches) + #[test] + fn tied_smudge_centers_on_shared_uvs_match_the_cpu() { + let Some(mut gpu) = Headless::for_required_tests() else { return }; + let wall = |shift: f32| [(-1.0, -1.0), (1.0, -1.0), (-1.0, 1.0), (1.0, 1.0)].map(|(x, y)| Vec3::new(x + shift, y, 0.0)); + let uvs = [(0.1, 0.9), (0.9, 0.9), (0.1, 0.1), (0.9, 0.1)].map(|(u, v)| Vec2::new(u, v)); + let mesh = texturecraft_geom::Mesh::from_parts( + wall(0.0).into_iter().chain(wall(4.0)).collect(), + Some(vec![Vec3::Z; 8]), + uvs.into_iter().chain(uvs).collect(), + vec![0, 1, 2, 2, 1, 3, 4, 5, 6, 6, 5, 7], + "Walls sharing UVs", + ) + .unwrap(); + let mesh = Arc::new(mesh); + let bvh = Arc::new(Bvh::new(&mesh)); + let uv = Arc::new(UvGBuffer::new(&mesh, 0, SIZE, SIZE)); + assert!(uv.shared_surfaces); + let settings = BrushSettings { alpha: BrushAlpha::Round, backface_culling: false, ..Default::default() }; + let shape = Shape::new(settings.alpha, None, None, settings.alpha_params); + + // y 0 is v 0.5, the edge between texel rows 63 and 64; x -0.6 to 0.4 crosses the source's edge + let stamps: Vec = (0..24) + .map(|i| Stamp { + center: Vec3::new(-0.6 + i as f32 * 0.044, 0.0, 0.0), + normal: Vec3::Z, + tangent: Vec3::X, + bitangent: Vec3::Y, + radius: 0.12, + flow: 0.9, + hardness: 0.6, + depth: 1.0, + seed: 0, + source: None, + }) + .collect(); + let pickup = || Pickup::new(PickupMode::Smudge { strength: 0.8 }, source(), uv.clone(), CHANNELS); + let mut cpu = StrokeCanvas::new(SIZE, SIZE); + cpu.pickup = Some(pickup()); + let input = BrushInput { + mesh: mesh.clone(), + bvh: bvh.clone(), + uv: uv.clone(), + material: 0, + depth: None, + settings: settings.clone(), + alpha_image: None, + stencil: None, + limit: None, + clone: None, + smudge: pickup().smudge_source(), + }; + let mut stroke = gpu.renderer.start_gpu_brush(&gpu.device, &gpu.queue, input).unwrap(); + let context = RasterCtx { + mesh: &mesh, + bvh: &bvh, + gbuf: &uv, + material: 0, + depth: None, + eye: Vec3::new(0.0, 0.0, 4.0), + backface_culling: false, + angle_fade: settings.angle_fade, + shape, + }; + rasterize(&mut cpu, &context, &stamps); + let tiles = stroke.append_world(&stamps).unwrap(); + let (alpha, values) = stroke.read_carried(&tiles).unwrap(); + let carried = &cpu.pickup.as_ref().unwrap().values; + let (alpha_differ, covered) = differing(&cpu.alpha, &alpha, &cpu.alpha, 64); + let alpha_differ = alpha_differ + extra_paint(&cpu.alpha, &alpha, 64); + assert!(covered > 300 && alpha_differ == 0, "{alpha_differ}/{covered} alpha texels differ"); + for channel in CHANNELS { + let (differ, _) = differing(&carried[&channel], &values[&channel], &cpu.alpha, 64); + assert_eq!(differ, 0, "{channel:?}: {differ}/{covered} texels differ"); + } + let dragged = (52..80).any(|x| carried[&Channel::Roughness].get(x, SIZE / 2)[0] > to_u16(0.3)); + assert!(dragged, "the CPU smudge drags the edge"); + } +} diff --git a/crates/render/src/gpu_composite.rs b/crates/render/src/gpu_composite.rs index a7b7841bd..da615237d 100644 --- a/crates/render/src/gpu_composite.rs +++ b/crates/render/src/gpu_composite.rs @@ -66,7 +66,6 @@ mod generator_p2; use groups::{BEGIN_GROUP, END_GROUP, GroupPlan, StackWork}; use pipelines::CompositePipelines; -const MAX_PAINT_WORDS: usize = (64 << 20) / size_of::(); const LOOKUP_WORDS: u32 = 4096; const NO_PAINT_IMAGE: u32 = u32::MAX; const BAKED_LIGHTING_OPCODE: u32 = 35; @@ -102,16 +101,12 @@ const BAKE_MAPS: [BakedMap; 4] = [BakedMap::AmbientOcclusion, BakedMap::Normal, const BAKE_ROW_MAPS: [BakedMap; 2] = [BakedMap::Height, BakedMap::WorldNormal]; /// Side-table words of the environment's diffuse light (`ProceduralInputs::reserve_environment`) const ENVIRONMENT_WORDS: usize = 28; -const MAX_ID_BAKE_BYTES: u64 = 1 << 30; -/// Most bytes of one texture set's baked-map atlas (16 bytes per texel, both row blocks counted): -/// 8192 x 8192 texels with the second block is 2 GiB, so the largest set the app bakes fits and -/// anything bigger takes the CPU path instead of asking the device for an allocation it may refuse. -const MAX_BAKED_INPUT_BYTES: u64 = 2 << 30; const MAX_ID_UPLOAD_BYTES: usize = 64 << 20; mod anchor_inputs; mod bake_cache; mod baked_inputs; +mod banded_inputs; mod composite_program; mod composite_region; mod curvature_cache; @@ -136,6 +131,7 @@ mod whole_set_pass; use anchor_inputs::AnchorInputs; use bake_cache::BakeCache; use baked_inputs::BakedInputs; +use banded_inputs::{BandInputs, BandedInputs}; pub use composite_program::CompositeProgram; pub use composite_region::CompositeRegion; use curvature_cache::CurvatureCache; @@ -147,7 +143,7 @@ pub(crate) use gpu_compositor::GpuCompositor; use id_bake::IdBake; use id_bake_cache::IdBakeCache; use late_environment::LateEnvironment; -pub use live_brush::LiveBrush; +pub use live_brush::{CarriedSlot, LiveBrush, LiveCarried}; pub use live_brush_target::LiveBrushTarget; use operation::Operation; use paint_inputs::PaintInputs; @@ -415,6 +411,7 @@ fn content_paint( image: Option<&TileImage>, brush_value: Option<([f32; 3], f32, bool)>, stencil_pigment: bool, + carried: Option, paint: &mut PaintInputs, ) -> Operation { let image_index = image.map_or(NO_PAINT_IMAGE, |image| paint.register(id, Some(channel), image)); @@ -423,6 +420,9 @@ fn content_paint( op.projection[3] = if stencil_pigment && channel == Channel::BaseColor { 2.0 } else { 1.0 }; op.uv = [r, g, b, opacity]; op.ext[2] = brush::live_paint_bits(erase, false); + if let Some(slot) = carried { + op.ext[3] = slot.descriptor(); + } } op } @@ -515,7 +515,8 @@ fn content_deposit( return Ok(None); } - content_paint(effect.id, channel, image, value, brush.is_some_and(|brush| brush.stencil.is_some()), paint) + let stencil_pigment = brush.is_some_and(|brush| brush.stencil.as_ref().is_some_and(|stencil| stencil.colors)); + content_paint(effect.id, channel, image, value, stencil_pigment, brush.and_then(|brush| brush.carried_slot(channel)), paint) }; op.low[3] = blend.opacity.min(1.0); op.balance[2] = blend_code(blend.mode) as f32; @@ -564,6 +565,9 @@ fn compile_mask( if let Some((value, opacity, erase, mask_image)) = live { op.projection[3] = 1.0; op.uv = [value, value, value, opacity]; + if let Some(slot) = brush.and_then(|brush| brush.carried_slot(texturecraft_compose::MASK_CHANNEL)) { + op.ext[3] = slot.descriptor(); + } let mask_image = mask_image.filter(|_| !erase); op.ext[2] = brush::live_paint_bits(erase, mask_image.is_some()); if let Some(name) = mask_image { @@ -1062,9 +1066,20 @@ thread_local! { pub(crate) static PRE_PASS_TEST_PAINT_WORDS: std::cell::Cell> = const { std::cell::Cell::new(None) }; /// Tests: the per-chunk paint windows the pre-pass uploaded pub(crate) static PRE_PASS_CHUNK_WINDOWS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Tests: the chunks that uploaded banded inputs (`BandedInputs::upload`) + pub(crate) static BANDED_UPLOADS: std::cell::Cell = const { std::cell::Cell::new(0) }; + /// Tests: the waits for earlier chunks before a chunk's paint and banded inputs upload + pub(crate) static UPLOAD_WAITS: std::cell::Cell = const { std::cell::Cell::new(0) }; } /// Bound scratch by the adapter limits and the shader's 32-bit word addressing. +/// The paint words one upload may hold: what the device binds as one storage buffer. Updates +/// split into windows of this size; only a single texel whose paint exceeds the device is +/// refused. +fn max_paint_words(limits: &wgpu::Limits) -> usize { + usize::try_from(scratch_limit(limits) / 4).unwrap_or(usize::MAX) +} + fn scratch_limit(limits: &wgpu::Limits) -> u64 { let addressable = (u64::from(u32::MAX) + 1) * 4; limits.max_storage_buffer_binding_size.min(limits.max_buffer_size).min(addressable) @@ -1120,19 +1135,44 @@ fn composite_band_size(width: u32, tile_work_per_pixel: u64) -> (u32, u32) { (width, rows) } +/// The set rows [low, high) whose row-addressed inputs (`BandedInputs`) the display rows of +/// `chunk` read: its source rows and `reach` texels around them, within the set +fn input_rows(chunk: CompositeRegion, shift: u32, reach: u32, height: u32) -> [u32; 2] { + let low = (chunk.min[1] << shift).saturating_sub(reach).min(height); + let high = (chunk.max[1] << shift).saturating_add(reach).min(height); + [low, high.max(low)] +} + /// Split only when the paint for this viewport window exceeds the device budget. Include a /// source halo because the UV padding shader can choose a texel from an adjoining window. +/// `sampled`: the composite reads paint only at its display texels (every 2^shift-th texel), so +/// the windows hold only those texels. `inputs` says whether the banded inputs of a chunk's +/// input rows ([`input_rows`]) fit the device; chunks whose inputs do not split by rows. fn paint_windows( program: &CompositeProgram, region: CompositeRegion, size: (u32, u32), - shift: u32, + (shift, sampled): (u32, bool), radius: u32, limit: usize, + inputs: &dyn Fn(CompositeRegion) -> bool, ) -> Result, String> { let mut work = vec![region]; let mut windows = Vec::new(); while let Some(chunk) = work.pop() { + if !inputs(chunk) { + // Tiling: the band's UV and baked inputs exceed the device, so it splits by rows + let length = chunk.max[1] - chunk.min[1]; + if length < 2 { + return Err("The UV and baked inputs of one row of GPU texels exceed the adapter's limits.".into()); + } + + let middle = chunk.min[1] + length / 2; + work.push(CompositeRegion { min: [chunk.min[0], middle], max: chunk.max }); + work.push(CompositeRegion { min: chunk.min, max: [chunk.max[0], middle] }); + continue; + } + let mut source = CompositeRegion { min: chunk.min.map(|p| p << shift), max: chunk.max.map(|p| p << shift) }.expanded(radius); if program.filters.wraps() { // A wrapping program's fields read the far side of the set across a crossed edge @@ -1142,7 +1182,10 @@ fn paint_windows( } } } - let window = CompositePaintWindow::covering(source.min, source.max, [size.0, size.1], &program.paint); + let mut window = CompositePaintWindow::covering(source.min, source.max, [size.0, size.1], &program.paint); + if sampled { + window = window.sampled(1 << shift); + } if let Some(words) = window.words(&program.paint, limit) { windows.push((chunk, window, words)); continue; @@ -1153,7 +1196,7 @@ fn paint_windows( let axis = usize::from(height >= width); let length = chunk.max[axis] - chunk.min[axis]; if length < 2 { - return Err("Paint inputs for one GPU texel exceed the adapter's upload budget".into()); + return Err("Paint inputs for one GPU texel exceed the adapter's buffer limit".into()); } let mut first = chunk; @@ -1657,6 +1700,7 @@ mod procedural_tests { erase: false, alpha: alpha.create_view(&Default::default()), stencil: None, + carried: Default::default(), }); let mut program = CompositeProgram::try_compile_with_brush(&project, &pixels, 0, None, live_brush).unwrap(); assert_eq!(program.filters.stages.len(), channels.len()); @@ -3122,16 +3166,9 @@ mod procedural_tests { mod paint_window_tests { use super::*; - #[test] - fn a_small_paint_budget_splits_the_output_without_losing_padding_sources() { - let mut paint = TileImage::new(256, 256, 4); - let pixels = Arc::new(vec![65535; 64 * 64 * 4]); - for y in 0..4 { - for x in 0..4 { - paint.set_tile(x, y, Some(pixels.clone())); - } - } - let program = CompositeProgram { + /// A program of one paint image and nothing else + fn program_of(paint: TileImage) -> CompositeProgram { + CompositeProgram { underlay: None, filters: FilterPlan::default(), groups: GroupPlan::default(), @@ -3145,6 +3182,7 @@ mod paint_window_tests { material_images: MaterialImages::default(), brush_alpha: None, brush_stencil: None, + brush_carried: None, region: None, coverage: None, surface: None, @@ -3157,6 +3195,7 @@ mod paint_window_tests { mask_preview: false, mask_layer: 0, mask_layers: Vec::new(), + thumb: [0; 4], image_words: Vec::new(), environment: None, bake_rows: false, @@ -3164,10 +3203,83 @@ mod paint_window_tests { udim_layout: None, p3b_fields: p3b::FieldPlan::default(), micro: generator_p2::MicroPlan::default(), - }; + } + } + + /// An update window holds as much paint as the device binds (here the whole 4K set's 128 MB + /// in one upload), not a fixed working size + #[test] + fn an_update_window_holds_what_the_device_binds() { + let mut paint = TileImage::new(4096, 4096, 4); + let pixels = Arc::new(vec![65535; (TILE * TILE * 4) as usize]); + for y in 0..4096 / TILE { + for x in 0..4096 / TILE { + paint.set_tile(x, y, Some(pixels.clone())); + } + } + let program = program_of(paint); + let region = CompositeRegion { min: [0, 0], max: [4096, 4096] }; + let limits = wgpu::Limits { max_storage_buffer_binding_size: 1 << 30, max_buffer_size: 1 << 30, ..wgpu::Limits::default() }; + + let windows = paint_windows(&program, region, (4096, 4096), (0, false), 0, max_paint_words(&limits), &|_| true).unwrap(); + + assert_eq!(windows.len(), 1, "the whole set's paint fits one upload"); + assert!(windows[0].2 * 4 > 64 << 20, "the window holds more than 64 MB"); + } + + /// A composite reading every 8th or every 128th texel uploads only those texels, packed where + /// the shader's sampled lookup finds them + #[test] + fn a_reduced_composite_uploads_only_its_sampled_paint() { + let mut paint = TileImage::new(256, 256, 4); + for y in 0..256 { + for x in 0..256 { + paint.set(x, y, &[x as u16, y as u16, 7, 9]); + } + } + let program = program_of(paint); + let region = CompositeRegion { min: [0, 0], max: [32, 32] }; + let full = paint_windows(&program, region, (256, 256), (3, false), 0, usize::MAX, &|_| true).unwrap(); + let sampled = paint_windows(&program, region, (256, 256), (3, true), 0, usize::MAX, &|_| true).unwrap(); + assert!(sampled[0].2 * 32 < full[0].2, "{} of {} words", sampled[0].2, full[0].2); + + // The shader's lookup (composite.wgsl stored_sample) of a sampled texel, as packed + for (step, region) in [(8u32, region), (128, CompositeRegion { min: [0, 0], max: [2, 2] })] { + let shift = step.ilog2(); + let windows = paint_windows(&program, region, (256, 256), (shift, true), 0, usize::MAX, &|_| true).unwrap(); + let (_, window, words) = &windows[0]; + let [origin_x, origin_y, columns, _] = window.params(); + assert_ne!(columns & (1 << 31), 0, "the window is flagged sampled"); + let columns = columns & !(1 << 31); + let mut packed = Vec::new(); + window.pack(&program.paint, *words, &mut packed); + assert_eq!(packed.len(), *words); + for (x, y) in [(0, 0), (1, 1), (region.max[0] - 1, 0), (region.max[0] - 1, region.max[1] - 1)] { + let pixel = [x * step, y * step]; + let tile = [pixel[0] / TILE - origin_x, pixel[1] / TILE - origin_y]; + let offset = packed[(packed[0] + tile[1] * columns + tile[0]) as usize]; + let sub = step.min(TILE); + let local = [pixel[0] % TILE, pixel[1] % TILE]; + let at = (local[1] / sub) * (TILE / sub) + local[0] / sub; + let texel = (offset + at * 2) as usize; + assert_eq!([packed[texel], packed[texel + 1]], [pixel[0] | (pixel[1] << 16), 7 | (9 << 16)], "texel {pixel:?} at step {step}"); + } + } + } + + #[test] + fn a_small_paint_budget_splits_the_output_without_losing_padding_sources() { + let mut paint = TileImage::new(256, 256, 4); + let pixels = Arc::new(vec![65535; 64 * 64 * 4]); + for y in 0..4 { + for x in 0..4 { + paint.set_tile(x, y, Some(pixels.clone())); + } + } + let program = program_of(paint); let region = CompositeRegion { min: [0, 0], max: [128, 128] }; let limit = 6 * 64 * 64 * 2 + 32; - let windows = paint_windows(&program, region, (256, 256), 1, 8, limit).unwrap(); + let windows = paint_windows(&program, region, (256, 256), (1, false), 8, limit, &|_| true).unwrap(); assert!(windows.len() > 1); let mut coverage = vec![0; 128 * 128]; for (chunk, window, words) in windows { diff --git a/crates/render/src/gpu_composite/bake_cache.rs b/crates/render/src/gpu_composite/bake_cache.rs index 851dea89a..65c60baf5 100644 --- a/crates/render/src/gpu_composite/bake_cache.rs +++ b/crates/render/src/gpu_composite/bake_cache.rs @@ -5,4 +5,6 @@ pub(super) struct BakeCache { /// The built-in maps, then the second row block's pub(super) maps: Vec>>>, pub(super) view: wgpu::TextureView, + /// Bytes of its texture, counted against the memory budget + pub(super) bytes: u64, } diff --git a/crates/render/src/gpu_composite/banded_inputs.rs b/crates/render/src/gpu_composite/banded_inputs.rs new file mode 100644 index 000000000..32b931d21 --- /dev/null +++ b/crates/render/src/gpu_composite/banded_inputs.rs @@ -0,0 +1,313 @@ +//! Tiling: a set whose row-addressed inputs (UV surface, UV coverage, baked maps) exceed what +//! the device holds as one texture or binding composites in bands. Each paint-window chunk then +//! uploads only the input rows its texels and their filter halo read, and the shader subtracts +//! the band's first row (`Params.inputs`, [`packages::INPUTS`]). Sizes follow the device limits. + +use super::{ + BAKE_ROW_MAPS, BakedInputs, CompositeProgram, DeviceExt, IndexedParallelIterator, IntoParallelIterator, ParallelIterator, ROWS, UvGBuffer, coverage_word, + encode_baked_normal, input_texture, packages, write_input, +}; + +/// Which of a program's row-addressed inputs the device cannot hold whole, so each chunk of +/// the update uploads only its rows +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(super) struct BandedInputs { + pub(super) surface: bool, + pub(super) coverage: bool, + pub(super) bake: bool, +} + +/// One chunk's banded inputs and its uniform words +pub(super) struct BandInputs { + pub(super) surface: Option, + pub(super) coverage: Option, + pub(super) baked: Option, + pub(super) words: [u32; 4], +} + +/// The bytes one storage buffer may bind on `limits` +fn binding_bytes(limits: &wgpu::Limits) -> u64 { + limits.max_storage_buffer_binding_size.min(limits.max_buffer_size) +} + +/// Coverage words per row of `map` +fn coverage_pitch(map: &UvGBuffer) -> u64 { + u64::from(map.width.div_ceil(32)) +} + +impl BandedInputs { + /// Which inputs of `program` exceed the device whole. An error names an input that does + /// not fit and cannot be banded: wider than the device, or read by a whole-set pass. + pub(super) fn plan(limits: &wgpu::Limits, program: &CompositeProgram, whole_set_pass: bool) -> Result { + // A banded coverage slices the triangle grid per band: refuse a grid that does not match + // its size as the whole upload does + if let Some((map, _)) = &program.coverage { + super::validate_triangle_grid(map)?; + } + + let dimension = limits.max_texture_dimension_2d; + let mut banded = Self::default(); + if let Some((_, gbuf)) = &program.surface + && gbuf.width.max(gbuf.height) > dimension + { + if gbuf.width > dimension { + return Err("UV surface data exceeds the GPU limits".into()); + } + banded.surface = true; + } + if let Some((map, _)) = &program.coverage + && coverage_pitch(map) * u64::from(map.height) * 4 > binding_bytes(limits) + { + banded.coverage = true; + } + if let Some(baked) = &program.baked { + let rows = u64::from(baked.height) * u64::from(baked.blocks()); + if !baked.separate() && u64::from(baked.width.max(1)).max(rows) > u64::from(dimension) { + if baked.width > dimension { + return Err("Baked maps exceed the GPU texture dimensions".into()); + } + banded.bake = true; + } + } + if banded == Self::default() { + return Ok(banded); + } + + // The UV surface and coverage share their first row (`Params.inputs.x`): band both + // where the program reads them + if banded.surface || banded.coverage { + banded.surface = banded.surface || (program.surface.is_some() && (program.needs_surface || !program.geometry.parts.is_empty())); + banded.coverage = program.coverage.is_some(); + } + + // Inputs read across the whole set at once (curvature levels, micro details, generator + // fields, whole-set filters, wrapping fields) need the whole input + let reason = if program.curvature_sizes.contains(&true) { + Some("Curvature detail sizes") + } else if !program.micro.is_empty() { + Some("Micro Details") + } else if !program.p3b_fields.requests.is_empty() { + Some("Whole-map generator fields") + } else if whole_set_pass { + Some("A whole-set filter") + } else if program.filters.wraps() { + Some("A wrapping filter") + } else { + None + }; + match reason { + Some(reason) => Err(format!("{reason} read UV or baked inputs larger than the GPU holds at once.")), + None => Ok(banded), + } + } + + pub(super) fn any(self) -> bool { + self != Self::default() + } + + /// The bake rows [low, high) that the set rows [low, high) read, with a row of slack for + /// float rounding; a scaled UDIM tile reads within its whole block's rows + fn bake_rows(program: &CompositeProgram, baked: &BakedInputs, source_height: u32, [low, high]: [u32; 2]) -> [u32; 2] { + let (low, high) = match program.udim_layout.as_ref().filter(|layout| layout.scaled) { + Some(layout) => { + let block = layout.block.max(1); + (low / block * block, high.div_ceil(block).saturating_mul(block).min(source_height)) + } + None => (low, high), + }; + let map = |row: u32| u64::from(row) * u64::from(baked.height) / u64::from(source_height.max(1)); + let first = map(low).saturating_sub(1) as u32; + let last = (map(high) + 2).min(u64::from(baked.height)) as u32; + [first, last.max(first + 1)] + } + + /// Whether the inputs of the set rows [low, high) fit the device as one band + pub(super) fn fit(self, limits: &wgpu::Limits, program: &CompositeProgram, source_height: u32, [low, high]: [u32; 2]) -> bool { + let rows = u64::from(high - low); + let surface = !self.surface || rows <= u64::from(limits.max_texture_dimension_2d); + let coverage = !self.coverage || program.coverage.as_ref().is_none_or(|(map, _)| coverage_pitch(map) * rows * 4 <= binding_bytes(limits)); + let bake = !self.bake + || program.baked.as_ref().is_none_or(|baked| { + let [first, last] = Self::bake_rows(program, baked, source_height, [low, high]); + u64::from(last - first) * u64::from(baked.blocks()) <= u64::from(limits.max_texture_dimension_2d) + }); + surface && coverage && bake + } + + /// Bytes [`Self::upload`] allocates on the device for the set rows [low, high) + pub(super) fn bytes(self, program: &CompositeProgram, source_height: u32, [low, high]: [u32; 2]) -> u64 { + let (low, high) = (low.min(source_height), high.min(source_height).max(low.min(source_height) + 1)); + let rows = u64::from(high - low); + let surface = match &program.surface { + Some((_, gbuf)) if self.surface => u64::from(gbuf.width) * rows * if program.needs_surface { 8 } else { 4 }, + _ => 0, + }; + let coverage = match &program.coverage { + Some((map, _)) if self.coverage => coverage_pitch(map) * rows * 4, + _ => 0, + }; + let baked = match &program.baked { + Some(baked) if self.bake => { + let [first, last] = Self::bake_rows(program, baked, source_height, [low, high]); + u64::from(baked.width) * u64::from(last - first) * u64::from(baked.blocks()) * 16 + } + _ => 0, + }; + surface + coverage + baked + } + + /// Upload the banded inputs of the set rows [low, high) (clamped to the set) + pub(super) fn upload( + self, + (device, queue): (&wgpu::Device, &wgpu::Queue), + program: &CompositeProgram, + source_height: u32, + [low, high]: [u32; 2], + ) -> Result { + let (low, high) = (low.min(source_height), high.min(source_height).max(low.min(source_height) + 1)); + #[cfg(all(test, not(target_arch = "wasm32")))] + super::BANDED_UPLOADS.set(super::BANDED_UPLOADS.get() + 1); + let mut words = [0; 4]; + if self.surface || self.coverage { + words[0] = low; + } + let surface = match &program.surface { + Some((_, gbuf)) if self.surface => Some(surface_band(device, queue, gbuf, program.needs_surface, [low, high])), + _ => None, + }; + let coverage = match &program.coverage { + Some((map, _)) if self.coverage => Some(coverage_band(device, map, [low, high])), + _ => None, + }; + let baked = match &program.baked { + Some(baked) if self.bake => { + let [first, last] = Self::bake_rows(program, baked, source_height, [low, high]); + words[1..4].copy_from_slice(&[first, last - first, baked.height]); + Some(bake_band(device, queue, baked, [first, last])) + } + _ => None, + }; + Ok(BandInputs { surface, coverage, baked, words }) + } +} + +impl BandInputs { + /// The band uniform's words of whole inputs + pub(super) const WHOLE: [u32; 4] = [0; 4]; + + pub(super) fn write_uniform(words: [u32; 4], values: &mut [u32; packages::UNIFORM_WORDS]) { + values[packages::INPUTS..packages::INPUTS + 4].copy_from_slice(&words); + } +} + +/// The UV surface rows [low, high) of `gbuf`: triangles, with barycentrics when `full` +fn surface_band(device: &wgpu::Device, queue: &wgpu::Queue, gbuf: &UvGBuffer, full: bool, [low, high]: [u32; 2]) -> wgpu::TextureView { + let width = gbuf.width; + let format = if full { wgpu::TextureFormat::Rg32Uint } else { wgpu::TextureFormat::R32Uint }; + let texture = input_texture(device, "tc_composite_uv_surface_band", (width, high - low), 1, format); + let start = low as usize * width as usize; + let end = high as usize * width as usize; + let stride = (width * ROWS) as usize; + let mut pixels = Vec::new(); + for (band, rows) in (start..end).step_by(stride).enumerate() { + let range = rows..(rows + stride).min(end); + let count = (range.len() / width as usize) as u32; + if full { + range + .into_par_iter() + .map(|i| { + let pack = |x: f32| u32::from(texturecraft_texel::to_u16(x)); + let [u, v] = gbuf.bary[i]; + [gbuf.tri[i], pack(u) | (pack(v) << 16)] + }) + .collect_into_vec(&mut pixels); + write_input(queue, &texture, (width, count), (band as u32 * ROWS, 0), &pixels); + } else { + write_input(queue, &texture, (width, count), (band as u32 * ROWS, 0), &gbuf.tri[range]); + } + } + texture.create_view(&Default::default()) +} + +/// The UV coverage words of the set rows [low, high) of `map` +fn coverage_band(device: &wgpu::Device, map: &UvGBuffer, [low, high]: [u32; 2]) -> wgpu::Buffer { + let width = map.width as usize; + let pitch = width.div_ceil(32); + let words: Vec = (low as usize * pitch..high as usize * pitch) + .into_par_iter() + .map(|i| { + let row = i / pitch * width; + let start = row + i % pitch * 32; + coverage_word(&map.tri[start..(start + 32).min(row + width)]) + }) + .collect(); + device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("tc_composite_coverage_band"), + contents: bytemuck::cast_slice(&words), + usage: wgpu::BufferUsages::STORAGE, + }) +} + +/// The bake rows [first, last) of each block, block after block +fn bake_band(device: &wgpu::Device, queue: &wgpu::Queue, baked: &BakedInputs, [first, last]: [u32; 2]) -> wgpu::TextureView { + let rows = last - first; + let texture = input_texture(device, "tc_composite_bakes_band", (baked.width, rows * baked.blocks()), 1, wgpu::TextureFormat::Rgba32Uint); + let mut texels = Vec::new(); + for block in 0..baked.blocks() { + for top in (first..last).step_by(ROWS as usize) { + let end = (top + ROWS).min(last); + pack_bake_rows(baked, block, [top, end], &mut texels); + write_input(queue, &texture, (baked.width, end - top), (block * rows + top - first, 0), &texels); + } + } + texture.create_view(&Default::default()) +} + +/// The bake texels of block `block`'s rows [top, end): AO, Curvature, Thickness and the packed +/// normal; in the second block the height and the stored world normal +pub(super) fn pack_bake_rows(baked: &BakedInputs, block: u32, [top, end]: [u32; 2], texels: &mut Vec<[u32; 4]>) { + let width = baked.width as usize; + let indices = top as usize * width..end as usize * width; + if block == 0 { + let value = |map: usize, i: usize, fallback: f32| baked.maps[map].as_ref().and_then(|data| data.get(i).copied()).unwrap_or(fallback); + indices + .into_par_iter() + .map(|i| { + let normal = + if baked.maps[1].is_some() { encode_baked_normal([value(1, i * 3, 0.5), value(1, i * 3 + 1, 0.5), value(1, i * 3 + 2, 1.0)]) } else { 0 }; + [value(0, i, 1.0).to_bits(), value(2, i, 0.5).to_bits(), value(3, i, 1.0).to_bits(), normal] + }) + .collect_into_vec(texels); + return; + } + + // Height in x, the stored world normal in yzw; zeros where a map is not baked + let row = |map: usize, i: usize, component: usize| { + let components = BAKE_ROW_MAPS[map].components(); + baked.rows[map].as_ref().and_then(|data| data.get(i * components + component).copied()).unwrap_or(0.0).to_bits() + }; + indices.into_par_iter().map(|i| [row(0, i, 0), row(1, i, 0), row(1, i, 1), row(1, i, 2)]).collect_into_vec(texels); +} + +#[cfg(test)] +mod tests { + use super::BandedInputs; + use crate::gpu_composite::*; + use texturecraft_core::TextureSet; + + /// A coverage grid whose triangles do not match its size is refused before banding, as the + /// whole coverage upload refuses it, instead of slicing past its end in the last band + #[test] + fn a_mismatched_coverage_grid_is_refused_before_banding() { + let mut project = Project::new("Banded coverage", "builtin:plane"); + project.texture_sets.push(TextureSet::new("Plane", 0, 64)); + let mut program = CompositeProgram::try_compile_region(&project, &PixelStore::default(), 0, None).unwrap(); + let mesh = texturecraft_geom::primitives::plane(1.0, 1); + let mut grid = UvGBuffer::new(&mesh, 0, 64, 64); + grid.tri.pop(); + program.coverage = Some((Arc::new(grid), 0)); + let limits = wgpu::Limits { max_storage_buffer_binding_size: 64, ..Default::default() }; + let planned = BandedInputs::plan(&limits, &program, false); + assert!(planned.is_err_and(|error| error.contains("does not match")), "a short triangle grid must be refused"); + } +} diff --git a/crates/render/src/gpu_composite/composite_program.rs b/crates/render/src/gpu_composite/composite_program.rs index a4ee1d3ed..fb64d5ea3 100644 --- a/crates/render/src/gpu_composite/composite_program.rs +++ b/crates/render/src/gpu_composite/composite_program.rs @@ -27,6 +27,8 @@ pub struct CompositeProgram { pub(super) material_images: MaterialImages, pub(super) brush_alpha: Option, pub(super) brush_stencil: Option, + /// A live clone's or smudge's carried values on the device + pub(super) brush_carried: Option, pub(crate) region: Option, pub(super) coverage: Option<(Arc, u32)>, pub(super) surface: Option<(Arc, Arc)>, @@ -54,6 +56,8 @@ pub struct CompositeProgram { pub(super) p3b_fields: p3b::FieldPlan, /// P2: the micro details the generators read pub(super) micro: generator_p2::MicroPlan, + /// A layer thumbnail's output (`set_thumbnail`): mode, channel slot, display encoding, 0 + pub(super) thumb: [u32; 4], } impl CompositeProgram { @@ -81,6 +85,7 @@ impl CompositeProgram { pub fn is_neutral(&self) -> bool { !self.mask_preview + && !self.is_thumbnail() && !self.glossiness && self.underlay.is_none() && self.layer_count == 0 @@ -91,6 +96,57 @@ impl CompositeProgram { self.mask_preview } + /// Write a layer thumbnail of `channel` into the grayscale view's slot instead of the display + /// maps: with `flat`, the program's draws of `channel` composited over nothing (straight + /// value, coverage as alpha; a paint or fill layer drawn alone); otherwise the composited + /// channel (a folder over the channel defaults). Texels no triangle covers are transparent. + /// Call before `set_surface_inputs`, which then reads coverage without padding. + pub fn set_thumbnail(&mut self, channel: Channel, flat: bool) -> Result<(), &'static str> { + if self.mask_preview || self.underlay.is_some() { + return Err("A thumbnail reads a material program's own draws."); + } + + let encoding = match channel.kind() { + super::ChannelKind::Color => 0, + super::ChannelKind::Signed => 1, + super::ChannelKind::Scalar | super::ChannelKind::NormalMap => 2, + }; + self.thumb = [if flat { 1 } else { 2 }, super::channel_slot(channel), encoding, 0]; + self.display_outputs = display_bit(DisplayKind::BaseColor); + Ok(()) + } + + /// Write a brush's pickup source instead of the display maps or the thumbnail: `channels` + /// (one channel of three components, or up to four scalar channels) as the CPU stores them + /// (16 bits, signed values around mid gray), one RGBA16 texel per texel in the Normal map's + /// place; texels outside the set are 0. Call on a composited-channel thumbnail (the + /// document's values) or a mask preview (the mask's value, `channels` its one channel). + pub fn set_pickup_output(&mut self, channels: &[Channel]) -> Result<(), &'static str> { + let colors = channels.iter().any(|channel| channel.components() == 3); + if channels.is_empty() || channels.len() > 4 || (colors && channels.len() > 1) || !(self.mask_preview || self.thumb[0] == 2) { + return Err("A pickup source is one channel of three components or up to four scalar channels."); + } + + let (mut slots, mut encodings) = (0, 0); + for (k, &channel) in channels.iter().enumerate() { + let encoding = match channel.kind() { + _ if channel.components() == 3 => 0, + super::ChannelKind::Signed => 1, + _ => 2, + }; + slots |= super::channel_slot(channel) << (8 * k); + encodings |= encoding << (2 * k); + } + self.thumb[1..4].copy_from_slice(&[slots, encodings, channels.len() as u32]); + self.display_outputs = display_bit(DisplayKind::Normal); + Ok(()) + } + + /// Whether the program writes a layer thumbnail ([`Self::set_thumbnail`]) + pub fn is_thumbnail(&self) -> bool { + self.thumb[0] != 0 + } + /// Work per output texel that sizes bands and submissions: Tile Generator placements per /// plane and sample, and what P1 declares for its fills (`fill_projection::work_per_texel`: /// symmetry copies times sampling cost). @@ -113,7 +169,7 @@ impl CompositeProgram { /// Let the shader sample the nearest covered UV texel for island padding. pub fn set_coverage(&mut self, coverage: Arc, radius: u32) { - self.coverage = Some((coverage, if self.mask_preview { 0 } else { radius.min(15) })); + self.coverage = Some((coverage, if self.mask_preview || self.is_thumbnail() { 0 } else { radius.min(15) })); } /// Resolve named images used by authored fills, decals and Tile Generators, and the @@ -183,12 +239,16 @@ impl CompositeProgram { // Texels no triangle covers keep the channels' defaults, as the CPU leaves them let partly_covered = gbuf.tri.contains(&NO_TRI); - if self.mask_preview || ((partly_covered || !self.filters.stages.is_empty() || !self.geometry.parts.is_empty()) && self.coverage.is_none()) { + if self.mask_preview + || self.is_thumbnail() + || ((partly_covered || !self.filters.stages.is_empty() || !self.geometry.parts.is_empty()) && self.coverage.is_none()) + { self.set_coverage(gbuf.clone(), 0); } self.baked = baked.map(|baked| BakedInputs::new(baked, self.bake_rows)).transpose()?.flatten(); self.id_bake = baked.filter(|_| self.operations.iter().any(|op| op.ids[1] == COLOR_SELECTION_OPCODE && op.procedural[2] != 0)).and_then(IdBake::new); - if !self.mask_preview && self.baked.as_ref().is_some_and(|baked| baked.maps[1].is_some()) { + // A thumbnail writes only its own output (a pickup source selects the Normal map itself) + if !self.mask_preview && !self.is_thumbnail() && self.baked.as_ref().is_some_and(|baked| baked.maps[1].is_some()) { self.display_outputs |= display_bit(DisplayKind::Normal); } Ok(()) @@ -240,6 +300,29 @@ impl CompositeProgram { region: Option, brush: Option, remaining: &mut usize, + ) -> Result { + Self::compile_draws(project, pixels, ts, (first_layer, false), region, brush, remaining) + } + + /// A layer thumbnail of `channel` ([`Self::set_thumbnail`]). A flat thumbnail draws fills + /// of the channel's default value too: over nothing they show it with full coverage. + pub fn try_compile_thumbnail(project: &Project, pixels: &PixelStore, ts: usize, channel: Channel, flat: bool) -> Result { + let mut remaining = generator_p2::MAX_CAPTURE_PROGRAMS; + let mut program = Self::compile_draws(project, pixels, ts, (0, flat), None, None, &mut remaining)?; + program.set_thumbnail(channel, flat)?; + Ok(program) + } + + /// The draws of the stack from `first_layer`; with `draw_neutral`, also fills that only + /// reset a channel to its default before anything wrote it + fn compile_draws( + project: &Project, + pixels: &PixelStore, + ts: usize, + (first_layer, draw_neutral): (usize, bool), + region: Option, + brush: Option, + remaining: &mut usize, ) -> Result { let set = project.texture_sets.get(ts).ok_or("The texture set is missing.")?; let stack = set.stack.get(first_layer..).ok_or("The CPU material boundary is outside the layer stack.")?; @@ -261,8 +344,8 @@ impl CompositeProgram { let mut groups = GroupPlan::default(); let mut group_depth = 0; let mut mask_layers = Vec::new(); - let mut non_default = [first_layer != 0; Channel::ALL.len()]; - let stencil_pigment = brush.as_ref().is_some_and(|brush| brush.stencil.is_some()); + let mut non_default = [first_layer != 0 || draw_neutral; Channel::ALL.len()]; + let stencil_pigment = brush.as_ref().is_some_and(|brush| brush.stencil.as_ref().is_some_and(|stencil| stencil.colors)); // Each draw carries the Scale and Rotation of the folders holding it (an instanced folder's too) let mut layers: Vec<_> = stack.iter().rev().map(|&id| (StackWork::Layer(id, 0, 0), ContentsOffset::NONE)).collect(); @@ -518,7 +601,8 @@ impl CompositeProgram { non_default[slot as usize] = true; let mut op = if fill.is_none() { - content_paint(layer.id, channel, painted, brush_value, stencil_pigment, &mut paint) + let carried = brush.as_ref().filter(|_| brush_value.is_some()).and_then(|brush| brush.carried_slot(channel)); + content_paint(layer.id, channel, painted, brush_value, stencil_pigment, carried, &mut paint) } else { fill.and_then(|fill| source_operation(source, &placed(around, &fill.projection), fill.sampling, default, channel.kind(), &mut procedural)) .ok_or("A fill source or projection uses CPU compositing.")? @@ -609,7 +693,7 @@ impl CompositeProgram { display_outputs |= display_bit(DisplayKind::Extra); } let region = filters.expand(region, project.texture_sets.get(ts).map_or((0, 0), texturecraft_core::TextureSet::size)); - let (brush_alpha, brush_stencil) = brush.map_or((None, None), |brush| (Some(brush.alpha), brush.stencil)); + let (brush_alpha, brush_stencil, brush_carried) = brush.map_or((None, None, None), |brush| (Some(brush.alpha), brush.stencil, brush.carried)); let needs_surface = brush_stencil.is_some() || needs_surface(&operations); generator_p2::compile_captures(&mut procedural.micro, project, pixels, ts, remaining, brush_alpha.is_some())?; @@ -628,6 +712,7 @@ impl CompositeProgram { material_images: procedural.materials, brush_alpha, brush_stencil, + brush_carried, region, coverage: None, surface: None, @@ -640,6 +725,7 @@ impl CompositeProgram { mask_preview: false, mask_layer: 0, mask_layers, + thumb: [0; 4], image_words: procedural.image_words, environment: LateEnvironment::new(procedural.environment_word, &project.display), bake_rows: procedural.bake_rows, @@ -704,7 +790,7 @@ impl CompositeProgram { filters.bind_anchors(&mut operations); let udim = udim::bind(layout.as_ref(), &mut filters, &mut procedural).ok_or("The UV tile layout exceeds the GPU parameter table.")?; let region = filters.expand(region, project.texture_sets.get(ts).map_or((0, 0), texturecraft_core::TextureSet::size)); - let (brush_alpha, brush_stencil) = brush.map_or((None, None), |brush| (Some(brush.alpha), brush.stencil)); + let (brush_alpha, brush_stencil, brush_carried) = brush.map_or((None, None, None), |brush| (Some(brush.alpha), brush.stencil, brush.carried)); let needs_surface = brush_stencil.is_some() || needs_surface(&operations); let mut remaining = generator_p2::MAX_CAPTURE_PROGRAMS; @@ -724,6 +810,7 @@ impl CompositeProgram { material_images: procedural.materials, brush_alpha, brush_stencil, + brush_carried, region, coverage: None, surface: None, @@ -737,6 +824,7 @@ impl CompositeProgram { mask_preview: true, mask_layer: 0, mask_layers: Vec::new(), + thumb: [0; 4], image_words: procedural.image_words, environment: LateEnvironment::new(procedural.environment_word, &project.display), bake_rows: procedural.bake_rows, @@ -747,3 +835,24 @@ impl CompositeProgram { }) } } + +#[cfg(test)] +mod tests { + use crate::gpu_composite::*; + use texturecraft_core::{Channel, TextureSet}; + + /// A thumbnail on a set with a baked normal map writes only its thumbnail, not the Normal map + #[test] + fn a_thumbnail_with_a_baked_normal_writes_only_the_thumbnail() { + let mut project = Project::new("Thumbnail", "builtin:plane"); + project.texture_sets.push(TextureSet::new("Plane", 0, 64)); + let mesh = Arc::new(texturecraft_geom::primitives::plane(1.0, 1)); + let gbuf = Arc::new(UvGBuffer::new(&mesh, 0, 64, 64)); + let baked = BakedMaps { resolution: 64, maps: BTreeMap::from([(BakedMap::Normal, Arc::new(vec![0.5; 64 * 64 * 3]))]) }; + let mut program = CompositeProgram::try_compile_region(&project, &PixelStore::default(), 0, None).unwrap(); + program.set_thumbnail(Channel::Roughness, false).unwrap(); + program.set_surface_inputs(&mesh, &gbuf, Some(&baked)).unwrap(); + assert!(program.writes_display(DisplayKind::BaseColor), "the thumbnail's own output"); + assert!(!program.writes_display(DisplayKind::Normal), "no copy into the Normal map"); + } +} diff --git a/crates/render/src/gpu_composite/gpu_compositor.rs b/crates/render/src/gpu_composite/gpu_compositor.rs index 387c56ceb..cb39abe9c 100644 --- a/crates/render/src/gpu_composite/gpu_compositor.rs +++ b/crates/render/src/gpu_composite/gpu_compositor.rs @@ -3,14 +3,14 @@ use super::PRE_PASS_CHUNK_WINDOWS; use super::{FIRST_GENERATOR, MaterialUnderlay, generator_p2, generator_p3a, p3b}; use super::{ - Arc, BAKE_ROW_MAPS, BTreeMap, BakeCache, BakedInputs, COLOR_SELECTION_OPCODE, CompositePaintWindow, CompositePipelines, CompositeProgram, CompositeRegion, - Cow, CurvatureCache, CurvatureGpu, CurvatureInput, CurvatureLevels, CurvatureResources, DECAL_PROJECTION, DeviceExt, DisplayKind, ENVIRONMENT_WORDS, - FIELD_WORDS, GPU_PIPELINES_PENDING, GpuStencil, IMAGE_SOURCE_OPCODE, INPUT2, IdBake, IdBakeCache, IndexedParallelIterator, IntoParallelIterator, - IntoParallelRefIterator, LOOKUP_WORDS, LateEnvironment, MAX_BAKED_INPUT_BYTES, MAX_ID_BAKE_BYTES, MAX_ID_UPLOAD_BYTES, MAX_PAINT_WORDS, - MAX_TILE_WORK_PER_SUBMISSION, Mesh, NeighbourhoodFilter, NeighbourhoodGpu, NeighbourhoodRegion, Operation, ParallelIterator, ParallelSlice, ROWS, - SEPARATE_MAPS, SurfaceCache, TILE_GENERATOR_OPCODE, TileImageAtlas, UvGBuffer, Vec3, WORKGROUP, Weak, WholeSetPass, Zeroable, channel_slot, - check_texel_work, chunk_paint, composite_band_size, coverage_word, encode_baked_normal, field_bounds, input_texture, packages, paint_windows, pipelines, - pre_pass_budget, pre_pass_paint_words, scratch_limit, udim, validate_triangle_grid, write_input, write_separate_bakes, + Arc, BTreeMap, BakeCache, BakedInputs, BandInputs, BandedInputs, COLOR_SELECTION_OPCODE, CompositePaintWindow, CompositePipelines, CompositeProgram, + CompositeRegion, Cow, CurvatureCache, CurvatureGpu, CurvatureInput, CurvatureLevels, CurvatureResources, DECAL_PROJECTION, DeviceExt, DisplayKind, + ENVIRONMENT_WORDS, FIELD_WORDS, GPU_PIPELINES_PENDING, GpuStencil, IMAGE_SOURCE_OPCODE, INPUT2, IdBake, IdBakeCache, IndexedParallelIterator, + IntoParallelIterator, IntoParallelRefIterator, LOOKUP_WORDS, LateEnvironment, MAX_ID_UPLOAD_BYTES, MAX_TILE_WORK_PER_SUBMISSION, Mesh, NeighbourhoodFilter, + NeighbourhoodGpu, NeighbourhoodRegion, Operation, ParallelIterator, ParallelSlice, ROWS, SEPARATE_MAPS, SurfaceCache, TILE_GENERATOR_OPCODE, + TileImageAtlas, UvGBuffer, Vec3, WORKGROUP, Weak, WholeSetPass, Zeroable, channel_slot, check_texel_work, chunk_paint, composite_band_size, coverage_word, + field_bounds, input_rows, input_texture, max_paint_words, packages, paint_windows, pipelines, pre_pass_budget, pre_pass_paint_words, scratch_limit, udim, + validate_triangle_grid, write_input, write_separate_bakes, }; pub(crate) struct GpuCompositor { @@ -26,9 +26,16 @@ pub(crate) struct GpuCompositor { pub(super) uniform_coverage: wgpu::Buffer, pub(super) coverage: Vec<(Weak, wgpu::Buffer)>, pub(super) surfaces: Vec, + /// The UV grids (surface and coverage) each texture set's last composite read, so the memory + /// budget counts and evicts them with the set's other inputs + pub(super) grids: BTreeMap>>, pub(super) baked: BTreeMap, - /// Most bytes one set's baked-map atlas may take (`MAX_BAKED_INPUT_BYTES`; tests lower it) - pub(super) baked_budget: u64, + /// Bytes the texture sets' cached inputs may hold before the least recently used are evicted + /// (`GpuMemoryBudget::bytes`) + pub(crate) memory_budget: u64, + /// When each texture set's inputs were last composited, for least-recently-used eviction + pub(crate) last_use: BTreeMap, + pub(super) use_count: u64, pub(super) id_bakes: BTreeMap, pub(super) curvature: Option, /// P3b: the whole-map generator fields at binding 17 (binding 16 is P2's micro maps), when the adapter has room for them @@ -42,10 +49,19 @@ pub(crate) struct GpuCompositor { pub(super) default_baked: wgpu::TextureView, pub(super) default_id_bake: Option, pub(super) default_brush_alpha: wgpu::TextureView, + /// Bound in place of a live stroke's carried values + pub(super) default_carried: wgpu::TextureView, pub(super) default_brush_stencil: GpuStencil, pub(super) default_tile_images: wgpu::TextureView, pub(super) tile_images: BTreeMap, + /// The projector depth raster's passes, compiled when a program first culls by depth + pub(super) projector_depth: Option, pub(super) paint_upload: Option, + /// The memory retry's paint window: half the largest window the failed attempt uploaded + /// ([`Self::halve_paint_windows`]); None uses what the device binds + pub(crate) paint_word_limit: Option, + /// The largest paint window (words) the last update uploaded + pub(crate) largest_paint_words: usize, pub(super) underlay_binding: bool, pub(super) underlays: BTreeMap, wgpu::Buffer)>, /// The working buffer of the last update, reused while the next one fits it @@ -58,9 +74,9 @@ impl GpuCompositor { pub(crate) fn supports(device: &wgpu::Device) -> bool { let limits = device.limits(); limits.max_storage_buffers_per_shader_stage >= 6 - && limits.max_sampled_textures_per_shader_stage >= 5 + && limits.max_sampled_textures_per_shader_stage >= 7 && limits.max_uniform_buffers_per_shader_stage >= 2 - && limits.max_bindings_per_bind_group >= 13 + && limits.max_bindings_per_bind_group >= 22 && limits.max_compute_invocations_per_workgroup >= WORKGROUP * WORKGROUP && limits.max_compute_workgroup_size_x >= WORKGROUP && limits.max_compute_workgroup_size_y >= WORKGROUP @@ -86,12 +102,12 @@ impl GpuCompositor { let limits = device.limits(); // Micro maps and detail sizes share the curvature pipeline - let supports_curvature = limits.max_sampled_textures_per_shader_stage >= 8 + let supports_curvature = limits.max_sampled_textures_per_shader_stage >= 10 && limits.max_uniform_buffers_per_shader_stage >= 3 && limits.max_bindings_per_bind_group >= 19 && limits.max_storage_textures_per_shader_stage >= 1 && limits.max_compute_workgroup_size_x >= 64; - let supports_id = limits.max_sampled_textures_per_shader_stage >= 6 + 3 * u32::from(supports_curvature) && limits.max_bindings_per_bind_group >= 16; + let supports_id = limits.max_sampled_textures_per_shader_stage >= 8 + 3 * u32::from(supports_curvature) && limits.max_bindings_per_bind_group >= 16; let mut entries = vec![ binding(0, uniform), binding(1, read), @@ -106,6 +122,9 @@ impl GpuCompositor { binding(10, array), binding(11, float), binding(12, uniform), + // A live clone's or smudge's carried values (scalar and color layers) + binding(20, array), + binding(21, array), ]; if supports_curvature { entries.extend([binding(13, uint), binding(14, uniform)]); @@ -121,7 +140,7 @@ impl GpuCompositor { // Whole-map fields require another sampled texture alongside the curvature and ID inputs let supports_fields = supports_curvature && supports_id - && limits.max_sampled_textures_per_shader_stage >= 10 + && limits.max_sampled_textures_per_shader_stage >= 12 && limits.max_bindings_per_bind_group >= 19 && limits.max_storage_buffers_per_shader_stage >= 2; if supports_fields { @@ -168,8 +187,11 @@ impl GpuCompositor { uniform_coverage, coverage: Vec::new(), surfaces: Vec::new(), + grids: BTreeMap::new(), baked: BTreeMap::new(), - baked_budget: MAX_BAKED_INPUT_BYTES, + memory_budget: crate::gpu_memory::GpuMemoryBudget::default().bytes(), + last_use: BTreeMap::new(), + use_count: 0, id_bakes: BTreeMap::new(), curvature: supports_curvature.then(|| CurvatureResources { gpu: None, empty: CurvatureLevels::empty(device), cache: BTreeMap::new() }), generator_fields: supports_fields.then(|| p3b::GeneratorFieldsGpu::new(device)), @@ -181,10 +203,14 @@ impl GpuCompositor { default_id_bake: supports_id .then(|| input_texture(device, "tc_composite_empty_id_bake", (1, 1), 1, wgpu::TextureFormat::Rgba32Uint).create_view(&Default::default())), default_brush_alpha, + default_carried: TileImageAtlas::empty_view(device), default_brush_stencil: GpuStencil::empty(device), default_tile_images: TileImageAtlas::empty_view(device), tile_images: BTreeMap::new(), + projector_depth: None, paint_upload: None, + paint_word_limit: None, + largest_paint_words: 0, underlay_binding, underlays: BTreeMap::new(), scratch: None, @@ -253,15 +279,39 @@ impl GpuCompositor { return Ok((view.clone(), vertices.clone())); } - let limits = device.limits(); + if gbuf.width.max(gbuf.height) > device.limits().max_texture_dimension_2d { + return Err("UV surface data exceeds the GPU limits".into()); + } + self.surfaces.retain(|cache| !cache.gbuf.ptr_eq(&key)); + let vertices = Self::surface_vertices(device, mesh)?; + let texture = input_texture(device, "tc_composite_uv_surface", (gbuf.width, gbuf.height), 1, wgpu::TextureFormat::Rg32Uint); + let stride = (gbuf.width * ROWS) as usize; + let mut pixels = Vec::new(); + for (band, (tri, bary)) in gbuf.tri.chunks(stride).zip(gbuf.bary.chunks(stride)).enumerate() { + tri.par_iter() + .zip(bary) + .map(|(&tri, &[u, v])| { + let pack = |x: f32| u32::from(texturecraft_texel::to_u16(x)); + [tri, pack(u) | (pack(v) << 16)] + }) + .collect_into_vec(&mut pixels); + write_input(queue, &texture, (gbuf.width, tri.len() as u32 / gbuf.width), (band as u32 * ROWS, 0), &pixels); + } + let view = texture.create_view(&Default::default()); + self.surfaces.push(SurfaceCache { gbuf: key, view: view.clone(), vertices: Some(vertices.clone()) }); + Ok((view, vertices)) + } + + /// The surface vertices of `mesh` the UV surface's triangles index + pub(super) fn surface_vertices(device: &wgpu::Device, mesh: &Mesh) -> Result { // Two vec4 per vertex, then the tangents two per 32-byte element (`surface_tangent` in WGSL) + let limits = device.limits(); let vertex_bytes = (mesh.indices.len() as u64 + (mesh.indices.len() as u64).div_ceil(2)) * 32; - if gbuf.width.max(gbuf.height) > limits.max_texture_dimension_2d || vertex_bytes > limits.max_storage_buffer_binding_size.min(limits.max_buffer_size) { + if vertex_bytes > limits.max_storage_buffer_binding_size.min(limits.max_buffer_size) { return Err("UV surface data exceeds the GPU limits".into()); } - self.surfaces.retain(|cache| !cache.gbuf.ptr_eq(&key)); let (lo, hi) = mesh.bounds(); let center = (lo + hi) * 0.5; let radius = ((hi - lo).length() * 0.5).max(1e-4); @@ -282,27 +332,99 @@ impl GpuCompositor { contents: bytemuck::cast_slice(&vertex_data), usage: wgpu::BufferUsages::STORAGE, }); - drop(vertex_data); + Ok(vertices) + } - let texture = input_texture(device, "tc_composite_uv_surface", (gbuf.width, gbuf.height), 1, wgpu::TextureFormat::Rg32Uint); - let stride = (gbuf.width * ROWS) as usize; - let mut pixels = Vec::new(); - for (band, (tri, bary)) in gbuf.tri.chunks(stride).zip(gbuf.bary.chunks(stride)).enumerate() { - tri.par_iter() - .zip(bary) - .map(|(&tri, &[u, v])| { - let pack = |x: f32| u32::from(texturecraft_texel::to_u16(x)); - [tri, pack(u) | (pack(v) << 16)] - }) - .collect_into_vec(&mut pixels); - write_input(queue, &texture, (gbuf.width, tri.len() as u32 / gbuf.width), (band as u32 * ROWS, 0), &pixels); + /// Tests: whether the baked inputs cached under `ts` include `map` + #[cfg(all(test, not(target_arch = "wasm32")))] + pub(crate) fn caches_baked_map(&self, ts: usize, map: &Arc>) -> bool { + self.baked.get(&ts).is_some_and(|cache| cache.maps.iter().flatten().any(|cached| cached.upgrade().is_some_and(|cached| Arc::ptr_eq(&cached, map)))) + } + + /// Bytes texture set `ts`'s cached inputs hold, its micro height captures' (`usize::MAX - ts`) included + fn cached_bytes(&self, ts: usize) -> u64 { + let key_bytes = |key: usize| { + let baked = self.baked.get(&key).map_or(0, |cache| cache.bytes); + let id_bake = self.id_bakes.get(&key).map_or(0, |cache| cache.bytes); + let atlas = self.tile_images.get(&key).map_or(0, |atlas| atlas.bytes); + let micro = self.micro.as_ref().map_or(0, |micro| micro.cached_bytes(key)); + baked + id_bake + atlas + micro + }; + let grids = self.grids.get(&ts).map_or(0, |grids| grids.iter().map(|grid| self.grid_bytes(grid)).sum()); + key_bytes(ts) + key_bytes(usize::MAX - ts) + grids + } + + /// Bytes the UV surface (its vertices included) and coverage of `grid` hold on the device + fn grid_bytes(&self, grid: &Weak) -> u64 { + let surfaces: u64 = self + .surfaces + .iter() + .filter(|cache| cache.gbuf.ptr_eq(grid)) + .map(|cache| { + let texture = cache.view.texture(); + let texel = texture.format().block_copy_size(None).map_or(0, u64::from); + u64::from(texture.width()) * u64::from(texture.height()) * texel + cache.vertices.as_ref().map_or(0, wgpu::Buffer::size) + }) + .sum(); + let coverage: u64 = self.coverage.iter().filter(|(cached, _)| cached.ptr_eq(grid)).map(|(_, buffer)| buffer.size()).sum(); + surfaces + coverage + } + + /// Free the UV grids texture set `ts` read that the set `keep` does not read + fn release_grids(&mut self, ts: usize, keep: usize) { + let Some(grids) = self.grids.remove(&ts) else { return }; + let kept = self.grids.get(&keep).cloned().unwrap_or_default(); + let unused = |grid: &Weak| grids.iter().any(|old| old.ptr_eq(grid)) && !kept.iter().any(|keep| keep.ptr_eq(grid)); + self.surfaces.retain(|cache| !unused(&cache.gbuf)); + self.coverage.retain(|(grid, _)| !unused(grid)); + } + + /// Free every texture set's cached inputs and working buffers after the GPU ran out of memory, + /// keeping the compiled pipelines + pub(crate) fn release_all_inputs(&mut self) { + self.clear_baked_inputs(); + self.tile_images.clear(); + self.underlays.clear(); + if let Some(fields) = &mut self.generator_fields { + fields.retain_texture_sets(0); + } + + self.surfaces.clear(); + self.coverage.clear(); + self.grids.clear(); + self.scratch = None; + self.paint_upload = None; + self.last_use.clear(); + } + + /// After running out of GPU memory: the next update uploads paint in windows of half the + /// largest one this update used, instead of asking for the same size again + pub(crate) fn halve_paint_windows(&mut self) { + self.paint_word_limit = (self.largest_paint_words > 1).then_some(self.largest_paint_words / 2); + } + + /// Mark texture set `ts` as just composited, then evict the inputs of the least recently + /// composited other sets while all cached inputs exceed the memory budget + pub(crate) fn make_room(&mut self, ts: usize) { + self.use_count += 1; + self.last_use.insert(ts, self.use_count); + let budget = self.memory_budget; + let mut held: u64 = self.last_use.keys().map(|&set| self.cached_bytes(set)).sum(); + while held > budget { + let oldest = self.last_use.iter().filter(|&(&set, _)| set != ts).min_by_key(|&(_, &used)| used).map(|(&set, _)| set); + let Some(oldest) = oldest else { break }; + + held = held.saturating_sub(self.cached_bytes(oldest)); + self.release_inputs(oldest); + self.release_inputs(usize::MAX - oldest); + self.release_grids(oldest, ts); + self.last_use.remove(&oldest); } - let view = texture.create_view(&Default::default()); - self.surfaces.push(SurfaceCache { gbuf: key, view: view.clone(), vertices: Some(vertices.clone()) }); - Ok((view, vertices)) } pub(crate) fn retain_texture_sets(&mut self, count: usize) { + self.last_use.retain(|&ts, _| ts < count); + self.grids.retain(|&ts, _| ts < count); self.release_unused_surfaces(); self.baked.retain(|&ts, _| ts < count); self.id_bakes.retain(|&ts, _| ts < count); @@ -394,8 +516,8 @@ impl GpuCompositor { // Pack four RGB words per texel so complete bake rows can upload directly let packed_height = (u64::from(height) * 3).div_ceil(4) as u32; let dimensions = device.limits().max_texture_dimension_2d; - if width.max(packed_height) > dimensions || u64::from(width) * u64::from(packed_height) * 16 > MAX_ID_BAKE_BYTES { - return Err("The ID map exceeds the adapter's GPU texture budget.".into()); + if width.max(packed_height) > dimensions { + return Err("The ID map exceeds the adapter's GPU texture dimensions.".into()); } self.id_bakes.remove(&ts); @@ -429,7 +551,8 @@ impl GpuCompositor { } } let view = texture.create_view(&Default::default()); - self.id_bakes.insert(ts, IdBakeCache { size: id_bake.size, data, view: view.clone() }); + let bytes = u64::from(width) * u64::from(packed_height) * size_of::<[u32; 4]>() as u64; + self.id_bakes.insert(ts, IdBakeCache { size: id_bake.size, data, view: view.clone(), bytes }); Ok(Some(view)) } @@ -469,54 +592,28 @@ impl GpuCompositor { if size.0.max(rows) > device.limits().max_texture_dimension_2d { return Err("Baked maps exceed the GPU texture dimensions".into()); } - if u64::from(size.0) * u64::from(rows) * size_of::<[u32; 4]>() as u64 > self.baked_budget { - return Err("The baked maps exceed the GPU texture budget.".into()); - } - self.baked.remove(&ts); + let bytes = u64::from(size.0) * u64::from(rows) * size_of::<[u32; 4]>() as u64; // Three full-precision scalars and one packed normal fit in one atlas texel let texture = input_texture(device, "tc_composite_bakes", (size.0, rows), 1, wgpu::TextureFormat::Rgba32Uint); if let Some(layout) = separate { write_separate_bakes(queue, &texture, baked, layout); let view = texture.create_view(&Default::default()); - self.baked.insert(ts, BakeCache { size, maps: refs, view: view.clone() }); + self.baked.insert(ts, BakeCache { size, maps: refs, view: view.clone(), bytes }); return Ok(view); } let mut texels = Vec::new(); - let value = |map: usize, i: usize, fallback: f32| baked.maps[map].as_ref().and_then(|data| data.get(i).copied()).unwrap_or(fallback); - for top in (0..size.1).step_by(ROWS as usize) { - let end = (top + ROWS).min(size.1); - let indices = top as usize * size.0 as usize..end as usize * size.0 as usize; - indices - .into_par_iter() - .map(|i| { - let normal = if baked.maps[1].is_some() { - encode_baked_normal([value(1, i * 3, 0.5), value(1, i * 3 + 1, 0.5), value(1, i * 3 + 2, 1.0)]) - } else { - 0 - }; - [value(0, i, 1.0).to_bits(), value(2, i, 0.5).to_bits(), value(3, i, 1.0).to_bits(), normal] - }) - .collect_into_vec(&mut texels); - write_input(queue, &texture, (size.0, end - top), (top, 0), &texels); - } - if baked.blocks() > 1 { - // Height in x, the stored world normal in yzw; zeros where a map is not baked - let row = |map: usize, i: usize, component: usize| { - let components = BAKE_ROW_MAPS[map].components(); - baked.rows[map].as_ref().and_then(|data| data.get(i * components + component).copied()).unwrap_or(0.0).to_bits() - }; + for block in 0..baked.blocks() { for top in (0..size.1).step_by(ROWS as usize) { let end = (top + ROWS).min(size.1); - let indices = top as usize * size.0 as usize..end as usize * size.0 as usize; - indices.into_par_iter().map(|i| [row(0, i, 0), row(1, i, 0), row(1, i, 1), row(1, i, 2)]).collect_into_vec(&mut texels); - write_input(queue, &texture, (size.0, end - top), (size.1 + top, 0), &texels); + super::banded_inputs::pack_bake_rows(baked, block, [top, end], &mut texels); + write_input(queue, &texture, (size.0, end - top), (block * size.1 + top, 0), &texels); } } let view = texture.create_view(&Default::default()); - self.baked.insert(ts, BakeCache { size, maps: refs, view: view.clone() }); + self.baked.insert(ts, BakeCache { size, maps: refs, view: view.clone(), bytes }); Ok(view) } @@ -642,7 +739,10 @@ impl GpuCompositor { if self.tile_images.get(&ts).is_none_or(|atlas| !atlas.matches(&gray, &color, raw)) { self.tile_images.remove(&ts); - let atlas = TileImageAtlas::new(device, queue, &gray, &color, raw)?; + if self.projector_depth.is_none() && raw.iter().any(|plane| plane.raster.is_some()) { + self.projector_depth = Some(crate::gpu_image_source::GpuProjectorDepth::new(device)?); + } + let atlas = TileImageAtlas::new(device, queue, &gray, &color, raw, self.projector_depth.as_ref())?; self.tile_images.insert(ts, atlas); } Ok(self.tile_images.get(&ts)) @@ -660,6 +760,7 @@ impl GpuCompositor { ) -> Result<(), String> { let (device, queue) = gpu; let (ts, source_size, shift, region) = target; + self.largest_paint_words = 0; // P2: the anchor heights micro details read, composited by their capture programs first let captures = if program.micro.captures_anchors() { generator_p2::compose_captures(self, gpu, (ts, source_size), program)? } else { Vec::new() }; @@ -687,6 +788,9 @@ impl GpuCompositor { let whole = program.filters.whole_set(); let halo = radius.saturating_add(program.filters.band_reach(whole.as_ref())); let limits = device.limits(); + + // Tiling: row-addressed inputs the device cannot hold whole upload per chunk of rows + let banded = BandedInputs::plan(&limits, program, whole.is_some())?; let underlay = match &program.underlay { Some(material) => { let bytes = (material.words.len() * size_of::()) as u64; @@ -722,9 +826,22 @@ impl GpuCompositor { self.filter_gpu.get_or_insert_with(|| NeighbourhoodGpu::for_device(device, shared)); } let (pipeline, prepare) = self.pipelines().get(device, &self.pipeline_layout, program, self.asynchronous)?.ok_or(GPU_PIPELINES_PENDING)?; - let coverage = self.coverage_buffer(device, program.coverage.as_ref().map(|(map, _)| map))?; - let (surface, vertices) = self.surface_inputs(device, queue, program)?; - let baked = self.baked_input(device, queue, ts, program.baked.as_ref())?; + let coverage = + if banded.coverage { self.uniform_coverage.clone() } else { self.coverage_buffer(device, program.coverage.as_ref().map(|(map, _)| map))? }; + let (surface, vertices) = match &program.surface { + Some((mesh, gbuf)) if banded.surface => { + validate_triangle_grid(gbuf)?; + if program.needs_surface && gbuf.bary.len() != gbuf.tri.len() { + return Err("The UV surface is missing barycentric data.".into()); + } + let vertices = if program.needs_surface { Self::surface_vertices(device, mesh)? } else { self.default_vertices.clone() }; + (self.default_surface.clone(), vertices) + } + _ => self.surface_inputs(device, queue, program)?, + }; + let grids = program.surface.iter().map(|(_, gbuf)| gbuf).chain(program.coverage.iter().map(|(map, _)| map)).map(Arc::downgrade).collect(); + self.grids.insert(ts, grids); + let baked = if banded.bake { self.default_baked.clone() } else { self.baked_input(device, queue, ts, program.baked.as_ref())? }; let curvature = self.curvature_inputs(device, queue, ts, program, &baked)?; // P2: a generator's micro details, texture or grunge need P2's bindings, which come with the curvature levels @@ -933,8 +1050,27 @@ impl GpuCompositor { contents: if operations.is_empty() { bytemuck::bytes_of(&empty_operation) } else { bytemuck::cast_slice(operations.as_ref()) }, usage: wgpu::BufferUsages::STORAGE, }); - let max_words = MAX_PAINT_WORDS.min((limits.max_storage_buffer_binding_size.min(limits.max_buffer_size) / 4) as usize); - let windows = paint_windows(program, region, source_size, shift, halo, max_words)?; + // The memory retry's halved window; a texel whose paint it cannot hold takes what the device binds + let device_words = max_paint_words(&limits); + let mut max_words = device_words.min(self.paint_word_limit.unwrap_or(usize::MAX)); + // Without UV padding (a coverage of radius 0 only hides uncovered texels) or filter + // stages the composite reads paint only at its display texels: paint is read only through + // `base_content(texel)`, whose texel the main pass builds at `display_pixel * step` and + // only filter stages (fields, anchors, captures) build elsewhere. A reduced composite + // (a thumbnail) then uploads only those texels. + let sampled = (shift, shift > 0 && halo == 0 && program.filters.stages.is_empty()); + // The UV padding of a field texel reaches its radius past the field's halo, and bilinear + // projections and height slopes read one row past a texel + let reach = halo.saturating_add(radius).saturating_add(1); + let inputs_fit = |chunk| !banded.any() || banded.fit(&limits, program, source_size.1, input_rows(chunk, shift, reach, source_size.1)); + let windows = match paint_windows(program, region, source_size, sampled, halo, max_words, &inputs_fit) { + Err(_) if max_words < device_words => { + max_words = device_words; + paint_windows(program, region, source_size, sampled, halo, max_words, &inputs_fit)? + } + windows => windows?, + }; + self.largest_paint_words = windows.iter().map(|&(_, _, words)| words).max().unwrap_or(0); // The band uniform: the positional words, the field layout and the package vec4s let band_values = @@ -996,7 +1132,10 @@ impl GpuCompositor { packages::write_band_uniform(program, &mut values); values }; - let make_bindings = |values: &[u32], paint: &wgpu::Buffer| { + let make_bindings = |values: &[u32], paint: &wgpu::Buffer, band: Option<&BandInputs>| { + let coverage = band.and_then(|band| band.coverage.as_ref()).unwrap_or(&coverage); + let surface = band.and_then(|band| band.surface.as_ref()).unwrap_or(&surface); + let baked = band.and_then(|band| band.baked.as_ref()).unwrap_or(&baked); let params = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("tc_composite_band"), contents: bytemuck::cast_slice(values), @@ -1009,19 +1148,19 @@ impl GpuCompositor { wgpu::BindGroupEntry { binding: 3, resource: scratch.as_entire_binding() }, wgpu::BindGroupEntry { binding: 4, resource: paint.as_entire_binding() }, wgpu::BindGroupEntry { binding: 5, resource: coverage.as_entire_binding() }, - wgpu::BindGroupEntry { binding: 6, resource: wgpu::BindingResource::TextureView(&surface) }, + wgpu::BindGroupEntry { binding: 6, resource: wgpu::BindingResource::TextureView(surface) }, wgpu::BindGroupEntry { binding: 7, resource: vertices.as_entire_binding() }, - wgpu::BindGroupEntry { binding: 8, resource: wgpu::BindingResource::TextureView(&baked) }, + wgpu::BindGroupEntry { binding: 8, resource: wgpu::BindingResource::TextureView(baked) }, wgpu::BindGroupEntry { binding: 9, resource: wgpu::BindingResource::TextureView(brush_alpha) }, wgpu::BindGroupEntry { binding: 10, resource: wgpu::BindingResource::TextureView(tile_images) }, wgpu::BindGroupEntry { binding: 11, resource: wgpu::BindingResource::TextureView(&brush_stencil.image) }, wgpu::BindGroupEntry { binding: 12, resource: brush_stencil.uniforms.as_entire_binding() }, - wgpu::BindGroupEntry { binding: 13, resource: wgpu::BindingResource::TextureView(curvature.as_ref().map_or(&baked, |levels| &levels.image)) }, + wgpu::BindGroupEntry { binding: 13, resource: wgpu::BindingResource::TextureView(curvature.as_ref().map_or(baked, |levels| &levels.image)) }, wgpu::BindGroupEntry { binding: 14, resource: curvature.as_ref().map_or_else(|| lookup.as_entire_binding(), |levels| levels.layout.as_entire_binding()), }, - wgpu::BindGroupEntry { binding: 15, resource: wgpu::BindingResource::TextureView(id_bake.as_ref().unwrap_or(&baked)) }, + wgpu::BindGroupEntry { binding: 15, resource: wgpu::BindingResource::TextureView(id_bake.as_ref().unwrap_or(baked)) }, ]; let mut count = if curvature.is_some() { 15 } else { 13 }; if id_bake.is_some() { @@ -1044,6 +1183,10 @@ impl GpuCompositor { let buffer = underlay.as_ref().unwrap_or(&lookup); entries.push(wgpu::BindGroupEntry { binding: 19, resource: buffer.as_entire_binding() }); } + let (carried_scalars, carried_colors) = + program.brush_carried.as_ref().map_or((&self.default_carried, &self.default_carried), |carried| (&carried.scalars, &carried.colors)); + entries.push(wgpu::BindGroupEntry { binding: 20, resource: wgpu::BindingResource::TextureView(carried_scalars) }); + entries.push(wgpu::BindGroupEntry { binding: 21, resource: wgpu::BindingResource::TextureView(carried_colors) }); device.create_bind_group(&wgpu::BindGroupDescriptor { label: Some("tc_composite_band"), layout: &self.bindings, entries: &entries }) }; let mut packed = Vec::new(); @@ -1091,6 +1234,7 @@ impl GpuCompositor { let paint_words = pre_pass_paint_words(max_words); let stripe_words = stripe_window.words(&program.paint, paint_words); if let Some(words) = stripe_words { + self.largest_paint_words = self.largest_paint_words.max(words); upload(&stripe_window, words, &mut encoder, (&mut self.paint_upload, &mut packed)); } for pass in &whole.stages.passes { @@ -1147,7 +1291,7 @@ impl GpuCompositor { let window = CompositePaintWindow::covering(low, high, [source_size.0, source_size.1], &program.paint); let Some(words) = window.words(&program.paint, paint_words) else { if chunk_rows < 2 { - return Err("Paint inputs of the whole-set filter exceed the adapter's upload budget.".into()); + return Err("Paint inputs of the whole-set filter exceed the adapter's buffer limit.".into()); } let half = chunk_rows / 2; @@ -1155,6 +1299,7 @@ impl GpuCompositor { continue; }; + self.largest_paint_words = self.largest_paint_words.max(words); upload(&window, words, &mut encoder, (&mut self.paint_upload, &mut packed)); #[cfg(all(test, not(target_arch = "wasm32")))] PRE_PASS_CHUNK_WINDOWS.set(PRE_PASS_CHUNK_WINDOWS.get() + 1); @@ -1169,7 +1314,7 @@ impl GpuCompositor { let mut source = stage_values(paint_params); source[28..32].copy_from_slice(&chunk); let paint = self.paint_upload.as_ref().ok_or("paint upload buffer is missing")?; - let source_bindings = make_bindings(&source, paint); + let source_bindings = make_bindings(&source, paint, None); let mut compute = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("tc_whole_set_source"), timestamp_writes: None }); compute.set_pipeline(prepare); @@ -1234,10 +1379,14 @@ impl GpuCompositor { } } for (chunk, window, words) in windows { - let bytes = (words * 4) as u64; + // The chunk's paint and banded inputs stay resident until its submission runs + let input_band = input_rows(chunk, shift, reach, source_size.1); + let bytes = (words * 4) as u64 + if banded.any() { banded.bytes(program, source_size.1, input_band) } else { 0 }; window.pack(&program.paint, words, &mut packed); let [paint_x, paint_y, paint_columns, paint_rows] = window.params(); if pending_bytes + bytes > (max_words * 4) as u64 { + #[cfg(all(test, not(target_arch = "wasm32")))] + super::UPLOAD_WAITS.set(super::UPLOAD_WAITS.get() + 1); device.poll(wgpu::PollType::Wait { submission_index: last_submission.take(), timeout: None }).map_err(|e| e.to_string())?; pending_bytes = 0; } @@ -1252,6 +1401,9 @@ impl GpuCompositor { } let paint = self.paint_upload.as_ref().ok_or("paint upload buffer is missing")?; queue.write_buffer(paint, 0, bytemuck::cast_slice(&packed)); + + // Tiling: this chunk's rows of the inputs the device cannot hold whole + let band_inputs = if banded.any() { Some(banded.upload(gpu, program, source_size.1, input_band)?) } else { None }; let mut encoder = make_encoder(); let mut work = 0u64; let mut bounds: Option = None; @@ -1280,10 +1432,11 @@ impl GpuCompositor { // Only wrapping stages may sample field-local texels across a set edge let set_bounds = field_bounds(field_rect, source_size); let mut values = band_values((width, rows, top, left), [paint_x, paint_y, paint_columns, paint_rows], field_rect, field_base); + BandInputs::write_uniform(band_inputs.as_ref().map_or(BandInputs::WHOLE, |band| band.words), &mut values); if let Some(whole) = &whole { whole.write_uniform(&mut values, whole_base); } - let bindings = |values: &[u32]| make_bindings(values, paint); + let bindings = |values: &[u32]| make_bindings(values, paint, band_inputs.as_ref()); if let (Some(prepare), Some(kernels)) = (&prepare, &self.filter_gpu) { let fields = program.filters.stages.len() as u32; let field_words = field_rect[2] * field_rect[3] * texel_words; @@ -1419,6 +1572,43 @@ impl GpuCompositor { self.pipelines().prewarm(device, &self.pipeline_layout, program); } + /// Remember the pipeline variant of texture set `ts`'s viewport program + pub(crate) fn remember_variant(&mut self, ts: usize, program: &CompositeProgram) { + self.pipelines().remember(ts, program); + } + + /// Forget every set's remembered variant (the sets were replaced) + pub(crate) fn forget_variants(&mut self) { + self.pipelines().forget(); + } + + /// Start compiling the variant a live clone or smudge stroke on texture set `ts` needs + /// (true once compiled) + pub(crate) fn prewarm_pickup(&mut self, device: &wgpu::Device, ts: usize) -> bool { + self.pipelines().prewarm_pickup(device, &self.pipeline_layout, ts) + } + + #[cfg(all(test, not(target_arch = "wasm32")))] + pub(crate) fn has_pickup_variant(&self, ts: usize) -> bool { + self.pipelines().has_pickup_variant(ts) + } + + /// [`Self::compose`] whole, compiling new pipelines in place even when they otherwise compile + /// on worker threads: for work that cannot wait for them (a brush's pickup source) + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] + pub(crate) fn compose_now( + &mut self, + gpu: (&wgpu::Device, &wgpu::Queue), + program: &CompositeProgram, + target: (usize, (u32, u32)), + textures: &[&wgpu::Texture], + ) -> Result<(), String> { + let asynchronous = std::mem::replace(&mut self.asynchronous, false); + let result = self.compose(gpu, program, (target.0, target.1, 0, None), textures, &mut None); + self.asynchronous = asynchronous; + result + } + /// Compile new pipelines on worker threads (the app's viewport) or in place (tests, wasm). pub(crate) fn set_asynchronous_compile(&mut self, asynchronous: bool) { self.asynchronous = asynchronous && !cfg!(target_arch = "wasm32"); @@ -1443,29 +1633,62 @@ mod tests { use texturecraft_core::TextureSet; use texturecraft_geom::primitives; - /// The baked-map atlas is refused above its byte budget (the caller then falls back to the CPU) - /// and accepted exactly at it, without caching anything for the refused set. - #[test] - fn baked_input_is_refused_above_its_byte_budget() { - let Some(gpu) = Headless::for_required_tests() else { return }; - const SIDE: u32 = 64; - let baked = BakedMaps { resolution: SIDE, maps: BTreeMap::from([(BakedMap::AmbientOcclusion, Arc::new(vec![0.5; (SIDE * SIDE) as usize]))]) }; - let mut project = Project::new("Baked budget", "builtin:plane"); - project.texture_sets.push(TextureSet::new("Plane", 0, SIDE)); + /// Inputs of two texture sets on the GPU, set 0 composited before set 1, under `budget` + fn two_cached_sets(gpu: &Headless, side: u32, budget: crate::gpu_memory::GpuMemoryBudget) -> GpuCompositor { + let baked = BakedMaps { resolution: side, maps: BTreeMap::from([(BakedMap::AmbientOcclusion, Arc::new(vec![0.5; (side * side) as usize]))]) }; + let mut project = Project::new("Memory budget", "builtin:plane"); + project.texture_sets.push(TextureSet::new("Plane", 0, side)); let mesh = Arc::new(primitives::plane(1.0, 1)); - let gbuf = Arc::new(UvGBuffer::new(&mesh, 0, SIDE, SIDE)); + let gbuf = Arc::new(UvGBuffer::new(&mesh, 0, side, side)); let mut program = CompositeProgram::try_compile_region(&project, &PixelStore::default(), 0, None).unwrap(); program.set_surface_inputs(&mesh, &gbuf, Some(&baked)).unwrap(); let mut compositor = GpuCompositor::new(&gpu.device); - // One Rgba32Uint texel (16 bytes) per baked texel, one block of rows - let bytes = u64::from(SIDE) * u64::from(SIDE) * 16; + compositor.memory_budget = budget.bytes(); + for ts in [0, 1] { + compositor.baked_input(&gpu.device, &gpu.queue, ts, program.baked.as_ref()).unwrap(); + if ts == 0 { + // Set 0 counts as holding more than any fixed automatic budget would allow + compositor.baked.get_mut(&0).unwrap().bytes = 64 << 30; + } + compositor.make_room(ts); + } + compositor + } - compositor.baked_budget = bytes - 1; - let refused = compositor.baked_input(&gpu.device, &gpu.queue, 0, program.baked.as_ref()); - assert!(refused.as_ref().is_err_and(|error| error.contains("budget")), "one byte over the budget must be refused: {refused:?}"); - assert!(compositor.baked.is_empty(), "a refused input must not be cached"); + /// A megabyte setting evicts the least recently composited set's inputs once all cached + /// inputs exceed it, and keeps the inputs of the set just composited + #[test] + fn a_chosen_budget_evicts_the_least_recently_used_set() { + let Some(gpu) = Headless::for_required_tests() else { return }; + let compositor = two_cached_sets(&gpu, 256, crate::gpu_memory::GpuMemoryBudget::from_megabytes(1)); + assert!(!compositor.baked.contains_key(&0), "the older set's inputs are evicted"); + assert!(compositor.baked.contains_key(&1), "the set just composited keeps its inputs"); + } - compositor.baked_budget = bytes; - assert!(compositor.baked_input(&gpu.device, &gpu.queue, 0, program.baked.as_ref()).is_ok(), "exactly the budget fits"); + /// A megabyte setting counts the UV surfaces a set's composites read: an older set's surface + /// is evicted with its other inputs, the surface of the set just composited stays + #[test] + fn a_chosen_budget_counts_and_evicts_uv_surfaces() { + let Some(gpu) = Headless::for_required_tests() else { return }; + let mesh = Arc::new(primitives::plane(1.0, 1)); + let grids = [0, 1].map(|_| Arc::new(UvGBuffer::new(&mesh, 0, 512, 512))); + let mut compositor = GpuCompositor::new(&gpu.device); + compositor.memory_budget = crate::gpu_memory::GpuMemoryBudget::from_megabytes(1).bytes(); + for (ts, grid) in grids.iter().enumerate() { + compositor.uv_surface(&gpu.device, &gpu.queue, &mesh, grid).unwrap(); + compositor.grids.insert(ts, vec![Arc::downgrade(grid)]); + compositor.make_room(ts); + } + let cached = |grid: &Arc| compositor.surfaces.iter().any(|cache| cache.gbuf.ptr_eq(&Arc::downgrade(grid))); + assert!(!cached(&grids[0]), "the older set's UV surface is evicted"); + assert!(cached(&grids[1]), "the set just composited keeps its UV surface"); + } + + /// Auto evicts nothing by size: only the GPU's refusal of an allocation frees cached inputs + #[test] + fn auto_keeps_cached_inputs_until_the_gpu_refuses() { + let Some(gpu) = Headless::for_required_tests() else { return }; + let compositor = two_cached_sets(&gpu, 64, crate::gpu_memory::GpuMemoryBudget::default()); + assert!(compositor.baked.contains_key(&0) && compositor.baked.contains_key(&1), "both sets keep their inputs"); } } diff --git a/crates/render/src/gpu_composite/id_bake_cache.rs b/crates/render/src/gpu_composite/id_bake_cache.rs index 96c87b621..23d5ea0ea 100644 --- a/crates/render/src/gpu_composite/id_bake_cache.rs +++ b/crates/render/src/gpu_composite/id_bake_cache.rs @@ -4,4 +4,6 @@ pub(super) struct IdBakeCache { pub(super) size: [u32; 2], pub(super) data: Weak>, pub(super) view: wgpu::TextureView, + /// Bytes of its texture, counted against the memory budget + pub(super) bytes: u64, } diff --git a/crates/render/src/gpu_composite/live_brush.rs b/crates/render/src/gpu_composite/live_brush.rs index 108a14255..ac0b5db11 100644 --- a/crates/render/src/gpu_composite/live_brush.rs +++ b/crates/render/src/gpu_composite/live_brush.rs @@ -1,4 +1,4 @@ -use super::{Channel, GpuStencil, LayerId, LiveBrushTarget}; +use super::{BTreeMap, Channel, GpuStencil, LayerId, LiveBrushTarget}; /// The active stroke's GPU alpha, sampled in the corresponding paint layer or mask effect. #[derive(Clone)] @@ -11,6 +11,46 @@ pub struct LiveBrush { pub alpha: wgpu::TextureView, /// Supplies opacity modulation and Base Color for a projection stroke. pub stencil: Option, + /// A clone or smudge stroke paints the values it carries on the device instead of the + /// target's values or gray; a mask's under `MASK_CHANNEL`. + pub carried: Option, +} + +/// Where a clone's or smudge's carried values live on the device: the compositor reads them at +/// each texel plus `offset` wherever the stroke has alpha (no readback while the stroke paints). +#[derive(Clone, Debug)] +pub struct LiveCarried { + /// Scalar channels: R16 layers (smudge) or four channels per RGBA16 layer (clone source) + pub scalars: wgpu::TextureView, + /// Channels of three components, one RGBA16 layer each + pub colors: wgpu::TextureView, + /// The clone offset in texels (zero for a smudge) + pub offset: [i32; 2], + /// Per carried channel: in the color layers, its layer and its component + pub channels: BTreeMap, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct CarriedSlot { + pub color: bool, + pub layer: u32, + pub component: u32, + /// The channel's own stroke alpha, an R16 layer of the scalar map (a source with per-channel + /// coverage); None: the stroke alpha + pub alpha: Option, +} + +/// `CarriedSlot::descriptor`'s bit for a channel's own alpha (composite.wgsl `CARRIED_ALPHA`) +pub(super) const CARRIED_ALPHA: u32 = 1 << 16; + +impl CarriedSlot { + /// The operation word `ext[3]` of a live paint operation that reads this slot (composite_brush.wgsl + /// `carried_value`): bit 0 set, bit 1 color, bits 2-3 the component, bits 4-15 the layer; with + /// the channel's own alpha bit 16 and its layer from bit 17 + pub(super) fn descriptor(self) -> u32 { + let alpha = self.alpha.map_or(0, |layer| CARRIED_ALPHA | (layer << 17)); + 1 | (u32::from(self.color) << 1) | ((self.component & 3) << 2) | ((self.layer & 0xfff) << 4) | alpha + } } impl LiveBrush { @@ -24,6 +64,20 @@ impl LiveBrush { LiveBrushTarget::Layer { values, .. } => values.values().flatten().all(|v| v.is_finite()), LiveBrushTarget::Mask { value, .. } => value.is_finite(), }; + let fits = |view: &wgpu::TextureView| (view.texture().width(), view.texture().height()) == size; + // The descriptor holds 12 bits of a value layer and 15 of an alpha layer + let carried_fits = self.carried.as_ref().is_none_or(|carried| { + fits(&carried.scalars) + && fits(&carried.colors) + && carried + .channels + .iter() + .all(|(channel, slot)| slot.color == (channel.components() == 3) && slot.layer < 1 << 12 && slot.alpha.is_none_or(|layer| layer < 1 << 15)) + }); + if !carried_fits { + return Err("The live clone values do not match the texture set."); + } + if !valid || !self.opacity.is_finite() { return Err("The live brush has invalid paint values."); } @@ -31,6 +85,11 @@ impl LiveBrush { Ok(()) } + /// Where the live compositor reads the carried values of `channel` + pub(super) fn carried_slot(&self, channel: Channel) -> Option { + self.carried.as_ref()?.channels.get(&channel).copied() + } + /// The live paint of `channel` on paint layer or content paint effect `id`: its value, the /// stroke opacity and whether it erases. pub(super) fn value_for_layer(&self, id: LayerId, channel: Channel) -> Option<([f32; 3], f32, bool)> { diff --git a/crates/render/src/gpu_composite_brush.rs b/crates/render/src/gpu_composite_brush.rs index a8e838269..2ae325e2e 100644 --- a/crates/render/src/gpu_composite_brush.rs +++ b/crates/render/src/gpu_composite_brush.rs @@ -5,8 +5,8 @@ //! `BRUSH_ERASE`), the Projection tool in both views, symmetry copies in both views, path curves, //! and one device stroke feeding every texture set of its size that draws the layer. A stencil //! stroke feeds only its own set, because the stencil is sampled at that set's surface. Pickup -//! strokes (Smudge, Clone, Paint with a material pattern) rasterise on the CPU and composite live -//! on the GPU from `display_stroke_pixels`. A mask stroke painting an image's gray reads it per +//! strokes (Smudge, Clone, Paint with a material pattern) paint their carried values live from +//! the device's textures (`LiveCarried`, `carried_value`). A mask stroke painting an image's gray reads it per //! texel (`BRUSH_MASK_IMAGE`). Still on the CPU: particle strokes, strokes with a brush alpha //! image or a library tip, and Polygon Fill, which fills whole triangles into the document //! pixels in one step with no live stroke to preview or composite. @@ -51,16 +51,18 @@ pub(super) fn live_paint_bits(erase: bool, mask_image: bool) -> u32 { pub(super) const WGSL: &str = include_str!("shaders/composite_brush.wgsl"); /// The same functions without P7's code, for programs that do not use it. -pub(super) const WGSL_STUB: &str = "fn live_brush_paint(layer: Operation, stored: vec4, m: f32, projected: ProjectedBrush, pixel: vec2, uv: vec2) -> vec4 { return stored; }"; +pub(super) const WGSL_STUB: &str = "fn live_brush_paint(layer: Operation, stored: vec4, m: f32, projected: ProjectedBrush, pixel: vec2, uv: vec2) -> vec4 { return stored; } + fn carried_value(layer: Operation, pixel: vec2) -> vec4 { return vec4(0.0); }"; /// Whether a program needs the full `composite_brush.wgsl`. pub(super) fn uses_shader(program: &CompositeProgram) -> bool { - program.operations.iter().any(|op| op.ext[2] & BRUSH_OP_BITS != 0) + program.brush_carried.is_some() || program.operations.iter().any(|op| op.ext[2] & BRUSH_OP_BITS != 0) } -/// P7's vec4 of the band uniform (`params.packages[6]`). -pub(super) fn band_uniform(_program: &CompositeProgram) -> [u32; 4] { - [0; 4] +/// P7's vec4 of the band uniform (`params.packages[6]`): a live clone's offset in texels. +pub(super) fn band_uniform(program: &CompositeProgram) -> [u32; 4] { + let [x, y] = program.brush_carried.as_ref().map_or([0; 2], |carried| carried.offset); + [x.cast_unsigned(), y.cast_unsigned(), 0, 0] } #[cfg(all(test, not(target_arch = "wasm32")))] @@ -186,7 +188,14 @@ mod tests { } PaintTarget::Mask(effect) => LiveBrushTarget::Mask { effect, value: 1.0, image: None }, }; - let live = LiveBrush { target: live_target, opacity: preview.opacity, erase: true, alpha: alpha.create_view(&Default::default()), stencil: None }; + let live = LiveBrush { + target: live_target, + opacity: preview.opacity, + erase: true, + alpha: alpha.create_view(&Default::default()), + stencil: None, + carried: Default::default(), + }; let mut program = CompositeProgram::try_compile_with_brush(&project, &pixels, 0, None, Some(live)).unwrap(); program.set_surface_inputs(&mesh, &gbuf, None).unwrap(); program.set_tile_images(&images); @@ -212,6 +221,155 @@ mod tests { } } + /// A live clone and a live smudge read their carried values on the device as the CPU paints + /// the same values: scalars packed four per source layer (clone) or one per layer (smudge), + /// the signed Height, Base Color, and a clone offset whose stroke reaches up to the set's edge; + /// a smudge of the layer's own paint deposits each channel by its own alpha + #[test] + fn a_live_pickup_reads_its_carried_values_on_the_device() { + use texturecraft_paint::{BrushAlpha, BrushSettings, Pickup, PickupMode, UvStamp}; + + let Some(mut gpu) = headless() else { return }; + const SIZE: u32 = TILE; + const OFFSET: [i64; 2] = [-21, 17]; + let size = (SIZE, SIZE); + let channels = [Channel::BaseColor, Channel::Height, Channel::Roughness, Channel::Metallic]; + let mesh = Arc::new(primitives::plane(2.0, 4)); + let gbuf = Arc::new(UvGBuffer::new(&mesh, 0, SIZE, SIZE)); + let mut project = Project::new("Live pickup", "builtin:plane"); + project.texture_sets.push(TextureSet::new("Plane", 0, SIZE)); + let layer_id = project.alloc_id(); + project.insert_layer(0, Layer::new(layer_id, "Painted layer", LayerKind::Paint, &channels), None, false).unwrap(); + let mut pixels = PixelStore::default(); + let roughness = pixels.layer_mut(layer_id, Channel::Roughness, size); + for y in 0..40 { + for x in 10..50 { + roughness.set(x, y, &[to_u16(0.7), to_u16(0.8)]); + } + } + + // Metallic less covered there: its own alpha stays below the stroke's + let metallic = pixels.layer_mut(layer_id, Channel::Metallic, size); + for y in 0..40 { + for x in 10..50 { + metallic.set(x, y, &[to_u16(0.2), to_u16(0.3)]); + } + } + let mut source = Composite::with_size(&channels, SIZE, SIZE); + for y in 0..SIZE { + for x in 0..SIZE { + for (index, channel) in channels[1..].iter().enumerate() { + let value = ((x * 3 + y * 5 + index as u32 * 17) % 61) as f32 / 60.0; + source.channels.get_mut(channel).unwrap().set(x, y, &[to_u16(value)]); + } + let color = [x as f32 / SIZE as f32, y as f32 / SIZE as f32, 0.5]; + source.channels.get_mut(&Channel::BaseColor).unwrap().set(x, y, &color.map(to_u16)); + } + } + let settings = BrushSettings { alpha: BrushAlpha::Round, backface_culling: false, ..Default::default() }; + let stamps: Vec = (0..14) + .map(|i| UvStamp { + center: texturecraft_geom::glam::Vec2::new(0.15 + i as f32 * 0.05, 0.35 + i as f32 * 0.04), + radius: 0.1, + angle: 0.0, + flow: 0.9, + hardness: 0.6, + seed: 0, + source: None, + }) + .collect(); + gpu.renderer.set_texture_sets(&gpu.device, &gpu.queue, &[(size, 0)], 1); + let (baked, images) = (BakedMaps::default(), ImageStore::default()); + let read = |gpu: &Headless, kind: DisplayKind| { + let texture = gpu.renderer.display_textures()[0][kind as usize]; + Readback::blocking_level(&gpu.device, &gpu.queue, texture, 0).unwrap().2 + }; + let values = + BTreeMap::from([(Channel::BaseColor, [0.9, 0.1, 0.1]), (Channel::Height, [0.0; 3]), (Channel::Roughness, [0.0; 3]), (Channel::Metallic, [1.0; 3])]); + let paint: BTreeMap = channels.iter().filter_map(|&channel| Some((channel, pixels.layer(layer_id, channel)?.clone()))).collect(); + for (mode, own) in + [(PickupMode::Clone { offset: OFFSET }, false), (PickupMode::Smudge { strength: 0.8 }, false), (PickupMode::Smudge { strength: 0.8 }, true)] + { + let pickup = + if own { Pickup::from_paint(mode, paint.clone(), gbuf.clone(), channels) } else { Pickup::new(mode, source.clone(), gbuf.clone(), channels) }; + let input = crate::gpu_brush::BrushInput { + mesh: mesh.clone(), + bvh: Arc::new(texturecraft_geom::Bvh::new(&mesh)), + uv: gbuf.clone(), + material: 0, + depth: None, + settings: settings.clone(), + alpha_image: None, + stencil: None, + limit: None, + clone: pickup.clone_source(), + smudge: pickup.smudge_source(), + }; + let mut stroke = gpu.renderer.start_gpu_brush(&gpu.device, &gpu.queue, input).unwrap(); + let tiles = stroke.append_uv(&stamps).unwrap(); + let (alpha, carried) = stroke.read_carried(&tiles).unwrap(); + let carried_alpha = stroke.read_channel_alphas(&tiles).unwrap(); + assert_eq!(carried_alpha.is_empty(), !own, "{mode:?}: only the own paint keeps an alpha per channel"); + let covered: Vec<(u32, u32)> = (0..SIZE).flat_map(|y| (0..SIZE).map(move |x| (x, y))).filter(|&(x, y)| alpha.get(x, y)[0] != 0).collect(); + let edge = own || covered.iter().any(|&(_, y)| i64::from(y) + OFFSET[1] >= i64::from(SIZE) - 3); + assert!(covered.len() > 200 && edge, "{mode:?}: the stroke covers {} texels, up to the clone's edge: {edge}", covered.len()); + + let preview = StrokePreview { + target: PaintTarget::Layer(layer_id), + alpha, + opacity: 0.85, + erase: false, + values: values.clone(), + mask_gray: MaskGray::Value(1.0), + stencil: None, + carried, + carried_alpha, + carried_mask: None, + }; + let inputs = Inputs { + project: &project, + ts: 0, + mesh: &mesh, + gbuf: &gbuf, + pixels: &pixels, + baked: &baked, + block_scales: project.texture_sets[0].block_scales(), + preview: Some(&preview), + images: &images, + bounds: mesh.bounds(), + }; + let mut cpu = Composite::new(&channels, SIZE); + composite_tiles(&inputs, &mut cpu, &[(0, 0)]); + + let live = LiveBrush { + target: LiveBrushTarget::Layer { layer: layer_id, values: values.clone() }, + opacity: preview.opacity, + erase: false, + alpha: stroke.view(), + stencil: None, + carried: stroke.carried(), + }; + let mut program = CompositeProgram::try_compile_with_brush(&project, &pixels, 0, None, Some(live)).unwrap(); + program.set_surface_inputs(&mesh, &gbuf, None).unwrap(); + program.set_tile_images(&images); + gpu.renderer.composite_on_gpu(&gpu.device, &gpu.queue, 0, &program).unwrap(); + for kind in [DisplayKind::BaseColor, DisplayKind::Orm, DisplayKind::Height] { + let (actual, expected) = (read(&gpu, kind), tile_bytes(&cpu, &baked, texturecraft_core::AoMixing::Multiply, kind, 0, 0)); + assert_eq!(actual.len(), expected.len()); + if kind == DisplayKind::Height { + for (actual, expected) in actual.as_chunks::<2>().0.iter().zip(expected.as_chunks::<2>().0) { + let actual = half::f16::from_le_bytes(*actual).to_f32(); + let expected = half::f16::from_le_bytes(*expected).to_f32(); + assert!((actual - expected).abs() <= 0.001, "{mode:?}: GPU height {actual}, CPU {expected}"); + } + } else { + let worst = actual.iter().zip(&expected).map(|(a, b)| a.abs_diff(*b)).max(); + assert!(worst <= Some(1), "{mode:?} {kind:?}: GPU differs from the CPU by {worst:?}"); + } + } + } + } + /// A live mask stroke painting an image's gray against the CPU's preview of it, over the /// whole set and in a partial update. #[test] @@ -295,7 +453,14 @@ mod tests { composite_tiles(&inputs, &mut cpu, &[(0, 0)]); let target = LiveBrushTarget::Mask { effect: mask_id, value: 0.0, image: Some(name) }; - let live = LiveBrush { target, opacity: preview.opacity, erase: false, alpha: alpha.create_view(&Default::default()), stencil: None }; + let live = LiveBrush { + target, + opacity: preview.opacity, + erase: false, + alpha: alpha.create_view(&Default::default()), + stencil: None, + carried: Default::default(), + }; let mut program = CompositeProgram::try_compile_with_brush(&project, &pixels, 0, None, Some(live)).unwrap(); program.set_surface_inputs(&mesh, &gbuf, None).unwrap(); program.set_tile_images(&images); diff --git a/crates/render/src/gpu_composite_oracle.rs b/crates/render/src/gpu_composite_oracle.rs index 8752970e0..b15c3c58d 100644 --- a/crates/render/src/gpu_composite_oracle.rs +++ b/crates/render/src/gpu_composite_oracle.rs @@ -107,7 +107,7 @@ pub(crate) fn assert_matches_cpu(gpu: &mut Headless, case: &OracleCase, toleranc } if let Some(owner) = case.mask_owner { - let extent = crate::mask_view_extent((width, height)); + let extent = crate::aux_extent((width, height), 0); let expected = mask_image_sized(&inputs, owner, extent).unwrap_or_else(|| panic!("{label}: no CPU mask")); let mut mask = CompositeProgram::try_compile_mask_preview(case.project, case.pixels, case.ts, owner, None, None) .unwrap_or_else(|reason| panic!("{label}: {reason}")); diff --git a/crates/render/src/gpu_composite_packages.rs b/crates/render/src/gpu_composite_packages.rs index 7b4033808..191c200d2 100644 --- a/crates/render/src/gpu_composite_packages.rs +++ b/crates/render/src/gpu_composite_packages.rs @@ -50,7 +50,14 @@ const PACKAGE_SLOTS: usize = 48; /// `whole_rect`), after the package vec4s. pub(super) const WHOLE_SET: usize = PACKAGE_SLOTS + 8 * 4; /// Words of the band uniform. -pub(super) const UNIFORM_WORDS: usize = MASK_VIEW + 4; +pub(super) const UNIFORM_WORDS: usize = INPUTS + 4; +/// Tiling (`inputs` in composite.wgsl, `BandedInputs`): the first set row of the UV surface and +/// coverage inputs, the first bake row, the bake rows per block (0: the whole bake) and the +/// bake's full height. +pub(super) const INPUTS: usize = THUMB + 4; +/// A layer thumbnail's output (`thumb` in composite.wgsl, `CompositeProgram::set_thumbnail`): +/// the channel's destination slot and its display encoding. +pub(super) const THUMB: usize = MASK_VIEW + 4; /// The lit Base Color's mask views (`mask_view` in composite.wgsl, `FilterPlan::add_lit_mask_views`). pub(super) const MASK_VIEW: usize = WHOLE_COMPACT + 4; /// The whole-set pre-pass's compact slots (`whole_compact` in composite.wgsl): the first stage @@ -224,6 +231,7 @@ pub(super) fn write_band_uniform(program: &CompositeProgram, values: &mut [u32; for (target, slot) in values[PACKAGE_SLOTS..].as_chunks_mut::<4>().0.iter_mut().zip(slots) { *target = slot; } + values[THUMB..THUMB + 3].copy_from_slice(&program.thumb[1..4]); } #[path = "composite_package/shader_flags.rs"] diff --git a/crates/render/src/gpu_composite_projection.rs b/crates/render/src/gpu_composite_projection.rs index 713cbe975..19764c17f 100644 --- a/crates/render/src/gpu_composite_projection.rs +++ b/crates/render/src/gpu_composite_projection.rs @@ -34,9 +34,9 @@ //! (`ImageRes::mip_chain`, or `linear_mip_chain` for an sRGB colour read); the atlas uploads //! the levels and `append_rgba` sets flag bit 9 and appends the level origins. //! - Depth culling: `MaterialImages::set_surface(mesh)` runs in `set_surface_inputs` before -//! the atlas is built; build the grids there with `ProjectorDepth::build`/`build_copies` and -//! `grid()` (compose), return them from `raw_planes()` as exact-f32 `RawPlane`s, and read -//! their origins with `TileImageAtlas::append_raw`. +//! the atlas is built; it sets the grids up there with `GridSetup` / `copy_setups` +//! (compose), returns them from `raw_planes()` as `RawPlane`s the atlas rasterizes on the GPU +//! (`GpuProjectorDepth`), and reads their origins with `TileImageAtlas::append_raw`. //! - P1 owns `gpu_tile_pattern.rs`'s atlas (`TileImageAtlas`, `AtlasMips`, `RawPlane`) from P0b on. //! - Band-wide values go in [`band_uniform`] (`params.packages[0]` in WGSL). //! - Keep [`uses_shader`] true for every program that needs the full WGSL file. @@ -1241,7 +1241,7 @@ mod tests { } /// Depth culling, the default of new planar and warp fills, hides surfaces behind the one - /// nearest the projector through the CPU's own grid, read from the atlas's float planes: + /// nearest the projector through the CPU's grid rasterized on the GPU, read from the atlas's float planes: /// planar axes, hard and soft, turned, placed frames, warps and symmetry copies' own grids #[test] fn depth_culling_matches_the_cpu() { diff --git a/crates/render/src/gpu_composite_udim.rs b/crates/render/src/gpu_composite_udim.rs index bec43b537..789372f48 100644 --- a/crates/render/src/gpu_composite_udim.rs +++ b/crates/render/src/gpu_composite_udim.rs @@ -974,7 +974,14 @@ mod tests { let tiles: Vec<(u32, u32)> = (0..SIDE / TILE).flat_map(|ty| (0..SIDE / TILE).map(move |tx| (tx, ty))).collect(); let mut cpu = Composite { block_scales: set.block_scales(), ..Composite::new(&channels, SIDE) }; composite_tiles(&inputs, &mut cpu, &tiles); - let live = LiveBrush { target: live_target, opacity: 0.85, erase: false, alpha: alpha.create_view(&Default::default()), stencil: None }; + let live = LiveBrush { + target: live_target, + opacity: 0.85, + erase: false, + alpha: alpha.create_view(&Default::default()), + stencil: None, + carried: Default::default(), + }; gpu.renderer.set_texture_sets(&gpu.device, &gpu.queue, &[(size, 0)], 1); let mut program = CompositeProgram::try_compile_with_brush(project, pixels, 0, None, Some(live)).unwrap(); diff --git a/crates/render/src/gpu_depth_grid.rs b/crates/render/src/gpu_depth_grid.rs index f810d0966..6860e1172 100644 --- a/crates/render/src/gpu_depth_grid.rs +++ b/crates/render/src/gpu_depth_grid.rs @@ -1,11 +1,12 @@ -//! Projector depth grids for the GPU compositor's depth culling (P1): the CPU evaluator's own -//! grids (`texturecraft_compose::projector_depth`), uploaded as exact-f32 planes of the image -//! atlas so the shader culls with the same numbers. +//! Projector depth grids for the GPU compositor's depth culling (P1): the CPU evaluator's grids +//! (`texturecraft_compose::projector_depth`) from the same setup, rasterized on the GPU into +//! exact-f32 planes of the image atlas so the shader culls with the same numbers. The GPU +//! rasterizes every cell, so a mesh of many large triangles keeps the full grid. use std::sync::{Arc, Mutex, Weak}; use texturecraft_compose::pattern::mesh_frame; -use texturecraft_compose::projector_depth::ProjectorDepth; +use texturecraft_compose::projector_depth::{GRID_SIDE, GridSetup, ProjectorDepth}; use texturecraft_compose::projector_view::ProjectorView; use texturecraft_core::{FillSymmetry, Projection}; use texturecraft_geom::Mesh; @@ -31,9 +32,12 @@ type CachedViews = Vec<(ViewKey, Option)>; /// The last mesh's grids, so a recompiled program keeps its atlas planes static CACHE: Mutex<(Weak, CachedViews)> = Mutex::new((Weak::new(), Vec::new())); +#[path = "gpu_depth_grid/gpu_raster.rs"] +mod gpu_raster; #[path = "gpu_depth_grid/depth_grid.rs"] mod grid; +pub(crate) use gpu_raster::{GpuProjectorDepth, GridJob}; pub(crate) use grid::DepthGrid; /// The directory entry of a copy without a grid: it culls nothing. @@ -92,9 +96,9 @@ pub(crate) fn depth_grids(mesh: &Arc, requests: &[(Projection, Option Option { let Some((symmetry, center, radius)) = copies else { - return ProjectorDepth::build(view, mesh).map(|depth| Arc::from([Some(DepthGrid::of(&depth))])); + return GridSetup::new(view, mesh, None, GRID_SIDE).map(|setup| Arc::from([Some(DepthGrid::of(&setup, mesh))])); }; - let maps = ProjectorDepth::build_copies(view, mesh, &symmetry, center, radius); - maps.iter().any(Option::is_some).then(|| maps.iter().map(|map| map.as_ref().map(DepthGrid::of)).collect()) + let setups = ProjectorDepth::copy_setups(view, mesh, &symmetry, center, radius); + setups.iter().any(Option::is_some).then(|| setups.iter().map(|setup| setup.as_ref().map(|setup| DepthGrid::of(setup, mesh))).collect()) } diff --git a/crates/render/src/gpu_depth_grid/depth_grid.rs b/crates/render/src/gpu_depth_grid/depth_grid.rs index 3519b4bb7..599fcc451 100644 --- a/crates/render/src/gpu_depth_grid/depth_grid.rs +++ b/crates/render/src/gpu_depth_grid/depth_grid.rs @@ -1,4 +1,7 @@ -use super::{Arc, ENTRY_WORDS, ProjectorDepth, RawPlane, Vec2}; +use texturecraft_compose::projector_depth::{BIAS, FADE, GridSetup, MAX_SLOPE_BIAS}; +use texturecraft_geom::Mesh; + +use super::{Arc, ENTRY_WORDS, GridJob, RawPlane, Vec2}; /// One projector depth grid as the shader reads it: its plane (per cell, row by row from the /// lower corner: the nearest surface's nearness and its slope across and up) and the numbers @@ -16,19 +19,18 @@ pub(crate) struct DepthGrid { } impl DepthGrid { - pub(super) fn of(depth: &ProjectorDepth) -> Self { - let grid = depth.grid(); - let side = grid.grid_side as u32; - let texels: Vec = grid.front.iter().flatten().copied().collect(); + /// The grid of `setup` over `mesh`, its plane rasterized on the GPU when the atlas takes it in + pub(super) fn of(setup: &GridSetup, mesh: &Mesh) -> Self { + let side = setup.grid_side as u32; Self { - plane: RawPlane { size: [side * 3, side], texels: Arc::new(texels) }, - origin: grid.origin, - cell: grid.cell, + plane: RawPlane { size: [side * 3, side], texels: Arc::new(Vec::new()), raster: Some(Arc::new(GridJob::new(setup, mesh))) }, + origin: setup.origin, + cell: setup.cell, side, - unit: grid.nearness_unit, - bias: grid.bias, - max_slope_bias: grid.max_slope_bias, - fade: grid.fade, + unit: setup.nearness_unit, + bias: BIAS, + max_slope_bias: MAX_SLOPE_BIAS, + fade: FADE, } } diff --git a/crates/render/src/gpu_depth_grid/gpu_raster.rs b/crates/render/src/gpu_depth_grid/gpu_raster.rs new file mode 100644 index 000000000..c2b4705fd --- /dev/null +++ b/crates/render/src/gpu_depth_grid/gpu_raster.rs @@ -0,0 +1,280 @@ +//! The projector depth grid rasterized on the GPU (shaders/projector_depth.wgsl), from the CPU +//! raster's own setup ([`GridSetup`]) and to its rules, on every cell of the grid: no coarser grid +//! for a mesh whose triangles cover many cells. + +use texturecraft_compose::projector_depth::{EDGE_TOLERANCE, GridSetup, MAX_SLOPE, MIN_SCREEN_AREA}; +use texturecraft_geom::Mesh; +use texturecraft_geom::glam::Vec2; +use wgpu::util::DeviceExt; + +/// Invocations per workgroup (`@workgroup_size` in projector_depth.wgsl) +const WORKGROUP: u32 = 64; + +/// Invocations per dispatch row: WebGPU allows 65535 workgroups along one dimension +const ROW_STRIDE: u32 = 65_535 * WORKGROUP; + +/// What one grid rasterizes: the mesh's corners in the view and the triangles the view sees +#[derive(Debug)] +pub(crate) struct GridJob { + corners: Vec<[f32; 4]>, + triangles: Vec<[u32; 4]>, + origin: Vec2, + cell: Vec2, + pub(crate) side: u32, +} + +impl GridJob { + pub(crate) fn new(setup: &GridSetup, mesh: &Mesh) -> Self { + let corners = setup.projected.iter().map(|corner| corner.map_or([0.0; 4], |corner| corner.extend(1.0).to_array())).collect(); + let seen = |index: u32| setup.projected.get(index as usize).is_some_and(Option::is_some); + let triangles = + mesh.indices.as_chunks::<3>().0.iter().filter(|indices| indices.iter().all(|&index| seen(index))).map(|&[a, b, c]| [a, b, c, 0]).collect(); + Self { corners, triangles, origin: setup.origin, cell: setup.cell, side: setup.grid_side as u32 } + } + + /// Words per output row: three per cell, padded to the copy alignment + fn row_words(&self) -> u32 { + (self.side * 3).next_multiple_of(wgpu::COPY_BYTES_PER_ROW_ALIGNMENT / 4) + } +} + +/// The compiled passes of projector_depth.wgsl +pub(crate) struct GpuProjectorDepth { + layout: wgpu::BindGroupLayout, + clear: wgpu::ComputePipeline, + nearness: wgpu::ComputePipeline, + nearest: wgpu::ComputePipeline, + write: wgpu::ComputePipeline, +} + +impl GpuProjectorDepth { + /// The passes, or the device's error compiling them + pub(crate) fn new(device: &wgpu::Device) -> Result { + crate::gpu_trace::scoped(device, "GPU projector depth pipelines", || Self::compile(device)) + } + + fn compile(device: &wgpu::Device) -> Self { + let storage = |binding: u32, read_only: bool| wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Storage { read_only }, has_dynamic_offset: false, min_binding_size: None }, + count: None, + }; + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("tc_projector_depth"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None }, + count: None, + }, + storage(1, true), + storage(2, true), + storage(3, false), + storage(4, false), + storage(5, false), + ], + }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("tc_projector_depth"), + bind_group_layouts: &[Some(&layout)], + immediate_size: 0, + }); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("tc_projector_depth"), + source: wgpu::ShaderSource::Wgsl(include_str!("../shaders/projector_depth.wgsl").into()), + }); + let pipeline = |entry: &str| { + device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("tc_projector_depth"), + layout: Some(&pipeline_layout), + module: &module, + entry_point: Some(entry), + compilation_options: Default::default(), + cache: None, + }) + }; + Self { clear: pipeline("clear"), nearness: pipeline("nearest_nearness"), nearest: pipeline("nearest_triangle"), write: pipeline("write_cells"), layout } + } + + /// Rasterize `job` and copy its plane (per cell its nearness and slope across and up, row by + /// row) into `texture` at `origin` (x, y, layer). + pub(crate) fn raster_into( + &self, + (device, queue): (&wgpu::Device, &wgpu::Queue), + job: &GridJob, + texture: &wgpu::Texture, + origin: [u32; 3], + ) -> Result<(), String> { + // A limit is a refusal (the CPU composites the set), not a device error + let limits = device.limits(); + let binding = limits.max_storage_buffer_binding_size.min(limits.max_buffer_size); + let largest = [job.corners.len() * 16, job.triangles.len() * 16, job.row_words() as usize * job.side as usize * 4].into_iter().max().unwrap_or(0); + if largest as u64 > binding { + return Err("The mesh's projector depth grid exceeds this GPU's buffer limit.".into()); + } + + crate::gpu_trace::scoped(device, "GPU projector depth", || { + let (mut encoder, front) = self.encode(device, job); + encoder.copy_buffer_to_texture( + wgpu::TexelCopyBufferInfo { + buffer: &front, + layout: wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(job.row_words() * 4), rows_per_image: None }, + }, + wgpu::TexelCopyTextureInfo { origin: wgpu::Origin3d { x: origin[0], y: origin[1], z: origin[2] }, ..texture.as_image_copy() }, + wgpu::Extent3d { width: job.side * 3, height: job.side, depth_or_array_layers: 1 }, + ); + queue.submit([encoder.finish()]); + }) + } + + /// The passes of `job` into a new encoder, and the buffer they write the plane to + fn encode(&self, device: &wgpu::Device, job: &GridJob) -> (wgpu::CommandEncoder, wgpu::Buffer) { + let cells = u64::from(job.side) * u64::from(job.side); + let params: [u32; 12] = [ + job.origin.x.to_bits(), + job.origin.y.to_bits(), + job.cell.x.to_bits(), + job.cell.y.to_bits(), + job.side, + job.triangles.len() as u32, + ROW_STRIDE, + job.row_words(), + MAX_SLOPE.to_bits(), + MIN_SCREEN_AREA.to_bits(), + EDGE_TOLERANCE.to_bits(), + 0, + ]; + let init = |label: &str, contents: &[u8]| { + // A binding needs at least one element + let contents = if contents.is_empty() { &[0; 16][..] } else { contents }; + device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some(label), contents, usage: wgpu::BufferUsages::STORAGE }) + }; + let scratch = |label: &str, size: u64| { + device.create_buffer(&wgpu::BufferDescriptor { + label: Some(label), + size: size.max(4), + usage: wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC, + mapped_at_creation: false, + }) + }; + let uniform = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("tc_projector_depth_params"), + contents: bytemuck::cast_slice(¶ms), + usage: wgpu::BufferUsages::UNIFORM, + }); + let corners = init("tc_projector_depth_corners", bytemuck::cast_slice(&job.corners)); + let triangles = init("tc_projector_depth_triangles", bytemuck::cast_slice(&job.triangles)); + let nearness = scratch("tc_projector_depth_nearness", cells * 4); + let nearest = scratch("tc_projector_depth_nearest", cells * 4); + let front = scratch("tc_projector_depth_front", u64::from(job.row_words()) * u64::from(job.side) * 4); + let bind = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("tc_projector_depth"), + layout: &self.layout, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 1, resource: corners.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 2, resource: triangles.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 3, resource: nearness.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 4, resource: nearest.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 5, resource: front.as_entire_binding() }, + ], + }); + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_projector_depth") }); + { + let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("tc_projector_depth"), timestamp_writes: None }); + pass.set_bind_group(0, &bind, &[]); + let mut dispatch = |pipeline: &wgpu::ComputePipeline, invocations: u64| { + let groups = invocations.div_ceil(u64::from(WORKGROUP)).max(1); + let row = u64::from(ROW_STRIDE / WORKGROUP); + pass.set_pipeline(pipeline); + pass.dispatch_workgroups(groups.min(row) as u32, groups.div_ceil(row) as u32, 1); + }; + dispatch(&self.clear, cells); + dispatch(&self.nearness, job.triangles.len() as u64); + dispatch(&self.nearest, job.triangles.len() as u64); + dispatch(&self.write, cells); + } + (encoder, front) + } + + /// The plane of `job` read back, row by row without padding (tests compare it with the CPU grid) + #[cfg(all(test, not(target_arch = "wasm32")))] + pub(crate) fn read(&self, (device, queue): (&wgpu::Device, &wgpu::Queue), job: &GridJob) -> Result, String> { + let (mut encoder, front) = self.encode(device, job); + let staging = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("tc_projector_depth_staging"), + size: front.size(), + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + encoder.copy_buffer_to_buffer(&front, 0, &staging, 0, front.size()); + queue.submit([encoder.finish()]); + let slice = staging.slice(..); + slice.map_async(wgpu::MapMode::Read, |_| {}); + device.poll(wgpu::PollType::Wait { submission_index: None, timeout: None }).map_err(|error| error.to_string())?; + let words: Vec = bytemuck::cast_slice(&slice.get_mapped_range().map_err(|error| error.to_string())?).to_vec(); + let (row, width) = (job.row_words() as usize, job.side as usize * 3); + Ok(words.chunks(row).flat_map(|line| line[..width].iter().copied()).collect()) + } +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + use std::sync::Arc; + + use texturecraft_compose::projector_depth::{GRID_SIDE, ProjectorDepth}; + use texturecraft_compose::projector_view::ProjectorView; + use texturecraft_core::{Projection, Projector, UvTransform}; + use texturecraft_geom::glam::Vec3; + + use super::*; + use crate::headless::Headless; + + /// `count` tilted squares stacked along +Z, each covering most of the view + fn stacked_squares(count: usize) -> Mesh { + let mut mesh = Mesh::default(); + for index in 0..count { + let (z, left) = (index as f32 * 0.003, -1.0 + index as f32 * 0.002); + let first = mesh.positions.len() as u32; + mesh.positions.extend([ + Vec3::new(left, -1.0, z + 0.1 * left), + Vec3::new(1.0, -1.0, z + 0.1), + Vec3::new(1.0, 1.0, z + 0.1 + 0.05), + Vec3::new(left, 1.0, z + 0.1 * left + 0.05), + ]); + mesh.indices.extend([first, first + 1, first + 2, first, first + 2, first + 3]); + } + mesh + } + + /// The GPU and the CPU raster keep the full grid for a mesh of many large overlapping + /// triangles, and each GPU cell holds what the CPU raster finds + #[test] + fn the_gpu_grid_keeps_full_resolution_and_matches_the_cpu_raster() { + let Some(gpu) = Headless::for_required_tests() else { return }; + let mesh = Arc::new(stacked_squares(300)); + let projection = + Projection::Planar { scale: 1.0, axis: 2, offset: [0.0; 3], uv: UvTransform::default(), projector: Projector::depth_culled(), placed: None }; + let view = ProjectorView::of(&projection, mesh.bounds()).unwrap(); + + let grids = super::super::depth_grids(&mesh, &[(projection, None)]); + let grid = grids[0].as_ref().unwrap()[0].clone().unwrap(); + assert_eq!(grid.side as usize, GRID_SIDE, "the GPU route keeps the full grid"); + + let passes = GpuProjectorDepth::new(&gpu.device).unwrap(); + let actual = passes.read((&gpu.device, &gpu.queue), grid.plane.raster.as_deref().unwrap()).unwrap(); + let cpu = ProjectorDepth::build(view, &mesh).unwrap(); + let expected = cpu.grid(); + assert_eq!(expected.grid_side, GRID_SIDE, "the CPU raster keeps the full grid"); + assert_eq!((grid.origin, grid.cell, grid.unit), (expected.origin, expected.cell, expected.nearness_unit)); + assert_eq!(actual.len(), expected.front.len() * 3); + let close = |gpu: f32, cpu: f32| if cpu.is_finite() { (gpu - cpu).abs() <= 1e-4 * (1.0 + cpu.abs()) } else { gpu == cpu }; + let differing = + actual.as_chunks::<3>().0.iter().zip(expected.front).filter(|(gpu, cpu)| !gpu.iter().zip(cpu.iter()).all(|(&gpu, &cpu)| close(gpu, cpu))).count(); + let covered = expected.front.iter().filter(|cell| cell[0].is_finite()).count(); + assert!(covered > expected.front.len() / 2, "the squares cover the view"); + assert!(differing * 200 <= covered, "{differing} of {covered} cells differ"); + } +} diff --git a/crates/render/src/gpu_eye_depth.rs b/crates/render/src/gpu_eye_depth.rs new file mode 100644 index 000000000..03ff8a919 --- /dev/null +++ b/crates/render/src/gpu_eye_depth.rs @@ -0,0 +1,243 @@ +//! The paint camera's eye-distance buffer ([`EyeDepth`]) rasterized on the GPU, from the same +//! screen points and depth keys as the software raster ([`DepthRaster`]) and to the same rules, +//! at any size the device's buffers allow. + +use texturecraft_geom::{Mesh, OrbitCamera}; +use texturecraft_paint::visibility::MIN_SCREEN_AREA; +use texturecraft_paint::{DepthRaster, EyeDepth}; +use wgpu::util::DeviceExt; + +/// Invocations per workgroup (`@workgroup_size` in eye_depth.wgsl) +const WORKGROUP: u32 = 64; + +/// Invocations per dispatch row: WebGPU allows 65535 workgroups along one dimension +const ROW_STRIDE: u32 = 65_535 * WORKGROUP; + +/// The compiled passes of eye_depth.wgsl +pub struct GpuEyeDepth { + layout: wgpu::BindGroupLayout, + clear: wgpu::ComputePipeline, + depth: wgpu::ComputePipeline, + nearest: wgpu::ComputePipeline, + distance: wgpu::ComputePipeline, +} + +impl GpuEyeDepth { + /// The passes, or the device's error compiling them + pub fn new(device: &wgpu::Device) -> Result { + crate::gpu_trace::scoped(device, "GPU paint visibility pipelines", || Self::compile(device)) + } + + fn compile(device: &wgpu::Device) -> Self { + let storage = |binding: u32, read_only: bool| wgpu::BindGroupLayoutEntry { + binding, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Storage { read_only }, has_dynamic_offset: false, min_binding_size: None }, + count: None, + }; + let layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("tc_eye_depth"), + entries: &[ + wgpu::BindGroupLayoutEntry { + binding: 0, + visibility: wgpu::ShaderStages::COMPUTE, + ty: wgpu::BindingType::Buffer { ty: wgpu::BufferBindingType::Uniform, has_dynamic_offset: false, min_binding_size: None }, + count: None, + }, + storage(1, true), + storage(2, true), + storage(3, false), + storage(4, false), + storage(5, false), + ], + }); + let pipeline_layout = device.create_pipeline_layout(&wgpu::PipelineLayoutDescriptor { + label: Some("tc_eye_depth"), + bind_group_layouts: &[Some(&layout)], + immediate_size: 0, + }); + let module = device.create_shader_module(wgpu::ShaderModuleDescriptor { + label: Some("tc_eye_depth"), + source: wgpu::ShaderSource::Wgsl(include_str!("shaders/eye_depth.wgsl").into()), + }); + let pipeline = |entry: &str| { + device.create_compute_pipeline(&wgpu::ComputePipelineDescriptor { + label: Some("tc_eye_depth"), + layout: Some(&pipeline_layout), + module: &module, + entry_point: Some(entry), + compilation_options: Default::default(), + cache: None, + }) + }; + Self { clear: pipeline("clear"), depth: pipeline("nearest_depth"), nearest: pipeline("nearest_triangle"), distance: pipeline("eye_distance"), layout } + } + + /// [`EyeDepth::rasterize`] of `mesh` seen by `camera` at `width × height` on the GPU: only the + /// triangles `include` accepts, and the nearest triangle per pixel when `record_triangles`. + pub fn render( + &self, + (device, queue): (&wgpu::Device, &wgpu::Queue), + mesh: &Mesh, + camera: &OrbitCamera, + (width, height): (u32, u32), + record_triangles: bool, + include: impl Fn(usize) -> bool, + ) -> Result { + let raster = DepthRaster::new(mesh, camera, width, height, record_triangles); + let pixels = u64::from(raster.width) * u64::from(raster.height); + let bytes = pixels.checked_mul(4).filter(|&bytes| bytes <= device.limits().max_storage_buffer_binding_size && pixels <= u64::from(u32::MAX)); + let Some(bytes) = bytes else { + return Err(format!("A {}×{} depth buffer exceeds this GPU's buffer limit.", raster.width, raster.height)); + }; + + let vertices: Vec<[f32; 4]> = + raster.screen.iter().zip(&raster.vertex_depth).map(|(point, &key)| point.map_or([0.0; 4], |point| [point.x, point.y, key, 1.0])).collect(); + let triangles: Vec<[u32; 4]> = (0..mesh.triangle_count()) + .filter(|&triangle| include(triangle)) + .filter_map(|triangle| { + let [a, b, c] = mesh.tri(triangle)?; + Some([a as u32, b as u32, c as u32, triangle as u32]) + }) + .collect(); + let params: [u32; 12] = [ + raster.width, + raster.height, + triangles.len() as u32, + ROW_STRIDE, + raster.depth_range.start().to_bits(), + raster.depth_range.end().to_bits(), + raster.edge_tolerance.to_bits(), + MIN_SCREEN_AREA.to_bits(), + raster.scale.x.to_bits(), + raster.scale.y.to_bits(), + u32::from(raster.ortho), + 0, + ]; + + // Allocation failures (out of memory) come back as errors, not as wgpu's default panic + let staging = crate::gpu_trace::scoped(device, "GPU paint visibility", || { + let init = |label: &str, contents: &[u8]| { + // A binding needs at least one element + let contents = if contents.is_empty() { &[0; 16][..] } else { contents }; + device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some(label), contents, usage: wgpu::BufferUsages::STORAGE }) + }; + let scratch = |label: &str, size: u64, usage: wgpu::BufferUsages| { + device.create_buffer(&wgpu::BufferDescriptor { label: Some(label), size, usage, mapped_at_creation: false }) + }; + let readable = wgpu::BufferUsages::STORAGE | wgpu::BufferUsages::COPY_SRC; + // Only the recorded pass writes triangle numbers; otherwise the binding needs one element + let nearest_bytes = if record_triangles { bytes } else { 16 }; + let (depth_keys, nearest, distance) = ( + scratch("tc_eye_depth_keys", bytes, readable), + scratch("tc_eye_depth_nearest", nearest_bytes, readable), + scratch("tc_eye_depth_distance", bytes, readable), + ); + let uniform = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { + label: Some("tc_eye_depth_params"), + contents: bytemuck::cast_slice(¶ms), + usage: wgpu::BufferUsages::UNIFORM, + }); + let vertex_buffer = init("tc_eye_depth_vertices", bytemuck::cast_slice(&vertices)); + let triangle_buffer = init("tc_eye_depth_triangles", bytemuck::cast_slice(&triangles)); + let bind = device.create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("tc_eye_depth"), + layout: &self.layout, + entries: &[ + wgpu::BindGroupEntry { binding: 0, resource: uniform.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 1, resource: vertex_buffer.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 2, resource: triangle_buffer.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 3, resource: depth_keys.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 4, resource: nearest.as_entire_binding() }, + wgpu::BindGroupEntry { binding: 5, resource: distance.as_entire_binding() }, + ], + }); + + let read_bytes = if record_triangles { bytes * 2 } else { bytes }; + let staging = device.create_buffer(&wgpu::BufferDescriptor { + label: Some("tc_eye_depth_staging"), + size: read_bytes, + usage: wgpu::BufferUsages::MAP_READ | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + }); + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_eye_depth") }); + { + let mut pass = encoder.begin_compute_pass(&wgpu::ComputePassDescriptor { label: Some("tc_eye_depth"), timestamp_writes: None }); + pass.set_bind_group(0, &bind, &[]); + let mut dispatch = |pipeline: &wgpu::ComputePipeline, invocations: u64| { + let groups = invocations.div_ceil(u64::from(WORKGROUP)).max(1); + let row = u64::from(ROW_STRIDE / WORKGROUP); + pass.set_pipeline(pipeline); + pass.dispatch_workgroups(groups.min(row) as u32, groups.div_ceil(row) as u32, 1); + }; + dispatch(&self.clear, pixels); + dispatch(&self.depth, triangles.len() as u64); + if record_triangles { + dispatch(&self.nearest, triangles.len() as u64); + } + dispatch(&self.distance, pixels); + } + encoder.copy_buffer_to_buffer(&distance, 0, &staging, 0, bytes); + if record_triangles { + encoder.copy_buffer_to_buffer(&nearest, 0, &staging, bytes, bytes); + } + queue.submit([encoder.finish()]); + staging + })?; + + let slice = staging.slice(..); + let (sender, receiver) = std::sync::mpsc::channel(); + slice.map_async(wgpu::MapMode::Read, move |result| drop(sender.send(result))); + device.poll(wgpu::PollType::Wait { submission_index: None, timeout: None }).map_err(|error| error.to_string())?; + receiver.recv().map_err(|error| error.to_string())?.map_err(|error| error.to_string())?; + let data = slice.get_mapped_range().map_err(|error| error.to_string())?; + let words: &[u32] = bytemuck::try_cast_slice(&data[..]).map_err(|error| error.to_string())?; + let (dist, triangle) = words.split_at(pixels as usize); + let dist: Vec = dist.iter().copied().map(f32::from_bits).collect(); + let triangle = triangle.to_vec(); + drop(data); + staging.unmap(); + Ok(raster.finish(dist, triangle)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::headless::Headless; + use texturecraft_geom::glam::Vec3; + use texturecraft_geom::primitives; + + /// The GPU buffer is the software raster's (a few silhouette pixels may round the other way), + /// for depth alone and with triangles, perspective and orthographic, at a size the software + /// raster used to cap + #[test] + fn gpu_eye_depth_matches_the_software_raster() { + let Some(gpu) = Headless::for_required_tests() else { return }; + let eye_depth = GpuEyeDepth::new(&gpu.device).unwrap(); + let mut mesh = primitives::sphere(1.0, 48, 24); + mesh.append(&primitives::cube(0.6)); + for (ortho, size, record) in [(false, (5000, 40), true), (true, (96, 80), false)] { + let mut camera = OrbitCamera { yaw: 0.6, pitch: 0.4, ortho, ..Default::default() }; + camera.frame(Vec3::splat(-1.0), Vec3::splat(1.0)); + let include = |triangle: usize| triangle % 7 != 3; + let cpu = EyeDepth::rasterize(&mesh, &camera, size.0, size.1, record, include); + let actual = eye_depth.render((&gpu.device, &gpu.queue), &mesh, &camera, size, record, include).unwrap(); + assert_eq!((actual.width, actual.height), size, "the GPU keeps the requested size"); + assert_eq!(actual.triangle.len(), cpu.triangle.len()); + let mut differing = 0; + for (index, (gpu_distance, cpu_distance)) in actual.dist.iter().zip(&cpu.dist).enumerate() { + let same_distance = if *cpu_distance == f32::MAX || *gpu_distance == f32::MAX { + gpu_distance == cpu_distance + } else { + (gpu_distance - cpu_distance).abs() <= 1e-4 * cpu_distance.abs() + }; + let same_triangle = cpu.triangle.get(index) == actual.triangle.get(index); + differing += usize::from(!same_distance || !same_triangle); + } + let covered = cpu.dist.iter().filter(|distance| **distance != f32::MAX).count(); + assert!(covered > 0, "the camera sees the mesh"); + assert!(differing * 200 <= covered, "ortho {ortho}: {differing} of {covered} pixels differ"); + } + } +} diff --git a/crates/render/src/gpu_generator_p2/micro_cache.rs b/crates/render/src/gpu_generator_p2/micro_cache.rs index 7ebc76799..3807234a0 100644 --- a/crates/render/src/gpu_generator_p2/micro_cache.rs +++ b/crates/render/src/gpu_generator_p2/micro_cache.rs @@ -6,4 +6,6 @@ use super::micro_maps::MicroMaps; pub(super) struct MicroCache { pub(super) key: MicroKey, pub(super) maps: Arc, + /// Bytes of its map array, counted against the memory budget + pub(super) bytes: u64, } diff --git a/crates/render/src/gpu_generator_p2/micro_gpu.rs b/crates/render/src/gpu_generator_p2/micro_gpu.rs index 37b5b9df7..2c51e72b1 100644 --- a/crates/render/src/gpu_generator_p2/micro_gpu.rs +++ b/crates/render/src/gpu_generator_p2/micro_gpu.rs @@ -20,9 +20,6 @@ use super::{LINE_WORKGROUP, WORKGROUP, block_groups, dispatch, single_blocks, te use crate::gpu_curvature::CurvatureLevels; use crate::gpu_trace::{entry, storage}; -// Bound one map array independently of the per-pass buffers and baked textures -const MAX_MICRO_MAP_BYTES: u64 = 256 << 20; - /// The micro detail passes, and each texture set's last maps pub(crate) struct MicroGpu { pub(super) layout: wgpu::BindGroupLayout, @@ -126,6 +123,11 @@ impl MicroGpu { self.cache.remove(&set); } + /// Bytes of texture set `set`'s cached maps + pub(crate) fn cached_bytes(&self, set: usize) -> u64 { + self.cache.get(&set).map_or(0, |entry| entry.bytes) + } + pub(crate) fn release_unused(&mut self) { self.cache.retain(|_, entry| entry.key.is_live()); } @@ -184,7 +186,8 @@ impl MicroGpu { // Anchor heights change with the stack below them, which the key does not see if captures.is_empty() { - gpu.cache.insert(ts, MicroCache { key, maps: maps.clone() }); + let bytes = extent.into_iter().map(u64::from).product::() * size_of::() as u64; + gpu.cache.insert(ts, MicroCache { key, maps: maps.clone(), bytes }); } Ok(Some(maps)) } @@ -387,11 +390,6 @@ fn map_extent(limits: &wgpu::Limits, width: u32, rows: u32, requests: usize) -> return Err("Micro Details exceed the GPU texture dimensions.".into()); } - let bytes = u64::from(width) * u64::from(height) * u64::from(layers) * size_of::() as u64; - if bytes > MAX_MICRO_MAP_BYTES.min(limits.max_buffer_size) { - return Err("Micro Details exceed the GPU map memory budget.".into()); - } - Ok([width, height, layers]) } @@ -450,3 +448,20 @@ fn capture_layout(program: &CompositeProgram, captures: &[(LayerId, wgpu::Textur None => CaptureLayout { working, block: 1, scales: Vec::new(), columns: 1 }, } } + +#[cfg(test)] +mod tests { + use super::map_extent; + + /// 8K maps for two micro details fit a desktop adapter; only its array layers refuse more + #[test] + fn micro_maps_take_what_the_device_limits_allow() { + let limits = wgpu::Limits { max_texture_dimension_2d: 16384, max_texture_array_layers: 4, ..wgpu::Limits::default() }; + + let two = map_extent(&limits, 8192, 8192, 2); + let three = map_extent(&limits, 8192, 8192, 3); + + assert_eq!(two, Ok([8192, 8193, 4])); + assert!(three.is_err(), "six layers exceed the adapter's four"); + } +} diff --git a/crates/render/src/gpu_generator_p2/mod.rs b/crates/render/src/gpu_generator_p2/mod.rs index bdb9cc371..ad69d35db 100644 --- a/crates/render/src/gpu_generator_p2/mod.rs +++ b/crates/render/src/gpu_generator_p2/mod.rs @@ -63,9 +63,6 @@ const RECORD_WORDS: usize = 5; const SLOT_WORDS: usize = 10; const SLOT_OPERATION: usize = 9; -/// Layers of the micro map texture: two per generator (its curvature term, its occlusion factor) -const MAX_MICRO_LAYERS: u32 = 256; - /// How steeply the micro height tilts the normal it is turned into, per unit of Height Details /// Intensity (compose's `HEIGHT_NORMAL_STRENGTH`) const HEIGHT_NORMAL_STRENGTH: f32 = 5.9; @@ -163,11 +160,8 @@ fn micro_record(generator: &Generator, inputs: &mut ProceduralInputs) -> Option< let plan = &mut inputs.micro; let index = match plan.requests.iter().position(|existing| *existing == request) { Some(index) => index, + // Each request takes two layers of the micro map array, which the device's limit bounds (`map_extent`) None => { - if (plan.requests.len() as u32 + 1) * 2 > MAX_MICRO_LAYERS { - return None; - } - plan.requests.push(request.clone()); plan.requests.len() - 1 } diff --git a/crates/render/src/gpu_generator_p2/tests.rs b/crates/render/src/gpu_generator_p2/tests.rs index 4a7f5b402..f33256c3a 100644 --- a/crates/render/src/gpu_generator_p2/tests.rs +++ b/crates/render/src/gpu_generator_p2/tests.rs @@ -242,7 +242,7 @@ fn micro_map_binding_limits_decline_before_creating_the_layout() { } #[test] -fn micro_map_budget_includes_the_metadata_row() { +fn micro_map_size_includes_the_metadata_row() { let (device, queue) = wgpu::Device::noop(&wgpu::DeviceDescriptor { required_limits: wgpu::Limits::default(), ..Default::default() }); let placeholder = super::empty_maps(&device); let mut project = Project::new("Micro texture budget", "builtin:plane"); @@ -256,7 +256,8 @@ fn micro_map_budget_includes_the_metadata_row() { occlusion: false, }; program.micro.requests = vec![request; 2]; - const BAKE_SIDE: u32 = 4096; + // The default limits' largest side: the metadata row needs one more + const BAKE_SIDE: u32 = 8192; let mut maps = std::array::from_fn(|_| None); maps[2] = Some(Arc::new(vec![0.0])); let mut heights = [0; super::super::SEPARATE_MAPS]; @@ -266,8 +267,8 @@ fn micro_map_budget_includes_the_metadata_row() { let result = super::MicroGpu::maps(&mut gpu, (&device, &queue), (0, true), &program, (&placeholder, &[])); - assert!(matches!(result, Err(error) if error.contains("map memory budget"))); - assert!(gpu.is_none(), "an over-budget map also skips layout creation"); + assert!(matches!(result, Err(error) if error.contains("texture dimensions"))); + assert!(gpu.is_none(), "an oversized map also skips layout creation"); } /// A micro height read from an anchor point matches the CPU: the anchor's height under the @@ -362,6 +363,7 @@ fn a_live_brush_declines_gpu_micro_height_anchor_captures() { erase: false, alpha: alpha.create_view(&Default::default()), stencil: None, + carried: Default::default(), }; let material = super::CompositeProgram::try_compile_with_brush(&project, &pixels, 0, None, Some(brush.clone())); diff --git a/crates/render/src/gpu_generator_p3a.rs b/crates/render/src/gpu_generator_p3a.rs index b21bc7e31..c433f33db 100644 --- a/crates/render/src/gpu_generator_p3a.rs +++ b/crates/render/src/gpu_generator_p3a.rs @@ -392,4 +392,67 @@ mod tests { assert_generator_matches(&mut gpu, &mesh, &baked, (generator, BlendMode::Normal, 1.0), Tolerance::POINT, label); } } + + /// Tiling: a set whose baked maps (World Normal adds a second row block) are taller than + /// the device's texture side, and one whose UV coverage exceeds its storage binding, composite + /// on the GPU in row bands that upload only their rows, as the CPU does: a blurred mask + /// reads across the band edges, and a partial update (from a band not at the set's top) + /// matches the full one (the + /// mask preview is compared in the coverage case: a blurred mask's preview differs today) + #[test] + fn inputs_larger_than_the_device_composite_in_bands() { + use texturecraft_core::Filter; + + use crate::gpu_composite::{BANDED_UPLOADS, CompositeRegion, UPLOAD_WAITS}; + + let tightened = |side: u32, binding: u64| { + Headless::for_tests_with_limits(move |adapter| wgpu::Limits { + max_texture_dimension_2d: side, + max_storage_buffer_binding_size: binding, + ..crate::device_limits(adapter) + }) + }; + let world_normal = |side: u32| { + let stored = (0..side * side).flat_map(|index| [(index % side) as f32 / side as f32, 0.3 + 0.4 * ((index / side) % 7) as f32 / 6.0, 0.8]).collect(); + BakedMaps { resolution: side, maps: BTreeMap::from([(BakedMap::WorldNormal, Arc::new(stored))]) } + }; + let axes = [ + AxisLayer { invert: true, blend: AxisBlend::Multiply, weight: 0.6 }, + AxisLayer { invert: false, blend: AxisBlend::Normal, weight: 1.0 }, + AxisLayer { invert: false, blend: AxisBlend::Max, weight: 0.4 }, + ]; + let generator = Generator { section: Some(neutral_section(axes)), ..Generator::new(GeneratorKind::WorldSpaceNormals) }; + let (pixels, images) = (PixelStore::default(), ImageStore::default()); + + // The bake: 512 rows per block, two blocks, on a device whose texture side is 512 + let Ok(mut gpu) = tightened(512, 1 << 30) else { return }; + let (mut project, owner) = generator_project(generator.clone(), BlendMode::Normal, 1.0); + project.texture_sets[0].resolution = 512; + let blur = Effect::new(project.alloc_id(), EffectKind::Filter(Filter::Blur { radius: 6.0, wrap: false })); + if let Some(mask) = project.layers.get_mut(&owner).and_then(|layer| layer.mask.as_mut()) { + mask.effects.push(blur); + } + let (mesh, baked) = (stretched_sphere(), world_normal(512)); + let mut case = OracleCase::new(&project, &pixels, &baked, &images, &mesh); + case.region = Some(CompositeRegion { min: [0, 200], max: [512, 330] }); + BANDED_UPLOADS.set(0); + assert_matches_cpu(&mut gpu, &case, Tolerance::NEIGHBOURHOOD, "bake taller than the device"); + assert!(BANDED_UPLOADS.get() >= 3, "the bake composited in {} bands", BANDED_UPLOADS.get()); + + // The coverage: 1024 rows of 32 words (128 KiB), on a device binding 40 KiB per storage buffer + let Ok(mut gpu) = tightened(1024, 40 << 10) else { return }; + let (mut project, owner) = generator_project(generator, BlendMode::Normal, 1.0); + project.texture_sets[0].resolution = 1024; + let mesh = Arc::new(primitives::sphere(1.0, 16, 8)); + let baked = BakedMaps::default(); + let mut case = OracleCase::new(&project, &pixels, &baked, &images, &mesh); + case.mask_owner = Some(owner); + BANDED_UPLOADS.set(0); + UPLOAD_WAITS.set(0); + assert_matches_cpu(&mut gpu, &case, Tolerance::POINT, "coverage larger than a binding"); + assert!(BANDED_UPLOADS.get() >= 3, "the coverage composited in {} bands", BANDED_UPLOADS.get()); + // The bands' coverage counts toward the uploads in flight: a mask without paint still + // waits for earlier bands before the next band's inputs exceed what one binding holds + assert!(UPLOAD_WAITS.get() >= 1, "no wait for earlier bands' inputs"); + } } diff --git a/crates/render/src/gpu_image_source.rs b/crates/render/src/gpu_image_source.rs index 3e9470aca..51ef22498 100644 --- a/crates/render/src/gpu_image_source.rs +++ b/crates/render/src/gpu_image_source.rs @@ -14,6 +14,7 @@ use crate::gpu_tile_pattern::{AtlasMips, RawPlane, TileImageAtlas}; #[path = "gpu_depth_grid.rs"] mod depth_grid; use depth_grid::{FillGrids, depth_grids, missing_entry}; +pub(crate) use depth_grid::{GpuProjectorDepth, GridJob}; pub(crate) const IMAGE_SOURCE_OPCODE: u32 = 14; pub(crate) const DECAL_PROJECTION: u32 = 9; diff --git a/crates/render/src/gpu_memory.rs b/crates/render/src/gpu_memory.rs new file mode 100644 index 000000000..5bb632f69 --- /dev/null +++ b/crates/render/src/gpu_memory.rs @@ -0,0 +1,50 @@ +//! How much GPU memory TextureCraft's cached GPU inputs may hold, and how a lack of it is told apart. +//! +//! The operating system's budget applies where wgpu reads it (Vulkan with `VK_EXT_memory_budget`, +//! D3D12): wgpu refuses an allocation past [`OS_BUDGET_PERCENT`] of it with an out-of-memory error, +//! after which the compositor frees its caches and tries once more. Reading that budget's size +//! directly needs `unsafe` access to the backend, which the workspace forbids. In Auto the cached +//! inputs therefore grow until the GPU refuses an allocation (that threshold on Vulkan and D3D12, +//! a real out-of-memory error elsewhere); a megabyte setting additionally evicts the least +//! recently used texture sets' inputs past [`GpuMemoryBudget::bytes`]. + +mod gpu_memory_budget; + +pub use gpu_memory_budget::GpuMemoryBudget; + +/// Percent of the operating system's GPU memory budget at which wgpu starts refusing new +/// allocations, leaving the rest to the system and other apps +pub const OS_BUDGET_PERCENT: u8 = 90; + +/// How an error caused by a lack of GPU memory starts +const OUT_OF_MEMORY: &str = "Not enough GPU memory"; + +/// The thresholds an instance gives wgpu, so allocations past the system's budget fail cleanly +pub fn instance_thresholds() -> wgpu::MemoryBudgetThresholds { + wgpu::MemoryBudgetThresholds { for_resource_creation: Some(OS_BUDGET_PERCENT), for_device_loss: None } +} + +/// The error for a lack of GPU memory while doing `what` +pub(crate) fn out_of_memory_error(what: &str, cause: &str) -> String { + format!("{OUT_OF_MEMORY} for {what}. Close other GPU programs or lower the texture resolution. ({cause})") +} + +/// Whether `error` comes from a lack of GPU memory +pub fn is_out_of_memory(error: &str) -> bool { + error.starts_with(OUT_OF_MEMORY) +} + +/// How an error the GPU device reported (other than a lack of memory) starts +const DEVICE_ERROR: &str = "The GPU reported an error"; + +/// The error the GPU device reported while doing `what` +pub(crate) fn device_error(what: &str, cause: &str) -> String { + format!("{DEVICE_ERROR} in {what}: {cause}") +} + +/// Whether `error` is one the GPU device reported (out of memory included), not a refusal to run +/// work on the GPU. Such work is not redone on the CPU: callers show the error. +pub fn is_device_error(error: &str) -> bool { + // Pipeline compiles wrap the device's error in their own message + is_out_of_memory(error) || error.contains(DEVICE_ERROR) +} diff --git a/crates/render/src/gpu_memory/gpu_memory_budget.rs b/crates/render/src/gpu_memory/gpu_memory_budget.rs new file mode 100644 index 000000000..28c45df4d --- /dev/null +++ b/crates/render/src/gpu_memory/gpu_memory_budget.rs @@ -0,0 +1,19 @@ +/// The GPU memory budget setting: automatic, or a number of megabytes the user chose +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub struct GpuMemoryBudget { + /// The user's budget in bytes; None is automatic + pub chosen_bytes: Option, +} + +impl GpuMemoryBudget { + /// The setting's value: 0 is automatic + pub fn from_megabytes(megabytes: u32) -> Self { + Self { chosen_bytes: (megabytes > 0).then(|| u64::from(megabytes) << 20) } + } + + /// Bytes the cached inputs may hold before the least recently used are evicted: no limit in + /// Auto, where only the GPU's refusal of an allocation evicts them + pub fn bytes(self) -> u64 { + self.chosen_bytes.unwrap_or(u64::MAX) + } +} diff --git a/crates/render/src/gpu_preview.rs b/crates/render/src/gpu_preview.rs new file mode 100644 index 000000000..27fc2761b --- /dev/null +++ b/crates/render/src/gpu_preview.rs @@ -0,0 +1,542 @@ +//! Small material pictures (shelf and orb previews, layer thumbnails, the material overview) +//! composited on the GPU by a renderer of their own, so they never touch the viewport's texture +//! sets. +//! +//! A preview is prepared first ([`PreparedPreview`]: the layer program compiled on the CPU, no +//! renderer needed) and then run on the preview renderer ([`PreviewCompositor::run`]). An +//! asynchronous compositor compiles new pipelines on worker threads and answers "not yet" until +//! they are ready, so a caller sharing the compositor behind a lock holds it only while it +//! composites, never while the CPU compiles the program or the GPU compiles pipelines. + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; + +use texturecraft_compose::{BakedMaps, DisplayKind, ImageStore, PixelStore, ThumbOutput}; +use texturecraft_core::Project; +use texturecraft_geom::{Mesh, UvGBuffer}; + +use crate::gpu_composite::{CompositeProgram, GPU_PIPELINES_PENDING}; +use crate::readback::Readback; +use crate::renderer::Renderer; + +/// What a preview composites: texture set `ts` of `project` on `mesh`, with `gbuf` at the set's +/// size, into maps of the set's size halved `shift` times (the compositor reads every +/// 2^shift-th texel); `padding` is the coverage and radius (set texels) the display maps pad +/// UV islands with +pub struct PreviewInputs<'a> { + pub project: &'a Project, + pub ts: usize, + pub pixels: &'a PixelStore, + pub mesh: &'a Arc, + pub gbuf: &'a Arc, + pub baked: &'a BakedMaps, + pub images: &'a ImageStore, + pub shift: u32, + pub padding: Option<(&'a Arc, u32)>, +} + +/// The display maps' size and each map's bytes +pub type DisplayMaps = ((u32, u32), Vec>); + +/// Why a preview did not composite on the GPU +#[derive(Debug, PartialEq, Eq)] +pub enum PreviewFailure { + /// The GPU compositor cannot take this material (the preview composites on the CPU) + Refused(String), + /// The GPU reported an error (after one retry when it ran out of memory) + Device(String), + /// The caller cancelled the preview before it composited + Cancelled, +} + +/// What a prepared preview reads back +enum Output { + Maps(Vec), + Thumbnail { mask: bool }, +} + +/// A preview's layer program, compiled on the CPU with its surface inputs: what +/// [`PreviewCompositor::run`] composites +pub struct PreparedPreview { + program: CompositeProgram, + ts: usize, + shift: u32, + sets: Vec<((u32, u32), usize)>, + materials: usize, + gbuf: Arc, + output: Output, +} + +/// A finished preview: display maps, or a thumbnail as (width, height, straight RGBA8) +pub enum PreviewResult { + Maps(DisplayMaps), + Thumbnail(u32, u32, Vec), +} + +impl PreparedPreview { + /// The display maps `kinds` of `inputs` + pub fn maps(inputs: &PreviewInputs, kinds: &[DisplayKind]) -> Result { + let mut program = CompositeProgram::try_compile_region(inputs.project, inputs.pixels, inputs.ts, None).map_err(refused)?; + if let Some((coverage, radius)) = inputs.padding { + program.set_coverage(coverage.clone(), radius); + } + Self::with(inputs, program, Output::Maps(kinds.to_vec())) + } + + /// The layer thumbnail `thumb` of `inputs` (whose project is already cut to the layer) + pub fn thumbnail(inputs: &PreviewInputs, thumb: ThumbOutput) -> Result { + let program = match thumb { + ThumbOutput::Mask(layer) => CompositeProgram::try_compile_mask_preview(inputs.project, inputs.pixels, inputs.ts, layer, None, None), + ThumbOutput::Flat(channel) => CompositeProgram::try_compile_thumbnail(inputs.project, inputs.pixels, inputs.ts, channel, true), + ThumbOutput::Composite(channel) => CompositeProgram::try_compile_thumbnail(inputs.project, inputs.pixels, inputs.ts, channel, false), + } + .map_err(refused)?; + Self::with(inputs, program, Output::Thumbnail { mask: matches!(thumb, ThumbOutput::Mask(_)) }) + } + + fn with(inputs: &PreviewInputs, mut program: CompositeProgram, output: Output) -> Result { + let set = inputs.project.texture_set(inputs.ts).map_err(|error| refused(&error.to_string()))?; + if (inputs.gbuf.width, inputs.gbuf.height) != set.size() { + return Err(refused("the preview's surface is not the texture set's size")); + } + + program.set_surface_inputs(inputs.mesh, inputs.gbuf, Some(inputs.baked)).map_err(refused)?; + program.set_tile_images(inputs.images); + Ok(PreparedPreview { + program, + ts: inputs.ts, + shift: inputs.shift, + sets: inputs.project.texture_sets.iter().map(|set| (set.size(), set.material)).collect(), + materials: inputs.project.texture_sets.iter().map(|set| set.material + 1).max().unwrap_or(1), + gbuf: inputs.gbuf.clone(), + output, + }) + } +} + +/// Run `prepared` until its pipelines are ready: `run` composites once (taking the caller's +/// lock only for that) and answers None while the pipelines still compile. Once `cancel` is +/// set, it stops before the next composite. +pub fn run_until_ready( + prepared: &PreparedPreview, + cancel: Option<&AtomicBool>, + mut run: impl FnMut(&PreparedPreview) -> Result, PreviewFailure>, +) -> Result { + loop { + if cancel.is_some_and(|cancel| cancel.load(Ordering::Acquire)) { + return Err(PreviewFailure::Cancelled); + } + + if let Some(result) = run(prepared)? { + return Ok(result); + } + + std::thread::sleep(std::time::Duration::from_millis(2)); + } +} + +/// A renderer for previews, created on first use +#[derive(Default)] +pub struct PreviewCompositor { + renderer: Option, + asynchronous: bool, + /// The user's optional cap on cached layer inputs (Auto: none of its own) + budget: crate::gpu_memory::GpuMemoryBudget, +} + +impl PreviewCompositor { + /// Apply the GPU memory setting to the preview renderer's cached inputs, as the viewport's + pub fn set_memory_budget(&mut self, budget: crate::gpu_memory::GpuMemoryBudget) { + self.budget = budget; + if let Some(renderer) = self.renderer.as_mut() { + renderer.set_memory_budget(budget); + } + } + + /// A compositor whose new pipelines compile on worker threads ([`Self::run`] answers None + /// meanwhile); synchronous on wasm + pub fn asynchronous() -> PreviewCompositor { + PreviewCompositor { renderer: None, asynchronous: !cfg!(target_arch = "wasm32"), budget: Default::default() } + } + + /// The display maps `kinds` of `inputs` (row-major at the display size, packed as + /// `texturecraft_compose::tile_bytes` packs them) and that size, composited on the GPU + pub fn display_maps( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + inputs: &PreviewInputs, + kinds: &[DisplayKind], + ) -> Result { + let prepared = PreparedPreview::maps(inputs, kinds)?; + match run_until_ready(&prepared, None, |prepared| self.run(device, queue, prepared))? { + PreviewResult::Maps(maps) => Ok(maps), + PreviewResult::Thumbnail(..) => Err(refused("the preview is not display maps")), + } + } + + /// The layer thumbnail `thumb` of `inputs` (whose project is already cut to the layer) as + /// straight RGBA8 at the display size: gray masks opaque on covered texels, layer content + /// with its coverage as alpha, texels no triangle covers transparent. + pub fn thumbnail( + &mut self, + device: &wgpu::Device, + queue: &wgpu::Queue, + inputs: &PreviewInputs, + thumb: ThumbOutput, + ) -> Result<(u32, u32, Vec), PreviewFailure> { + let prepared = PreparedPreview::thumbnail(inputs, thumb)?; + match run_until_ready(&prepared, None, |prepared| self.run(device, queue, prepared))? { + PreviewResult::Thumbnail(width, height, rgba) => Ok((width, height, rgba)), + PreviewResult::Maps(_) => Err(refused("the preview is not a thumbnail")), + } + } + + /// Composite `prepared` on the preview renderer and read it back; None while an + /// asynchronous compositor still compiles its pipelines (run it again later) + pub fn run(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, prepared: &PreparedPreview) -> Result, PreviewFailure> { + let Some(renderer) = self.composite(device, queue, prepared)? else { return Ok(None) }; + let ts = prepared.ts; + match &prepared.output { + Output::Maps(kinds) => { + let (width, height) = renderer.display_extent(ts).ok_or_else(|| refused("texture set does not exist"))?; + let textures = renderer.display_textures(); + let textures = textures.get(ts).ok_or_else(|| refused("texture set does not exist"))?; + let maps = kinds + .iter() + .map(|&kind| { + let texture = textures.get(kind as usize).ok_or_else(|| refused("display map does not exist"))?; + let (w, h, bytes) = read(device, queue, texture)?; + + // A map the material does not write is one neutral texel + match (w, h) { + (1, 1) => Ok(bytes.repeat((width * height) as usize)), + size if size == (width, height) => Ok(bytes), + _ => Err(refused("the GPU display map is not the display size")), + } + }) + .collect::>()?; + Ok(Some(PreviewResult::Maps(((width, height), maps)))) + } + &Output::Thumbnail { mask } => { + let extent = renderer.display_extent(ts); + let texture = renderer.aux_texture(ts).ok_or_else(|| refused("texture set does not exist"))?; + let (width, height, mut rgba) = read(device, queue, texture)?; + if Some((width, height)) != extent { + return Err(refused("the GPU thumbnail is not the display size")); + } + + // The mask view leaves uncovered texels opaque black; thumbnails show them transparent + if mask { + let gbuf = &prepared.gbuf; + let step = gbuf.width.checked_div(width).unwrap_or(1).max(1); + for (offset, pixel) in rgba.as_chunks_mut::<4>().0.iter_mut().enumerate() { + let (x, y) = (offset as u32 % width, offset as u32 / width); + if !gbuf.covered((y * step * gbuf.width + x * step) as usize) { + *pixel = [0; 4]; + } + } + } + Ok(Some(PreviewResult::Thumbnail(width, height, rgba))) + } + } + } + + /// Composite `prepared` on the preview renderer; None while its pipelines compile + fn composite(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, prepared: &PreparedPreview) -> Result, PreviewFailure> { + // Display textures stay one texel until a composite writes them at the display size. A + // setup the GPU fails is a device error, and the next job starts a new renderer + let (asynchronous, budget) = (self.asynchronous, self.budget); + let setup = crate::gpu_trace::scoped(device, "preview renderer setup", || { + let renderer = self.renderer.get_or_insert_with(|| { + let mut renderer = Renderer::new(device, queue, wgpu::TextureFormat::Rgba8Unorm); + renderer.set_asynchronous_compile(asynchronous); + renderer.set_memory_budget(budget); + renderer + }); + renderer.set_display_shift(prepared.shift); + renderer.set_texture_sets(device, queue, &prepared.sets, prepared.materials); + #[cfg(test)] + if FAIL_SETUP.replace(false) { + // An invalid texture stands for an allocation the GPU refuses + let size = wgpu::Extent3d { width: 0, height: 0, depth_or_array_layers: 1 }; + let _invalid = device.create_texture(&wgpu::TextureDescriptor { + label: Some("tc_test_failed_setup"), + size, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }); + } + }); + if let Err(error) = setup { + self.renderer = None; + return Err(PreviewFailure::Device(error)); + } + let renderer = self.renderer.as_mut().ok_or_else(|| refused("the preview renderer is missing"))?; + + // The composite frees its cached inputs and retries once when the GPU runs out of memory + match renderer.composite_on_gpu(device, queue, prepared.ts, &prepared.program) { + Ok(()) => Ok(Some(renderer)), + Err(error) if error == GPU_PIPELINES_PENDING => Ok(None), + Err(error) if crate::gpu_memory::is_device_error(&error) => Err(PreviewFailure::Device(error)), + Err(error) => Err(PreviewFailure::Refused(error)), + } + } + + /// Tests: make the next `attempts` composites run out of GPU memory + #[cfg(any(test, feature = "test-support"))] + pub fn fail_next_gpu_attempts(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, attempts: u32) { + self.renderer.get_or_insert_with(|| Renderer::new(device, queue, wgpu::TextureFormat::Rgba8Unorm)).fail_next_gpu_attempts(attempts); + } +} + +fn refused(reason: &str) -> PreviewFailure { + PreviewFailure::Refused(reason.to_string()) +} + +#[cfg(test)] +thread_local! { + /// Tests: the next preview renderer setup fails on the device + static FAIL_SETUP: std::cell::Cell = const { std::cell::Cell::new(false) }; +} + +/// Read `texture` back; the staging allocation and copy run in an error scope, so a GPU that +/// refuses them is a device error +fn read(device: &wgpu::Device, queue: &wgpu::Queue, texture: &wgpu::Texture) -> Result<(u32, u32, Vec), PreviewFailure> { + crate::gpu_trace::scoped(device, "preview readback", || Readback::blocking(device, queue, texture)) + .map_err(PreviewFailure::Device)? + .ok_or_else(|| PreviewFailure::Device(crate::gpu_memory::device_error("preview readback", "the map could not be read"))) +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + + use texturecraft_compose::{Composite, Inputs, all_tiles, composite_tiles, tile_bytes}; + use texturecraft_compose::{ThumbPlan, ThumbTarget, thumb}; + use texturecraft_core::{ + AoMixing, Channel, Effect, EffectKind, Fill, Filter, Layer, LayerKind, Mask, MaskBackground, Procedural, ProceduralKind, Source, TextureSet, + }; + use texturecraft_geom::primitives; + use texturecraft_texel::TILE; + + use super::*; + + /// A procedural fill with a blur over it, the kind of material the shelf previews show + fn material(size: u32) -> Project { + let mut project = Project::new("preview", ""); + project.texture_sets.push(TextureSet::new("preview", 0, size)); + let mut fill = Fill::default(); + let clouds = Source::Procedural { + pattern: Procedural { scale: 2.0, ..Procedural::new(ProceduralKind::Clouds) }, + low: [0.1; 3], + high: [0.9, 0.5, 0.2], + ramp: Vec::new(), + }; + fill.sources.insert(Channel::BaseColor, clouds); + let channels = [Channel::BaseColor, Channel::Metallic, Channel::Roughness, Channel::Height]; + let mut layer = Layer::new(project.alloc_id(), "sample", LayerKind::Fill(fill), &channels); + layer.content_effects.push(Effect::new(project.alloc_id(), EffectKind::Filter(Filter::Invert))); + project.insert_layer(0, layer, None, false).unwrap(); + project + } + + /// The GPU preview's display maps match the CPU composite the previews used before + #[test] + fn a_preview_composites_on_the_gpu_as_the_cpu_does() { + let Some(gpu) = crate::headless::Headless::for_required_tests() else { return }; + let size = 2 * TILE; + let project = material(size); + let mesh = Arc::new(primitives::sphere(1.0, 32, 16)); + let gbuf = Arc::new(UvGBuffer::new(&mesh, 0, size, size)); + let (pixels, baked, images) = (PixelStore::default(), BakedMaps::default(), ImageStore::default()); + let inputs = + PreviewInputs { project: &project, ts: 0, pixels: &pixels, mesh: &mesh, gbuf: &gbuf, baked: &baked, images: &images, shift: 0, padding: None }; + let kinds = [DisplayKind::BaseColor, DisplayKind::Orm, DisplayKind::Height]; + + let mut compositor = PreviewCompositor::default(); + let (_, maps) = compositor.display_maps(&gpu.device, &gpu.queue, &inputs, &kinds).unwrap(); + + let cpu_inputs = Inputs { + project: &project, + ts: 0, + mesh: &mesh, + gbuf: &gbuf, + pixels: &pixels, + baked: &baked, + block_scales: project.texture_sets[0].block_scales(), + preview: None, + images: &images, + bounds: mesh.bounds(), + }; + let channels: Vec = project.texture_sets[0].channels.iter().map(|&(channel, _)| channel).collect(); + let mut cpu = Composite::new(&channels, size); + let tiles = all_tiles(size, size); + composite_tiles(&cpu_inputs, &mut cpu, &tiles); + for (&kind, gpu_map) in kinds.iter().zip(&maps) { + let bytes = kind.bytes_per_texel(); + assert_eq!(gpu_map.len(), (size * size) as usize * bytes, "{kind:?}"); + let mut differing = 0; + for &(tx, ty) in &tiles { + let tile = tile_bytes(&cpu, &baked, AoMixing::Multiply, kind, tx, ty); + for (y, row) in tile.chunks_exact(TILE as usize * bytes).enumerate() { + let start = ((ty * TILE + y as u32) * size + tx * TILE) as usize * bytes; + let near = |(g, c): (&u8, &u8)| g.abs_diff(*c) <= 2; + differing += usize::from(bytes == 4 && !gpu_map[start..start + row.len()].iter().zip(row).all(near)); + if bytes == 8 { + let half = |b: &[u8]| -> Vec { b.as_chunks::<2>().0.iter().map(|&h| half::f16::from_le_bytes(h).to_f32()).collect() }; + let (g, c) = (half(&gpu_map[start..start + row.len()]), half(row)); + assert!(g.iter().zip(&c).all(|(g, c)| (g - c).abs() <= 1e-2), "{kind:?} row {y} of tile {tx},{ty}"); + } + } + } + assert!(differing * 200 <= tiles.len() * TILE as usize, "{kind:?}: {differing} rows differ"); + } + } + + /// Layer thumbnails on the GPU at half the set's size match the CPU thumbnails evaluated on + /// the set's G-buffer at the texels the GPU reads: a paint layer's content with its coverage + /// (color and scalar), its painted mask, a folder composited over the channel defaults and a + /// fill of the channel's default value (opaque) + #[test] + fn layer_thumbnails_composite_on_the_gpu_as_the_cpu_does() { + let Some(gpu) = crate::headless::Headless::for_required_tests() else { return }; + let size = 2 * TILE; + let channels = [Channel::BaseColor, Channel::Roughness]; + let mut project = Project::new("thumbnails", ""); + project.texture_sets.push(TextureSet::new("thumbnails", 0, size)); + let paint = project.alloc_id(); + let mut layer = Layer::new(paint, "Paint", LayerKind::Paint, &channels); + let mut mask = Mask::new(MaskBackground::Black); + let mask_paint = project.alloc_id(); + mask.effects.push(Effect::new(mask_paint, EffectKind::Paint)); + layer.mask = Some(mask); + project.insert_layer(0, layer, None, false).unwrap(); + let folder = project.alloc_id(); + project.insert_layer(0, Layer::new(folder, "Folder", LayerKind::folder(), &channels), None, false).unwrap(); + let mut fill = Fill::default(); + let clouds = Source::Procedural { pattern: Procedural::new(ProceduralKind::Clouds), low: [0.1; 3], high: [0.9, 0.5, 0.2], ramp: Vec::new() }; + fill.sources.insert(Channel::BaseColor, clouds); + let filled = project.alloc_id(); + project.insert_layer(0, Layer::new(filled, "Fill", LayerKind::Fill(fill), &channels), Some(folder), true).unwrap(); + let neutral = project.alloc_id(); + project.insert_layer(0, Layer::new(neutral, "Default fill", LayerKind::Fill(Fill::default()), &channels), None, false).unwrap(); + + // Paint whose coverage ramps across the set, a mask painted on its left half + let mut pixels = PixelStore::default(); + let unit = |value: f32| (value.clamp(0.0, 1.0) * 65535.0).round() as u16; + for y in 0..size { + for x in 0..size { + let coverage = x as f32 / size as f32; + pixels.layer_mut(paint, Channel::BaseColor, (size, size)).set(x, y, &[0.8, 0.3, 0.1, 1.0].map(|v| unit(v * coverage))); + pixels.layer_mut(paint, Channel::Roughness, (size, size)).set(x, y, &[unit(0.6 * coverage), unit(coverage)]); + if x < size / 2 { + pixels.mask_mut(mask_paint, (size, size)).set(x, y, &[unit(y as f32 / size as f32), u16::MAX]); + } + } + } + let mesh = Arc::new(primitives::sphere(1.0, 32, 16)); + let gbuf = Arc::new(UvGBuffer::new(&mesh, 0, size, size)); + let (baked, images) = (BakedMaps::default(), ImageStore::default()); + let cpu_inputs = Inputs { + project: &project, + ts: 0, + mesh: &mesh, + gbuf: &gbuf, + pixels: &pixels, + baked: &baked, + block_scales: project.texture_sets[0].block_scales(), + preview: None, + images: &images, + bounds: mesh.bounds(), + }; + + let mut compositor = PreviewCompositor::default(); + let targets = [ + ThumbTarget::Content { layer: paint, channel: Channel::BaseColor }, + ThumbTarget::Content { layer: paint, channel: Channel::Roughness }, + ThumbTarget::Mask { layer: paint }, + ThumbTarget::Content { layer: folder, channel: Channel::BaseColor }, + ThumbTarget::Content { layer: neutral, channel: Channel::Roughness }, + ]; + // Every 2nd texel, and one texel per tile (a 4K set's thumbnail): sampled paint windows + for (shift, target) in [1, 6].into_iter().flat_map(|shift| targets.map(|target| (shift, target))) { + let plan = ThumbPlan::new(&project, 0, target).unwrap(); + let inputs = PreviewInputs { + project: &plan.project, + ts: 0, + pixels: &pixels, + mesh: &mesh, + gbuf: &gbuf, + baked: &baked, + images: &images, + shift, + padding: None, + }; + let (width, height, rgba) = compositor.thumbnail(&gpu.device, &gpu.queue, &inputs, plan.output).unwrap(); + let cpu = thumb::render(&cpu_inputs, target).unwrap(); + + assert_eq!((width, height), (size >> shift, size >> shift), "{target:?}"); + let mut differing = 0; + let mut partly_covered = 0; + for y in 0..height { + for x in 0..width { + let gpu_texel = &rgba[((y * width + x) * 4) as usize..][..4]; + let cpu_texel = &cpu.rgba[(((y * size + x) << shift) * 4) as usize..][..4]; + let same = + gpu_texel[3].abs_diff(cpu_texel[3]) <= 2 && (cpu_texel[3] == 0 || gpu_texel.iter().zip(cpu_texel).all(|(g, c)| g.abs_diff(*c) <= 2)); + differing += usize::from(!same); + partly_covered += usize::from(gpu_texel[3] > 0 && gpu_texel[3] < 255); + } + } + assert!(differing * 100 <= (width * height) as usize, "{target:?} at shift {shift}: {differing} texels differ"); + let paint_content = matches!(target, ThumbTarget::Content { layer, .. } if layer == paint); + assert_eq!(partly_covered > 0, paint_content, "{target:?}: coverage is the paint's alpha"); + assert!(paint_content || rgba.as_chunks::<4>().0.iter().any(|texel| texel[3] == 255), "{target:?}: opaque where covered"); + } + } + + /// A composite that runs out of GPU memory twice is a device error, not a refusal + #[test] + fn a_preview_out_of_gpu_memory_is_a_device_error() { + let Some(gpu) = crate::headless::Headless::for_required_tests() else { return }; + let size = TILE; + let project = material(size); + let mesh = Arc::new(primitives::sphere(1.0, 16, 8)); + let gbuf = Arc::new(UvGBuffer::new(&mesh, 0, size, size)); + let (pixels, baked, images) = (PixelStore::default(), BakedMaps::default(), ImageStore::default()); + let inputs = + PreviewInputs { project: &project, ts: 0, pixels: &pixels, mesh: &mesh, gbuf: &gbuf, baked: &baked, images: &images, shift: 0, padding: None }; + + let mut compositor = PreviewCompositor::default(); + compositor.fail_next_gpu_attempts(&gpu.device, &gpu.queue, 2); + let failure = compositor.display_maps(&gpu.device, &gpu.queue, &inputs, &[DisplayKind::BaseColor]).unwrap_err(); + + assert!(matches!(failure, PreviewFailure::Device(_)), "{failure:?}"); + } + + /// A renderer setup the GPU fails is a device error, and the next preview starts a new + /// renderer instead of compositing on the failed one + #[test] + fn a_failed_preview_renderer_setup_is_a_device_error() { + let Some(gpu) = crate::headless::Headless::for_required_tests() else { return }; + let size = TILE; + let project = material(size); + let mesh = Arc::new(primitives::sphere(1.0, 16, 8)); + let gbuf = Arc::new(UvGBuffer::new(&mesh, 0, size, size)); + let (pixels, baked, images) = (PixelStore::default(), BakedMaps::default(), ImageStore::default()); + let inputs = + PreviewInputs { project: &project, ts: 0, pixels: &pixels, mesh: &mesh, gbuf: &gbuf, baked: &baked, images: &images, shift: 0, padding: None }; + + let mut compositor = PreviewCompositor::default(); + FAIL_SETUP.set(true); + let failure = compositor.display_maps(&gpu.device, &gpu.queue, &inputs, &[DisplayKind::BaseColor]); + assert!(matches!(failure, Err(PreviewFailure::Device(_))), "{:?}", failure.map(|_| ())); + assert!(compositor.renderer.is_none(), "the failed renderer is dropped"); + assert!(compositor.display_maps(&gpu.device, &gpu.queue, &inputs, &[DisplayKind::BaseColor]).is_ok(), "the next preview composites"); + } +} diff --git a/crates/render/src/gpu_quick_mask.rs b/crates/render/src/gpu_quick_mask.rs index f4d086627..47854615d 100644 --- a/crates/render/src/gpu_quick_mask.rs +++ b/crates/render/src/gpu_quick_mask.rs @@ -12,10 +12,10 @@ pub use quick_mask_alpha::QuickMaskAlpha; pub(crate) use quick_mask_gpu::QuickMaskGpu; pub use quick_mask_overlay::QuickMaskOverlay; -fn coverage_texture(device: &wgpu::Device, size: u32) -> wgpu::Texture { +fn coverage_texture(device: &wgpu::Device, (width, height): (u32, u32)) -> wgpu::Texture { device.create_texture(&wgpu::TextureDescriptor { label: Some("tc_quick_mask_coverage"), - size: wgpu::Extent3d { width: size, height: size, depth_or_array_layers: 1 }, + size: wgpu::Extent3d { width, height, depth_or_array_layers: 1 }, mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, @@ -25,31 +25,32 @@ fn coverage_texture(device: &wgpu::Device, size: u32) -> wgpu::Texture { }) } -fn upload_coverage(device: &wgpu::Device, queue: &wgpu::Queue, size: u32, mask: &TileImage) -> wgpu::TextureView { - let texture = coverage_texture(device, size); +fn upload_coverage(device: &wgpu::Device, queue: &wgpu::Queue, extent: (u32, u32), mask: &TileImage) -> wgpu::TextureView { + let texture = coverage_texture(device, extent); + let (columns, rows) = extent; let (width, height) = (mask.width(), mask.height()); - let mut coverage = vec![0u16; (size * size) as usize]; + let mut coverage = vec![0u16; (columns * rows) as usize]; for (tx, ty) in mask.allocated() { let Some(tile) = mask.tile(tx, ty) else { continue }; // Only visit samples in allocated tiles. Their source position matches the CPU overlay - let first_x = (tx * TILE * size).div_ceil(width); - let last_x = (((tx + 1) * TILE).min(width) * size).div_ceil(width); - let first_y = (ty * TILE * size).div_ceil(height); - let last_y = (((ty + 1) * TILE).min(height) * size).div_ceil(height); + let first_x = (tx * TILE * columns).div_ceil(width); + let last_x = (((tx + 1) * TILE).min(width) * columns).div_ceil(width); + let first_y = (ty * TILE * rows).div_ceil(height); + let last_y = (((ty + 1) * TILE).min(height) * rows).div_ceil(height); for y in first_y..last_y { - let row = y * height / size % TILE; + let row = y * height / rows % TILE; for x in first_x..last_x { - let column = x * width / size % TILE; - coverage[(y * size + x) as usize] = tile[(row * TILE + column) as usize]; + let column = x * width / columns % TILE; + coverage[(y * columns + x) as usize] = tile[(row * TILE + column) as usize]; } } } queue.write_texture( texture.as_image_copy(), bytemuck::cast_slice(&coverage), - wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(size * 2), rows_per_image: None }, - wgpu::Extent3d { width: size, height: size, depth_or_array_layers: 1 }, + wgpu::TexelCopyBufferLayout { offset: 0, bytes_per_row: Some(columns * 2), rows_per_image: None }, + wgpu::Extent3d { width: columns, height: rows, depth_or_array_layers: 1 }, ); texture.create_view(&Default::default()) } diff --git a/crates/render/src/gpu_quick_mask/quick_mask_gpu.rs b/crates/render/src/gpu_quick_mask/quick_mask_gpu.rs index bcdb01f20..4d3a1bfce 100644 --- a/crates/render/src/gpu_quick_mask/quick_mask_gpu.rs +++ b/crates/render/src/gpu_quick_mask/quick_mask_gpu.rs @@ -53,7 +53,7 @@ impl QuickMaskGpu { multiview_mask: None, cache: None, }); - Self { pipeline, empty: coverage_texture(device, 1).create_view(&Default::default()), coverage: BTreeMap::new() } + Self { pipeline, empty: coverage_texture(device, (1, 1)).create_view(&Default::default()), coverage: BTreeMap::new() } } pub(crate) fn clear_coverage(&mut self) { @@ -68,7 +68,7 @@ impl QuickMaskGpu { &mut self, (device, queue): (&wgpu::Device, &wgpu::Queue), ts: usize, - size: u32, + extent: (u32, u32), base: &wgpu::TextureView, overlay: &QuickMaskOverlay, ) -> wgpu::BindGroup { @@ -77,18 +77,21 @@ impl QuickMaskGpu { self.coverage.remove(&ts); self.empty.clone() } else { - if self.coverage.get(&ts).is_none_or(|(previous, _)| !previous.same_tiles(mask)) { + // The coverage extent follows the display shift: a new extent uploads again + let stale = + |(previous, view): &(TileImage, wgpu::TextureView)| !previous.same_tiles(mask) || (view.texture().width(), view.texture().height()) != extent; + if self.coverage.get(&ts).is_none_or(stale) { self.coverage.remove(&ts); - self.coverage.insert(ts, (mask.clone(), upload_coverage(device, queue, size, mask))); + self.coverage.insert(ts, (mask.clone(), upload_coverage(device, queue, extent, mask))); } self.coverage.get(&ts).map_or_else(|| self.empty.clone(), |(_, view)| view.clone()) }; let (stroke, opacity, erase) = match &overlay.stroke { Some((QuickMaskAlpha::Gpu(view), opacity, erase)) => (view.clone(), *opacity, *erase), - Some((QuickMaskAlpha::Cpu(mask), opacity, erase)) => (upload_coverage(device, queue, size, mask), *opacity, *erase), + Some((QuickMaskAlpha::Cpu(mask), opacity, erase)) => (upload_coverage(device, queue, extent, mask), *opacity, *erase), None => (self.empty.clone(), 0.0, false), }; - let params = [size, u32::from(overlay.inverted), u32::from(erase), opacity.to_bits()]; + let params = [extent.0, extent.1, u32::from(overlay.inverted), u32::from(erase), opacity.to_bits(), 0, 0, 0]; let uniforms = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("tc_quick_mask_params"), contents: bytemuck::cast_slice(¶ms), @@ -106,3 +109,38 @@ impl QuickMaskGpu { }) } } + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + use super::*; + use crate::headless::Headless; + + /// After a display shift change the committed mask uploads again at the new extent instead of + /// stretching the old upload + #[test] + fn a_shift_change_uploads_the_mask_coverage_at_the_new_extent() { + let Some(gpu) = Headless::for_required_tests() else { return }; + let mut quick_mask = QuickMaskGpu::new(&gpu.device); + let base = gpu + .device + .create_texture(&wgpu::TextureDescriptor { + label: Some("tc_test_base"), + size: wgpu::Extent3d { width: 1, height: 1, depth_or_array_layers: 1 }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: wgpu::TextureFormat::Rgba8Unorm, + usage: wgpu::TextureUsages::TEXTURE_BINDING, + view_formats: &[], + }) + .create_view(&Default::default()); + let mut mask = TileImage::new(64, 64, 1); + mask.set(0, 0, &[u16::MAX]); + let overlay = QuickMaskOverlay { mask, inverted: false, stroke: None }; + for extent in [(64, 64), (32, 32)] { + quick_mask.bindings((&gpu.device, &gpu.queue), 0, extent, &base, &overlay); + let texture = quick_mask.coverage.get(&0).map(|(_, view)| view.texture().size()); + assert_eq!(texture.map(|size| (size.width, size.height)), Some(extent), "coverage at the overlay's extent"); + } + } +} diff --git a/crates/render/src/gpu_stencil.rs b/crates/render/src/gpu_stencil.rs index 3f49cb117..82816b87c 100644 --- a/crates/render/src/gpu_stencil.rs +++ b/crates/render/src/gpu_stencil.rs @@ -15,20 +15,30 @@ use placement::Placement; pub struct GpuStencil { pub(crate) image: wgpu::TextureView, pub(crate) uniforms: wgpu::Buffer, + /// The Projection tool paints the image's colors; any other tool paints through its gray + pub(crate) colors: bool, } +/// How the shader reads the image (`rotation_flags.w` in stencil_projection.wgsl) +#[cfg(not(target_arch = "wasm32"))] +const STENCIL_RAW: f32 = 0.0; +#[cfg(not(target_arch = "wasm32"))] +const STENCIL_SRGB: f32 = 1.0; +#[cfg(not(target_arch = "wasm32"))] +const STENCIL_MASK: f32 = 2.0; + impl GpuStencil { - fn from_placement(device: &wgpu::Device, image: wgpu::TextureView, placement: Placement) -> Self { + fn from_placement(device: &wgpu::Device, image: wgpu::TextureView, placement: Placement, colors: bool) -> Self { let uniforms = device.create_buffer_init(&wgpu::util::BufferInitDescriptor { label: Some("tc_stencil_placement"), contents: bytemuck::bytes_of(&placement), usage: wgpu::BufferUsages::UNIFORM, }); - Self { image, uniforms } + Self { image, uniforms, colors } } pub(crate) fn empty(device: &wgpu::Device) -> Self { - Self::from_placement(device, image_texture(device, 1, 1).create_view(&Default::default()), Placement::zeroed()) + Self::from_placement(device, image_texture(device, 1, 1).create_view(&Default::default()), Placement::zeroed(), true) } #[cfg(not(target_arch = "wasm32"))] @@ -42,9 +52,19 @@ impl GpuStencil { let placement = Placement { view_proj: (stencil.view_proj * world).to_cols_array_2d(), center_half: [x, y, w.max(1e-6), h.max(1e-6)], - rotation_flags: [sin, cos, u32::from(stencil.tile) as f32, u32::from(stencil.image.srgb) as f32], + rotation_flags: [sin, cos, u32::from(stencil.tile) as f32, read_mode(stencil)], }; - Self::from_placement(device, image, placement) + Self::from_placement(device, image, placement, stencil.colors) + } +} + +/// A mask stencil reads the stored values; colors are linearized from sRGB images +#[cfg(not(target_arch = "wasm32"))] +fn read_mode(stencil: &Stencil) -> f32 { + match (stencil.colors, stencil.image.srgb) { + (false, _) => STENCIL_MASK, + (true, true) => STENCIL_SRGB, + (true, false) => STENCIL_RAW, } } diff --git a/crates/render/src/gpu_tile_pattern.rs b/crates/render/src/gpu_tile_pattern.rs index 51288a559..d7b12bb7a 100644 --- a/crates/render/src/gpu_tile_pattern.rs +++ b/crates/render/src/gpu_tile_pattern.rs @@ -13,9 +13,6 @@ const NO_IMAGE: u32 = u32::MAX; // Keep uploads banded even for an image that fills an entire atlas slice const IMAGE_ROWS: usize = 64; -// Put a bound on packing overhead as well as authored pixels -const MAX_ATLAS_BYTES: u64 = 256 << 20; -const MAX_COLOR_ATLAS_BYTES: u64 = 1 << 30; const MAX_PENDING_UPLOAD_BYTES: u64 = 64 << 20; mod atlas_mips; @@ -61,7 +58,7 @@ fn levels_of(image: &ImageRes, mips: AtlasMips) -> Vec<(&[[f32; 4]], [u32; 2])> chain.iter().map(|level| (level.rgba.as_slice(), [level.width.max(1), level.height.max(1)])).collect() } -fn arrange_images(images: &[[u32; 2]], side_limit: u32, layer_limit: u32, backend: wgpu::Backend, budget: u64) -> Result<([u32; 3], Vec), String> { +fn arrange_images(images: &[[u32; 2]], side_limit: u32, layer_limit: u32, backend: wgpu::Backend) -> Result<([u32; 3], Vec), String> { let mut order: Vec<_> = images.iter().enumerate().map(|(i, &[w, h])| (i, w, h)).collect(); order.sort_by_key(|&(_, _, height)| std::cmp::Reverse(height)); let widest = order.iter().map(|&(_, width, _)| width).max().unwrap_or(1); @@ -107,13 +104,7 @@ fn arrange_images(images: &[[u32; 2]], side_limit: u32, layer_limit: u32, backen return Err("The authored image atlas exceeds the GPU array limit.".into()); } } - let extent = [used_w, used_h, layers]; - let bytes = extent.into_iter().map(u64::from).product::() * size_of::() as u64; - if bytes > budget { - return Err("The authored image atlas exceeds the GPU memory budget.".into()); - } - - Ok((extent, regions)) + Ok(([used_w, used_h, layers], regions)) } fn atlas_texture(device: &wgpu::Device, width: u32, height: u32, layers: u32) -> wgpu::Texture { @@ -133,14 +124,16 @@ fn atlas_texture(device: &wgpu::Device, width: u32, height: u32, layers: u32) -> mod tests { use super::*; + /// Two 8K images fill two array slices; only the device's slice count refuses a third #[test] - fn image_atlas_counts_unoccupied_space_in_every_array_slice() { + fn image_atlas_holds_what_the_device_limits_allow() { let large = [8192; 2]; - let small = [16; 2]; - let (extent, _) = arrange_images(&[large], 8192, 16, wgpu::Backend::Vulkan, MAX_ATLAS_BYTES).unwrap(); - assert_eq!(extent, [8192, 8192, 1]); - let error = arrange_images(&[large, small], 8192, 16, wgpu::Backend::Vulkan, MAX_ATLAS_BYTES).err(); - assert!(error.is_some_and(|error| error.contains("memory budget"))); + + let (extent, _) = arrange_images(&[large, large], 8192, 2, wgpu::Backend::Vulkan).unwrap(); + let error = arrange_images(&[large; 3], 8192, 2, wgpu::Backend::Vulkan).err(); + + assert_eq!(extent, [8192, 8192, 2]); + assert!(error.is_some_and(|error| error.contains("array limit"))); } /// Without mips or raw planes the atlas words are exactly the old ones and the cache still @@ -152,7 +145,7 @@ mod tests { let image = Arc::new(ImageRes::new(8, 4, (0..32).map(|i| [i as f32 / 31.0, 0.5, 0.25, 1.0]).collect(), true)); let bytes = Arc::new(ImageRes::new(2, 2, vec![[1.0, 0.0, 0.0, 1.0]; 4], true)); let plain = [(&image, AtlasMips::None), (&bytes, AtlasMips::None)]; - let atlas = TileImageAtlas::new(&gpu.device, &gpu.queue, &[], &plain, &[]).unwrap(); + let atlas = TileImageAtlas::new(&gpu.device, &gpu.queue, &[], &plain, &[], None).unwrap(); assert!(atlas.matches(&[], &plain, &[])); for (index, (image, _)) in plain.iter().enumerate() { let mut words = Vec::new(); @@ -165,8 +158,8 @@ mod tests { let with_mips = [(&image, AtlasMips::LinearColor), (&bytes, AtlasMips::None)]; assert!(!atlas.matches(&[], &with_mips, &[])); - let plane = RawPlane { size: [3, 2], texels: Arc::new(vec![0.5, -1.0, f32::NEG_INFINITY, 2.0, 3.0, 4.0]) }; - let atlas = TileImageAtlas::new(&gpu.device, &gpu.queue, &[], &with_mips, std::slice::from_ref(&plane)).unwrap(); + let plane = RawPlane { size: [3, 2], texels: Arc::new(vec![0.5, -1.0, f32::NEG_INFINITY, 2.0, 3.0, 4.0]), raster: None }; + let atlas = TileImageAtlas::new(&gpu.device, &gpu.queue, &[], &with_mips, std::slice::from_ref(&plane), None).unwrap(); assert!(atlas.matches(&[], &with_mips, std::slice::from_ref(&plane))); assert!(!atlas.matches(&[], &with_mips, &[RawPlane { texels: Arc::new(plane.texels.to_vec()), ..plane.clone() }])); let mut words = Vec::new(); @@ -185,9 +178,9 @@ mod tests { #[test] fn gl_image_atlas_uses_a_2d_array_target() { let image = [4; 2]; - let (extent, _) = arrange_images(&[image], 4, 16, wgpu::Backend::Gl, MAX_ATLAS_BYTES).unwrap(); + let (extent, _) = arrange_images(&[image], 4, 16, wgpu::Backend::Gl).unwrap(); assert_eq!(extent, [4, 4, 2]); - let (extent, _) = arrange_images(&[image; 6], 4, 16, wgpu::Backend::Gl, MAX_ATLAS_BYTES).unwrap(); + let (extent, _) = arrange_images(&[image; 6], 4, 16, wgpu::Backend::Gl).unwrap(); assert_eq!(extent, [4, 4, 7]); } } diff --git a/crates/render/src/gpu_tile_pattern/raw_plane.rs b/crates/render/src/gpu_tile_pattern/raw_plane.rs index 2eb2ae090..c0d4d3eff 100644 --- a/crates/render/src/gpu_tile_pattern/raw_plane.rs +++ b/crates/render/src/gpu_tile_pattern/raw_plane.rs @@ -1,9 +1,11 @@ use super::Arc; -/// One exact-f32 plane of the atlas (P1: a projector depth grid), row by row. The atlas keeps a -/// weak pointer to `texels`, so a plane rebuilt for every program rebuilds the atlas. +/// One exact-f32 plane of the atlas (P1: a projector depth grid), row by row: `texels`, or what +/// `raster` writes on the GPU. The atlas keeps a weak pointer to `texels` (empty for a GPU +/// raster), so a plane rebuilt for every program rebuilds the atlas. #[derive(Clone, Debug)] pub(crate) struct RawPlane { pub(crate) size: [u32; 2], pub(crate) texels: Arc>, + pub(crate) raster: Option>, } diff --git a/crates/render/src/gpu_tile_pattern/tile_image_atlas.rs b/crates/render/src/gpu_tile_pattern/tile_image_atlas.rs index f57876278..ac090f144 100644 --- a/crates/render/src/gpu_tile_pattern/tile_image_atlas.rs +++ b/crates/render/src/gpu_tile_pattern/tile_image_atlas.rs @@ -1,6 +1,6 @@ use super::{ - Arc, AtlasMips, ColorPart, IMAGE_ROWS, ImageRegion, ImageRes, MAX_ATLAS_BYTES, MAX_COLOR_ATLAS_BYTES, MAX_PENDING_UPLOAD_BYTES, RawPlane, RgbaEncoding, - RgbaLevel, RgbaRegion, Weak, arrange_images, atlas_texture, levels_of, + Arc, AtlasMips, ColorPart, IMAGE_ROWS, ImageRegion, ImageRes, MAX_PENDING_UPLOAD_BYTES, RawPlane, RgbaEncoding, RgbaLevel, RgbaRegion, Weak, + arrange_images, atlas_texture, levels_of, }; pub(crate) struct TileImageAtlas { @@ -10,6 +10,8 @@ pub(crate) struct TileImageAtlas { pub(super) color_mips: Vec, pub(super) raw: Vec<(Weak>, ImageRegion)>, pub(crate) view: wgpu::TextureView, + /// Bytes of its texture, counted against the memory budget + pub(crate) bytes: u64, } impl TileImageAtlas { @@ -68,13 +70,15 @@ impl TileImageAtlas { } /// Upload `gray` (one plane each), `color` (one to four planes each by encoding, plus the - /// chosen halved levels) and `raw` (one exact-f32 plane each) into one array texture. + /// chosen halved levels) and `raw` (one exact-f32 plane each, `depth` rasterizing the planes + /// the GPU writes) into one array texture. pub(crate) fn new( device: &wgpu::Device, queue: &wgpu::Queue, gray: &[&Arc], color: &[(&Arc, AtlasMips)], raw: &[RawPlane], + depth: Option<&crate::gpu_image_source::GpuProjectorDepth>, ) -> Result { let limits = device.limits(); let size = |image: &Arc| [image.width.max(1), image.height.max(1)]; @@ -95,9 +99,7 @@ impl TileImageAtlas { .chain(color_parts.iter().flatten().flat_map(|&(_, size, encoding)| std::iter::repeat_n(size, encoding as usize))) .chain(raw.iter().map(|plane| plane.size.map(|side| side.max(1)))) .collect(); - let budget = if color.is_empty() && raw.is_empty() { MAX_ATLAS_BYTES } else { MAX_COLOR_ATLAS_BYTES }; - let (extent, regions) = - arrange_images(&sizes, limits.max_texture_dimension_2d, limits.max_texture_array_layers, device.adapter_info().backend, budget)?; + let (extent, regions) = arrange_images(&sizes, limits.max_texture_dimension_2d, limits.max_texture_array_layers, device.adapter_info().backend)?; let texture = atlas_texture(device, extent[0], extent[1], extent[2]); let mut pixels = Vec::new(); let mut pending = 0; @@ -151,7 +153,13 @@ impl TileImageAtlas { } let mut raw_layout = Vec::new(); for (plane, region) in raw.iter().zip(remaining) { - upload(region, &|index| plane.texels.get(index).copied().unwrap_or_default().to_bits())?; + match &plane.raster { + Some(job) => { + let depth = depth.ok_or("The GPU projector depth passes are missing.")?; + depth.raster_into((device, queue), job, &texture, region.origin)?; + } + None => upload(region, &|index| plane.texels.get(index).copied().unwrap_or_default().to_bits())?, + } raw_layout.push((Arc::downgrade(&plane.texels), *region)); } let view = texture.create_view(&wgpu::TextureViewDescriptor { dimension: Some(wgpu::TextureViewDimension::D2Array), ..Default::default() }); @@ -162,6 +170,7 @@ impl TileImageAtlas { color_mips: color.iter().map(|&(_, mips)| mips).collect(), raw: raw_layout, view, + bytes: extent.into_iter().map(u64::from).product::() * size_of::() as u64, }) } } diff --git a/crates/render/src/gpu_trace.rs b/crates/render/src/gpu_trace.rs index ab182ff51..1f7a1b8f8 100644 --- a/crates/render/src/gpu_trace.rs +++ b/crates/render/src/gpu_trace.rs @@ -23,8 +23,10 @@ use crate::Renderer; use crate::ibl::EnvImage; use crate::trace::{TraceDisplay, TraceScene, TraceSettings}; -/// Texture sets the tracer takes (one more array layer holds the default material). -pub const MAX_SETS: usize = 255; +/// Texture-set entries of the trace uniform (`SET_ENTRIES` in trace.wgsl): the most array layers +/// desktop adapters report. The tracer takes one set fewer than the entries and the adapter's +/// array layers allow (one more layer holds the default material). +const SET_ENTRIES: usize = 2048; /// Depth of the shader's BVH traversal stack (`STACK` in trace.wgsl). pub(crate) const STACK: usize = 64; const KINDS: usize = DisplayKind::ALL.len(); @@ -34,8 +36,8 @@ const _: () = assert!(KINDS == 8); /// The placeholder mask word's bit for a set with Smooth (Sobel) height to normal (trace.wgsl reads it) const SMOOTH_HEIGHT_BIT: f32 = (1 << KINDS) as f32; -/// Bytes of the trace uniform: [`Head`], 256 texture-set entries (`MAX_SETS` in trace.wgsl), then their height slope factors down the texture, four per entry -const PARAMS_SIZE: u64 = (size_of::() + 256 * 16 + 256 * 4) as u64; +/// Bytes of the trace uniform: [`Head`], the texture-set entries, then their height slope factors down the texture, four per entry +const PARAMS_SIZE: u64 = (size_of::() + SET_ENTRIES * 16 + SET_ENTRIES * 4) as u64; /// Post uniform slots: resolve and denoise init, then the five à-trous steps. const STEPS: [u32; 6] = [0, 1, 2, 4, 8, 16]; const WORKGROUP: u32 = 8; @@ -153,9 +155,15 @@ pub(crate) fn scoped(device: &wgpu::Device, what: &str, f: impl FnOnce() -> T let oom = device.push_error_scope(wgpu::ErrorFilter::OutOfMemory); let invalid = device.push_error_scope(wgpu::ErrorFilter::Validation); let out = f(); - let errors = [caught(invalid.pop()), caught(oom.pop())]; - match errors.into_iter().flatten().next() { - Some(e) => Err(format!("{what}: {e}")), + let (invalid, oom) = (caught(invalid.pop()), caught(oom.pop())); + + // Callers free their caches and try again on a lack of memory (`gpu_memory::is_out_of_memory`) + if let Some(e) = oom { + return Err(crate::gpu_memory::out_of_memory_error(what, &e.to_string())); + } + + match invalid { + Some(e) => Err(crate::gpu_memory::device_error(what, &e.to_string())), None => Ok(out), } } @@ -183,7 +191,10 @@ pub(crate) fn checked(device: &wgpu::Device, what: &str, f: impl FnOnce() -> let oom = oom.await; // An allocation that ran out of memory also makes later calls on it invalid: the // out-of-memory error is the cause. - oom.or(invalid).map(|e| format!("{what}: {e}")) + match oom { + Some(e) => Some(crate::gpu_memory::out_of_memory_error(&what, &e.to_string())), + None => invalid.map(|e| crate::gpu_memory::device_error(&what, &e.to_string())), + } }); #[cfg(not(target_arch = "wasm32"))] { @@ -455,14 +466,15 @@ impl GpuTracer { } let sets = renderer.display_textures(); - if sets.len() > MAX_SETS || sets.iter().any(|s| s.len() != KINDS) { - return Err(format!("GPU path tracing takes at most {MAX_SETS} texture sets")); + if sets.iter().any(|s| s.len() != KINDS) { + return Err("GPU path tracing: a texture set misses display maps".into()); } let layers = sets.len() as u32 + 1; let limits = device.limits(); - if layers > limits.max_texture_array_layers { - return Err(format!("this GPU takes at most {} texture sets", limits.max_texture_array_layers.saturating_sub(1))); + let most_layers = limits.max_texture_array_layers.min(SET_ENTRIES as u32); + if layers > most_layers { + return Err(format!("GPU path tracing takes at most {} texture sets on this GPU", most_layers - 1)); } let old = self.materials.take(); @@ -544,9 +556,10 @@ impl GpuTracer { /// 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)); - let bytes = u64::from(width) * u64::from(height) * 16; let limits = device.limits(); + let side = limits.max_texture_dimension_2d; + let (width, height) = (width.clamp(1, side), height.clamp(1, side)); + let bytes = u64::from(width) * u64::from(height) * 16; // Reject unsupported sizes before invalidating the displayed render if bytes > limits.max_storage_buffer_binding_size.min(limits.max_buffer_size) { @@ -641,13 +654,13 @@ impl GpuTracer { eye: cam.eye().extend(1.0).to_array(), lens: [if sc.lens[0] > 0.0 { sc.lens[0] } else { cam.distance }, sc.lens[1], sc.ior, sc.dielectric_f0_scale], }; - let mut sets = [[0.0f32; 4]; 256]; + let mut sets = vec![[0.0f32; 4]; SET_ENTRIES]; for (i, (slot, m)) in sets.iter_mut().zip(&mat.info).enumerate() { // The bit past the placeholder mask bits: Smooth (Sobel) height to normal let smooth = if sc.smooth.get(i).copied().unwrap_or(false) { SMOOTH_HEIGHT_BIT } else { 0.0 }; *slot = [m[0], m[1], m[2] + smooth, sc.heights.get(i).copied().unwrap_or(0.0)]; } - let mut height_y_factors = [1.0f32; 256]; + let mut height_y_factors = vec![1.0f32; SET_ENTRIES]; for (slot, factor) in height_y_factors.iter_mut().zip(&sc.height_y_factors) { *slot = *factor; } @@ -725,9 +738,10 @@ impl GpuTracer { /// The texture [`GpuTracer::resolve`] writes (RGBA8, sRGB-encoded values, as the CPU tracer's /// `rgba8`): also sampled by the UI and copied for read-back. pub fn output_texture(device: &wgpu::Device, width: u32, height: u32) -> wgpu::Texture { + let side = device.limits().max_texture_dimension_2d; device.create_texture(&wgpu::TextureDescriptor { label: Some("tc_trace_out"), - size: wgpu::Extent3d { width: width.clamp(1, 8192), height: height.clamp(1, 8192), depth_or_array_layers: 1 }, + size: wgpu::Extent3d { width: width.clamp(1, side), height: height.clamp(1, side), depth_or_array_layers: 1 }, mip_level_count: 1, sample_count: 1, dimension: wgpu::TextureDimension::D2, @@ -783,7 +797,7 @@ fn geometry_data(mesh: &Mesh, bvh: &texturecraft_geom::Bvh, tri_set: &[usize]) - let vcount = mesh.positions.len(); let rows = bvh_rows(bvh, (0, 0), |o| { let idx = [0, 1, 2].map(|k| mesh.indices.get(o * 3 + k).copied().filter(|i| (*i as usize) < vcount).unwrap_or(0)); - let set = tri_set.get(o).copied().filter(|s| *s < MAX_SETS).map_or(u32::MAX, |s| s as u32); + let set = tri_set.get(o).copied().filter(|s| *s < SET_ENTRIES - 1).map_or(u32::MAX, |s| s as u32); let sign: f32 = mesh.tangents.get(idx[0] as usize).map_or(1.0, |t| if t.w < 0.0 { -1.0 } else { 1.0 }); ([set, sign.to_bits(), 0], [idx[0], idx[1], idx[2], o as u32]) }); diff --git a/crates/render/src/headless.rs b/crates/render/src/headless.rs index b43d1fe67..120c6dba1 100644 --- a/crates/render/src/headless.rs +++ b/crates/render/src/headless.rs @@ -24,7 +24,9 @@ pub struct Headless { /// (`high`, the default, `low` or `none`); the instance reads wgpu's other variables /// (`WGPU_BACKEND`, `WGPU_ALLOW_UNDERLYING_NONCOMPLIANT_ADAPTER`, ...). pub fn adapter() -> Result { - let instance = wgpu::Instance::new(wgpu::InstanceDescriptor::new_without_display_handle_from_env()); + let mut descriptor = wgpu::InstanceDescriptor::new_without_display_handle_from_env(); + descriptor.memory_budget_thresholds = crate::gpu_memory::instance_thresholds(); + let instance = wgpu::Instance::new(descriptor); let power = wgpu::PowerPreference::from_env().unwrap_or(wgpu::PowerPreference::HighPerformance); if let Ok(name) = std::env::var("WGPU_ADAPTER_NAME") { let adapters = pollster::block_on(instance.enumerate_adapters(wgpu::Backends::all())); diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 7b50dbb2c..850f9a9ed 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -19,13 +19,21 @@ pub mod cage_geometry; mod cage_gpu; pub mod displace; #[cfg(not(target_arch = "wasm32"))] +mod gpu_alpha; +pub mod gpu_aux_view; +#[cfg(not(target_arch = "wasm32"))] pub mod gpu_bake; #[cfg(not(target_arch = "wasm32"))] pub mod gpu_brush; pub mod gpu_composite; mod gpu_curvature; +#[cfg(not(target_arch = "wasm32"))] +pub mod gpu_eye_depth; mod gpu_image_source; +pub mod gpu_memory; mod gpu_neighbourhood; +#[cfg(not(target_arch = "wasm32"))] +pub mod gpu_preview; pub mod gpu_quick_mask; #[cfg(not(target_arch = "wasm32"))] pub mod gpu_resize; @@ -55,7 +63,7 @@ pub use cage_geometry::CageGeometry; pub use neutral_material::NeutralMaterial; pub use overlay_quad::OverlayQuad; pub use renderer::{ - COLOR_FORMAT, DEFAULT_BACKGROUND, Frame, MSAA, Renderer, Shade, UV_VIEW_MAX_ZOOM, UV_VIEW_MIN_ZOOM, ViewKind, aux_size, mask_view_extent, uv_view_scale, + COLOR_FORMAT, DEFAULT_BACKGROUND, Frame, MSAA, Renderer, Shade, UV_VIEW_MAX_ZOOM, UV_VIEW_MIN_ZOOM, ViewKind, aux_extent, set_shift, uv_view_scale, }; pub use set_highlight::SetHighlight; pub use wgpu; diff --git a/crates/render/src/mesh_maps.rs b/crates/render/src/mesh_maps.rs index 9e720c6cc..2ae087465 100644 --- a/crates/render/src/mesh_maps.rs +++ b/crates/render/src/mesh_maps.rs @@ -3,19 +3,19 @@ use texturecraft_compose::BakedMaps; use texturecraft_core::{BakedMap, BlockScales}; -/// RGBA8 of baked map `m` resampled to `size × size` stretched over the map (mid gray where not -/// baked). Scalar maps are shown as grayscale; ID maps as their colors. Values are display -/// (sRGB) encoded. -pub fn mesh_map_rgba(baked: Option<&BakedMaps>, m: BakedMap, size: u32, working_size: (u32, u32), scales: &BlockScales) -> Vec { - let size = size.max(1); - let mut out = vec![128u8; (size * size * 4) as usize]; +/// RGBA8 of baked map `m` resampled to `extent` (width, height) stretched over the map (mid gray +/// where not baked). Scalar maps are shown as grayscale; ID maps as their colors. Values are +/// display (sRGB) encoded. The GPU draws the same view with [`crate::Renderer::draw_aux_view`]. +pub fn mesh_map_rgba(baked: Option<&BakedMaps>, m: BakedMap, extent: (u32, u32), working_size: (u32, u32), scales: &BlockScales) -> Vec { + let (width, height) = (extent.0.max(1), extent.1.max(1)); + let mut out = vec![128u8; (width * height * 4) as usize]; let Some(b) = baked.filter(|b| b.maps.contains_key(&m)) else { return out }; - for y in 0..size { - for x in 0..size { - let uv = [(x as f32 + 0.5) / size as f32, (y as f32 + 0.5) / size as f32]; + for y in 0..height { + for x in 0..width { + let uv = [(x as f32 + 0.5) / width as f32, (y as f32 + 0.5) / height as f32]; let v = scales.bake_uv(uv, working_size).and_then(|uv| b.sample_uv(m, uv)).unwrap_or([0.5; 3]); - let i = ((y * size + x) * 4) as usize; + let i = ((y * width + x) * 4) as usize; for k in 0..3 { // Data maps are shown as stored out[i + k] = (v[k].clamp(0.0, 1.0) * 255.0 + 0.5) as u8; @@ -27,13 +27,13 @@ pub fn mesh_map_rgba(baked: Option<&BakedMaps>, m: BakedMap, size: u32, working_ } /// RGBA8 of the neutral value of map `m` (what a map not baked yet shows during a bake: flat -/// normals, white occlusion, mid-gray height ...), `size × size`, encoded like [`mesh_map_rgba`]. -pub fn neutral_rgba(m: BakedMap, size: u32) -> Vec { +/// normals, white occlusion, mid-gray height ...) at `extent`, encoded like [`mesh_map_rgba`]. +pub fn neutral_rgba(m: BakedMap, extent: (u32, u32)) -> Vec { let value = m.neutral(); let pixel = [0, 1, 2].map(|k| (value[k].clamp(0.0, 1.0) * 255.0 + 0.5) as u8); - let size = size.max(1); - let mut out = Vec::with_capacity((size * size * 4) as usize); - for _ in 0..size * size { + let texels = extent.0.max(1) * extent.1.max(1); + let mut out = Vec::with_capacity((texels * 4) as usize); + for _ in 0..texels { out.extend_from_slice(&[pixel[0], pixel[1], pixel[2], 255]); } out @@ -52,7 +52,7 @@ mod tests { set.tile_resolutions.insert(1002, 128); let pixels = (0..128).flat_map(|y| (0..256).map(move |x| ((x % 128) + y) as f32 / 255.0)).collect(); let baked = BakedMaps { resolution: 256, maps: [(BakedMap::AmbientOcclusion, Arc::new(pixels))].into() }; - let preview = mesh_map_rgba(Some(&baked), BakedMap::AmbientOcclusion, 512, set.size(), &set.block_scales()); + let preview = mesh_map_rgba(Some(&baked), BakedMap::AmbientOcclusion, (512, 512), set.size(), &set.block_scales()); assert_eq!(preview[(240 * 512 + 376) * 4], 240); assert_eq!(preview[(400 * 512 + 500) * 4], 128, "unused working block area stays neutral"); } diff --git a/crates/render/src/paint_window/composite_paint_window.rs b/crates/render/src/paint_window/composite_paint_window.rs index 9017e95e0..51047e309 100644 --- a/crates/render/src/paint_window/composite_paint_window.rs +++ b/crates/render/src/paint_window/composite_paint_window.rs @@ -4,8 +4,14 @@ use super::{COMPOSITE_IMAGE_WORDS, TileImage, TileWindow}; pub(crate) enum CompositePaintWindow { Uniform(TileWindow), PerImage(Vec), + /// A uniform window holding only the texels at multiples of the composite's display step + /// (a power of two above 1): for a composite that reads paint only there + Sampled(TileWindow, u32), } +/// The flag in the window's column count (`params.paint_window.z`) marking a sampled window +const SAMPLED_PAINT: u32 = 1 << 31; + impl CompositePaintWindow { pub fn covering(min: [u32; 2], max: [u32; 2], size: [u32; 2], images: &[TileImage]) -> Self { let common = TileWindow::covering(min, max, size); @@ -30,16 +36,27 @@ impl CompositePaintWindow { Self::PerImage(windows) } + /// This window holding only the texels at multiples of `step`, when it is uniform and + /// `step` is above 1 + pub fn sampled(self, step: u32) -> Self { + match self { + Self::Uniform(window) if step > 1 => Self::Sampled(window, step), + window => window, + } + } + pub fn params(&self) -> [u32; 4] { match self { Self::Uniform(window) => [window.origin[0], window.origin[1], window.size[0], window.size[1]], Self::PerImage(_) => [u32::MAX, 0, 0, 0], + Self::Sampled(window, _) => [window.origin[0], window.origin[1], window.size[0] | SAMPLED_PAINT, window.size[1]], } } pub fn words(&self, images: &[TileImage], limit: usize) -> Option { let windows = match self { Self::Uniform(window) => return window.words(images, limit), + Self::Sampled(window, step) => return window.sampled_words(images, *step, limit), Self::PerImage(windows) => windows, }; let mut words = images.len().max(1); @@ -54,6 +71,7 @@ impl CompositePaintWindow { pub fn pack(&self, images: &[TileImage], words: usize, output: &mut Vec) { let windows = match self { Self::Uniform(window) => return window.pack(images, words, output), + Self::Sampled(window, step) => return window.pack_sampled(images, *step, words, output), Self::PerImage(windows) => windows, }; output.clear(); diff --git a/crates/render/src/paint_window/tile_window.rs b/crates/render/src/paint_window/tile_window.rs index dc0c6960e..fcf75eed2 100644 --- a/crates/render/src/paint_window/tile_window.rs +++ b/crates/render/src/paint_window/tile_window.rs @@ -62,4 +62,64 @@ impl TileWindow { } } } + + /// The words of [`Self::pack_sampled`]: only the texels a composite reading every + /// `step`-th texel samples (`stored_sample` with the sampled flag) + pub fn sampled_words(self, images: &[TileImage], step: u32, limit: usize) -> Option { + let (texels, tile_step) = sampled_layout(step); + let mut words = images.len().max(1); + for image in images { + words += (self.size[0] * self.size[1]) as usize; + let per_tile = texels * image.comps() / 2; + for y in self.read_tiles(1, tile_step) { + let allocated = self.read_tiles(0, tile_step).filter(|&x| image.is_allocated(x, y)).count(); + words += allocated * per_tile; + if words > limit { + return None; + } + } + } + (words <= limit).then_some(words) + } + + /// [`Self::pack`] holding only the texels at multiples of `step` (a power of two): per tile + /// the sampled texels row-major, and only the tiles holding one + pub fn pack_sampled(self, images: &[TileImage], step: u32, words: usize, output: &mut Vec) { + let (_, tile_step) = sampled_layout(step); + let sub = step.min(TILE) as usize; + output.clear(); + output.reserve(words); + output.resize(images.len().max(1), 0); + for (i, image) in images.iter().enumerate() { + output[i] = output.len() as u32; + let table = output.len(); + let comps = image.comps(); + output.resize(table + (self.size[0] * self.size[1]) as usize, 0); + for y in self.read_tiles(1, tile_step) { + for x in self.read_tiles(0, tile_step) { + let Some(tile) = image.tile(x, y) else { continue }; + output[table + ((y - self.origin[1]) * self.size[0] + x - self.origin[0]) as usize] = output.len() as u32; + for row in (0..TILE as usize).step_by(sub) { + for column in (0..TILE as usize).step_by(sub) { + let at = (row * TILE as usize + column) * comps; + output.extend(tile[at..at + comps].as_chunks::<2>().0.iter().map(|&[lo, hi]| u32::from(lo) | (u32::from(hi) << 16))); + } + } + } + } + } + } + + /// The window's tiles along `axis` that hold a sampled texel: every `tile_step`-th atlas tile + fn read_tiles(self, axis: usize, tile_step: u32) -> impl Iterator { + let (start, end) = (self.origin[axis], self.origin[axis] + self.size[axis]); + (start.next_multiple_of(tile_step)..end).step_by(tile_step as usize) + } +} + +/// The sampled texels per tile and the atlas tile step for a composite reading every `step`-th +/// texel (a power of two) +fn sampled_layout(step: u32) -> (usize, u32) { + let sub = step.clamp(1, TILE); + (((TILE / sub) * (TILE / sub)) as usize, (step / TILE).max(1)) } diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 4f73f984f..2a8794b69 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -34,6 +34,7 @@ use texturecraft_texel::TILE; use crate::bake_visualization::BakeVisualization; use crate::cage_geometry::CageGeometry; use crate::cage_gpu::CageGpu; +use crate::gpu_aux_view::{AuxSource, AuxViewGpu}; use crate::gpu_composite::{CompositeProgram, CompositeRegion, GpuCompositor}; use crate::gpu_quick_mask::{QuickMaskAlpha, QuickMaskGpu, QuickMaskOverlay}; use crate::gpu_trace::{Checked, checked}; @@ -404,26 +405,20 @@ fn display_dims(size: (u32, u32), shift: u32) -> (u32, u32) { ((size.0 >> shift).max(1), (size.1 >> shift).max(1)) } -/// Side of the square aux (mesh map / mask / quick mask) texture of a set of `size` texels; it -/// stretches over the set like its other textures. -pub fn aux_size(size: (u32, u32)) -> u32 { - size.0.max(size.1).clamp(1, MAX_AUX_SIDE) +/// How many times a set of `size` texels is halved for display: the display shift +/// (`Renderer::set_display_shift`), or more where the device's textures cannot hold the set +/// (`max_side`: `max_texture_dimension_2d`). +pub fn set_shift(size: (u32, u32), display_shift: u32, max_side: u32) -> u32 { + (0..=31).find(|s| size.0.max(size.1) >> s <= max_side.max(1)).unwrap_or(0).max(display_shift) } -/// The longest side of an aux texture. -const MAX_AUX_SIDE: u32 = 2048; - -/// Width and height of the mask view's aux texture for a set of `size` texels: the set halved -/// until its longer side fits [`aux_size`]'s limit, so a set of UV tiles shows each tile as the -/// square its block is. Output texel (x, y) shows the set's texel (x · width / mask width, y · -/// height / mask height), as `texturecraft_compose::mask_image_sized` samples it. -pub fn mask_view_extent(size: (u32, u32)) -> (u32, u32) { - display_dims(size, mask_view_shift(size)) -} - -/// How many times [`mask_view_extent`] halves a set of `size` texels. -fn mask_view_shift(size: (u32, u32)) -> u32 { - size.0.max(size.1).max(1).div_ceil(MAX_AUX_SIDE).next_power_of_two().trailing_zeros() +/// Width and height of the aux (mesh map / image / ID mask / quick mask / mask view) texture of +/// a set of `size` texels halved `shift` times ([`set_shift`]): the set's display size, so a set +/// of UV tiles shows each tile as the square its block is. Output texel (x, y) shows the set's +/// texel (x · width / aux width, y · height / aux height), as +/// `texturecraft_compose::mask_image_sized` samples it. +pub fn aux_extent(size: (u32, u32), shift: u32) -> (u32, u32) { + display_dims(size, shift) } impl Tex { @@ -484,6 +479,9 @@ struct SetGpu { pending: Vec>, /// The overview we are waiting to bind, and detail tiles to apply over it. pending_seed: Option, + /// A composite or a display tile wrote the textures since the set was created: a late + /// overview ([`Renderer::seed_display_unless_written`]) would only hide it + written: bool, } /// A full-size texture waiting for WebGPU's verdict on its allocation. @@ -695,12 +693,18 @@ pub struct Renderer { dof_pipeline: wgpu::RenderPipeline, shadow_pipeline: wgpu::RenderPipeline, compositor: Option, + /// How much GPU memory the compositor's cached inputs may hold (`set_memory_budget`) + memory_budget: crate::gpu_memory::GpuMemoryBudget, + /// Tests: this many next composite, mask preview, aux view or brush start attempts run out of GPU memory + #[cfg(any(test, feature = "test-support"))] + failing_gpu_attempts: u32, /// The compositor compiles new pipelines on worker threads (`set_asynchronous_compile`) asynchronous_compile: bool, /// The compositor takes the pipelines the tests on the shared device share /// (`Renderer::share_test_pipelines`) shared_test_pipelines: bool, quick_mask: Option, + aux_view: Option, #[cfg(not(target_arch = "wasm32"))] brush: Option, mip_pipelines: HashMap, @@ -1011,8 +1015,8 @@ const CLEAR: wgpu::LoadOp = wgpu::LoadOp::Clear(wgpu::Color::TRANSP /// Depth bias of the shadow map, per unit of surface slope: keeps lit surfaces from shadowing themselves const SHADOW_SLOPE_BIAS: f32 = 1.5; -/// Anisotropic filtering of the texture sets' sampler -const MAX_ANISOTROPY: u16 = 8; +/// Anisotropic filtering of the texture sets' sampler: the most wgpu takes +const MAX_ANISOTROPY: u16 = 16; /// Size of the environment texture before the first environment loads const PLACEHOLDER_ENV_SIZE: [u32; 2] = [512, 256]; @@ -1351,9 +1355,13 @@ impl Renderer { accum_pipeline, mip_pipelines: HashMap::new(), compositor: None, + memory_budget: Default::default(), + #[cfg(any(test, feature = "test-support"))] + failing_gpu_attempts: 0, asynchronous_compile: false, shared_test_pipelines: false, quick_mask: None, + aux_view: None, #[cfg(not(target_arch = "wasm32"))] brush: None, util_module, @@ -1440,9 +1448,11 @@ impl Renderer { self.quick_mask = None; - // A late overview from the previous mesh must never replace the current textures + // A late overview from the previous mesh must never replace the current textures; the new + // mesh's overview may replace the previous mesh's for set in &mut self.sets { set.pending_seed = None; + set.written = false; set.pending.iter_mut().take(DisplayKind::ALL.len()).for_each(|slot| *slot = None); } if let Some(compositor) = &mut self.compositor { @@ -1594,6 +1604,11 @@ impl Renderer { let mut reset = Vec::new(); self.content_rev += 1; self.sets.truncate(sets.len()); + + // New or resized sets (another project): their earlier variants are not what a stroke prewarms + if let Some(compositor) = &mut self.compositor { + compositor.forget_variants(); + } if let Some(quick_mask) = &mut self.quick_mask { quick_mask.retain_texture_sets(sets.len()); } @@ -1603,7 +1618,7 @@ impl Renderer { let max = device.limits().max_texture_dimension_2d.max(1); for (i, &(size, material)) in sets.iter().enumerate() { // Downscale sets that exceed the device's texture dimension limit - let shift = (0..31).find(|s| size.0.max(size.1) >> s <= max).unwrap_or(0).max(self.display_shift); + let shift = set_shift(size, self.display_shift, max); if self.sets.get(i).is_some_and(|s| s.size == size && s.shift == shift && s.material == material) { continue; } @@ -1624,6 +1639,7 @@ impl Renderer { failed: vec![false; n], pending: (0..n).map(|_| None).collect(), pending_seed: None, + written: false, }; if i < self.sets.len() { self.sets[i] = gpu; @@ -1648,20 +1664,39 @@ impl Renderer { queue: &wgpu::Queue, input: crate::gpu_brush::BrushInput, ) -> Result { - if !GpuCompositor::supports(device) { + // The brush binds one storage buffer more than the compositor (surface covers) + if !GpuCompositor::supports(device) || device.limits().max_storage_buffers_per_shader_stage < 7 { return Err("adapter limits do not support the GPU brush".into()); } let compile = (self.asynchronous_compile, self.shared_test_pipelines); - let (compositor, brush, stroke) = crate::gpu_trace::scoped(device, "GPU brush startup", || { - let mut compositor = self.compositor.take().unwrap_or_else(|| Self::new_compositor(device, compile)); - let mut brush = self.brush.take().unwrap_or_else(|| crate::gpu_brush::BrushPipeline::new(device)); - let stroke = compositor.uv_surface(device, queue, &input.mesh, &input.uv).and_then(|surface| brush.begin(device, queue, input, surface)); - (compositor, brush, stroke) - })?; + let mut compositor = self.compositor.take().unwrap_or_else(|| Self::new_compositor(device, compile)); + compositor.memory_budget = self.memory_budget.bytes(); + let mut brush = self.brush.take().unwrap_or_else(|| crate::gpu_brush::BrushPipeline::new(device)); + let stroke = crate::gpu_trace::scoped(device, "GPU brush startup", || { + let surface = compositor.uv_surface(device, queue, &input.mesh, &input.uv)?; + let source_maps = crate::gpu_brush::composite_pickup_source(&mut compositor, (device, queue), &input)?; + brush.begin(device, queue, input, surface, source_maps) + }); + + // Tests: the simulated failure drops the stroke that did start + #[cfg(any(test, feature = "test-support"))] + let stroke = match self.failing_gpu_attempts.checked_sub(1) { + Some(left) => { + self.failing_gpu_attempts = left; + Err(crate::gpu_memory::out_of_memory_error("a test brush start", "simulated")) + } + None => stroke, + }; + + // A device error keeps the compositor and its cached inputs (a retry may free them), but + // not a library tip or surface covers its error may have left invalid + if !matches!(stroke, Ok(Ok(_))) { + brush.forget_failed_start(); + } self.compositor = Some(compositor); self.brush = Some(brush); - stroke + stroke? } /// Drop the inputs a texture set no longer needs for GPU compositing. @@ -1671,6 +1706,14 @@ impl Renderer { } } + /// Free every texture set's cached compositor inputs, keeping the compiled pipelines: room + /// for other GPU work that ran out of memory. + pub fn release_all_composite_inputs(&mut self) { + if let Some(compositor) = &mut self.compositor { + compositor.release_all_inputs(); + } + } + /// Bytes of the GPU compositor's last update: its working buffer and its paint upload buffer. #[cfg(all(test, not(target_arch = "wasm32")))] pub(crate) fn composite_update_bytes(&self) -> [u64; 2] { @@ -1714,6 +1757,17 @@ impl Renderer { self.compositor.get_or_insert_with(|| Self::new_compositor(device, compile)).prewarm(device, program); } + /// Start compiling, on worker threads, the pipelines a live clone or smudge stroke on texture + /// set `ts` composites with (its last composite's variant with the brush package), so the + /// stroke's first preview does not wait for them. True once they are compiled. + pub fn prewarm_pickup_composite(&mut self, device: &wgpu::Device, ts: usize) -> bool { + if !self.asynchronous_compile || cfg!(target_arch = "wasm32") || !GpuCompositor::supports(device) { + return false; + } + + self.compositor.as_mut().is_some_and(|compositor| compositor.prewarm_pickup(device, ts)) + } + /// Whether `program`'s pipelines are compiled (starting them otherwise): with asynchronous /// compiles, a composite first waits for this. An error when their compile failed. fn composite_pipelines_ready(&mut self, device: &wgpu::Device, program: &CompositeProgram) -> Result { @@ -1725,6 +1779,11 @@ impl Renderer { self.compositor.get_or_insert_with(|| Self::new_compositor(device, compile)).pipelines_ready(device, program) } + /// How much GPU memory the compositor's cached inputs may hold: the setting, or automatic + pub fn set_memory_budget(&mut self, budget: crate::gpu_memory::GpuMemoryBudget) { + self.memory_budget = budget; + } + /// Composite a supported layer stack or standalone mask into the viewport's textures. /// Scratch holds one band. The final maps stay on the adapter for shading and mip generation. pub fn composite_on_gpu(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, ts: usize, program: &CompositeProgram) -> Result<(), String> { @@ -1733,7 +1792,17 @@ impl Renderer { return Err(crate::gpu_composite::GPU_PIPELINES_PENDING.into()); } - if program.is_mask_preview() { + // A viewport program's variant is what a live clone or smudge stroke prewarms from + if !program.is_neutral() + && !program.is_mask_preview() + && !program.is_thumbnail() + && let Some(compositor) = &mut self.compositor + { + compositor.remember_variant(ts, program); + } + + // A layer thumbnail is one RGBA8 view, as the mask preview is + if program.is_mask_preview() || program.is_thumbnail() { return self.composite_mask_preview(device, queue, ts, program); } @@ -1751,6 +1820,7 @@ impl Renderer { })?; let set = &mut self.sets[ts]; set.pending_seed = None; + set.written = true; // A replaced slot's earlier allocation failure no longer holds: later tiles may grow it for (i, texture) in textures.into_iter().enumerate() { @@ -1776,44 +1846,81 @@ impl Renderer { let mut submitted = None; let mut in_place = [false; DisplayKind::ALL.len()]; let compile = (self.asynchronous_compile, self.shared_test_pipelines); - let mut compositor = self.compositor.take().unwrap_or_else(|| Self::new_compositor(device, compile)); - let result = crate::gpu_trace::scoped(device, "viewport GPU composite", || { - let mut maps: Vec<_> = DisplayKind::ALL - .iter() - .zip(&self.default_texels) - .zip(&set.tex) - .map(|((&kind, neutral), old)| { - let composed = program.writes_display(kind); - let extent = if composed { size } else { (1, 1) }; - - // A 1×1 inactive map can still hold a painted texel - if extent == (old.texture.width(), old.texture.height()) && (composed || size != (1, 1)) { - in_place[kind as usize] = composed; - old.clone() - } else if composed && region.is_none() { - Tex::new(device, "tc_composite", extent.0, extent.1, display_format(kind), mip_count(extent.0.max(extent.1))) - } else { - neutral_tex(device, queue, extent, display_format(kind), mip_count(extent.0.max(extent.1)), neutral) - } - }) - .collect(); - let targets: &[Tex; DisplayKind::ALL.len()] = maps.as_slice().try_into().map_err(|_| "The GPU display textures are missing.")?; - compositor.compose( - (device, queue), - program, - (ts, set.size, set.shift, region), - &targets.each_ref().map(|target| &target.texture), - &mut submitted, - )?; - maps.extend(set.tex.last().cloned()); - Ok::<_, String>(maps) - }); - let textures = match Self::keep_compositor_unless_gpu_failed(&mut self.compositor, compositor, result) { - Ok(textures) => textures, - Err(error) => { + let budget = self.memory_budget.bytes(); + let mut retried = false; + let mut out_of_memory = None; + let textures = loop { + let set = self.sets.get(ts).ok_or("texture set does not exist")?; + let mut compositor = self.compositor.take().unwrap_or_else(|| Self::new_compositor(device, compile)); + compositor.memory_budget = budget; + if !retried { + compositor.paint_word_limit = None; + } + compositor.make_room(ts); + let result = crate::gpu_trace::scoped(device, "viewport GPU composite", || { + let mut maps: Vec<_> = DisplayKind::ALL + .iter() + .zip(&self.default_texels) + .zip(&set.tex) + .map(|((&kind, neutral), old)| { + let composed = program.writes_display(kind); + let extent = if composed { size } else { (1, 1) }; + + // A 1×1 inactive map can still hold a painted texel + if extent == (old.texture.width(), old.texture.height()) && (composed || size != (1, 1)) { + in_place[kind as usize] = composed; + old.clone() + } else if composed && region.is_none() { + Tex::new(device, "tc_composite", extent.0, extent.1, display_format(kind), mip_count(extent.0.max(extent.1))) + } else { + neutral_tex(device, queue, extent, display_format(kind), mip_count(extent.0.max(extent.1)), neutral) + } + }) + .collect(); + let targets: &[Tex; DisplayKind::ALL.len()] = maps.as_slice().try_into().map_err(|_| "The GPU display textures are missing.")?; + compositor.compose( + (device, queue), + program, + (ts, set.size, set.shift, region), + &targets.each_ref().map(|target| &target.texture), + &mut submitted, + )?; + maps.extend(set.tex.last().cloned()); + compositor.make_room(ts); + Ok::<_, String>(maps) + }); + #[cfg(any(test, feature = "test-support"))] + let result = match self.failing_gpu_attempts.checked_sub(1) { + Some(left) => { + self.failing_gpu_attempts = left; + Err(crate::gpu_memory::out_of_memory_error("a test composite", "simulated")) + } + None => result, + }; + let result = unsplittable_paint_is_out_of_memory(result, out_of_memory.as_ref()); + let out_of_memory_now = matches!(&result, Err(error) | Ok(Err(error)) if crate::gpu_memory::is_out_of_memory(error)); + + // Free every cached input of every set, keeping the compiled pipelines, and try once + // more with half the paint window + if out_of_memory_now && !retried { + out_of_memory = first_error(&result); let slots = in_place.into_iter().enumerate().filter_map(|(slot, reused)| reused.then_some(slot)); - self.invalidate_gpu_writes(ts, submitted, slots); - return Err(error); + self.invalidate_gpu_writes(ts, submitted.take(), slots); + compositor.release_all_inputs(); + compositor.halve_paint_windows(); + self.compositor = Some(compositor); + retried = true; + in_place = [false; DisplayKind::ALL.len()]; + continue; + } + + match Self::keep_compositor_unless_gpu_failed(&mut self.compositor, compositor, result) { + Ok(textures) => break textures, + Err(error) => { + let slots = in_place.into_iter().enumerate().filter_map(|(slot, reused)| reused.then_some(slot)); + self.invalidate_gpu_writes(ts, submitted.take(), slots); + return Err(error); + } } }; if let Some(set) = self.sets.get_mut(ts) { @@ -1833,6 +1940,7 @@ impl Renderer { set.pending.iter_mut().take(DisplayKind::ALL.len()).for_each(|slot| *slot = None); set.failed.iter_mut().take(DisplayKind::ALL.len()).for_each(|failed| *failed = false); set.pending_seed = None; + set.written = true; set.bind_group = set_bind_group(device, &self.set_bgl, &self.sampler, &set.tex); self.content_rev += 1; } @@ -1847,33 +1955,72 @@ impl Renderer { let set = self.sets.get(ts).ok_or("texture set does not exist")?; let slot = DisplayKind::ALL.len(); let old = set.tex.get(slot).ok_or("The GPU aux texture is missing.")?; - let shift = mask_view_shift(set.size); - let (width, height) = mask_view_extent(set.size); + let shift = set.shift; + let (width, height) = aux_extent(set.size, shift); // The GPU reads every 2^shift-th texel: the CPU's nearest texel only when both sides divide if (width << shift, height << shift) != set.size { return Err("The mask preview layout uses CPU compositing.".into()); } - let reuse = (old.texture.width(), old.texture.height()) == (width, height); + let mut reuse = (old.texture.width(), old.texture.height()) == (width, height); let region = if reuse { program.region } else { None }; let mut submitted = None; let compile = (self.asynchronous_compile, self.shared_test_pipelines); - let mut compositor = self.compositor.take().unwrap_or_else(|| Self::new_compositor(device, compile)); - let result = crate::gpu_trace::scoped(device, "viewport GPU mask preview", || { - let tex = if reuse { - old.clone() - } else { - Tex::new(device, "tc_gpu_mask_preview", width, height, wgpu::TextureFormat::Rgba8Unorm, mip_count(width.max(height))) + let budget = self.memory_budget.bytes(); + let mut retried = false; + let mut out_of_memory = None; + + // The viewport composite's budget and recovery: evict other sets' inputs past the budget, + // and after running out of GPU memory free every cached input and try once more + let tex = loop { + let set = self.sets.get(ts).ok_or("texture set does not exist")?; + let old = set.tex.get(slot).ok_or("The GPU aux texture is missing.")?; + let mut compositor = self.compositor.take().unwrap_or_else(|| Self::new_compositor(device, compile)); + compositor.memory_budget = budget; + if !retried { + compositor.paint_word_limit = None; + } + compositor.make_room(ts); + let result = crate::gpu_trace::scoped(device, "viewport GPU mask preview", || { + let tex = if reuse { + old.clone() + } else { + Tex::new(device, "tc_gpu_mask_preview", width, height, wgpu::TextureFormat::Rgba8Unorm, mip_count(width.max(height))) + }; + compositor.compose((device, queue), program, (ts, set.size, shift, region.filter(|_| reuse)), &[&tex.texture], &mut submitted)?; + compositor.make_room(ts); + Ok::<_, String>(tex) + }); + #[cfg(any(test, feature = "test-support"))] + let result = match self.failing_gpu_attempts.checked_sub(1) { + Some(left) => { + self.failing_gpu_attempts = left; + Err(crate::gpu_memory::out_of_memory_error("a test mask preview", "simulated")) + } + None => result, }; - compositor.compose((device, queue), program, (ts, set.size, shift, region), &[&tex.texture], &mut submitted)?; - Ok::<_, String>(tex) - }); - let tex = match Self::keep_compositor_unless_gpu_failed(&mut self.compositor, compositor, result) { - Ok(tex) => tex, - Err(error) => { - self.invalidate_gpu_writes(ts, submitted, reuse.then_some(slot)); - return Err(error); + let result = unsplittable_paint_is_out_of_memory(result, out_of_memory.as_ref()); + let out_of_memory_now = matches!(&result, Err(error) | Ok(Err(error)) if crate::gpu_memory::is_out_of_memory(error)); + if out_of_memory_now && !retried { + out_of_memory = first_error(&result); + self.invalidate_gpu_writes(ts, submitted.take(), reuse.then_some(slot)); + compositor.release_all_inputs(); + compositor.halve_paint_windows(); + self.compositor = Some(compositor); + retried = true; + + // The aux texture may hold a partial write: compose the whole preview into a new one + reuse = false; + continue; + } + + match Self::keep_compositor_unless_gpu_failed(&mut self.compositor, compositor, result) { + Ok(tex) => break tex, + Err(error) => { + self.invalidate_gpu_writes(ts, submitted, reuse.then_some(slot)); + return Err(error); + } } }; let set = &mut self.sets[ts]; @@ -1975,6 +2122,14 @@ impl Renderer { self.replace_display_seed(device, queue, ts, Some(textures)); } + /// [`Self::seed_display`] for an overview made off the UI thread: only while no composite + /// or display tile has written the set's textures since it was created (newer content wins) + pub fn seed_display_unless_written(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, ts: usize, size: (u32, u32), maps: &[(DisplayKind, Vec)]) { + if self.sets.get(ts).is_some_and(|set| !set.written) { + self.seed_display(device, queue, ts, size, maps); + } + } + fn replace_display_seed(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, ts: usize, textures: Option>>) { let Some(set) = self.sets.get_mut(ts) else { return }; let pending = match textures { @@ -2132,6 +2287,7 @@ impl Renderer { drop(validation_scope); drop(out_of_memory_scope); self.content_rev += 1; + set.written = true; if let Some(d) = set.mips_dirty.get_mut(kind_index) { d.add(origin_x, origin_y, origin_x + w, origin_y + h); } @@ -2160,20 +2316,48 @@ impl Renderer { return Err("The Quick Mask coverage does not match the texture set.".into()); } - let size = aux_size(set.size); + let extent = aux_extent(set.size, set.shift); let slot = DisplayKind::ALL.len(); - let old = set.tex.get(slot).ok_or("The GPU aux texture is missing.")?; - let reused = (old.texture.width(), old.texture.height()) == (size, size); - let (gpu, tex) = crate::gpu_trace::scoped(device, "GPU Quick Mask overlay", || { - let mut gpu = self.quick_mask.take().unwrap_or_else(|| QuickMaskGpu::new(device)); - let aux = if reused { old.clone() } else { Tex::new(device, "tc_quick_mask", size, size, wgpu::TextureFormat::Rgba8Unorm, mip_count(size)) }; - let view = aux.texture.create_view(&wgpu::TextureViewDescriptor { mip_level_count: Some(1), ..Default::default() }); - let bindings = gpu.bindings((device, queue), ts, size, &set.tex[DisplayKind::BaseColor as usize].view, overlay); - let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_quick_mask") }); - fullscreen(&mut encoder, "tc_quick_mask", &view, CLEAR, &gpu.pipeline, &bindings); - queue.submit([encoder.finish()]); - (gpu, aux) - })?; + let mut retried = false; + + // Out of GPU memory: free the uploaded coverage and the compositor's cached inputs, and + // try once more on the GPU + let (gpu, tex, reused) = loop { + let set = self.sets.get(ts).ok_or("texture set does not exist")?; + let old = set.tex.get(slot).ok_or("The GPU aux texture is missing.")?; + let reused = (old.texture.width(), old.texture.height()) == extent; + let result = crate::gpu_trace::scoped(device, "GPU Quick Mask overlay", || { + let mut gpu = self.quick_mask.take().unwrap_or_else(|| QuickMaskGpu::new(device)); + let aux = if reused { + old.clone() + } else { + Tex::new(device, "tc_quick_mask", extent.0, extent.1, wgpu::TextureFormat::Rgba8Unorm, mip_count(extent.0.max(extent.1))) + }; + let view = aux.texture.create_view(&wgpu::TextureViewDescriptor { mip_level_count: Some(1), ..Default::default() }); + let bindings = gpu.bindings((device, queue), ts, extent, &set.tex[DisplayKind::BaseColor as usize].view, overlay); + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_quick_mask") }); + fullscreen(&mut encoder, "tc_quick_mask", &view, CLEAR, &gpu.pipeline, &bindings); + queue.submit([encoder.finish()]); + (gpu, aux) + }); + #[cfg(any(test, feature = "test-support"))] + let result = match self.failing_gpu_attempts.checked_sub(1) { + Some(left) => { + self.failing_gpu_attempts = left; + Err(crate::gpu_memory::out_of_memory_error("a test Quick Mask overlay", "simulated")) + } + None => result, + }; + match result { + Ok((gpu, tex)) => break (gpu, tex, reused), + Err(error) if crate::gpu_memory::is_out_of_memory(&error) && !retried => { + self.quick_mask = None; + self.release_all_composite_inputs(); + retried = true; + } + Err(error) => return Err(error), + } + }; self.quick_mask = Some(gpu); let set = &mut self.sets[ts]; set.pending[slot] = None; @@ -2187,21 +2371,127 @@ impl Renderer { Ok(()) } - /// Upload the aux (mesh map / debug) texture of a set: RGBA8, `size × size` with `size` from - /// [`aux_size`]. The first upload allocates it. - pub fn upload_aux(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, texture_set: usize, size: u32, rgba: &[u8]) { - self.upload_aux_sized(device, queue, texture_set, (size, size), rgba); + /// Draw `source` into the aux texture of set `ts` at its [`aux_extent`] on the GPU: the + /// mesh-map, image and ID-mask views where layers composite on the GPU. Running out of GPU + /// memory frees the uploaded view sources and the compositor's cached inputs and tries once + /// more; another failure is returned. + pub fn draw_aux_view(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, ts: usize, source: &AuxSource) -> Result<(), String> { + let set = self.sets.get(ts).ok_or("texture set does not exist")?; + let (extent, working) = (aux_extent(set.size, set.shift), set.size); + let slot = DisplayKind::ALL.len(); + let mut retried = false; + let tex = loop { + let set = self.sets.get(ts).ok_or("texture set does not exist")?; + let old = set.tex.get(slot).ok_or("The GPU aux texture is missing.")?; + // The pass overwrites every texel, so even the retry draws into the installed texture + let reuse = (old.texture.width(), old.texture.height()) == extent; + let mut gpu = self.aux_view.take().unwrap_or_else(|| AuxViewGpu::new(device)); + let result = crate::gpu_trace::scoped(device, "GPU aux view", || { + let aux = if reuse { + old.clone() + } else { + Tex::new(device, "tc_aux_view", extent.0, extent.1, wgpu::TextureFormat::Rgba8Unorm, mip_count(extent.0.max(extent.1))) + }; + let view = aux.texture.create_view(&wgpu::TextureViewDescriptor { mip_level_count: Some(1), ..Default::default() }); + let mut encoder = device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_aux_view") }); + match (source, gpu.bindings((device, queue), source, extent, working)) { + (_, Some(bindings)) => fullscreen(&mut encoder, "tc_aux_view", &view, CLEAR, &gpu.pipeline, &bindings), + (AuxSource::Fill(rgba), None) => { + let channel = |k: usize| f64::from(rgba[k]) / 255.0; + let color = wgpu::Color { r: channel(0), g: channel(1), b: channel(2), a: channel(3) }; + encoder.begin_render_pass(&wgpu::RenderPassDescriptor { + label: Some("tc_aux_view_fill"), + color_attachments: &[Some(wgpu::RenderPassColorAttachment { + view: &view, + resolve_target: None, + depth_slice: None, + ops: wgpu::Operations { load: wgpu::LoadOp::Clear(color), store: wgpu::StoreOp::Store }, + })], + depth_stencil_attachment: None, + timestamp_writes: None, + occlusion_query_set: None, + multiview_mask: None, + }); + } + (_, None) => {} + } + queue.submit([encoder.finish()]); + aux + }); + #[cfg(any(test, feature = "test-support"))] + let result = match self.failing_gpu_attempts.checked_sub(1) { + Some(left) => { + self.failing_gpu_attempts = left; + Err(crate::gpu_memory::out_of_memory_error("a test aux view", "simulated")) + } + None => result, + }; + match result { + Ok(tex) => { + self.aux_view = Some(gpu); + break (tex, reuse); + } + Err(error) if crate::gpu_memory::is_out_of_memory(&error) && !retried => { + gpu.release_sources(); + self.aux_view = Some(gpu); + self.release_all_composite_inputs(); + retried = true; + } + // The caller reports the error; no CPU view replaces it + Err(error) => { + gpu.release_sources(); + self.aux_view = Some(gpu); + return Err(error); + } + } + }; + let (tex, reused) = tex; + let set = &mut self.sets[ts]; + set.pending[slot] = None; + set.failed[slot] = false; + if reused { + set.mips_dirty[slot] = MipsDirty::All; + } else { + install(set, slot, tex, device, &self.set_bgl, &self.sampler); + } + self.content_rev += 1; + Ok(()) + } + + /// Tests: whether the GPU brush keeps surface covers + #[cfg(all(test, not(target_arch = "wasm32")))] + pub(crate) fn has_brush_covers(&self) -> bool { + self.brush.as_ref().is_some_and(crate::gpu_brush::BrushPipeline::has_covers) + } + + /// Tests: the side of the library alpha the GPU brush generated last + #[cfg(all(test, not(target_arch = "wasm32")))] + pub(crate) fn library_tip_side(&self) -> Option { + self.brush.as_ref().and_then(crate::gpu_brush::BrushPipeline::library_tip_side) + } + + /// Tests: make the next `attempts` composites, mask previews, aux views or GPU brush starts + /// run out of GPU memory (two outlast the one retry) + #[cfg(any(test, feature = "test-support"))] + pub fn fail_next_gpu_attempts(&mut self, attempts: u32) { + self.failing_gpu_attempts = attempts; + } + + /// Drop the view sources [`Renderer::draw_aux_view`] uploaded (the aux view is no longer shown). + pub fn release_aux_view_sources(&mut self) { + if let Some(gpu) = &mut self.aux_view { + gpu.release_sources(); + } } - /// [`Renderer::upload_aux`] at `extent` (width, height): `aux_size` × `aux_size`, or the - /// mask view's [`mask_view_extent`]. - pub fn upload_aux_sized(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, texture_set: usize, extent: (u32, u32), rgba: &[u8]) { + /// Upload the aux (mesh map / mask / debug) texture of a set produced on the CPU: RGBA8 at + /// its [`aux_extent`]. The first upload allocates it. + pub fn upload_aux(&mut self, device: &wgpu::Device, queue: &wgpu::Queue, texture_set: usize, extent: (u32, u32), rgba: &[u8]) { let Some(set) = self.sets.get_mut(texture_set) else { return }; - let square = aux_size(set.size); let aux_index = set.tex.len().saturating_sub(1); let Some(texture) = set.tex.last() else { return }; let (width, height) = extent; - let known = extent == (square, square) || extent == mask_view_extent(set.size); + let known = extent == aux_extent(set.size, set.shift); if !known || rgba.len() < (width as usize) * (height as usize) * 4 { return; } @@ -2307,9 +2597,14 @@ impl Renderer { } } - /// Size of the aux texture of a set (1 until a mesh map or mask was shown). - pub fn aux_size(&self, ts: usize) -> Option { - self.aux_texture(ts).map(wgpu::Texture::width) + /// The display size of texture set `ts`: its size halved by its display shift + pub fn display_extent(&self, ts: usize) -> Option<(u32, u32)> { + self.sets.get(ts).map(|set| display_dims(set.size, set.shift)) + } + + /// Width and height of the aux texture of a set ((1, 1) until a mesh map or mask was shown). + pub fn aux_extent(&self, ts: usize) -> Option<(u32, u32)> { + self.aux_texture(ts).map(|texture| (texture.width(), texture.height())) } pub fn aux_texture(&self, ts: usize) -> Option<&wgpu::Texture> { @@ -2518,7 +2813,8 @@ impl Renderer { } fn targets(&mut self, device: &wgpu::Device, id: u64, size: [u32; 2], bloom: bool, fx: bool, refraction: bool) -> Option<&mut ViewTargets> { - let size = [size[0].clamp(1, 8192), size[1].clamp(1, 8192)]; + let side = device.limits().max_texture_dimension_2d; + let size = [size[0].clamp(1, side), size[1].clamp(1, side)]; if self.views.get(&id).is_none_or(|v| v.size != size) { let v = self.create_targets(device, size); self.views.insert(id, v); @@ -3219,29 +3515,155 @@ fn highlight_shift(size: [u32; 2]) -> [f32; 4] { [half_extra_width * clip_per_pixel[0], half_extra_width * clip_per_pixel[1], 0.0, 0.0] } +/// The memory retry's error when its halved paint window cannot split one texel's or one +/// row's paint (a refusal would send the set to the CPU for what was a memory error) +fn unsplittable_paint_is_out_of_memory(result: Result, String>, out_of_memory: Option<&String>) -> Result, String> { + let unsplittable = + |error: &String| error.starts_with("Paint inputs for one GPU texel exceed") || error.starts_with("Paint inputs of the whole-set filter exceed"); + match (result, out_of_memory) { + (Err(error), Some(first)) if unsplittable(&error) => Err(first.clone()), + (Ok(Err(error)), Some(first)) if unsplittable(&error) => Ok(Err(first.clone())), + (result, _) => result, + } +} + +/// The error of a failed attempt +fn first_error(result: &Result, String>) -> Option { + match result { + Err(error) | Ok(Err(error)) => Some(error.clone()), + Ok(Ok(_)) => None, + } +} + #[cfg(test)] mod tests { use super::*; use crate::headless::Headless; - /// The mask view halves a set until its longer side fits 2048 texels, keeping its shape: a - /// classic square set as before, a grid of UV tiles one square per block. + /// A composite or mask preview that runs out of GPU memory frees the compositor's caches and + /// composites again on the GPU instead of failing #[test] - fn the_mask_view_halves_a_set_until_it_fits() { - let cases = [ - ((1024, 1024), (1024, 1024)), - ((4096, 4096), (2048, 2048)), - ((128, 64), (128, 64)), - ((3072, 1024), (1536, 512)), - ((6144, 4096), (1536, 1024)), - ((3000, 3000), (1500, 1500)), - ]; + fn a_composite_out_of_gpu_memory_frees_caches_and_retries() { + let Some(mut h) = Headless::for_required_tests() else { return }; + let mut project = texturecraft_core::Project::new("Memory retry", "builtin:plane"); + project.texture_sets.push(texturecraft_core::TextureSet::new("Plane", 0, 64)); + let id = project.alloc_id(); + let color = texturecraft_core::Source::Uniform([0.6, 0.3, 0.2]); + let fill = texturecraft_core::Fill { sources: [(texturecraft_core::Channel::BaseColor, color)].into(), ..Default::default() }; + let mut layer = texturecraft_core::Layer::new(id, "Fill", texturecraft_core::LayerKind::Fill(fill), &[texturecraft_core::Channel::BaseColor]); + layer.mask = Some(texturecraft_core::Mask::new(texturecraft_core::MaskBackground::White)); + project.insert_layer(0, layer, None, false).unwrap(); + let material = crate::gpu_composite::CompositeProgram::try_compile_region(&project, &Default::default(), 0, None).unwrap(); + let mask = crate::gpu_composite::CompositeProgram::try_compile_mask_preview(&project, &Default::default(), 0, id, None, None).unwrap(); + h.renderer.set_texture_sets(&h.device, &h.queue, &[((64, 64), 0), ((64, 64), 0)], 1); + for (label, program) in [("composite", &material), ("mask preview", &mask)] { + h.renderer.composite_on_gpu(&h.device, &h.queue, 1, program).unwrap(); + + h.renderer.fail_next_gpu_attempts(1); + let result = h.renderer.composite_on_gpu(&h.device, &h.queue, 0, program); + + assert_eq!(result, Ok(()), "the {label} retries on the GPU"); + assert_eq!(h.renderer.failing_gpu_attempts, 0, "the {label} met the refusal"); + let compositor = h.renderer.compositor.as_ref().unwrap(); + assert!(!compositor.last_use.contains_key(&1), "the {label} freed the other set's cached inputs"); + assert!(compositor.last_use.contains_key(&0), "the {label} counts toward the budget"); + } + } - for (size, extent) in cases { - assert_eq!(mask_view_extent(size), extent, "{size:?}"); - let shift = mask_view_shift(size); + /// A picked clone or smudge tool starts compiling the variant its live stroke composites + /// with: the set's last composite's, with the brush package (`brush::uses_shader`, which a + /// stroke's carried values turn on, is the only feature they change) + #[test] + fn a_pickup_prewarm_compiles_the_live_brush_variant_of_the_last_composite() { + use texturecraft_core::{Channel, Layer, LayerKind, Project, TextureSet}; + let Some(mut h) = Headless::for_required_tests() else { return }; + let size = 64; + let mut project = Project::new("Pickup prewarm", "builtin:plane"); + project.texture_sets.push(TextureSet::new("Plane", 0, size)); + let id = project.alloc_id(); + project.insert_layer(0, Layer::new(id, "Paint", LayerKind::Paint, &[Channel::BaseColor]), None, false).unwrap(); + let mut pixels = texturecraft_compose::PixelStore::default(); + pixels.layer_mut(id, Channel::BaseColor, (size, size)).set(3, 4, &[40_000, 20_000, 10_000, 65_535]); + let mesh = std::sync::Arc::new(texturecraft_geom::primitives::plane(1.0, 1)); + let gbuf = std::sync::Arc::new(texturecraft_geom::UvGBuffer::new(&mesh, 0, size, size)); + let mut program = crate::gpu_composite::CompositeProgram::try_compile_region(&project, &pixels, 0, None).unwrap(); + program.set_surface_inputs(&mesh, &gbuf, None).unwrap(); + + // The app's renderer: its own pipelines, compiled on worker threads + h.renderer.shared_test_pipelines = false; + h.renderer.set_asynchronous_compile(true); + h.renderer.set_texture_sets(&h.device, &h.queue, &[((size, size), 0)], 1); + let mut composited = h.renderer.composite_on_gpu(&h.device, &h.queue, 0, &program); + for _ in 0..6000 { + if composited.as_ref().err().map(String::as_str) != Some(crate::gpu_composite::GPU_PIPELINES_PENDING) { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + composited = h.renderer.composite_on_gpu(&h.device, &h.queue, 0, &program); + } + assert_eq!(composited, Ok(())); + assert!(!h.renderer.compositor.as_ref().unwrap().has_pickup_variant(0)); + + let mut ready = h.renderer.prewarm_pickup_composite(&h.device, 0); + assert!(h.renderer.compositor.as_ref().unwrap().has_pickup_variant(0), "the live clone/smudge variant compiles ahead"); + + // Its worker finishes before the device goes away + for _ in 0..6000 { + if ready { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + ready = h.renderer.prewarm_pickup_composite(&h.device, 0); + } + assert!(ready); + } + + /// The memory retry uploads paint in windows of half the size the failed attempt used, + /// instead of asking for the same window again + #[test] + fn a_composite_out_of_gpu_memory_retries_with_half_the_paint_window() { + use texturecraft_core::{Channel, Layer, LayerKind, Project, TextureSet}; + let Some(mut h) = Headless::for_required_tests() else { return }; + let size = 256; + let mut project = Project::new("Paint window retry", "builtin:plane"); + project.texture_sets.push(TextureSet::new("Plane", 0, size)); + let id = project.alloc_id(); + project.insert_layer(0, Layer::new(id, "Paint", LayerKind::Paint, &[Channel::BaseColor]), None, false).unwrap(); + let mut pixels = texturecraft_compose::PixelStore::default(); + for y in 0..size { + for x in 0..size { + pixels.layer_mut(id, Channel::BaseColor, (size, size)).set(x, y, &[40_000, 20_000, 10_000, 65_535]); + } + } + let mesh = std::sync::Arc::new(texturecraft_geom::primitives::plane(1.0, 1)); + let gbuf = std::sync::Arc::new(texturecraft_geom::UvGBuffer::new(&mesh, 0, size, size)); + let mut program = crate::gpu_composite::CompositeProgram::try_compile_region(&project, &pixels, 0, None).unwrap(); + program.set_surface_inputs(&mesh, &gbuf, None).unwrap(); + h.renderer.set_texture_sets(&h.device, &h.queue, &[((size, size), 0)], 1); + h.renderer.composite_on_gpu(&h.device, &h.queue, 0, &program).unwrap(); + let whole = h.renderer.compositor.as_ref().unwrap().largest_paint_words; + assert!(whole > 0); + + h.renderer.fail_next_gpu_attempts(1); + let result = h.renderer.composite_on_gpu(&h.device, &h.queue, 0, &program); + + assert_eq!(result, Ok(())); + let retried = h.renderer.compositor.as_ref().unwrap().largest_paint_words; + assert!(retried > 0 && retried <= whole / 2, "the retry's window {retried} is not half of {whole}"); + h.renderer.composite_on_gpu(&h.device, &h.queue, 0, &program).unwrap(); + assert_eq!(h.renderer.compositor.as_ref().unwrap().largest_paint_words, whole, "the next composite binds what the device binds again"); + } + + /// The mask view shows a large set at its display size, halved only by the display shift or + /// the device's texture limit: every 2^shift-th texel, as the CPU samples it, in the set's shape. + #[test] + fn the_mask_view_keeps_the_display_size() { + for (size, display_shift, max_side, shift) in [((8192, 8192), 0, 16384, 0), ((6144, 4096), 1, 16384, 1), ((16384, 8192), 0, 8192, 1)] { + assert_eq!(set_shift(size, display_shift, max_side), shift, "{size:?}"); + let extent = aux_extent(size, shift); assert_eq!((extent.0 << shift, extent.1 << shift), size, "{size:?}: every 2^shift-th texel, as the CPU samples it"); } + assert_eq!(set_shift((u32::MAX, 1), 0, 1), 31, "the last shift that fits counts too"); } #[test] diff --git a/crates/render/src/shaders/alpha_gen.wgsl b/crates/render/src/shaders/alpha_gen.wgsl new file mode 100644 index 000000000..13ed9a67e --- /dev/null +++ b/crates/render/src/shaders/alpha_gen.wgsl @@ -0,0 +1,315 @@ +// The built-in library alphas (paint/src/alphas.rs) generated on the GPU: one generator per kind, +// ported from the CPU closures, which stay the GPU-off path and the oracle. Needs noise.wgsl. + +struct Alpha { + // kind (the generator's place in SHAPES, 31 for letters), side, seed, item count + header: vec4, + // the generator's settings (LibraryAlpha::gpu_spec) + values: array, 2>, + // the edge width in stamp units (f32 bits), the band's first row + band: vec4, +} + +@group(0) @binding(0) var alpha: Alpha; +@group(0) @binding(1) var items: array>; +@group(0) @binding(2) var level_out: texture_storage_2d; +@group(0) @binding(3) var level_in: texture_2d; + +const PI: f32 = 3.14159265358979; +const TAU: f32 = 6.28318530717959; + +fn value_at(i: u32) -> f32 { + return alpha.values[i / 4u][i % 4u]; +} + +// The CPU's smoothstep (brush.rs): a degenerate range still steps +fn step_smooth(e0: f32, e1: f32, x: f32) -> f32 { + let t = clamp((x - e0) / max(e1 - e0, 1e-6), 0.0, 1.0); + return t * t * (3.0 - 2.0 * t); +} + +fn soft_fill(d: f32, softness: f32) -> f32 { + return clamp(0.5 - d / (bitcast(alpha.band.x) * softness), 0.0, 1.0); +} + +fn fill(d: f32) -> f32 { + return soft_fill(d, 1.0); +} + +// Distance from p to segment a–b, and the position 0..1 of the closest point along it +fn seg(p: vec2, a: vec2, b: vec2) -> vec2 { + let d = b - a; + let t = clamp(dot(p - a, d) / max(dot(d, d), 1e-12), 0.0, 1.0); + return vec2(length(p - a - d * t), t); +} + +fn ngon(p: vec2, n: u32, apothem: f32, phase: f32) -> f32 { + var most = -3.40282347e38; + for (var k = 0u; k < n; k++) { + let t = phase + f32(k) * TAU / f32(n); + most = max(most, p.x * cos(t) + p.y * sin(t)); + } + return most - apothem; +} + +// pow with the CPU's value at a zero base +fn power(base: f32, exponent: f32) -> f32 { + return select(pow(base, exponent), 0.0, base <= 0.0); +} + +fn star(p: vec2, k: f32, inner: f32, outer: f32, curve: f32) -> f32 { + let t = abs(fract(atan2(p.x, p.y) / (TAU / k)) - 0.5) * 2.0; + return fill(length(p) - (inner + (outer - inner) * power(t, curve))); +} + +fn fade(p: vec2) -> f32 { + return 1.0 - step_smooth(0.55, 0.97, length(p)); +} + +fn dome(r: f32, radius: f32, softness: f32) -> f32 { + let q = r / radius; + return 0.35 * soft_fill(r - radius, softness) + 0.65 * sqrt(max(1.0 - q * q, 0.0)); +} + +fn perlin_fbm(p: vec3, octaves: u32, seed: u32) -> f32 { + return fbm(p, clamp(octaves, 1u, 12u), seed, true); +} + +fn value_fbm(p: vec3, octaves: u32, seed: u32) -> f32 { + return fbm(p, clamp(octaves, 1u, 12u), seed, false); +} + +// As composite_patterns.wgsl's cellular with details: nearest and second distances and the id +fn cellular_noise(p: vec3, seed: u32) -> vec3 { + let cell = vec3(floor(p)); + let local = fract(p); + var nearest = 4.0; + var second = 4.0; + var feature_id = 0u; + for (var z = -1; z <= 1; z++) { + for (var y = -1; y <= 1; y++) { + for (var x = -1; x <= 1; x++) { + let shift = vec3(x, y, z); + let bits = hash(cell + shift, seed * 0xc2b2ae35u); + let delta = vec3(shift) + vec3(bits) / 4294967296.0 - local; + let distance = dot(delta, delta); + if distance < nearest { + second = nearest; + nearest = distance; + feature_id = bits.x ^ bits.y; + } else if distance < second { + second = distance; + } + } + } + } + return vec3(min(sqrt(nearest), 1.0), min(sqrt(second), 1.0), f32(feature_id) / 4294967296.0); +} + +fn cell_hash(cell: vec3, seed: u32) -> f32 { + return f32(hash(cell, seed * 0x9e3779b9u).x) / 4294967296.0; +} + +// Rust's f32::round: halves away from zero +fn round_away(x: f32) -> f32 { + return sign(x) * floor(abs(x) + 0.5); +} + +fn shape(kind: u32, p: vec2) -> f32 { + let x = p.x; + let y = p.y; + let a = abs(p); + let r = length(p); + let seed = alpha.header.z; + let count = alpha.header.w; + let v0 = value_at(0u); + let v1 = value_at(1u); + let v2 = value_at(2u); + let v3 = value_at(3u); + switch kind { + // Basic + case 0u: { + let coverage = max(1.0 - (x * x + y * y), 0.0); + return select(power(coverage, 2.0 / v0), coverage * coverage, v0 == 1.0); + } + case 1u: { return soft_fill(r - 0.95, v0); } + case 2u: { return soft_fill(max(a.x, a.y) - 0.9, v0); } + case 3u: { return soft_fill(max(a.x - 0.95, a.y - 0.45), v0); } + case 4u: { return soft_fill(ngon(vec2(x, y + 0.24), 3u, 0.475, -PI / 2.0), v0); } + case 5u: { return soft_fill(ngon(p, 6u, 0.82, 0.0), v0); } + case 6u: { return fill(abs(r - 0.72) - v0); } + case 7u: { return fill(min(max(a.x - v0, a.y - 0.92), max(a.x - 0.92, a.y - v0))); } + case 8u: { return star(vec2(x, y + 0.06), 5.0, v0, 0.97, 1.0); } + case 9u: { return star(p, 4.0, v0, 0.97, 3.0); } + case 10u: { return star(p, 6.0, v0, 0.95, 1.0); } + case 11u: { return fill(min(max(max(a.x - v0, y - 0.15), -0.9 - y), ngon(vec2(x, y - 0.35), 3u, 0.25, -PI / 2.0))); } + case 12u: { + let center = clamp(floor((p + 0.9) / v1), vec2(0.0), vec2(v0 - 1.0)) * v1 - v3; + return fill(length(p - center) - v2); + } + + // Grunge + case 13u: { + var m = 0.0; + for (var i = 0u; i < count; i += 2u) { + let line = items[i]; + let look = items[i + 1u]; + let hit = seg(p, line.xy, line.zw); + let t = hit.y * 2.0 - 1.0; + m = max(m, fill(hit.x - look.x * sqrt(1.0 - t * t)) * look.y); + } + return m * fade(p); + } + case 14u: { + let uv = p * v0; + let w = perlin_fbm(vec3(uv * 3.0, 1.7), u32(v2), seed) - 0.5; + let cells = cellular_noise(vec3(uv * 3.5 + w * 0.8 * v3, 0.5), seed); + if cells.z >= 0.45 * v1 { return 0.0; } + let rough = value_fbm(vec3(uv * 14.0, 2.3), 3u, seed + 1u); + return fill(0.1 + 0.12 * rough - (cells.y - cells.x)) * fade(p); + } + case 15u: { + let angle = atan2(y, x); + let edge = 0.36 + 0.3 * (perlin_fbm(vec3(cos(angle) * 1.5 + 4.0, sin(angle) * 1.5, 0.0), 3u, seed) - 0.5) * v0; + var m = fill(r - edge); + for (var i = 0u; i < count; i++) { + let drop = items[i]; + m = max(m, fill(length(p - drop.xy) - drop.z)); + } + return m; + } + case 16u: { + let uv = p * v0; + let holes = cellular_noise(vec3(uv * 7.0, 0.3), seed).x; + let fine = cellular_noise(vec3(uv * 15.0, 1.1), seed + 3u).x; + let body = fill(r - 0.75 - 0.4 * (perlin_fbm(vec3(uv * 2.0, 0.8), 3u, seed) - 0.5) * v2); + return clamp((holes - (0.28 - 0.2 * (v1 - 1.0))) * 5.0, 0.0, 1.0) * clamp((fine - (0.2 - 0.15 * (v1 - 1.0))) * 4.0, 0.0, 1.0) * body; + } + case 17u: { + let uv = p * v0; + let spots = clamp((perlin_fbm(vec3(uv * 2.6, 3.1), u32(v2), seed) - (0.55 - 0.2 * (v1 - 1.0))) * 7.0, 0.0, 1.0); + let specks = clamp((noise(vec3(uv * 30.0, 0.5), seed, false) - (0.86 - 0.1 * (v1 - 1.0))) * 8.0, 0.0, 0.6); + return min(spots + specks, 1.0) * fade(p); + } + case 18u: { + let uv = p * v0; + let w = perlin_fbm(vec3(uv * 2.0, 5.0), 3u, seed) - 0.5; + let cells = cellular_noise(vec3(uv.x * 2.6 + w, uv.y * 2.6 + w * 0.7, 0.2), seed + 5u); + let line = 1.0 - step_smooth(0.015 * v1, 0.045 * v1, cells.y - cells.x); + let interruption = clamp((value_fbm(vec3(uv * 4.0, 7.0), 3u, seed + 2u) - 0.35 * v2) * 4.0, 0.0, 1.0); + return line * interruption * fade(p); + } + case 19u: { return clamp((noise(vec3(p * v0, 0.0), seed, false) - v1) * 10.0, 0.0, 1.0) * fade(p); } + + // Organic + case 20u: { + var m = 0.0; + for (var i = 0u; i < count; i += 4u) { + let bounds = items[i + 2u]; + if x < bounds.x || y < bounds.y || x > bounds.z || y > bounds.w { continue; } + var points = array, 4>(items[i].xy, items[i].zw, items[i + 1u].xy, items[i + 1u].zw); + let width = items[i + 3u].x; + for (var k = 0u; k < 3u; k++) { + let hit = seg(p, points[k], points[k + 1u]); + m = max(m, fill(hit.x - width * (1.0 - (f32(k) + hit.y) / 3.0))); + } + } + return m; + } + case 21u: { + let u = x * v3 - y * v2; + let v = x * v2 + y * v3; + let stem = fill(seg(vec2(u, v), vec2(0.0, -0.97), vec2(0.0, -0.8)).x - 0.015); + let t = (v + 0.85) / 1.7; + if !(t >= 0.0 && t <= 1.0) { return stem; } + let half = 0.38 * power(max(sin(PI * t), 0.0), 0.8) * (1.0 - 0.3 * t); + let q = (v - abs(u) * 0.8) * v0; + let vein = max(fill(abs(u) - 0.012 * v1), fill(abs(q - round_away(q)) / v0 - 0.006 * v1)); + return max(fill(abs(u) - half) * (1.0 - 0.45 * vein), stem); + } + case 22u: { + let d = length(vec2(x / 0.55, y)) + (perlin_fbm(vec3(p * 2.5, 9.0), 3u, seed) - 0.5) * 0.25 * v1; + let rings = 0.5 + 0.5 * cos(d * v0); + let core = 1.0 - step_smooth(0.12, 0.22, d); + return max(rings * 0.7, core) * (1.0 - step_smooth(0.7, 0.95, d)); + } + + // Hard surface + case 23u: { return dome(r, 0.7, v0); } + case 24u: { + return max(max(soft_fill(r - 0.95, v1) * 0.4, soft_fill(ngon(p, u32(v0), 0.7, 0.0), v1) * 0.75), soft_fill(r - 0.6, v1)); + } + case 25u: { return dome(r, 0.9, 1.0) * (1.0 - fill(max(a.y - v0, a.x - 0.7))); } + case 26u: { + let cut = min(max(a.y - v0, a.x - 0.5), max(a.x - v0, a.y - 0.5)); + return dome(r, 0.9, 1.0) * (1.0 - fill(cut)); + } + case 27u: { + var m = 0.0; + for (var i = 0u; i < u32(v0); i++) { + let cx = v3 + f32(i) * v1; + m = max(m, fill(seg(p, vec2(cx - 0.07, -0.2), vec2(cx + 0.07, 0.2)).x - v2)); + } + return m; + } + case 28u: { + var m = 0.0; + for (var i = 0u; i < u32(v0); i++) { + let cy = v3 + f32(i) * v1; + m = max(m, fill(seg(p, vec2(-0.7, cy), vec2(0.7, cy)).x - v2)); + } + return m; + } + case 29u: { + let uv = p * v0; + let cell = vec2(floor(uv)); + let over = ((cell.x + cell.y) & 1) == 0; + let thread = select(sin(PI * fract(uv.x)), sin(PI * fract(uv.y)), over); + return thread * fill(max(a.x, a.y) - 0.92); + } + case 30u: { + let v = y * v1; + let row = floor(v); + let u = x * v0 + select(0.0, 0.5, (i32(row) & 1) == 0); + let fu = fract(u); + let fv = fract(v); + let d = max((abs(fu - 0.5) - (0.47 - 0.03 * (v2 - 1.0))) / v0, (abs(fv - 0.5) - (0.44 - 0.06 * (v2 - 1.0))) / v1); + let tint = 0.7 + 0.3 * cell_hash(vec3(i32(floor(u)), i32(row), 0), seed); + return fill(d) * tint * fill(max(a.x, a.y) - 0.92); + } + + // Stencil letters + default: { + var nearest = 3.40282347e38; + for (var i = 0u; i < count; i++) { + nearest = min(nearest, seg(p, items[i].xy, items[i].zw).x); + } + return fill(nearest - 0.11 * v0); + } + } +} + +// The finest level: one sample at each texel's centre, as LibraryAlpha::render_configured +@compute @workgroup_size(8, 8) +fn generate(@builtin(global_invocation_id) id: vec3) { + let side = alpha.header.y; + let texel = vec2(id.x, id.y + alpha.band.y); + if texel.x >= side || texel.y >= side { return; } + + let centre = (vec2(texel) + 0.5) / f32(side); + let coverage = shape(alpha.header.x, vec2(centre.x * 2.0 - 1.0, 1.0 - centre.y * 2.0)); + let finite = coverage == coverage && abs(coverage) <= 3.40282347e38; + textureStore(level_out, vec2(texel), vec4(select(0.0, clamp(coverage, 0.0, 1.0), finite))); +} + +// The next level: the mean of each 2×2 block of the level above, as AlphaImage::new +@compute @workgroup_size(8, 8) +fn downsample(@builtin(global_invocation_id) id: vec3) { + let side = textureDimensions(level_out).x; + if id.x >= side || id.y >= side { return; } + + let at = vec2(id.xy) * 2; + let sum = textureLoad(level_in, at, 0).x + textureLoad(level_in, at + vec2(1, 0), 0).x + textureLoad(level_in, at + vec2(0, 1), 0).x + + textureLoad(level_in, at + vec2(1, 1), 0).x; + textureStore(level_out, vec2(id.xy), vec4(sum * 0.25)); +} diff --git a/crates/render/src/shaders/aux_view.wgsl b/crates/render/src/shaders/aux_view.wgsl new file mode 100644 index 000000000..38b005c55 --- /dev/null +++ b/crates/render/src/shaders/aux_view.wgsl @@ -0,0 +1,127 @@ +// The mesh-map, image and ID-mask views of a texture set's aux texture, sampled from their +// source texels as their CPU producers sample them (`mesh_maps::mesh_map_rgba`, +// `Session::image_view_rgba`, `Session::id_mask_view_rgba`) + +struct AuxParams { + // 0: mesh map through the block scales, 1: image bilinear, 2: ID mask image at texel centres + mode: u32, + // Values per source texel (1: scalar, shown gray) + components: u32, + // Tile block side of the block scales (0: every tile fills its block) + block: u32, + // Blocks across in the block scales + columns: u32, + // The aux texture's size + extent: vec2, + // The texture set's size + working: vec2, + // The source's size in texels + source: vec2, + // Entries in the block scales + scale_count: u32, + pad: u32, +} + +// The source's values, one float per texel in row order: a row-major array of `components` +// floats per source texel, wrapped across this texture's rows, then its layers +@group(0) @binding(0) var values: texture_2d_array; +@group(0) @binding(1) var scales: texture_2d; +@group(0) @binding(2) var params: AuxParams; + +@vertex +fn vs(@builtin(vertex_index) i: u32) -> @builtin(position) vec4 { + let corner = vec2(vec2(i << 1u, i) & vec2(2u)); + return vec4(corner * 2.0 - 1.0, 0.0, 1.0); +} + +fn value(index: u32) -> f32 { + let size = textureDimensions(values); + let row = index / size.x; + return textureLoad(values, vec2(index % size.x, row % size.y), row / size.y, 0).r; +} + +fn texel(x: u32, y: u32) -> vec3 { + let first = (min(y, params.source.y - 1u) * params.source.x + min(x, params.source.x - 1u)) * params.components; + if params.components == 1u { + return vec3(value(first)); + } + return vec3(value(first), value(first + 1u), value(first + 2u)); +} + +// `BlockScales::bake_uv`: the working atlas position in the uniform bake atlas, or none +// (negative) in a block's unused part +fn bake_uv(uv: vec2) -> vec2 { + if params.block == 0u { + return uv; + } + + let block = f32(params.block); + let position = vec2(uv.x * f32(params.working.x) / block, uv.y * f32(params.working.y) / block); + let origin = floor(position); + let column = u32(origin.x); + let row = u32(origin.y); + var scale = 1.0; + let index = row * params.columns + column; + if column < params.columns && index < params.scale_count { + scale = textureLoad(scales, vec2(index, 0u), 0).r; + } + let local = (position - origin) / scale; + if any(local < vec2(0.0)) || any(local >= vec2(1.0)) { + return vec2(-1.0); + } + return vec2((origin.x + local.x) * block / f32(params.working.x), (origin.y + local.y) * block / f32(params.working.y)); +} + +fn mesh_map(p: vec2) -> vec3 { + let uv = vec2((f32(p.x) + 0.5) / f32(params.extent.x), (f32(p.y) + 0.5) / f32(params.extent.y)); + let bake = bake_uv(uv); + if bake.x < 0.0 { + return vec3(0.5); + } + return texel(u32(bake.x * f32(params.source.x)), u32(bake.y * f32(params.source.y))); +} + +fn image(p: vec2) -> vec3 { + let u = max((f32(p.x) + 0.5) / f32(params.extent.x) * f32(params.source.x) - 0.5, 0.0); + let v = max((f32(p.y) + 0.5) / f32(params.extent.y) * f32(params.source.y) - 0.5, 0.0); + let x0 = u32(floor(u)); + let y0 = u32(floor(v)); + let fx = fract(u); + let fy = fract(v); + let a = texel(x0, y0); + let b = texel(x0 + 1u, y0); + let c = texel(x0, y0 + 1u); + let d = texel(x0 + 1u, y0 + 1u); + return (a * (1.0 - fx) + b * fx) * (1.0 - fy) + (c * (1.0 - fx) + d * fx) * fy; +} + +// The centre of the texture set texel under view pixel `pixel` of `count`, across `extent` texels +fn texel_centre(pixel: u32, count: u32, extent: u32) -> f32 { + let texel = min(floor((f32(pixel) + 0.5) / f32(count) * f32(extent)), f32(extent - 1u)); + return (texel + 0.5) / f32(extent); +} + +fn id_mask(p: vec2) -> vec3 { + let u = texel_centre(p.x, params.extent.x, params.working.x); + let v = texel_centre(p.y, params.extent.y, params.working.y); + + // The image's nearest texel, wrapping as `ImageRes::sample_nearest` does + let x = i32(floor(u * f32(params.source.x))); + let y = i32(floor(v * f32(params.source.y))); + let size = vec2(params.source); + return texel(u32(((x % size.x) + size.x) % size.x), u32(((y % size.y) + size.y) % size.y)); +} + +@fragment +fn fs(@builtin(position) position: vec4) -> @location(0) vec4 { + let p = vec2(position.xy); + var color: vec3; + switch params.mode { + case 0u: { color = mesh_map(p); } + case 1u: { color = image(p); } + default: { color = id_mask(p); } + } + + // Quantize as the CPU views do (stored values, no color conversion) + return vec4(floor(clamp(color, vec3(0.0), vec3(1.0)) * 255.0 + 0.5) / 255.0, 1.0); +} diff --git a/crates/render/src/shaders/brush.wgsl b/crates/render/src/shaders/brush.wgsl index 0b3135a13..e98930739 100644 --- a/crates/render/src/shaders/brush.wgsl +++ b/crates/render/src/shaders/brush.wgsl @@ -11,6 +11,10 @@ struct Params { alpha_rotation: vec4, // sine and cosine of the alpha angle flags: vec4, // UV mode, culling, invert brush tip, quick-mask mode stamp_blending: u32, + // Scalars keep the Rust layout (a vec2 would align to 8 bytes) + clone_x: i32, + clone_y: i32, + clone_mode: u32, } struct Vertex { position: vec4, @@ -30,11 +34,16 @@ struct Dab { // Corresponds to the BrushAlpha mapping in BrushPipeline::pipeline override alpha_kind: u32 = 0u; +// Whether other surfaces share texels with their owners (gbuf.shared_surfaces) +override shared_surfaces: bool = false; // Match texturecraft_paint::StampBlending const BLEND_LIGHTEN: u32 = 1u; const BLEND_ADD: u32 = 2u; const LIBRARY_ALPHA_KIND: u32 = 7u; +// Params.clone_mode: a clone reads covered source texels, and with coverage weighs them by it +const CLONE_SOURCE: u32 = 1u; +const CLONE_COVERAGE: u32 = 2u; const IMAGE_ALPHA_KIND: u32 = 8u; @group(0) @binding(0) var params: Params; @group(0) @binding(3) var uv_surface: texture_2d; @@ -45,6 +54,11 @@ const IMAGE_ALPHA_KIND: u32 = 8u; @group(0) @binding(8) var tiles: array; @group(0) @binding(9) var alpha_out: array; @group(0) @binding(10) var tip: texture_2d; +// Per texel the first covering surface + 1 (0: none), entries: triangle (high bit on the last), weight bits +@group(0) @binding(11) var cover_first: texture_2d; +@group(0) @binding(12) var covers: array; + +const LAST_COVER: u32 = 0x80000000u; fn accept(i: u32, direction: vec3) -> bool { return true; } @@ -267,6 +281,20 @@ fn copy_visible(dab: Dab, point: vec3, view: BrushView) -> bool { return test.y && ray_visible(allowed, view.geometric, view.direction); } +// What a clone's source lets through at `pixel`, as Pickup::stamp weighs each dab: nothing beyond +// the set or off the UV islands, else the cloned layer's coverage there (offset: the packed tile) +fn clone_factor(pixel: vec2, offset: u32) -> f32 { + if params.clone_mode == 0u { return 1.0; } + let source = vec2(pixel) + vec2(params.clone_x, params.clone_y); + if any(source < vec2(0)) || any(source >= vec2(textureDimensions(uv_surface))) { return 0.0; } + if textureLoad(uv_surface, source, 0).x == NONE { return 0.0; } + if params.clone_mode != CLONE_COVERAGE { return 1.0; } + if offset == 0u { return 0.0; } + let local = pixel % 64u; + let index = local.y * 64u + local.x; + return f32((tiles[offset + index / 2u] >> (index % 2u * 16u)) & 65535u) / 65535.0; +} + fn quick_limit(pixel: vec2, offset: u32) -> f32 { if params.flags.w == 0u { return 1.0; } var coverage = 0.0; @@ -278,117 +306,176 @@ fn quick_limit(pixel: vec2, offset: u32) -> f32 { return select(coverage, 1.0 - coverage, params.flags.w == 2u); } -fn stroke_alpha(pixel: vec2, first: u32, count: u32, mask: u32) -> u32 { +// The surface point a texel shows on one triangle, as the CPU raster's scan_triangle sees it +struct TexelSurface { + point: vec3, + normal: vec3, + geometric: vec3, + view: BrushView, + has_normal: bool, + back_facing: bool, + texels_per_unit: f32, +} + +fn texel_surface(triangle: u32, weights: vec3) -> TexelSurface { + let v = triangle * 3u; + let a = vertices[v]; + let b = vertices[v + 1u]; + let c = vertices[v + 2u]; + let interpolated = a.normal.xyz * weights.x + b.normal.xyz * weights.y + c.normal.xyz * weights.z; + var surface = TexelSurface(vec3(0.0), unit(interpolated, vec3(0.0)), vec3(0.0), BrushView(vec3(0.0), vec3(0.0), 1.0), false, false, 1.0); + surface.point = (a.position.xyz * weights.x + b.position.xyz * weights.y + c.position.xyz * weights.z) * params.mesh.w + params.mesh.xyz; + let world_cross = cross(b.position.xyz - a.position.xyz, c.position.xyz - a.position.xyz); + surface.geometric = unit(world_cross, vec3(0.0)); + if alpha_kind == LIBRARY_ALPHA_KIND { + let size = vec2(textureDimensions(uv_surface)); + let uv_a = vec2(a.position.w, a.normal.w); + let uv_b = vec2(b.position.w, b.normal.w); + let uv_c = vec2(c.position.w, c.normal.w); + let area = abs(edge(uv_a, uv_b, uv_c)) * size.x * size.y; + let world_area = length(world_cross) * params.mesh.w * params.mesh.w; + surface.texels_per_unit = sqrt(area / world_area); + } + surface.has_normal = dot(surface.normal, surface.normal) > 0.0; + if surface.has_normal { + surface.view = brush_view(surface.point, surface.geometric, surface.normal); + + // Symmetry copies see the texel from their source's side + surface.back_facing = params.flags.y != 0u && surface.view.facing <= 0.0; + } + return surface; +} + +// One world dab's opacity on one surface point. `tested` and `hidden` keep the point's own +// visibility between the dabs of one texel +fn world_opacity(dab: Dab, surface: TexelSurface, limit: f32, tested: ptr, hidden: ptr) -> f32 { + let offset = surface.point - dab.center.xyz; + let local = vec2(dot(offset, dab.tangent.xyz), dot(offset, dab.bitangent.xyz)) / dab.center.w; + if dot(local, local) > 2.0 || abs(dot(offset, dab.normal.xyz)) > dab.center.w * dab.normal.w { + return 0.0; + } + + if surface.has_normal && dot(surface.normal, dab.normal.xyz) <= 0.0 { return 0.0; } + let symmetry_copy = dab.source.w != 0.0; + var dab_view = surface.view; + if symmetry_copy { + dab_view = copy_view(dab, surface.point, surface.geometric, select(dab.normal.xyz, surface.normal, surface.has_normal)); + if params.flags.y != 0u && dab_view.facing <= 0.0 { return 0.0; } + } else if surface.has_normal { + if surface.back_facing || *hidden { return 0.0; } + } else { + dab_view = brush_view(surface.point, surface.geometric, dab.normal.xyz); + if params.flags.y != 0u && dab_view.facing <= 0.0 { return 0.0; } + } + var fade = 1.0; + if params.flags.y != 0u { + let f = clamp((dab_view.facing - params.view_scale.y) / max(1e-6, params.view_scale.z - params.view_scale.y), 0.0, 1.0); + fade = f * f * (3.0 - 2.0 * f); + } + let opacity = stamp_shape(local, dab.bitangent.w, dab.seed, dab.center.w * surface.texels_per_unit) * dab.tangent.w * fade * limit; + if opacity <= 0.0 { return 0.0; } + if symmetry_copy { + if !copy_visible(dab, surface.point, dab_view) { return 0.0; } + } else if !*tested { + if !visible(surface.point, dab_view.geometric, dab_view.direction, dab_view.facing) { + *hidden = surface.has_normal; + return 0.0; + } + + *tested = surface.has_normal; + } + return opacity; +} + +// One 2D view dab's opacity at `pixel` +fn uv_opacity(dab: Dab, pixel: vec2) -> f32 { + let reach = dab.center.w * PLANAR_RADIUS_SCALE; + let p = vec2(pixel); + if any(p < floor(dab.center.xy - reach)) || any(p >= ceil(dab.center.xy + reach)) { + return 0.0; + } + + let d = (p + 0.5 - dab.center.xy) * vec2(1.0, -1.0) / dab.center.w; + let local = vec2(dot(d, dab.tangent.xy), dot(d, vec2(-dab.tangent.y, dab.tangent.x))); + return stamp_shape(local, dab.bitangent.w, dab.seed, dab.center.w) * dab.tangent.w; +} + +// The strongest opacity of one dab on the other surfaces sharing the texel (CPU: the strongest +// coverage per texel before the stamp blends) +fn cover_opacity(dab: Dab, first: u32, limit: f32) -> f32 { + var strongest = 0.0; + var entry = first - 1u; + loop { + let triangle = covers[entry * 3u]; + let second = bitcast(covers[entry * 3u + 1u]); + let third = bitcast(covers[entry * 3u + 2u]); + let surface = texel_surface(triangle & ~LAST_COVER, vec3(1.0 - second - third, second, third)); + var tested = false; + var hidden = false; + strongest = max(strongest, world_opacity(dab, surface, limit, &tested, &hidden)); + if (triangle & LAST_COVER) != 0u { break; } + entry++; + } + return strongest; +} + +// The surface point of the texel's G-buffer owner `hit` (triangle, packed weights) +fn owner_surface(pixel: vec2, hit: vec2) -> TexelSurface { + let xy = unpack2x16unorm(hit.y); + var weights = vec3(max(0.0, 1.0 - xy.x - xy.y), xy); + let v = hit.x * 3u; + let a = vertices[v]; + let b = vertices[v + 1u]; + let c = vertices[v + 2u]; + let interpolated = a.normal.xyz * weights.x + b.normal.xyz * weights.y + c.normal.xyz * weights.z; + + // Recover full barycentric weights near normal cancellation before using the dab normal + let packed_error = 4.0 / 65535.0; + if dot(interpolated, interpolated) <= packed_error * packed_error { + let size = vec2(textureDimensions(uv_surface)); + let uv_a = vec2(a.position.w, a.normal.w) * size; + let uv_b = vec2(b.position.w, b.normal.w) * size; + let uv_c = vec2(c.position.w, c.normal.w) * size; + let center = vec2(pixel) + 0.5; + let area = edge(uv_a, uv_b, uv_c); + if abs(area) >= 1e-12 { + let full = vec2(edge(uv_c, uv_a, center), edge(uv_a, uv_b, center)) * (1.0 / area); + weights = vec3(1.0 - full.x - full.y, full); + } + } + return texel_surface(hit.x, weights); +} + +fn stroke_alpha(pixel: vec2, first: u32, count: u32, mask: u32, source: u32) -> u32 { var coverage = textureLoad(alpha_in, vec2(pixel), 0).x; - let limit = quick_limit(pixel, mask); + let limit = quick_limit(pixel, mask) * clone_factor(pixel, source); if limit == 0.0 { return coverage; } let hit = textureLoad(uv_surface, vec2(pixel), 0).xy; if hit.x == NONE { return coverage; } let uv_mode = params.flags.x != 0u; - var point = vec3(0.0); - var normal = vec3(0.0); - var geometric = vec3(0.0); - var back_facing = false; - var view = BrushView(vec3(0.0), vec3(0.0), 1.0); - var has_normal = false; - var texels_per_unit = 1.0; + var owner = TexelSurface(vec3(0.0), vec3(0.0), vec3(0.0), BrushView(vec3(0.0), vec3(0.0), 1.0), false, false, 1.0); + var first_cover = 0u; if !uv_mode { - let xy = unpack2x16unorm(hit.y); - var weights = vec3(max(0.0, 1.0 - xy.x - xy.y), xy); - let v = hit.x * 3u; - let a = vertices[v]; - let b = vertices[v + 1u]; - let c = vertices[v + 2u]; - var interpolated = a.normal.xyz * weights.x + b.normal.xyz * weights.y + c.normal.xyz * weights.z; - - // Recover full barycentric weights near normal cancellation before using the dab normal - let packed_error = 4.0 / 65535.0; - if dot(interpolated, interpolated) <= packed_error * packed_error { - let size = vec2(textureDimensions(uv_surface)); - let uv_a = vec2(a.position.w, a.normal.w) * size; - let uv_b = vec2(b.position.w, b.normal.w) * size; - let uv_c = vec2(c.position.w, c.normal.w) * size; - let center = vec2(pixel) + 0.5; - let area = edge(uv_a, uv_b, uv_c); - if abs(area) >= 1e-12 { - let full = vec2(edge(uv_c, uv_a, center), edge(uv_a, uv_b, center)) * (1.0 / area); - weights = vec3(1.0 - full.x - full.y, full); - interpolated = a.normal.xyz * weights.x + b.normal.xyz * weights.y + c.normal.xyz * weights.z; - } - } - point = (a.position.xyz * weights.x + b.position.xyz * weights.y + c.position.xyz * weights.z) * params.mesh.w + params.mesh.xyz; - normal = unit(interpolated, vec3(0.0)); - let world_cross = cross(b.position.xyz - a.position.xyz, c.position.xyz - a.position.xyz); - geometric = unit(world_cross, vec3(0.0)); - if alpha_kind == LIBRARY_ALPHA_KIND { - let size = vec2(textureDimensions(uv_surface)); - let uv_a = vec2(a.position.w, a.normal.w); - let uv_b = vec2(b.position.w, b.normal.w); - let uv_c = vec2(c.position.w, c.normal.w); - let area = abs(edge(uv_a, uv_b, uv_c)) * size.x * size.y; - let world_area = length(world_cross) * params.mesh.w * params.mesh.w; - texels_per_unit = sqrt(area / world_area); - } - has_normal = dot(normal, normal) > 0.0; - if has_normal { - view = brush_view(point, geometric, normal); - - // Symmetry copies see the texel from their source's side - back_facing = params.flags.y != 0u && view.facing <= 0.0; + owner = owner_surface(pixel, hit); + if shared_surfaces { + first_cover = textureLoad(cover_first, vec2(pixel), 0).x; } } var tested_visibility = false; var hidden = false; for (var i = 0u; i < count; i++) { let dab = dabs[tiles[first + i]]; - var local = vec2(0.0); - var fade = 1.0; - var dab_view = view; - let symmetry_copy = !uv_mode && dab.source.w != 0.0; + var opacity = 0.0; if uv_mode { - let reach = dab.center.w * PLANAR_RADIUS_SCALE; - let p = vec2(pixel); - if any(p < floor(dab.center.xy - reach)) || any(p >= ceil(dab.center.xy + reach)) { - continue; - } - - let d = (p + 0.5 - dab.center.xy) * vec2(1.0, -1.0) / dab.center.w; - local = vec2(dot(d, dab.tangent.xy), dot(d, vec2(-dab.tangent.y, dab.tangent.x))); + opacity = uv_opacity(dab, pixel) * limit; } else { - let offset = point - dab.center.xyz; - local = vec2(dot(offset, dab.tangent.xyz), dot(offset, dab.bitangent.xyz)) / dab.center.w; - if dot(local, local) > 2.0 || abs(dot(offset, dab.normal.xyz)) > dab.center.w * dab.normal.w { - continue; - } - - if has_normal && dot(normal, dab.normal.xyz) <= 0.0 { continue; } - if symmetry_copy { - dab_view = copy_view(dab, point, geometric, select(dab.normal.xyz, normal, has_normal)); - if params.flags.y != 0u && dab_view.facing <= 0.0 { continue; } - } else if has_normal { - if back_facing || hidden { continue; } - } else { - dab_view = brush_view(point, geometric, dab.normal.xyz); - if params.flags.y != 0u && dab_view.facing <= 0.0 { continue; } - } - if params.flags.y != 0u { - let f = clamp((dab_view.facing - params.view_scale.y) / max(1e-6, params.view_scale.z - params.view_scale.y), 0.0, 1.0); - fade = f * f * (3.0 - 2.0 * f); + opacity = world_opacity(dab, owner, limit, &tested_visibility, &hidden); + if first_cover != 0u { + opacity = max(opacity, cover_opacity(dab, first_cover, limit)); } } - let opacity = stamp_shape(local, dab.bitangent.w, dab.seed, dab.center.w * texels_per_unit) * dab.tangent.w * fade * limit; if opacity <= 0.0 { continue; } - if symmetry_copy { - if !copy_visible(dab, point, dab_view) { continue; } - } else if !uv_mode && !tested_visibility { - if !visible(point, dab_view.geometric, dab_view.direction, dab_view.facing) { - hidden = has_normal; - continue; - } - - tested_visibility = has_normal; - } let old = f32(coverage) / 65535.0; var blended = opacity + old * (1.0 - opacity); switch params.stamp_blending { @@ -403,12 +490,13 @@ fn stroke_alpha(pixel: vec2, first: u32, count: u32, mask: u32) -> u32 { @compute @workgroup_size(8, 8) fn brush(@builtin(global_invocation_id) id: vec3) { - let header = id.z * 5u; + let header = id.z * 6u; let origin = vec2(tiles[header], tiles[header + 1u]) + vec2(id.x * 2u, id.y); let first = tiles[header + 2u]; let count = tiles[header + 3u]; let mask = tiles[header + 4u]; - let a = stroke_alpha(origin, first, count, mask); - let b = stroke_alpha(origin + vec2(1u, 0u), first, count, mask); + let source = tiles[header + 5u]; + let a = stroke_alpha(origin, first, count, mask, source); + let b = stroke_alpha(origin + vec2(1u, 0u), first, count, mask, source); alpha_out[id.z * 4096u + id.y * 64u + id.x] = a | (b << 16u); } diff --git a/crates/render/src/shaders/composite.wgsl b/crates/render/src/shaders/composite.wgsl index 04105bd1e..b1a9fc1f8 100644 --- a/crates/render/src/shaders/composite.wgsl +++ b/crates/render/src/shaders/composite.wgsl @@ -51,6 +51,23 @@ struct Params { whole_compact: vec4, // Mask-view slots are one-based so zero can mark an inactive view mask_view: vec4, + // A layer thumbnail's channel slot and display encoding (0 sRGB, 1 signed, 2 as stored); a + // pickup source's slots, encodings and channel count (`pickup_texel`) + thumb: vec4, + // Tiling (BandedInputs): the first set row the UV surface and coverage inputs hold, the + // first bake row and rows per block the bake input holds (0: the whole bake), and the bake's + // full height + inputs: vec4, +} + +// A set texel's place in the UV surface input, which may hold only a band's rows +fn surface_texel(pixel: vec2) -> vec2 { + return vec2(vec2(pixel.x, pixel.y - params.inputs.x)); +} + +// The first coverage word of a set row, whose input may hold only a band's rows +fn coverage_row(row: u32) -> u32 { + return (row - params.inputs.x) * params.coverage.y; } @group(0) @binding(0) var params: Params; @@ -119,7 +136,7 @@ fn surface_at(pixel: vec2) -> Surface { return NO_SURFACE; } - let hit = textureLoad(surface_uv, vec2(pixel), 0).xy; + let hit = textureLoad(surface_uv, surface_texel(pixel), 0).xy; if hit.x == 0xffffffffu { return NO_SURFACE; } @@ -150,12 +167,26 @@ fn surface_at(pixel: vec2) -> Surface { return Surface(position, unit, true, vec4(direction, select(1.0, -1.0, ta.w < 0.0))); } -// A zero block height selects the entire bake texture +// A zero block height selects the entire bake texture; a banded bake names its full height fn bake_block_size() -> vec2 { let size = textureDimensions(bake_maps); + if params.inputs.z != 0u { + return vec2(size.x, params.inputs.w); + } + return vec2(size.x, select(params.id_bake.z, size.y, params.id_bake.z == 0u)); } +// A bake texel of block `block` in the bake input, which may hold only a band's rows per block +fn bake_texel(at: vec2, block: u32) -> vec2 { + if params.inputs.z == 0u { + return vec2(at + vec2(0u, block * bake_block_size().y)); + } + + let row = min(at.y - min(at.y, params.inputs.y), params.inputs.z - 1u); + return vec2(vec2(at.x, row + block * params.inputs.z)); +} + fn bake_pixel_at(pixel: vec2) -> vec2 { let size = bake_block_size(); @@ -184,8 +215,7 @@ fn baked_block_at(pixel: vec2, block: u32) -> vec4 { return udim_separate_bake(pixel, block); } - let at = bake_pixel_at(pixel) + vec2(0u, block * bake_block_size().y); - return textureLoad(bake_maps, vec2(at), 0); + return textureLoad(bake_maps, bake_texel(bake_pixel_at(pixel), block), 0); } fn baked_at(pixel: vec2) -> vec4 { @@ -300,7 +330,11 @@ fn fill_value(layer: Operation, uv: vec2, surface: Surface) -> vec4 { return decal_fill_value(placed, uv, surface); } -fn stored_sample(layer: Operation, table: u32, origin: vec2, size: vec2, pixel: vec2, empty: vec4) -> vec4 { +// A sampled window (flag in `params.paint_window.z`) holds per tile only the texels at +// multiples of the display step, row-major (CompositePaintWindow::Sampled) +const SAMPLED_PAINT = 0x80000000u; + +fn stored_sample(layer: Operation, table: u32, origin: vec2, size: vec2, pixel: vec2, empty: vec4, sampled: bool) -> vec4 { let atlas_tile = pixel / 64u; if any(atlas_tile < origin) { return empty; @@ -317,7 +351,12 @@ fn stored_sample(layer: Operation, table: u32, origin: vec2, size: vec2, empty: vec4< let window = vec2(paint[image + 4u], paint[image + 5u]); let table = image + 6u; if all(texels == params.source.xy) { - return stored_sample(layer, table, origin, window, pixel, empty); + return stored_sample(layer, table, origin, window, pixel, empty, false); } let pos = max((vec2(pixel) + 0.5) * vec2(texels) / vec2(params.source.xy) - 0.5, vec2(0.0)); @@ -343,10 +382,10 @@ fn resampled_sample(layer: Operation, image: u32, pixel: vec2, empty: vec4< let base = vec2(cell); let weights = clamp(pos - cell, vec2(0.0), vec2(1.0)); let last = texels - 1u; - let a = stored_sample(layer, table, origin, window, min(base, last), empty); - let b = stored_sample(layer, table, origin, window, min(base + vec2(1u, 0u), last), empty); - let c = stored_sample(layer, table, origin, window, min(base + vec2(0u, 1u), last), empty); - let d = stored_sample(layer, table, origin, window, min(base + 1u, last), empty); + let a = stored_sample(layer, table, origin, window, min(base, last), empty, false); + let b = stored_sample(layer, table, origin, window, min(base + vec2(1u, 0u), last), empty, false); + let c = stored_sample(layer, table, origin, window, min(base + vec2(0u, 1u), last), empty, false); + let d = stored_sample(layer, table, origin, window, min(base + 1u, last), empty, false); let top = a * (1.0 - weights.x) + b * weights.x; let bottom = c * (1.0 - weights.x) + d * weights.x; return min(floor(top * (1.0 - weights.y) + bottom * weights.y + 0.5), vec4(65535.0)); @@ -363,7 +402,8 @@ fn stored_paint(layer: Operation, pixel: vec2) -> vec4 { if params.paint_window.x == 0xffffffffu { raw = resampled_sample(layer, image, pixel, empty); } else { - raw = stored_sample(layer, image, params.paint_window.xy, params.paint_window.zw, pixel, empty); + let window = vec2(params.paint_window.z & ~SAMPLED_PAINT, params.paint_window.w); + raw = stored_sample(layer, image, params.paint_window.xy, window, pixel, empty, (params.paint_window.z & SAMPLED_PAINT) != 0u); } } let p = raw / 65535.0; @@ -398,7 +438,22 @@ fn painted(layer: Operation, pixel: vec2, projected: ProjectedBrush) -> vec stored = live_brush_paint(layer, stored, m, projected, pixel, uv); } else if m > 0.0 { // Match the paint commit's premultiplied over and 16-bit channel encoding - let value = select(layer.uv.xxx, layer.uv.xyz, layer.ids.w == 4u); + var value = select(layer.uv.xxx, layer.uv.xyz, layer.ids.w == 4u); + + // A clone or smudge carries values on the device (composite_brush.wgsl carried_value) + if layer.ext.w != 0u { + let carried = carried_value(layer, pixel); + if carried.a <= 0.0 { + m = 0.0; + } else { + value = carried.rgb; + + // A channel with its own stroke alpha deposits by it (bit 16, CARRIED_ALPHA) + if (layer.ext.w & 0x10000u) != 0u { + m = carried.a * layer.uv.w; + } + } + } let pigment = select(value, projected.rgba.rgb, layer.projection.w == 2.0); let remaining = 1.0 - m; let premul = pigment * m + stored.rgb * remaining; @@ -737,7 +792,7 @@ fn geometry_allows(offset: u32, triangle: u32) -> bool { } fn uv_texel_covered(pixel: vec2) -> bool { - let word = uv_coverage[pixel.y * params.coverage.y + pixel.x / 32u]; + let word = uv_coverage[coverage_row(pixel.y) + pixel.x / 32u]; return (word & (1u << (pixel.x % 32u))) != 0u; } @@ -793,7 +848,7 @@ fn padded_source(pixel: vec2) -> vec2 { continue; } - let index = row * pitch + start_word; + let index = coverage_row(row) + start_word; var bits = uv_coverage[index] >> start_bit; if right / 32u != start_word { bits |= uv_coverage[index + 1u] << (32u - start_bit); @@ -825,6 +880,64 @@ fn padded_source(pixel: vec2) -> vec2 { // Keep mask preview evaluation out of the material pipeline override composite_mask_preview: bool = false; +// A layer thumbnail instead of the display maps: 1 the layer's content in one channel with its +// coverage as alpha (layers composited over nothing), 2 the composited channel (a folder) +override composite_thumb: u32 = 0u; + +// The value of destination `slot` (`channel_slot` in Rust) among the material values +fn thumb_slot_value(values: MaterialValues, slot: u32) -> vec3 { + var scalars = values.scalars; + var lobe_colors = values.lobe_colors; + var lobe_values = values.lobe_values; + if slot == 0u { + return values.base; + } + if slot == 7u { + return values.normal; + } + if slot >= 12u { + return vec3(lobe_values[min(slot - 12u, 8u)]); + } + if slot >= 8u { + return lobe_colors[slot - 8u]; + } + return vec3(scalars[slot - 1u]); +} + +// A thumbnail texel as the CPU's thumbnails encode it: colors to sRGB, signed values with 0 at +// mid gray, the rest as stored; straight alpha +fn thumb_texel(value: vec3, alpha: f32) -> u32 { + let a = u32(clamp(alpha, 0.0, 1.0) * 255.0 + 0.5) << 24u; + if params.thumb.y == 0u { + return (pack_srgb(value, 0.0) & 0x00ffffffu) | a; + } + var shown = value; + if params.thumb.y == 1u { + shown = value * 0.5 + 0.5; + } + return (pack4x8unorm(vec4(clamp(shown, vec3(0.0), vec3(1.0)), 0.0)) & 0x00ffffffu) | a; +} + +// A brush's pickup source (`set_pickup_output`): thumb.z channels whose slots thumb.x holds in +// bytes and whose encodings thumb.y holds in two bits each (0 three components, 1 signed, 2 +// unsigned), encoded as the CPU stores them +fn pickup_component(values: MaterialValues, k: u32) -> u32 { + if k >= params.thumb.z { + return 0u; + } + let value = thumb_slot_value(values, (params.thumb.x >> (8u * k)) & 0xffu).x; + return select(to_u16(value), to_u16(value * 0.5 + 0.5), ((params.thumb.y >> (2u * k)) & 3u) == 1u); +} + +// One RGBA16 texel: a channel of three components alone, or up to four scalar channels +fn pickup_texel(values: MaterialValues) -> vec2 { + if (params.thumb.y & 3u) == 0u { + let color = thumb_slot_value(values, params.thumb.x & 0xffu); + return vec2(to_u16(color.r) | (to_u16(color.g) << 16u), to_u16(color.b)); + } + return vec2(pickup_component(values, 0u) | (pickup_component(values, 1u) << 16u), pickup_component(values, 2u) | (pickup_component(values, 3u) << 16u)); +} + @compute @workgroup_size(8, 8) fn compose(@builtin(global_invocation_id) id: vec3) { if id.x >= params.band.x || id.y >= params.band.y { @@ -861,10 +974,19 @@ fn compose(@builtin(global_invocation_id) id: vec3) { } let index = id.y * params.program.y + id.x; let texel = LayerTexel(pixel, uv, surface, mask_bakes, projected); + if params.thumb.z != 0u && !covered { + output[2u * index] = 0u; + output[2u * index + 1u] = 0u; + return; + } if composite_mask_preview && !covered { output[index] = 0xff000000u; return; } + if composite_thumb != 0u && !covered { + output[index] = 0u; + return; + } var base = vec3(0.5); var normal = vec3(0.5, 0.5, 1.0); @@ -894,9 +1016,11 @@ fn compose(@builtin(global_invocation_id) id: vec3) { var mask_value = 1.0; var triangle = 0xffffffffu; if covered && (params.coverage.w & GEOMETRY_MASKS) != 0u { - triangle = textureLoad(surface_uv, vec2(pixel), 0).x; + triangle = textureLoad(surface_uv, surface_texel(pixel), 0).x; } var group_depth = 0u; + var thumb_value = vec3(0.0); + var thumb_cover = 0.0; // Share the mask call site to avoid inlining a separate copy for each mask var first = 0u; @@ -931,6 +1055,11 @@ fn compose(@builtin(global_invocation_id) id: vec3) { } } if composite_mask_preview { + if params.thumb.z != 0u { + output[2u * index] = to_u16(mask); + output[2u * index + 1u] = 0u; + return; + } output[index] = (u32(mask * 255.0 + 0.5) * 0x00010101u) | 0xff000000u; return; } @@ -963,6 +1092,12 @@ fn compose(@builtin(global_invocation_id) id: vec3) { if weight <= 0.0 { continue; } let source = content.rgb; let destination = layer.ids.x; + if composite_thumb == 1u && destination == params.thumb.x { + // Over nothing: premultiplied value and coverage + let own = select(vec3(source.x), source, destination == 0u || destination == 7u || (destination >= 8u && destination < 12u)); + thumb_value = mix(thumb_value, own, weight); + thumb_cover = mix(thumb_cover, 1.0, weight); + } // FXC tries to unroll the layer loop if its local array writes use dynamic indices if destination == 0u { @@ -1007,6 +1142,21 @@ fn compose(@builtin(global_invocation_id) id: vec3) { } } } + if composite_thumb == 1u { + // Nothing drawn: transparent black, as the CPU leaves it + output[index] = select(0u, thumb_texel(thumb_value / max(thumb_cover, 1e-6), thumb_cover), thumb_cover > 0.0); + return; + } + if composite_thumb == 2u && params.thumb.z != 0u { + let words = pickup_texel(MaterialValues(base, normal, scalars, lobe_colors, lobe_values)); + output[2u * index] = words.x; + output[2u * index + 1u] = words.y; + return; + } + if composite_thumb == 2u { + output[index] = thumb_texel(thumb_slot_value(MaterialValues(base, normal, scalars, lobe_colors, lobe_values), params.thumb.x), 1.0); + return; + } output[index] = pack_srgb(base, scalars[0]); let ao = clamp(display_ao * f32(to_u16(scalars[1])) / 65535.0, 0.0, 1.0); let roughness = select(to_u16(scalars[2]) >> 8u, 255u - (to_u16(lobe_values[8]) >> 8u), params.source.w != 0u); diff --git a/crates/render/src/shaders/composite_brush.wgsl b/crates/render/src/shaders/composite_brush.wgsl index c5aee796d..d425f0014 100644 --- a/crates/render/src/shaders/composite_brush.wgsl +++ b/crates/render/src/shaders/composite_brush.wgsl @@ -45,3 +45,40 @@ fn erased_paint(layer: Operation, stored: vec4, m: f32) -> vec4 { let coverage = f32(to_u16(stored.a * remaining)) / 65535.0; return vec4(rgb, coverage); } + +// live_brush.rs CARRIED_ALPHA: the descriptor names the channel's own stroke alpha +const CARRIED_ALPHA: u32 = 0x10000u; + +// A live clone's or smudge's carried values (gpu_composite/live_brush.rs LiveCarried) +@group(0) @binding(20) var carried_scalars: texture_2d_array; +@group(0) @binding(21) var carried_colors: texture_2d_array; + +// The straight value a clone or smudge carries to `pixel`, with 1 in alpha (or the channel's own +// stroke alpha), or 0 where its source lies beyond the set. `ext.w` is CarriedSlot::descriptor: +// bit 1 color, bits 2-3 the component, bits 4-15 the layer, bit 16 an own alpha in the scalar +// layer from bit 17; the clone offset is the brush's band uniform. +fn carried_value(layer: Operation, pixel: vec2) -> vec4 { + let at = vec2(pixel) + bitcast>(params.packages[6].xy); + if any(at < vec2(0)) || any(at >= vec2(params.source.xy)) { + return vec4(0.0); + } + + let descriptor = layer.ext.w; + let index = i32((descriptor >> 4u) & 0xfffu); + var raw = vec3(0.0); + if (descriptor & 2u) != 0u { + raw = vec3(textureLoad(carried_colors, at, index, 0).rgb); + } else { + raw = vec3(f32(textureLoad(carried_scalars, at, index, 0)[(descriptor >> 2u) & 3u])); + } + + // A channel with its own stroke alpha (per-channel coverage) + var alpha = 1.0; + if (descriptor & CARRIED_ALPHA) != 0u { + alpha = f32(textureLoad(carried_scalars, at, i32(descriptor >> 17u), 0).x) / 65535.0; + } + + // Encoded as the paint layers store them (signed: v * 0.5 + 0.5) + let p = raw / 65535.0; + return vec4(select(p, p * 2.0 - 1.0, layer.ids.x == 6u), alpha); +} diff --git a/crates/render/src/shaders/composite_spatial.wgsl b/crates/render/src/shaders/composite_spatial.wgsl index a9177b422..069e06871 100644 --- a/crates/render/src/shaders/composite_spatial.wgsl +++ b/crates/render/src/shaders/composite_spatial.wgsl @@ -158,7 +158,7 @@ fn prepare_filter(@builtin(global_invocation_id) id: vec3) { let mask = anchor_mask || (!capture && !generator && (flags & 0x80000000u) != 0u); var triangle = 0xffffffffu; if (capture || anchor_mask) && (params.coverage.w & GEOMETRY_MASKS) != 0u { - triangle = textureLoad(surface_uv, vec2(pixel), 0).x; + triangle = textureLoad(surface_uv, surface_texel(pixel), 0).x; } if generator { generator_second_stage = (flags & SECOND_GENERATOR_STAGE) != 0u; diff --git a/crates/render/src/shaders/eye_depth.wgsl b/crates/render/src/shaders/eye_depth.wgsl new file mode 100644 index 000000000..a19e83859 --- /dev/null +++ b/crates/render/src/shaders/eye_depth.wgsl @@ -0,0 +1,160 @@ +// The paint camera's eye-distance buffer on the GPU: the software raster of +// texturecraft_paint::visibility (EyeDepth::rasterize) per triangle, keeping the nearest depth key +// per pixel with an atomic minimum, then the lowest-numbered triangle at that depth (the one the +// software raster keeps, walking triangles in order with a strict "nearer"), then eye distances. + +struct Params { + width: u32, + height: u32, + triangle_count: u32, + // Invocations per dispatch row (a large mesh dispatches in two dimensions) + row_stride: u32, + depth_min: f32, + depth_max: f32, + edge_tolerance: f32, + min_area: f32, + scale: vec2, + ortho: u32, + _pad: u32, +} + +@group(0) @binding(0) var params: Params; +// Per vertex: screen x, y (pixels, origin top-left), depth key, and 1 when in front of the camera +@group(0) @binding(1) var vertices: array>; +// Per included triangle: its three vertices and its number in the mesh +@group(0) @binding(2) var triangles: array>; +@group(0) @binding(3) var depth: array>; +@group(0) @binding(4) var nearest: array>; +@group(0) @binding(5) var distance: array; + +const EMPTY: f32 = 3.40282347e38; +const NO_TRIANGLE: u32 = 0xffffffffu; + +// A depth key as an unsigned number with the same order +fn ordered(key: f32) -> u32 { + let bits = bitcast(key); + if (bits & 0x80000000u) != 0u { + return ~bits; + } + return bits | 0x80000000u; +} + +fn unordered(bits: u32) -> f32 { + if (bits & 0x80000000u) != 0u { + return bitcast(bits & 0x7fffffffu); + } + return bitcast(~bits); +} + +fn perp_dot(a: vec2, b: vec2) -> f32 { + return a.x * b.y - a.y * b.x; +} + +@compute @workgroup_size(64) +fn clear(@builtin(global_invocation_id) id: vec3) { + let at = id.y * params.row_stride + id.x; + if at >= params.width * params.height { + return; + } + atomicStore(&depth[at], ordered(EMPTY)); + // Without recorded triangles the binding holds one element only + if at < arrayLength(&nearest) { + atomicStore(&nearest[at], NO_TRIANGLE); + } +} + +// Rasterize one triangle: keep its depth (pass 0) or, where its depth is the nearest, its number +// (pass 1) +fn raster(index: u32, record: bool) { + if index >= params.triangle_count { + return; + } + let triangle = triangles[index]; + let a = vertices[triangle.x]; + let b = vertices[triangle.y]; + let c = vertices[triangle.z]; + if a.w == 0.0 || b.w == 0.0 || c.w == 0.0 { + return; + } + let size = vec2(f32(params.width), f32(params.height)); + let top_row = max(floor(min(a.y, min(b.y, c.y))), 0.0); + let bottom_row = min(ceil(max(a.y, max(b.y, c.y))), size.y); + if !(bottom_row > top_row) { + return; + } + let area = perp_dot(b.xy - a.xy, c.xy - a.xy); + if abs(area) < params.min_area { + return; + } + + let low = floor(min(a.xy, min(b.xy, c.xy))); + let high = ceil(max(a.xy, max(b.xy, c.xy))); + let left = u32(max(low.x, 0.0)); + let right = min(u32(max(min(high.x, size.x), 0.0)), params.width); + let top = u32(max(low.y, 0.0)); + let bottom = min(u32(max(min(high.y, size.y), 0.0)), params.height); + let tolerance = -params.edge_tolerance; + for (var row = top; row < bottom; row++) { + for (var column = left; column < right; column++) { + let sample = vec2(f32(column) + 0.5, f32(row) + 0.5); + let first = perp_dot(c.xy - b.xy, sample - b.xy) / area; + let second = perp_dot(a.xy - c.xy, sample - c.xy) / area; + let third = 1.0 - first - second; + if first < tolerance || second < tolerance || third < tolerance { + continue; + } + + let key = first * a.z + second * b.z + third * c.z; + if !(key >= params.depth_min && key <= params.depth_max) { + continue; + } + + let at = row * params.width + column; + if record { + // Within one step of the kept key: the passes are separate pipelines, which a + // compiler may fuse differently + let stored = atomicLoad(&depth[at]); + let mine = ordered(key); + if max(stored, mine) - min(stored, mine) <= 1u { + atomicMin(&nearest[at], triangle.w); + } + } else { + atomicMin(&depth[at], ordered(key)); + } + } + } +} + +@compute @workgroup_size(64) +fn nearest_depth(@builtin(global_invocation_id) id: vec3) { + raster(id.y * params.row_stride + id.x, false); +} + +@compute @workgroup_size(64) +fn nearest_triangle(@builtin(global_invocation_id) id: vec3) { + raster(id.y * params.row_stride + id.x, true); +} + +// Each pixel's nearest depth key as the eye distance brush visibility queries read +@compute @workgroup_size(64) +fn eye_distance(@builtin(global_invocation_id) id: vec3) { + let at = id.y * params.row_stride + id.x; + if at >= params.width * params.height { + return; + } + let key = unordered(atomicLoad(&depth[at])); + if key == EMPTY { + distance[at] = EMPTY; + return; + } + let column = at % params.width; + let row = at / params.width; + let view_x = ((f32(column) + 0.5) / f32(params.width) * 2.0 - 1.0) / params.scale.x; + let view_y = (1.0 - (f32(row) + 0.5) / f32(params.height) * 2.0) / params.scale.y; + let radial_squared = view_x * view_x + view_y * view_y; + if params.ortho != 0u { + distance[at] = sqrt(radial_squared + key * key); + } else { + distance[at] = sqrt(radial_squared + 1.0) / -key; + } +} diff --git a/crates/render/src/shaders/projector_depth.wgsl b/crates/render/src/shaders/projector_depth.wgsl new file mode 100644 index 000000000..ddebbb59f --- /dev/null +++ b/crates/render/src/shaders/projector_depth.wgsl @@ -0,0 +1,183 @@ +// A projector depth grid on the GPU: the raster of texturecraft_compose::projector_depth +// (ProjectorDepth::raster) per triangle over every cell, keeping the nearest surface per cell with +// an atomic maximum, then the lowest-numbered triangle at that nearness (the one the CPU raster +// keeps, walking triangles in order with a strict "nearer"), then its nearness and slope. + +struct Params { + origin: vec2, + cell: vec2, + side: u32, + triangle_count: u32, + // Invocations per dispatch row (a large mesh dispatches in two dimensions) + row_stride: u32, + // Words per output row: three per cell, padded for the copy into the atlas + row_words: u32, + max_slope: f32, + min_area: f32, + edge_tolerance: f32, + _pad: u32, +} + +@group(0) @binding(0) var params: Params; +// Per mesh corner: across, up and nearness in the view +@group(0) @binding(1) var corners: array>; +// Per triangle the view sees: its three corners +@group(0) @binding(2) var triangles: array>; +@group(0) @binding(3) var nearness: array>; +@group(0) @binding(4) var nearest: array>; +@group(0) @binding(5) var front: array; + +const NO_TRIANGLE: u32 = 0xffffffffu; + +// A nearness as an unsigned number with the same order +fn ordered(value: f32) -> u32 { + let bits = bitcast(value); + if (bits & 0x80000000u) != 0u { + return ~bits; + } + return bits | 0x80000000u; +} + +fn unordered(bits: u32) -> f32 { + if (bits & 0x80000000u) != 0u { + return bitcast(bits & 0x7fffffffu); + } + return bitcast(~bits); +} + +fn finite(value: f32) -> bool { + return (bitcast(value) & 0x7f800000u) != 0x7f800000u; +} + +// Twice the signed area of triangle a, b, q +fn edge(a: vec2, b: vec2, q: vec2) -> f32 { + let ab = b - a; + let aq = q - a; + return ab.x * aq.y - ab.y * aq.x; +} + +// The triangle's nearness slope across and up, or false where it is seen edge on +struct Plane { + slope: vec2, + seen: bool, +} + +fn plane(a: vec3, b: vec3, c: vec3) -> Plane { + let ab = b - a; + let ac = c - a; + let determinant = ab.x * ac.y - ab.y * ac.x; + if !finite(determinant) || abs(determinant) < params.min_area { + return Plane(vec2(0.0), false); + } + let slope = vec2((ab.z * ac.y - ac.z * ab.y) / determinant, (ab.x * ac.z - ac.x * ab.z) / determinant); + return Plane(clamp(slope, vec2(-params.max_slope), vec2(params.max_slope)), true); +} + +fn nearness_at(a: vec3, slope: vec2, x: u32, y: u32) -> f32 { + let centre = vec2(f32(x) + 0.5, f32(y) + 0.5); + return a.z + dot(slope, params.origin + centre * params.cell - a.xy); +} + +@compute @workgroup_size(64) +fn clear(@builtin(global_invocation_id) id: vec3) { + let at = id.y * params.row_stride + id.x; + if at >= params.side * params.side { + return; + } + atomicStore(&nearness[at], ordered(bitcast(0xff800000u))); + atomicStore(&nearest[at], NO_TRIANGLE); +} + +// Rasterize one triangle: keep its nearness (pass 0) or, where its nearness is the nearest, its +// number (pass 1) +fn raster(index: u32, record: bool) { + if index >= params.triangle_count { + return; + } + let triangle = triangles[index]; + let a = corners[triangle.x].xyz; + let b = corners[triangle.y].xyz; + let c = corners[triangle.z].xyz; + let surface = plane(a, b, c); + if !surface.seen { + return; + } + + // Coverage at cell centres + let pa = (a.xy - params.origin) / params.cell; + let pb = (b.xy - params.origin) / params.cell; + let pc = (c.xy - params.origin) / params.cell; + let low = min(pa, min(pb, pc)); + let high = max(pa, max(pb, pc)); + let side = f32(params.side); + let first = vec2(clamp(ceil(low - 0.5), vec2(0.0), vec2(side))); + let end = vec2(clamp(floor(high - 0.5) + 1.0, vec2(0.0), vec2(side))); + let area = edge(pa, pb, pc); + let facing = select(1.0, -1.0, area < 0.0 || (area == 0.0 && bitcast(area) != 0u)); + let tolerance = -params.edge_tolerance * abs(area); + for (var y = first.y; y < end.y; y++) { + for (var x = first.x; x < end.x; x++) { + let centre = vec2(f32(x) + 0.5, f32(y) + 0.5); + // Written as "all inside" so a NaN weight rejects the cell, as on the CPU + let inside = edge(pb, pc, centre) * facing >= tolerance && edge(pc, pa, centre) * facing >= tolerance && edge(pa, pb, centre) * facing >= tolerance; + if !inside { + continue; + } + + let near = nearness_at(a, surface.slope, x, y); + if !finite(near) { + continue; + } + let at = y * params.side + x; + if record { + // Close to the kept nearness: the passes are separate pipelines, which a compiler + // may fuse differently, so the rounding follows the size of every term summed + // (the slope products before they cancel, and the offset's own terms) + let kept = unordered(atomicLoad(&nearness[at])); + let reach = abs(params.origin) + abs(centre * params.cell) + abs(a.xy); + let terms = abs(a.z) + dot(abs(surface.slope), reach); + if abs(near - kept) <= 4.0e-7 * terms { + atomicMin(&nearest[at], index); + } + } else { + atomicMax(&nearness[at], ordered(near)); + } + } + } +} + +@compute @workgroup_size(64) +fn nearest_nearness(@builtin(global_invocation_id) id: vec3) { + raster(id.y * params.row_stride + id.x, false); +} + +@compute @workgroup_size(64) +fn nearest_triangle(@builtin(global_invocation_id) id: vec3) { + raster(id.y * params.row_stride + id.x, true); +} + +// Each cell's nearest triangle as the CPU grid stores it: its nearness at the cell centre and its +// slope across and up (nearness -inf where no surface is) +@compute @workgroup_size(64) +fn write_cells(@builtin(global_invocation_id) id: vec3) { + let at = id.y * params.row_stride + id.x; + if at >= params.side * params.side { + return; + } + let x = at % params.side; + let y = at / params.side; + let out = y * params.row_words + x * 3u; + let index = atomicLoad(&nearest[at]); + if index == NO_TRIANGLE { + front[out] = bitcast(0xff800000u); + front[out + 1u] = 0.0; + front[out + 2u] = 0.0; + return; + } + let triangle = triangles[index]; + let a = corners[triangle.x].xyz; + let surface = plane(a, corners[triangle.y].xyz, corners[triangle.z].xyz); + front[out] = nearness_at(a, surface.slope, x, y); + front[out + 1u] = surface.slope.x; + front[out + 2u] = surface.slope.y; +} diff --git a/crates/render/src/shaders/quick_mask.wgsl b/crates/render/src/shaders/quick_mask.wgsl index 1968558bf..4ac6702f4 100644 --- a/crates/render/src/shaders/quick_mask.wgsl +++ b/crates/render/src/shaders/quick_mask.wgsl @@ -1,5 +1,6 @@ struct QuickMaskParams { - size: u32, + // The aux texture's width and height + size: vec2, inverted: u32, erase: u32, opacity: f32, diff --git a/crates/render/src/shaders/smudge.wgsl b/crates/render/src/shaders/smudge.wgsl new file mode 100644 index 000000000..bac25541f --- /dev/null +++ b/crates/render/src/shaders/smudge.wgsl @@ -0,0 +1,480 @@ +// Smudge on the GPU brush, one stamp at a time as texturecraft_paint::Pickup::stamp: every stamp +// reads what earlier stamps deposited at texels shifted by its movement. +// smudge_measure: the stamp's raw opacity per texel (before the quick mask) into the scratch +// (alpha_out), its texel bounding box and, in the 3D view, the nearest distance of a texel in its +// volume. smudge_center: the first texel at that distance. smudge_resolve: the shift from the +// stamp's lane's previous center and whether the stamp deposits. smudge_deposit: the stamp's +// alpha and carried values into the stroke (and the lane) through `deposit_out`. + +// Per stamp: bounding box (min x, min y, max x, max y), nearest distance bits, nearest texel +// index, deposits, shift x and y (i32 bits), lane, 2D view center x and y (f32 bits) +@group(1) @binding(0) var stamp_state: array>; +// Per lane: has a previous center, previous center x and y (f32 bits), unused +@group(1) @binding(1) var lane_state: array; + +struct Smudge { + strength: f32, + // 1 when every symmetry copy drags its own trail (lane textures bound) + isolated: u32, + // Carried channels with one component (R16Uint layers) and with three (Rgba16Uint layers) + scalars: u32, + colors: u32, + // u32 words per tile in deposit_out + tile_words: u32, + // 1: every channel weighs its deposits by its source coverage (four per RGBA16 layer after + // the source's scalar values) and keeps its own alpha (R16 layers after the carried and the + // lanes' scalar values), scalar channels first, then colors (Pickup::stamp per channel) + channel_alphas: u32, + // 1: a clone painted stamp by stamp, reading the source at clone_x, clone_y and never what the + // stroke deposited + clone_mode: u32, + // Scalars keep the Rust layout (a vec2 would align to 8 bytes) + clone_x: i32, + clone_y: i32, +} +@group(1) @binding(2) var smudge: Smudge; +@group(1) @binding(3) var lane_alpha: texture_2d; +// Four scalar channels per layer (RGBA16), as the compositor writes pickup sources +@group(1) @binding(4) var source_scalars: texture_2d_array; +@group(1) @binding(5) var source_colors: texture_2d_array; +@group(1) @binding(6) var carried_scalars: texture_2d_array; +@group(1) @binding(7) var carried_colors: texture_2d_array; +@group(1) @binding(8) var lane_scalars: texture_2d_array; +@group(1) @binding(9) var lane_colors: texture_2d_array; +// Per tile: stroke alpha, lane alpha (isolated), then per scalar channel the stroke's and the +// lane's values, then per color channel the stroke's and the lane's, then with per-channel +// alphas each channel's stroke and lane alpha (rows of 256 bytes for R16, 512 for RGBA16) +@group(1) @binding(10) var deposit_out: array; + +const STATE_MIN_X: u32 = 0u; +const STATE_MAX_X: u32 = 2u; +const STATE_DISTANCE: u32 = 4u; +const STATE_CENTER: u32 = 5u; +const STATE_ACTIVE: u32 = 6u; +const STATE_SHIFT: u32 = 7u; +const STATE_LANE: u32 = 9u; +const STATE_UV_CENTER: u32 = 10u; +const NO_DISTANCE: f32 = 3.402823466e38; +// Lower bound when normalizing a nearly transparent pickup (MIN_BLEND_WEIGHT) +const MIN_BLEND_WEIGHT: f32 = 1e-6; +// How close (in squared texels of the triangle) a texel comes to the nearest and still ties with +// it, the first row-major tied texel being the center (texturecraft_paint raster CENTER_TIE) +const CENTER_TIE: f32 = 0.0625; + +// A triangle's tie allowance in squared world units: CENTER_TIE times its world area per texel +fn center_tie(triangle: u32) -> f32 { + let v = triangle * 3u; + let a = vertices[v]; + let b = vertices[v + 1u]; + let c = vertices[v + 2u]; + let size = vec2(textureDimensions(uv_surface)); + let uv_area = abs(edge(vec2(a.position.w, a.normal.w), vec2(b.position.w, b.normal.w), vec2(c.position.w, c.normal.w))) * size.x * size.y; + if !(uv_area > 0.0) { return 0.0; } + let world_area = length(cross(b.position.xyz - a.position.xyz, c.position.xyz - a.position.xyz)) * params.mesh.w * params.mesh.w; + return CENTER_TIE * world_area / uv_area; +} + +// The owner's surface point at the texel center from full-precision barycentrics, as the CPU's +// G-buffer has them (the packed ones are off by up to the triangle's texel extent / 65535) +fn owner_point(pixel: vec2, hit: vec2) -> vec3 { + let v = hit.x * 3u; + let a = vertices[v]; + let b = vertices[v + 1u]; + let c = vertices[v + 2u]; + let size = vec2(textureDimensions(uv_surface)); + let uv_a = vec2(a.position.w, a.normal.w) * size; + let uv_b = vec2(b.position.w, b.normal.w) * size; + let uv_c = vec2(c.position.w, c.normal.w) * size; + let area = edge(uv_a, uv_b, uv_c); + let xy = unpack2x16unorm(hit.y); + var weights = vec3(max(0.0, 1.0 - xy.x - xy.y), xy); + if abs(area) >= 1e-12 { + let center = vec2(pixel) + 0.5; + let full = vec2(edge(uv_c, uv_a, center), edge(uv_a, uv_b, center)) * (1.0 / area); + weights = vec3(1.0 - full.x - full.y, full); + } + return (a.position.xyz * weights.x + b.position.xyz * weights.y + c.position.xyz * weights.z) * params.mesh.w + params.mesh.xyz; +} + +// The squared distance from the dab center of a surface point inside the dab's volume +fn volume_distance(dab: Dab, point: vec3) -> f32 { + let offset = point - dab.center.xyz; + let local = vec2(dot(offset, dab.tangent.xyz), dot(offset, dab.bitangent.xyz)) / dab.center.w; + if dot(local, local) > 2.0 || abs(dot(offset, dab.normal.xyz)) > dab.center.w * dab.normal.w { + return NO_DISTANCE; + } + + return dot(offset, offset); +} + +// The nearest in-volume squared distance over the texel's owner and the other surfaces sharing +// it, and the least of their distances less their triangle's tie allowance (NO_DISTANCE outside) +fn texel_distance(dab: Dab, pixel: vec2, hit: vec2) -> vec2 { + var nearest = volume_distance(dab, owner_point(pixel, hit)); + var reach = NO_DISTANCE; + if nearest < NO_DISTANCE { reach = nearest - center_tie(hit.x); } + if shared_surfaces { + let first = textureLoad(cover_first, vec2(pixel), 0).x; + if first != 0u { + var entry = first - 1u; + loop { + let triangle = covers[entry * 3u]; + let second = bitcast(covers[entry * 3u + 1u]); + let third = bitcast(covers[entry * 3u + 2u]); + let surface = triangle & ~LAST_COVER; + let distance = volume_distance(dab, texel_surface(surface, vec3(1.0 - second - third, second, third)).point); + if distance < NO_DISTANCE { + nearest = min(nearest, distance); + reach = min(reach, distance - center_tie(surface)); + } + if (triangle & LAST_COVER) != 0u { break; } + entry++; + } + } + } + return vec2(nearest, reach); +} + +// The stamp's opacity at `pixel` as the CPU raster gathers it (before the quick mask), and its +// nearest in-volume distance less the tie allowance (NO_DISTANCE outside) for the center +fn smudge_texel(pixel: vec2, first: u32) -> vec2 { + let hit = textureLoad(uv_surface, vec2(pixel), 0).xy; + if hit.x == NONE { return vec2(0.0, NO_DISTANCE); } + let dab = dabs[tiles[first]]; + var opacity = 0.0; + var reach = NO_DISTANCE; + if params.flags.x != 0u { + opacity = uv_opacity(dab, pixel); + } else { + let distance = texel_distance(dab, pixel, hit); + reach = distance.y; + if distance.x < NO_DISTANCE { + atomicMin(&stamp_state[STATE_DISTANCE], bitcast(distance.x)); + } + let owner = owner_surface(pixel, hit); + var tested = false; + var hidden = false; + opacity = world_opacity(dab, owner, 1.0, &tested, &hidden); + if shared_surfaces { + let first_cover = textureLoad(cover_first, vec2(pixel), 0).x; + if first_cover != 0u { + opacity = max(opacity, cover_opacity(dab, first_cover, 1.0)); + } + } + } + if opacity > 0.0 { + atomicMin(&stamp_state[STATE_MIN_X], pixel.x); + atomicMin(&stamp_state[STATE_MIN_X + 1u], pixel.y); + atomicMax(&stamp_state[STATE_MAX_X], pixel.x); + atomicMax(&stamp_state[STATE_MAX_X + 1u], pixel.y); + } + return vec2(max(opacity, 0.0), reach); +} + +// The scratch: per tile the opacity per texel, and from the tile header's last word the +// distance less the tie allowance per texel, which the center compares with the nearest +@compute @workgroup_size(8, 8) +fn smudge_measure(@builtin(global_invocation_id) id: vec3) { + let header = id.z * 6u; + let origin = vec2(tiles[header], tiles[header + 1u]) + vec2(id.x * 2u, id.y); + let first = tiles[header + 2u]; + let local = id.y * 64u + id.x * 2u; + let distances = tiles[header + 5u] + local; + let a = smudge_texel(origin, first); + let b = smudge_texel(origin + vec2(1u, 0u), first); + alpha_out[id.z * 4096u + local] = bitcast(a.x); + alpha_out[id.z * 4096u + local + 1u] = bitcast(b.x); + alpha_out[distances] = bitcast(a.y); + alpha_out[distances + 1u] = bitcast(b.y); +} + +// The first texel (row-major) tied with the nearest distance, the CPU raster's stamp center +@compute @workgroup_size(8, 8) +fn smudge_center(@builtin(global_invocation_id) id: vec3) { + let header = id.z * 6u; + let nearest = atomicLoad(&stamp_state[STATE_DISTANCE]); + let width = textureDimensions(uv_surface).x; + let distances = tiles[header + 5u] + id.y * 64u + id.x * 2u; + for (var k = 0u; k < 2u; k++) { + let pixel = vec2(tiles[header], tiles[header + 1u]) + vec2(id.x * 2u + k, id.y); + if nearest != bitcast(NO_DISTANCE) && bitcast(alpha_out[distances + k]) <= bitcast(nearest) { + atomicMin(&stamp_state[STATE_CENTER], pixel.y * width + pixel.x); + } + } +} + +// Rust's f32::round (half away from zero); the fraction is compared, as adding 0.5 rounds up a +// value just below a half +fn round_away(v: f32) -> f32 { + let whole = floor(abs(v)); + return sign(v) * (whole + select(0.0, 1.0, abs(v) - whole >= 0.5)); +} + +@compute @workgroup_size(1) +fn smudge_resolve() { + let low = vec2(atomicLoad(&stamp_state[STATE_MIN_X]), atomicLoad(&stamp_state[STATE_MIN_X + 1u])); + let high = vec2(atomicLoad(&stamp_state[STATE_MAX_X]), atomicLoad(&stamp_state[STATE_MAX_X + 1u])); + atomicStore(&stamp_state[STATE_ACTIVE], 0u); + + // A stamp with no texels changes nothing, not even the previous center + if any(high < low) { return; } + + // A clone reads at its fixed offset from the first stamp on + if smudge.clone_mode != 0u { + atomicStore(&stamp_state[STATE_SHIFT], bitcast(smudge.clone_x)); + atomicStore(&stamp_state[STATE_SHIFT + 1u], bitcast(smudge.clone_y)); + atomicStore(&stamp_state[STATE_ACTIVE], 1u); + return; + } + var center = vec2(bitcast(atomicLoad(&stamp_state[STATE_UV_CENTER])), bitcast(atomicLoad(&stamp_state[STATE_UV_CENTER + 1u]))); + if params.flags.x == 0u { + let width = textureDimensions(uv_surface).x; + let index = atomicLoad(&stamp_state[STATE_CENTER]); + + // Texels but no center cannot happen (opacity needs the volume); drag nothing, keep the trail + if index == 0xffffffffu { return; } + center = vec2(f32(index % width), f32(index / width)) + 0.5; + } + let lane = atomicLoad(&stamp_state[STATE_LANE]) * 4u; + let had_previous = lane_state[lane] != 0u; + let previous = vec2(bitcast(lane_state[lane + 1u]), bitcast(lane_state[lane + 2u])); + lane_state[lane] = 1u; + lane_state[lane + 1u] = bitcast(center.x); + lane_state[lane + 2u] = bitcast(center.y); + + // The first stamp only picks up; a jump across a seam or a lifted cursor drags nothing + if !had_previous { return; } + let moved = center - previous; + let extent = f32(max(high.x - low.x, high.y - low.y)) + 1.0; + if length(moved) > extent { return; } + atomicStore(&stamp_state[STATE_SHIFT], bitcast(i32(-round_away(moved.x)))); + atomicStore(&stamp_state[STATE_SHIFT + 1u], bitcast(i32(-round_away(moved.y)))); + atomicStore(&stamp_state[STATE_ACTIVE], 1u); +} + +fn unit16(v: u32) -> f32 { + return f32(v) / 65535.0; +} + +fn quantize(v: f32) -> u32 { + return u32(clamp(v, 0.0, 1.0) * 65535.0 + 0.5); +} + +// StampBlending::weights: the previous coverage's and the stamp's share +fn blend_weights(previous: f32, stamp: f32) -> vec2 { + switch params.stamp_blending { + case BLEND_LIGHTEN: { + if stamp > previous { return vec2(0.0, stamp); } + return vec2(previous, 0.0); + } + case BLEND_ADD: { return vec2(previous, stamp); } + default: { return vec2(previous * (1.0 - stamp), stamp); } + } +} + +// What one texel deposits: its source texel, the stamp's alpha and the stroke's (or the lane's) +// shared coverage seen at the source +struct Deposit { + deposits: bool, + source: vec2, + stamp: f32, + seen: f32, +} + +fn deposit_at(pixel: vec2, opacity: f32, mask: u32) -> Deposit { + var result = Deposit(false, vec2(0), 0.0, 0.0); + if atomicLoad(&stamp_state[STATE_ACTIVE]) == 0u { return result; } + let shift = vec2(bitcast(atomicLoad(&stamp_state[STATE_SHIFT])), bitcast(atomicLoad(&stamp_state[STATE_SHIFT + 1u]))); + let source = vec2(pixel) + shift; + let a = opacity * quick_limit(pixel, mask); + if !(a > 0.0) || any(source < vec2(0)) || any(source >= vec2(textureDimensions(uv_surface))) { return result; } + if textureLoad(uv_surface, source, 0).x == NONE { return result; } + let stamp = a * smudge.strength; + if stamp <= 0.0 { return result; } + result.deposits = true; + result.source = source; + result.stamp = stamp; + + // A clone reads the source only + if smudge.clone_mode != 0u { return result; } + if smudge.isolated != 0u { + result.seen = unit16(textureLoad(lane_alpha, source, 0).x); + } else { + result.seen = unit16(textureLoad(alpha_in, source, 0).x); + } + return result; +} + +fn channel_count() -> u32 { + return smudge.scalars + smudge.colors; +} + +// A channel's own alpha (per-channel alphas) at `at`: the stroke's or the lane's +fn own_alpha(at: vec2, k: u32, lane: bool) -> f32 { + if lane { return unit16(textureLoad(lane_scalars, at, smudge.scalars + k, 0).x); } + return unit16(textureLoad(carried_scalars, at, smudge.scalars + k, 0).x); +} + +// A channel's own alpha, 0 without per-channel alphas (the maps then hold no such layers) +fn own_or_zero(at: vec2, k: u32, lane: bool) -> f32 { + if smudge.channel_alphas == 0u { return 0.0; } + return own_alpha(at, k, lane); +} + +// What channel `k` sees deposited at the source: its own alpha there (the lane's when isolated), +// or the shared coverage +fn channel_seen(d: Deposit, k: u32) -> f32 { + if smudge.channel_alphas == 0u || smudge.clone_mode != 0u { return d.seen; } + return own_alpha(d.source, k, smudge.isolated != 0u); +} + +// The source's coverage of channel `k` (1 without per-channel coverage) +fn source_coverage(source: vec2, k: u32) -> f32 { + if smudge.channel_alphas == 0u { return 1.0; } + let layer = (smudge.scalars + 3u) / 4u + k / 4u; + return unit16(textureLoad(source_scalars, source, layer, 0)[k % 4u]); +} + +// Channel `k`'s share of the stamp: the stamp times the coverage it reads, the deposits seen +// over the source's coverage (Pickup::stamp's channel_alpha) +fn channel_stamp(d: Deposit, k: u32) -> f32 { + let seen = channel_seen(d, k); + return d.stamp * (seen + source_coverage(d.source, k) * (1.0 - seen)); +} + +// What a texel reads: the carried value seen over the source by its coverage +fn picked(base: vec4, carried: vec4, seen: f32, coverage: f32) -> vec4 { + let b = vec4(base) / 65535.0; + if seen <= 0.0 { return b; } + let source_weight = coverage * (1.0 - seen); + return (vec4(carried) / 65535.0 * seen + b * source_weight) / (seen + source_weight); +} + +fn blended(value: vec4, destination: vec4, weights: vec2) -> vec4 { + let total = max(weights.x + weights.y, MIN_BLEND_WEIGHT); + let mixed = (value * weights.y + vec4(destination) / 65535.0 * weights.x) / total; + return vec4(quantize(mixed.x), quantize(mixed.y), quantize(mixed.z), quantize(mixed.w)); +} + +// A value deposited into `old`: by the shared weights, or by the channel's own alpha `alpha` +// (unchanged where its share of the stamp is none) +fn deposited(value: vec4, old: vec4, stroke_weights: vec2, alpha: f32, stamp: f32) -> vec4 { + if smudge.channel_alphas == 0u { return blended(value, old, stroke_weights); } + let weights = blend_weights(alpha, stamp); + if weights.y <= 0.0 { return old; } + return blended(value, old, weights); +} + +fn put_scalar(base: u32, pixel: vec2, value: u32) { + let local = pixel % 64u; + let word = base + local.y * 64u + local.x / 2u; + let shift = (local.x % 2u) * 16u; + deposit_out[word] = (deposit_out[word] & ~(0xffffu << shift)) | (value << shift); +} + +fn put_color(base: u32, pixel: vec2, value: vec4) { + let local = pixel % 64u; + let word = base + local.y * 128u + local.x * 2u; + deposit_out[word] = value.x | (value.y << 16u); + deposit_out[word + 1u] = value.z | (value.w << 16u); +} + +fn deposit_texel(pixel: vec2, opacity: f32, mask: u32, tile: u32) { + let at = vec2(pixel); + let d = deposit_at(pixel, opacity, mask); + let isolated = smudge.isolated != 0u; + let own = smudge.channel_alphas != 0u; + + // The texel takes the strongest channel's share (every channel's without per-channel alphas) + var strongest = d.stamp; + if own && d.deposits { + strongest = 0.0; + for (var k = 0u; k < channel_count(); k++) { + strongest = max(strongest, channel_stamp(d, k)); + } + } + let deposits = d.deposits && strongest > 0.0; + var base = tile * smudge.tile_words; + let old_alpha = textureLoad(alpha_in, at, 0).x; + let stroke = blend_weights(unit16(old_alpha), strongest); + put_scalar(base, pixel, select(old_alpha, quantize(stroke.x + stroke.y), deposits)); + base += 4096u; + var lane = vec2(0.0); + if isolated { + // With per-channel alphas a lane has no shared alpha (Pickup's lanes) + let old_lane = textureLoad(lane_alpha, at, 0).x; + lane = blend_weights(unit16(old_lane), strongest); + put_scalar(base, pixel, select(old_lane, quantize(lane.x + lane.y), deposits && !own)); + base += 4096u; + } + for (var c = 0u; c < smudge.scalars; c++) { + let stroke_old = vec4(textureLoad(carried_scalars, at, c, 0).x, 0u, 0u, 0u); + var stroke_new = stroke_old; + var lane_old = vec4(0u); + if isolated { lane_old = vec4(textureLoad(lane_scalars, at, c, 0).x, 0u, 0u, 0u); } + var lane_new = lane_old; + if deposits { + let base_value = vec4(textureLoad(source_scalars, d.source, c / 4u, 0)[c % 4u], 0u, 0u, 0u); + var seen_value = vec4(textureLoad(carried_scalars, d.source, c, 0).x, 0u, 0u, 0u); + if isolated { seen_value = vec4(textureLoad(lane_scalars, d.source, c, 0).x, 0u, 0u, 0u); } + let value = picked(base_value, seen_value, channel_seen(d, c), source_coverage(d.source, c)); + let share = channel_stamp(d, c); + stroke_new = deposited(value, stroke_old, stroke, own_or_zero(at, c, false), share); + if isolated { lane_new = deposited(value, lane_old, lane, own_or_zero(at, c, true), share); } + } + put_scalar(base, pixel, stroke_new.x); + base += 4096u; + if isolated { + put_scalar(base, pixel, lane_new.x); + base += 4096u; + } + } + for (var c = 0u; c < smudge.colors; c++) { + let k = smudge.scalars + c; + let stroke_old = textureLoad(carried_colors, at, c, 0); + var stroke_new = stroke_old; + var lane_old = vec4(0u); + if isolated { lane_old = textureLoad(lane_colors, at, c, 0); } + var lane_new = lane_old; + if deposits { + var seen_value = textureLoad(carried_colors, d.source, c, 0); + if isolated { seen_value = textureLoad(lane_colors, d.source, c, 0); } + let value = picked(textureLoad(source_colors, d.source, c, 0), seen_value, channel_seen(d, k), source_coverage(d.source, k)); + let share = channel_stamp(d, k); + stroke_new = deposited(value, stroke_old, stroke, own_or_zero(at, k, false), share); + if isolated { lane_new = deposited(value, lane_old, lane, own_or_zero(at, k, true), share); } + } + put_color(base, pixel, stroke_new); + base += 8192u; + if isolated { + put_color(base, pixel, lane_new); + base += 8192u; + } + } + + // Each channel's own alpha grows by its share of the stamp + if !own { return; } + for (var k = 0u; k < channel_count(); k++) { + let share = select(0.0, channel_stamp(d, k), deposits); + let stroke_alpha = own_alpha(at, k, false); + let stroke_weights = blend_weights(stroke_alpha, share); + put_scalar(base, pixel, select(quantize(stroke_alpha), quantize(stroke_weights.x + stroke_weights.y), share > 0.0 && stroke_weights.y > 0.0)); + base += 4096u; + if isolated { + let lane_alpha_k = own_alpha(at, k, true); + let lane_weights = blend_weights(lane_alpha_k, share); + put_scalar(base, pixel, select(quantize(lane_alpha_k), quantize(lane_weights.x + lane_weights.y), share > 0.0 && lane_weights.y > 0.0)); + base += 4096u; + } + } +} + +@compute @workgroup_size(8, 8) +fn smudge_deposit(@builtin(global_invocation_id) id: vec3) { + let header = id.z * 6u; + let origin = vec2(tiles[header], tiles[header + 1u]) + vec2(id.x * 2u, id.y); + let mask = tiles[header + 4u]; + let local = id.z * 4096u + id.y * 64u + id.x * 2u; + deposit_texel(origin, bitcast(alpha_out[local]), mask, id.z); + deposit_texel(origin + vec2(1u, 0u), bitcast(alpha_out[local + 1u]), mask, id.z); +} diff --git a/crates/render/src/shaders/stencil_projection.wgsl b/crates/render/src/shaders/stencil_projection.wgsl index 89d958f44..85b5816b0 100644 --- a/crates/render/src/shaders/stencil_projection.wgsl +++ b/crates/render/src/shaders/stencil_projection.wgsl @@ -1,4 +1,8 @@ // Shared by live material compositing and projected stroke commit +// rotation_flags.w: how the image's colors are read +const STENCIL_SRGB: f32 = 1.0; +const STENCIL_MASK: f32 = 2.0; + struct StencilProjection { view_proj: mat4x4, center_half: vec4, @@ -58,8 +62,14 @@ fn stencil_sample(image: texture_2d, placement: StencilProjection, position return vec4(0.0); } + // A mask stencil passes its stored gray times its alpha, like CPU `Stencil::mask_world` + if placement.rotation_flags.w == STENCIL_MASK { + let gray = dot(rgba.rgb, vec3(0.2126, 0.7152, 0.0722)); + return vec4(rgba.rgb, clamp(gray * rgba.w, 0.0, 1.0)); + } + var color = rgba.rgb; - if placement.rotation_flags.w != 0.0 { + if placement.rotation_flags.w == STENCIL_SRGB { let srgb = clamp(color, vec3(0.0), vec3(1.0)); color = select(pow((srgb + 0.055) / 1.055, vec3(2.4)), srgb / 12.92, srgb <= vec3(0.04045)); } diff --git a/crates/render/src/shaders/trace.wgsl b/crates/render/src/shaders/trace.wgsl index 0b1ea9c4f..5030307c0 100644 --- a/crates/render/src/shaders/trace.wgsl +++ b/crates/render/src/shaders/trace.wgsl @@ -7,9 +7,9 @@ const PI: f32 = 3.14159265358979; const TAU: f32 = 6.28318530717959; const BIG: f32 = 3.0e38; const WALK_STEPS: u32 = 48u; -const MAX_SETS: u32 = 256u; -// MAX_SETS / 4: the height slope factors pack four sets to an entry -const HEIGHT_Y_FACTOR_ENTRIES: u32 = 64u; +const SET_ENTRIES: u32 = 2048u; +// SET_ENTRIES / 4: the height slope factors pack four sets to an entry +const HEIGHT_Y_FACTOR_ENTRIES: u32 = 512u; struct Params { inv_vp: mat4x4, @@ -21,7 +21,7 @@ struct Params { eye: vec4, // camera position lens: vec4, // focus depth along the view axis, lens radius (0: pinhole), transmission IOR, dielectric F0 scale // Per texture set (array layer): width, height, bit mask of 1×1 placeholder kinds (bit 8: Smooth (Sobel) height to normal), height strength - sets: array, MAX_SETS>, + sets: array, SET_ENTRIES>, // Per texture set, four to an entry: how much more the height slope tilts down the texture than across it height_y_factors: array, HEIGHT_Y_FACTOR_ENTRIES>, }; diff --git a/crates/render/src/trace.rs b/crates/render/src/trace.rs index ec1e52e1a..77db059dc 100644 --- a/crates/render/src/trace.rs +++ b/crates/render/src/trace.rs @@ -348,8 +348,8 @@ pub struct Tracer { impl Tracer { pub fn new(width: u32, height: u32) -> Tracer { - let (w, h) = (width.clamp(1, 8192), height.clamp(1, 8192)); - Tracer { width: w, height: h, samples: 0, row: 0, acc: vec![Px::default(); (w * h) as usize] } + let (w, h) = (width.max(1), height.max(1)); + Tracer { width: w, height: h, samples: 0, row: 0, acc: vec![Px::default(); w as usize * h as usize] } } /// Add one sample per pixel. diff --git a/crates/render/tests/headless.rs b/crates/render/tests/headless.rs index 74915841a..44c5dcacc 100644 --- a/crates/render/tests/headless.rs +++ b/crates/render/tests/headless.rs @@ -472,10 +472,10 @@ fn bake_neutral_material_shades_the_low_poly_in_its_settings() { fn bake_neutral_material_reads_the_bent_normal_in_the_tangent_frame() { let Some((mut h, frame)) = setup() else { return }; let upload_bent = |h: &mut Headless, texel: [u8; 4]| { - let size = texturecraft_render::aux_size((256, 256)); - let rgba = texel.repeat((size * size) as usize); + let extent = texturecraft_render::aux_extent((256, 256), 0); + let rgba = texel.repeat((extent.0 * extent.1) as usize); for ts in 0..2 { - h.renderer.upload_aux(&h.device, &h.queue, ts, size, &rgba); + h.renderer.upload_aux(&h.device, &h.queue, ts, extent, &rgba); } }; @@ -1341,7 +1341,7 @@ fn texture_sets_take_no_gpu_memory_until_painted() { let sets: Vec<((u32, u32), usize)> = (0..40).map(|m| ((2048, 2048), m)).collect(); h.renderer.set_texture_sets(&h.device, &h.queue, &sets, 40); assert!(widths(&h).iter().flatten().all(|w| *w == 1), "every display texture starts as a 1×1 placeholder"); - assert!((0..40).all(|ts| h.renderer.aux_size(ts) == Some(1)), "so does every aux texture"); + assert!((0..40).all(|ts| h.renderer.aux_extent(ts) == Some((1, 1))), "so does every aux texture"); // A neutral tile changes nothing; the first painted one allocates that kind alone. let kind = DisplayKind::BaseColor; let neutral = kind.default_texel().repeat(64 * 64); @@ -1352,10 +1352,10 @@ fn texture_sets_take_no_gpu_memory_until_painted() { assert_eq!(w[3][0], 2048, "the painted kind is full size"); assert!(w[3][1..].iter().all(|w| *w == 1) && w[2].iter().all(|w| *w == 1), "nothing else was allocated"); // The aux texture is allocated by its first upload, at the set's aux size only. - h.renderer.upload_aux(&h.device, &h.queue, 3, 512, &[0; 512 * 512 * 4]); - assert_eq!(h.renderer.aux_size(3), Some(1), "a wrong aux size is ignored"); - h.renderer.upload_aux(&h.device, &h.queue, 3, 2048, &[90; 2048 * 2048 * 4]); - assert_eq!(h.renderer.aux_size(3), Some(2048)); + h.renderer.upload_aux(&h.device, &h.queue, 3, (512, 512), &[0; 512 * 512 * 4]); + assert_eq!(h.renderer.aux_extent(3), Some((1, 1)), "a wrong aux size is ignored"); + h.renderer.upload_aux(&h.device, &h.queue, 3, (2048, 2048), &[90; 2048 * 2048 * 4]); + assert_eq!(h.renderer.aux_extent(3), Some((2048, 2048))); assert!(h.renderer.take_memory_failures().is_empty()); } diff --git a/crates/ui-egui/src/bake_mode/map_thumbnails.rs b/crates/ui-egui/src/bake_mode/map_thumbnails.rs index fe7e96b3a..637e57426 100644 --- a/crates/ui-egui/src/bake_mode/map_thumbnails.rs +++ b/crates/ui-egui/src/bake_mode/map_thumbnails.rs @@ -44,7 +44,7 @@ impl MapThumbnails { return Some(texture.clone()); } - let rgba = texturecraft_render::mesh_maps::mesh_map_rgba(baked, map, THUMBNAIL_PIXELS, cache.size, &cache.composite.block_scales); + let rgba = texturecraft_render::mesh_maps::mesh_map_rgba(baked, map, (THUMBNAIL_PIXELS, THUMBNAIL_PIXELS), cache.size, &cache.composite.block_scales); let side = THUMBNAIL_PIXELS as usize; let image = ColorImage::from_rgba_unmultiplied([side, side], &rgba); let texture = context.load_texture(format!("bake_map_{texture_set}_{}", map.id()), image, TextureOptions::LINEAR); diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index b5d7de55f..2db07f90b 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -288,6 +288,7 @@ fn refresh_draft_preferences(draft: &mut Prefs, previous: &Prefs, current: &Pref language, viewport_texture, gpu_compositing, + gpu_memory_budget_mb, material_start_preview, brightness, accent, diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index cb720ee46..7ff3df612 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -3,7 +3,7 @@ use std::borrow::Cow; use std::collections::{BTreeMap, BTreeSet, HashMap}; -use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::atomic::{AtomicBool, AtomicU32, AtomicUsize, Ordering}; use std::sync::{Arc, Mutex, PoisonError, Weak}; use eframe::egui_wgpu::{self, CallbackResources, CallbackTrait, ScreenDescriptor}; @@ -28,6 +28,7 @@ use texturecraft_render::{ gpu_composite::{LiveBrush, LiveBrushTarget}, }; +use texturecraft_render::gpu_aux_view::AuxSource; use texturecraft_render::gpu_quick_mask::{QuickMaskAlpha, QuickMaskOverlay}; use crate::bake_scene::{BakeSceneLink, CageUpload}; @@ -61,9 +62,13 @@ mod composite_work; mod device_stroke; mod lit_environment; mod mask_preview; +#[cfg(not(target_arch = "wasm32"))] +mod preview_composite_device; mod set_compositor; #[cfg(not(target_arch = "wasm32"))] mod viewport_brush_device; +#[cfg(not(target_arch = "wasm32"))] +mod viewport_depth_device; use composite_key::CompositeKey; use composite_work::CompositeWork; @@ -71,9 +76,13 @@ use composite_work::CompositeWork; use device_stroke::DeviceStroke; use lit_environment::LitEnvironment; use mask_preview::MaskPreview; +#[cfg(not(target_arch = "wasm32"))] +use preview_composite_device::PreviewCompositeDevice; use set_compositor::SetCompositor; #[cfg(not(target_arch = "wasm32"))] use viewport_brush_device::ViewportBrushDevice; +#[cfg(not(target_arch = "wasm32"))] +use viewport_depth_device::ViewportDepthDevice; /// The low poly's hard edges without a UV seam (vertex pairs) per material pub type MissingSeamEdges = Vec>; @@ -91,21 +100,35 @@ pub struct SceneSync { /// Reduction applied when preparing each display tile. pub tile_shift: u32, pub overview: Option<(usize, texturecraft_engine::MaterialOverview)>, + /// The overview was composited off the UI thread: it seeds the set only while nothing + /// newer (a composite or a tile) has reached the set's textures + late_overview: bool, cleared_overviews: Vec, cpu_texture_sets: Vec, composites: Vec, /// Programs whose pipelines the GPU starts compiling ahead (the project's sets at load) prewarm: Vec, + /// The set whose live clone or smudge pipelines the GPU starts compiling ahead (the tool is + /// picked and the set composites on the GPU) + prewarm_pickup: Option, composite_work: Option, pub(crate) compositor_changed: bool, + /// The GPU memory budget setting + memory_budget: texturecraft_render::gpu_memory::GpuMemoryBudget, pub tiles: Vec<(usize, DisplayKind, u32, u32, Vec)>, released_dabs: Vec, + /// Aux textures produced on the CPU (layers composite on the CPU): set, extent, RGBA8 pub aux: Vec<(usize, (u32, u32), Vec)>, + /// Aux views the GPU draws from their sources (layers composite on the GPU) + aux_views: Vec<(usize, AuxSource)>, + /// Where the GPU records the sets whose aux view failed to draw ([`GpuLink::aux_failed`]) + aux_failed: Option>>>, + release_aux_views: bool, quick_masks: Vec<(usize, QuickMaskOverlay)>, quick_mask_failed: Option>, release_quick_mask: bool, - /// One image buffer per resolution, with all texture sets that need it. - pub image_aux: BTreeMap, Vec)>, + /// One image buffer per aux extent, with all texture sets that need it. + pub image_aux: BTreeMap<(u32, u32), (Vec, Vec)>, /// Bake mode's high poly (`None` removes it) and the id it is sent under pub bake_high: Option<(Option>, u64)>, /// Which vertices of the high poly (by its id) the bake's rays miss (1) or reach (0) @@ -130,6 +153,7 @@ impl SceneSync { /// The sets recreated, the errors, and whether a composite waits for its pipelines. fn apply_display(&self, renderer: &mut Renderer, device: &wgpu::Device, queue: &wgpu::Queue) -> (Vec, Vec<(usize, String)>, bool) { let mut reset = Vec::new(); + renderer.set_memory_budget(self.memory_budget); if let Some((sets, material_count, shift)) = &self.sets { renderer.set_display_shift(*shift); reset = renderer.set_texture_sets(device, queue, sets, *material_count); @@ -144,20 +168,28 @@ impl SceneSync { for program in &self.prewarm { renderer.prewarm_composite(device, program); } + if let Some(ts) = self.prewarm_pickup { + let _ = renderer.prewarm_pickup_composite(device, ts); + } let mut errors = Vec::new(); let mut waiting = false; - for CompositeSubmission { ts, program, failed, pending, underlay_drawn } in &self.composites { + for CompositeSubmission { ts, program, failed, pending, underlay_drawn, written } in &self.composites { match renderer.composite_on_gpu(device, queue, *ts, program) { // Its pipelines still compile: the set keeps its last result, and plans again Err(error) if error == GPU_PIPELINES_PENDING => { pending.store(true, Ordering::Release); waiting = true; } + // A GPU error (after the renderer's one retry when memory ran out) is shown, and + // the set keeps its last textures: nothing composites on the CPU instead + Err(error) if texturecraft_render::gpu_memory::is_device_error(&error) => errors.push((*ts, error)), + // A refusal (a layout or limit the compositor cannot take) composites on the CPU Err(error) => { failed.store(true, Ordering::Release); errors.push((*ts, error)); } Ok(()) => { + written.store(true, Ordering::Release); if let Some(drawn) = underlay_drawn { drawn.store(true, Ordering::Release); } @@ -165,7 +197,11 @@ impl SceneSync { } } if let Some((ts, overview)) = &self.overview { - renderer.seed_display(device, queue, *ts, overview.size, &overview.maps); + if self.late_overview { + renderer.seed_display_unless_written(device, queue, *ts, overview.size, &overview.maps); + } else { + renderer.seed_display(device, queue, *ts, overview.size, &overview.maps); + } } for (texture_set, kind, tile_x, tile_y, bytes) in &self.tiles { renderer.upload_display_tile(device, queue, *texture_set, *kind, *tile_x, *tile_y, bytes, self.tile_shift); @@ -175,13 +211,26 @@ impl SceneSync { } for (ts, overlay) in &self.quick_masks { if let Err(err) = renderer.draw_quick_mask(device, queue, *ts, overlay) { - if let Some(failed) = &self.quick_mask_failed { + // Only a refusal (coverage that does not match the set) draws the overlay on the CPU + if let Some(failed) = self.quick_mask_failed.as_ref().filter(|_| !texturecraft_render::gpu_memory::is_device_error(&err)) { failed.store(true, Ordering::Release); } errors.push((*ts, err)); break; } } + if self.release_aux_views { + renderer.release_aux_view_sources(); + } + for (ts, source) in &self.aux_views { + // No CPU view replaces a failed GPU view: the error is shown + if let Err(error) = renderer.draw_aux_view(device, queue, *ts, source) { + if let Some(failed) = &self.aux_failed { + failed.lock().unwrap_or_else(PoisonError::into_inner).insert(*ts); + } + errors.push((*ts, error)); + } + } for dab in &self.released_dabs { dab.acknowledge_upload(); } @@ -213,7 +262,7 @@ pub struct GpuReports { const MAX_GPU_ERRORS: usize = 8; /// How often a frame looks again while a composite waits for its pipelines const PIPELINE_POLL: std::time::Duration = std::time::Duration::from_millis(30); -const GPU_COMPOSITE_ERROR: &str = n_("GPU compositing reported a device error. See the app log for details."); +const GPU_COMPOSITE_REFUSED: &str = n_("The GPU compositor cannot take this material. See the app log for details."); const NO_COVERED_TEXELS: &str = n_("The texture set has no covered UV texels."); /// The project the GPU compositor compiles for the view: while a layer is soloed, the material @@ -243,6 +292,11 @@ pub struct GpuLink { env: (String, Option>), /// What each set's aux texture holds: (view key, revision). aux: BTreeMap, + /// Sets whose GPU aux view failed to draw, reported by the GPU side + aux_failed: Arc>>, + /// The view each set drew once more after a failure: a second failure of the same view + /// keeps the error until the view changes, so a failing view is not redrawn every frame + aux_retried: BTreeMap, /// Image identity without holding its decoded pixels alive. aux_image: Option>, /// Weak identity of the last uploaded ID mask image. @@ -259,12 +313,30 @@ pub struct GpuLink { upload_cursor: Option, pending_overviews: BTreeSet, active_overviews: BTreeSet, + /// The material overview the composite device makes on a worker thread + #[cfg(not(target_arch = "wasm32"))] + overview_job: Option, gpu_composite_enabled: bool, /// Why the adapter never composites on the GPU (None: it may), shown as the status reason composite_refusal: Option<&'static str>, + /// A hardware adapter (not a software rasterizer): it draws the aux views even where the + /// layer compositor is refused (GL, Direct3D 12 with FXC) + real_gpu: bool, #[cfg(not(target_arch = "wasm32"))] brush_device: Option>, + #[cfg(not(target_arch = "wasm32"))] + depth_device: Option>, + /// Composites the shelf and orb material previews + #[cfg(not(target_arch = "wasm32"))] + composite_device: Option>, pub(crate) prefer_gpu_layers: bool, + /// The device's largest texture side, which can halve a set's display beyond `shift` + max_texture_side: u32, + /// Megabytes of the GPU memory budget setting (0: automatic) + pub(crate) memory_budget_mb: u32, + /// The setting as the preview renderer ([`PreviewCompositeDevice`]) applies it to its own + /// cached inputs + preview_memory_budget_mb: Arc, pub(crate) material_start_preview: bool, compositors: Vec, underlay_budget: u64, @@ -286,6 +358,69 @@ const FRAME_BUDGET_MS: f64 = 35.0; const MIN_SLICE_MS: f64 = 4.0; /// Display tiles converted between budget checks. const UPLOAD_CHUNK: usize = 64; + +/// A material overview the composite device makes on a worker thread +#[cfg(not(target_arch = "wasm32"))] +struct OverviewJob { + ts: usize, + result: std::sync::mpsc::Receiver>, + /// Set when the job is dropped (reset, shift change, preview off, the set's composite + /// arrived): the worker stops before its next composite + cancel: Arc, +} + +#[cfg(not(target_arch = "wasm32"))] +impl Drop for OverviewJob { + fn drop(&mut self) { + self.cancel.store(true, Ordering::Release); + } +} + +#[cfg(not(target_arch = "wasm32"))] +impl OverviewJob { + /// Render `snapshot` of set `ts` on `device` on a new worker thread + fn start( + ts: usize, + snapshot: texturecraft_engine::OverviewSnapshot, + device: Arc, + ) -> Option { + let (sender, result) = std::sync::mpsc::channel(); + let cancel = Arc::new(AtomicBool::new(false)); + let cancelled = cancel.clone(); + let spawned = std::thread::Builder::new().name("material-overview".into()).spawn(move || { + // The receiver is gone when the set was reset meanwhile: nothing waits for this one + let _ = sender.send(snapshot.render(Some(device.as_ref()), Some(&cancelled))); + }); + match spawned { + Ok(_) => Some(OverviewJob { ts, result, cancel }), + Err(error) => { + log::error!("The material overview could not start: {error}"); + None + } + } + } + + /// The finished overview of `job` and its set, while the set still waits for its material; + /// a GPU error is shown to the user (no CPU overview stands in for it) + fn take(job: &mut Option, session: &Session) -> Option<(usize, texturecraft_engine::MaterialOverview)> { + let ts = job.as_ref()?.ts; + let result = match job.as_ref()?.result.try_recv() { + Ok(result) => result, + Err(std::sync::mpsc::TryRecvError::Empty) => return None, + Err(std::sync::mpsc::TryRecvError::Disconnected) => Err("the overview worker stopped".into()), + }; + *job = None; + match result { + Ok(overview) if session.caches.get(ts).is_some_and(|cache| !cache.dirty.is_empty() || !cache.upload.is_empty()) => Some((ts, overview)), + Ok(_) => None, + // Shown to the user as the shelf's preview errors are (the log has no reader) + Err(error) => { + crate::preview_device::report_error(&format!("texture set {}", ts + 1), &error); + None + } + } + } +} /// Estimated GPU upload cost of one display tile (write_texture of one 64×64 tile of one /// display kind, measured at ~5.5 µs on a desktop GPU), counted against the frame budget. const UPLOAD_MS_PER_TILE: f64 = 0.006; @@ -338,6 +473,7 @@ pub fn init(rs: &egui_wgpu::RenderState, ctx: &egui::Context) -> GpuLink { wake.request_repaint(); })); let mut renderer = Renderer::new(&rs.device, &rs.queue, rs.target_format); + let preview_memory_budget_mb = Arc::new(AtomicU32::new(0)); // New composite pipelines compile on worker threads; the viewport keeps its last result renderer.set_asynchronous_compile(!cfg!(test)); @@ -358,6 +494,8 @@ pub fn init(rs: &egui_wgpu::RenderState, ctx: &egui::Context) -> GpuLink { shift: 0, env: Default::default(), aux: BTreeMap::new(), + aux_failed: Arc::default(), + aux_retried: BTreeMap::new(), aux_image: None, aux_id_mask: None, sent: HashMap::new(), @@ -366,13 +504,23 @@ pub fn init(rs: &egui_wgpu::RenderState, ctx: &egui::Context) -> GpuLink { upload_cursor: None, pending_overviews: BTreeSet::new(), active_overviews: BTreeSet::new(), + #[cfg(not(target_arch = "wasm32"))] + overview_job: None, gpu_composite_enabled: !cfg!(target_arch = "wasm32") && composite_refusal.is_none() && std::env::var("TEXTURECRAFT_GPU_COMPOSITE").as_deref() != Ok("0"), composite_refusal, + real_gpu: !cfg!(target_arch = "wasm32") && info.device_type != wgpu::DeviceType::Cpu, #[cfg(not(target_arch = "wasm32"))] brush_device: Some(Arc::new(ViewportBrushDevice(rs.clone()))), + #[cfg(not(target_arch = "wasm32"))] + depth_device: Some(Arc::new(ViewportDepthDevice { render_state: rs.clone(), passes: Default::default() })), + #[cfg(not(target_arch = "wasm32"))] + composite_device: Some(Arc::new(PreviewCompositeDevice::new(rs.clone(), preview_memory_budget_mb.clone()))), prefer_gpu_layers: true, + max_texture_side: rs.device.limits().max_texture_dimension_2d, + memory_budget_mb: 0, + preview_memory_budget_mb, material_start_preview: true, compositors: Vec::new(), underlay_budget: CompositeProgram::material_underlay_limit(&rs.device.limits()), @@ -391,6 +539,53 @@ impl GpuLink { self.gpu_composite_enabled } + /// Whether the GPU draws the mesh-map, image and ID-mask views from their sources: on a + /// hardware adapter unless the user chose CPU compositing (then the CPU resamples them) + fn gpu_aux_views(&self) -> bool { + self.prefer_gpu_layers && self.real_gpu + } + + /// How many times the renderer halves a set of `size` texels for display + fn set_shift(&self, size: (u32, u32)) -> u32 { + texturecraft_render::set_shift(size, self.shift, self.max_texture_side) + } + + /// The device rasterizing the paint camera's depth: the GPU unless compositing is off or the + /// adapter composites on the CPU + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn depth_device(&self) -> Option> { + self.depth_device.clone().filter(|_| self.gpu_composite_enabled && self.prefer_gpu_layers) + } + + /// Whether the material overview of `ts` is still being made on a worker thread (its tiles + /// wait for it) + #[cfg(not(target_arch = "wasm32"))] + fn overview_pending_for(&self, ts: usize) -> bool { + self.overview_job.as_ref().is_some_and(|job| job.ts == ts) + } + + #[cfg(target_arch = "wasm32")] + fn overview_pending_for(&self, _ts: usize) -> bool { + false + } + + /// The device compositing the shelf and orb material previews: the GPU unless compositing is + /// off or the adapter composites on the CPU + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn composite_device(&self) -> Option> { + self.composite_device.clone().filter(|_| self.gpu_composite_enabled && self.prefer_gpu_layers) + } + + /// The GPU brush for repainting recorded strokes on a resize: any view, while layers composite on the GPU + #[cfg(not(target_arch = "wasm32"))] + pub(crate) fn resize_brush_device(&self) -> Option> { + if !self.gpu_composite_enabled || !self.prefer_gpu_layers { + return None; + } + + self.brush_device.clone() + } + #[cfg(not(target_arch = "wasm32"))] pub(crate) fn brush_device(&self, session: &Session) -> Option { let ts = session.ts(); @@ -485,14 +680,14 @@ impl GpuLink { return (n_("Mask: GPU"), n_("The graphics card composes the displayed mask.")); } - let reason = if compositor.failed.load(Ordering::Acquire) { GPU_COMPOSITE_ERROR } else { compositor.reason }; + let reason = if compositor.failed.load(Ordering::Acquire) { GPU_COMPOSITE_REFUSED } else { compositor.reason }; return (n_("Mask: CPU"), reason); } let cpu = self.compositors.iter().find(|set| !set.uses_gpu()); let uses_gpu = self.compositors.iter().any(|set| set.uses_gpu() && !set.neutral); let reason = - cpu.map_or(n_("Waiting for the first material update"), |set| if set.failed.load(Ordering::Acquire) { GPU_COMPOSITE_ERROR } else { set.reason }); + cpu.map_or(n_("Waiting for the first material update"), |set| if set.failed.load(Ordering::Acquire) { GPU_COMPOSITE_REFUSED } else { set.reason }); match (uses_gpu, cpu) { (true, None) if self.compositors.iter().any(SetCompositor::uses_underlay) => { (n_("Layers: GPU + CPU"), n_("The GPU composites over cached material from the CPU.")) @@ -520,15 +715,29 @@ impl GpuLink { let global_reason = self.gpu_composite_reason(interactive); let mut submitted_stroke = false; let mut cpu_changed = false; + #[cfg(not(target_arch = "wasm32"))] + let overview_device = self.composite_device().is_some(); + #[cfg(target_arch = "wasm32")] + let overview_device = false; for (ts, state) in self.compositors.iter_mut().enumerate() { let reason = match state.plan(session, ts, shift, global_reason, None, self.underlay_budget) { Ok(program) => { + // Until the set's first composite is accepted (its pipelines may still + // compile), the composite device makes its overview off the UI thread; an + // overview arriving after the composite does not replace it + let first_composite = overview_device && program.as_ref().is_some_and(|program| !program.is_neutral()); if let Some(program) = program { out.composites.push(state.submission(ts, program)); submitted_stroke |= session.pending_display_stroke(ts).is_some(); self.sent.entry(ts).or_default().extend(DisplayKind::ALL); } - self.pending_overviews.remove(&ts); + if !first_composite { + self.pending_overviews.remove(&ts); + #[cfg(not(target_arch = "wasm32"))] + if self.overview_job.as_ref().is_some_and(|job| job.ts == ts) { + self.overview_job = None; + } + } self.active_overviews.remove(&ts); "" } @@ -663,7 +872,13 @@ impl GpuLink { let time_left_ms = |queued: usize| FRAME_BUDGET_MS - spent_ms - (crate::now_ms() - start_ms) - queued as f64 * UPLOAD_MS_PER_TILE; let demand = session.tile_demand(visible_uv); - let mut out = SceneSync { mesh_id: session.mesh_id, tile_shift: shift.min(texturecraft_engine::texel::TILE.ilog2()), ..Default::default() }; + let mut out = SceneSync { + mesh_id: session.mesh_id, + tile_shift: shift.min(texturecraft_engine::texel::TILE.ilog2()), + memory_budget: texturecraft_render::gpu_memory::GpuMemoryBudget::from_megabytes(self.memory_budget_mb), + ..Default::default() + }; + self.preview_memory_budget_mb.store(self.memory_budget_mb, Ordering::Relaxed); if self.lost.swap(false, Ordering::AcqRel) { self.mesh_id = 0; self.sets.clear(); @@ -676,6 +891,7 @@ impl GpuLink { out.mesh = Some((session.mesh.clone(), session.mesh_id)); self.mesh_id = session.mesh_id; self.aux.clear(); + self.aux_retried.clear(); self.aux_id_mask = None; } @@ -692,17 +908,28 @@ impl GpuLink { // Replaced textures can receive dirty tiles only after recomposition cache.queue_ready_uploads(); self.pending_overviews.remove(&ts); + #[cfg(not(target_arch = "wasm32"))] + if self.overview_job.as_ref().is_some_and(|job| job.ts == ts) { + self.overview_job = None; + } if self.material_start_preview && cache.dirty.len() >= UPLOAD_CHUNK { self.pending_overviews.insert(ts); } } } + // A removed set's overview would hold the one overview slot until it finishes + #[cfg(not(target_arch = "wasm32"))] + if self.overview_job.as_ref().is_some_and(|job| job.ts >= sets.len()) { + self.overview_job = None; + } + // Retained GPU sets need their prior kinds to overwrite stale textures self.sent.retain(|&texture_set, _| texture_set < sets.len()); // Recreated sets start with blank aux textures: resend the shown view self.aux.clear(); + self.aux_retried.clear(); self.mask_preview = None; self.quick_mask_failed = Arc::default(); @@ -729,6 +956,10 @@ impl GpuLink { if !self.material_start_preview { self.pending_overviews.clear(); + #[cfg(not(target_arch = "wasm32"))] + { + self.overview_job = None; + } for ts in std::mem::take(&mut self.active_overviews) { if let Some(cache) = session.caches.get_mut(ts) { out.cleared_overviews.push(ts); @@ -752,6 +983,8 @@ impl GpuLink { let gpu_mask = self.plan_gpu_mask(session, aux_map, shift, bake.is_some(), &mut out); if !gpu_mask { self.plan_gpu_composites(session, shift, interactive, gpu_quick_mask, &mut out, start_ms); + let pickup = matches!(session.tool.tool, texturecraft_engine::Tool::Clone | texturecraft_engine::Tool::Smudge); + out.prewarm_pickup = Some(session.ts()).filter(|&ts| pickup && self.compositors.get(ts).is_some_and(SetCompositor::uses_gpu)); } if out.composites.iter().any(|submission| !submission.program.is_neutral()) { self.gpu_composite_in_flight.fetch_add(1, Ordering::AcqRel); @@ -798,6 +1031,45 @@ impl GpuLink { } else { self.pending_overviews.pop_first() }; + #[cfg(not(target_arch = "wasm32"))] + let next_overview = { + if !gpu_mask && let Some((ts, overview)) = OverviewJob::take(&mut self.overview_job, session) { + self.sent.entry(ts).or_default().extend(overview.maps.iter().map(|(kind, _)| *kind)); + + // Turning the preview off clears it only from sets the CPU composites: a set the + // GPU composites shows its composite (or the overview until it arrives) + if !self.compositors.get(ts).is_some_and(SetCompositor::uses_gpu) { + self.active_overviews.insert(ts); + } + out.overview = Some((ts, overview)); + out.late_overview = true; + } + + // A brush on the active set needs its tiles now: an overview started before the + // stroke stops, as one does not start during it + if demand.has_brush() && self.overview_job.as_ref().is_some_and(|job| job.ts == active) { + self.overview_job = None; + } + + // With a composite device the overview composites on it on a worker thread (its + // pipelines may compile first; a material it refuses composites on the CPU there): the + // UI thread never waits for it, and the set's tiles wait for the overview + match (next_overview, self.composite_device()) { + (Some(ts), _) if out.overview.is_some() => { + self.pending_overviews.insert(ts); + None + } + (Some(ts), Some(device)) if !(ts == active && demand.has_brush()) && !session.caches[ts].dirty.is_empty() => { + if self.overview_job.is_some() || out.overview.is_some() { + self.pending_overviews.insert(ts); + } else if let Some(snapshot) = session.overview_snapshot(ts, 128) { + self.overview_job = OverviewJob::start(ts, snapshot, device); + } + None + } + (next, _) => next, + } + }; if let Some(ts) = next_overview && !(ts == active && demand.has_brush()) && !session.caches[ts].dirty.is_empty() @@ -824,7 +1096,7 @@ impl GpuLink { let order = boost.then_some((active, true)).into_iter().chain(rotation.map(|set| (set, false))); 'uploads: for (texture_set, boosted) in order.filter(|(ts, _)| uses_cpu(*ts)) { let cache = &mut session.caches[texture_set]; - if cache.upload.is_empty() || self.pending_overviews.contains(&texture_set) { + if cache.upload.is_empty() || self.pending_overviews.contains(&texture_set) || self.overview_pending_for(texture_set) { continue; } @@ -879,6 +1151,19 @@ impl GpuLink { self.aux_id_mask = None; } + // A view the GPU failed to draw is drawn once more (the memory may be free now) + for texture_set in std::mem::take(&mut *self.aux_failed.lock().unwrap_or_else(PoisonError::into_inner)) { + if let Some(key) = self.aux.get(&texture_set) + && self.aux_retried.get(&texture_set) != Some(key) + { + self.aux_retried.insert(texture_set, key.clone()); + self.aux.remove(&texture_set); + } + } + + let gpu_views = self.gpu_aux_views(); + out.aux_failed = Some(self.aux_failed.clone()); + out.release_aux_views = !gpu_views || !matches!(aux_map, Some(AuxView::MeshMap(_) | AuxView::IdMask(_) | AuxView::Image)); match aux_map { Some(AuxView::MeshMap(map)) => self.sync_mesh_maps(session, map, None, &mut out), Some(AuxView::IdMask(effect)) => { @@ -886,13 +1171,13 @@ impl GpuLink { self.sync_mesh_maps(session, BakedMap::Id, shown, &mut out); } Some(AuxView::Mask(id)) => { - if !gpu_mask && let Some((texture_set, _, _)) = session.doc.project.locate(id) { + if !gpu_mask + && let Some((texture_set, _, _)) = session.doc.project.locate(id) + && let Some(cache) = session.caches.get(texture_set) + { let key = (format!("mask{}", id.0), session.revision); if self.aux.get(&texture_set) != Some(&key) && !session.stroke_active() { - let extent = session - .caches - .get(texture_set) - .map_or((MASK_VIEW_FALLBACK_RESOLUTION, MASK_VIEW_FALLBACK_RESOLUTION), |cache| texturecraft_render::mask_view_extent(cache.size)); + let extent = texturecraft_render::aux_extent(cache.size, self.set_shift(cache.size)); let rgba = session.mask_view_rgba(id, extent).unwrap_or_else(|| MASK_VIEW_BLANK.repeat((extent.0 * extent.1) as usize)); out.aux.push((texture_set, extent, rgba)); self.aux.insert(texture_set, key); @@ -903,10 +1188,14 @@ impl GpuLink { let shown = session.doc.project.locate(id).map(|(texture_set, _, _)| texture_set); for texture_set in (0..session.caches.len()).filter(|set| Some(*set) != shown) { let Some(cache) = session.caches.get(texture_set) else { continue }; - let resolution = texturecraft_render::aux_size(cache.size); - let key = ("maskblank".to_owned(), u64::from(resolution)); + let extent = texturecraft_render::aux_extent(cache.size, self.set_shift(cache.size)); + let key = (format!("maskblank{}x{}", extent.0, extent.1), 0); if self.aux.get(&texture_set) != Some(&key) { - out.aux.push((texture_set, (resolution, resolution), MASK_VIEW_BLANK.repeat((resolution * resolution) as usize))); + if gpu_views { + out.aux_views.push((texture_set, AuxSource::Fill(MASK_VIEW_BLANK))); + } else { + out.aux.push((texture_set, extent, MASK_VIEW_BLANK.repeat((extent.0 * extent.1) as usize))); + } self.aux.insert(texture_set, key); } } @@ -920,6 +1209,7 @@ impl GpuLink { }; if !same_image { self.aux.clear(); + self.aux_retried.clear(); self.aux_image = shown.map(Arc::downgrade); } @@ -928,12 +1218,16 @@ impl GpuLink { continue; } - let resolution = texturecraft_render::aux_size(cache.size); - let (sets, _) = out.image_aux.entry(resolution).or_insert_with(|| { - let rgba = session.image_view_rgba(resolution).unwrap_or_else(|| MASK_VIEW_BLANK.repeat((resolution * resolution) as usize)); - (Vec::new(), rgba) - }); - sets.push(texture_set); + if gpu_views { + out.aux_views.push((texture_set, shown.map_or(AuxSource::Fill(MASK_VIEW_BLANK), |image| AuxSource::Image(image.clone())))); + } else { + let extent = texturecraft_render::aux_extent(cache.size, self.set_shift(cache.size)); + let (sets, _) = out.image_aux.entry(extent).or_insert_with(|| { + let rgba = session.image_view_rgba(extent).unwrap_or_else(|| MASK_VIEW_BLANK.repeat((extent.0 * extent.1) as usize)); + (Vec::new(), rgba) + }); + sets.push(texture_set); + } self.aux.insert(texture_set, ("image".into(), 0)); } } @@ -962,9 +1256,9 @@ impl GpuLink { )); out.quick_mask_failed = Some(self.quick_mask_failed.clone()); } else { - let resolution = texturecraft_render::aux_size(cache.size); - if let Some(rgba) = session.quick_mask_rgba(texture_set, resolution) { - out.aux.push((texture_set, (resolution, resolution), rgba)); + let extent = texturecraft_render::aux_extent(cache.size, self.set_shift(cache.size)); + if let Some(rgba) = session.quick_mask_rgba(texture_set, extent) { + out.aux.push((texture_set, extent, rgba)); } } self.aux.insert(texture_set, key); @@ -995,13 +1289,20 @@ impl GpuLink { } let Some(cache) = session.caches.get(texture_set) else { continue }; - let resolution = texturecraft_render::aux_size(cache.size); - let rgba = if preview.is_some() && have.is_none() { - texturecraft_render::mesh_maps::neutral_rgba(map, resolution) + let gpu_view = self.gpu_aux_views(); + if gpu_view { + let source = + if preview.is_some() && have.is_none() { AuxSource::neutral(map) } else { AuxSource::mesh_map(baked, map, &cache.composite.block_scales) }; + out.aux_views.push((texture_set, source)); } else { - texturecraft_render::mesh_maps::mesh_map_rgba(baked, map, resolution, cache.size, &cache.composite.block_scales) - }; - out.aux.push((texture_set, (resolution, resolution), rgba)); + let extent = texturecraft_render::aux_extent(cache.size, self.set_shift(cache.size)); + let rgba = if preview.is_some() && have.is_none() { + texturecraft_render::mesh_maps::neutral_rgba(map, extent) + } else { + texturecraft_render::mesh_maps::mesh_map_rgba(baked, map, extent, cache.size, &cache.composite.block_scales) + }; + out.aux.push((texture_set, extent, rgba)); + } self.aux.insert(texture_set, key); } } @@ -1014,13 +1315,17 @@ impl GpuLink { }; let cache = session.caches.get(texture_set)?; - let resolution = texturecraft_render::aux_size(cache.size); - let key = (format!("idMask{}:{resolution}", effect.0), Arc::as_ptr(image) as u64); + let extent = texturecraft_render::aux_extent(cache.size, self.set_shift(cache.size)); + let key = (format!("idMask{}:{}x{}", effect.0, extent.0, extent.1), Arc::as_ptr(image) as u64); let same_image = self.aux_id_mask.as_ref().is_some_and(|previous| std::ptr::eq(previous.as_ptr(), Arc::as_ptr(image))); - if (!same_image || self.aux.get(&texture_set) != Some(&key)) - && let Some(rgba) = session.id_mask_view_rgba(effect, resolution) - { - out.aux.push((texture_set, (resolution, resolution), rgba)); + let gpu_view = self.gpu_aux_views(); + let rgba = (!gpu_view && (!same_image || self.aux.get(&texture_set) != Some(&key))).then(|| session.id_mask_view_rgba(effect, extent)).flatten(); + if gpu_view && (!same_image || self.aux.get(&texture_set) != Some(&key)) { + out.aux_views.push((texture_set, AuxSource::IdMask(image.clone()))); + self.aux.insert(texture_set, key); + self.aux_id_mask = Some(Arc::downgrade(image)); + } else if let Some(rgba) = rgba { + out.aux.push((texture_set, extent, rgba)); self.aux.insert(texture_set, key); // A weak owner keeps the address unique without retaining the decoded pixels @@ -1041,11 +1346,11 @@ fn record_recreated_uploads(recreated: &mut BTreeMap| { + let limits = |adapter: &wgpu::Adapter| { + let limits = texturecraft_render::device_limits(adapter); + wgpu::Limits { max_storage_buffer_binding_size: binding.unwrap_or(limits.max_storage_buffer_binding_size), ..limits } + }; + let mut headless = Headless::for_tests_with_limits(limits).ok()?; + let mut link = link(); + link.gpu_composite_enabled = true; + let scene = link.sync(&mut session, None, None, 0, 0.0); + let (_, errors, _) = scene.apply_display(&mut headless.renderer, &headless.device, &headless.queue); + assert!(errors.is_empty(), "{errors:?}"); + assert!(!link.compositors[0].failed.load(Ordering::Acquire), "the GPU refused the set"); + assert_eq!(link.compositor_status().0, "Layers: GPU"); + // Only a missing adapter skips the test: once the set composites, it reads back + let (width, height, image) = + Readback::blocking(&headless.device, &headless.queue, headless.renderer.display_textures()[0][0]).expect("the composite reads back"); + Some(((width, height), image)) + }; + let Some((banded_extent, banded)) = composite(Some(256 << 10)) else { return }; + let (whole_extent, whole) = composite(None).expect("the adapter that composited in bands composites the whole set"); + assert_eq!(banded_extent, whole_extent, "both composites show the set at one extent"); + assert!(banded.chunks(4).any(|texel| texel[0] > 200 && texel[2] < 50), "the red fill shows"); + assert!(banded.chunks(4).any(|texel| texel[2] > 200 && texel[0] < 50), "the blue paint shows"); + let differing = banded.iter().zip(&whole).filter(|(banded, whole)| banded != whole).count(); + assert_eq!(differing, 0, "bands differ from the whole set"); + } + #[cfg(not(target_arch = "wasm32"))] #[test] fn gpu_layers_cover_uv_islands_and_their_padding() { @@ -1828,12 +2220,12 @@ pub(crate) mod tests { assert_eq!(link.compositor_status().0, "Layers: GPU"); assert_eq!(session.memory().geometry, geometry_bytes); - // A device error still enables the dense padding only on the CPU path + // A refusal still enables the dense padding only on the CPU path scene.composites[0].failed.store(true, Ordering::Release); let scene = link.sync(&mut session, None, None, 0, 0.0); assert!(scene.composites.is_empty()); assert_eq!(link.compositor_status().0, "Layers: CPU"); - assert!(session.log.iter().any(|entry| entry.message.contains(GPU_COMPOSITE_ERROR))); + assert!(session.log.iter().any(|entry| entry.message.contains(GPU_COMPOSITE_REFUSED))); assert!(session.memory().geometry > geometry_bytes, "only the CPU path allocates the dense padding map"); } @@ -2636,7 +3028,7 @@ pub(crate) mod tests { failed.store(true, Ordering::Release); for _ in 0..2 { assert!(link.sync(&mut session, None, None, 0, 0.0).composites.is_empty()); - assert_eq!(link.compositor_status(), ("Layers: CPU", GPU_COMPOSITE_ERROR)); + assert_eq!(link.compositor_status(), ("Layers: CPU", GPU_COMPOSITE_REFUSED)); } execute(&mut session, "layer.add.fill", &json!({"color": [0.45, 0.15, 0.35]})).unwrap(); @@ -2646,6 +3038,609 @@ pub(crate) mod tests { assert_eq!(link.compositor_status().0, "Layers: GPU", "a stale completion cannot reject the updated material"); } + /// A set the GPU composites gets its material overview from the composite device on a + /// worker thread: the frame that asks for it does not wait, the overview that arrives + /// matches the CPU composite at the texels the GPU reads (UV islands padded as on the CPU), + /// and it never replaces a composite that reached the set first + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_gpu_set_overview_composites_on_the_device_off_the_ui_thread() { + use texturecraft_engine::compose::tile_bytes; + use texturecraft_engine::texel::TILE; + + let Some(mut gpu) = Headless::for_required_tests() else { return }; + let device = Arc::new(HeadlessPreviews::new(&gpu)); + let size = 1024; + let build = || { + let mut mesh = primitives::plane(1.0, 1); + for uv in &mut mesh.uvs { + *uv = *uv * 0.5 + Vec2::splat(0.25); + } + let mut session = Session::new_project("overview", mesh, "builtin:plane", None, size).unwrap(); + execute(&mut session, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0]})).unwrap(); + execute(&mut session, "layer.add.paint", &json!({})).unwrap(); + let layer = session.selected_layer().unwrap(); + let paint = session.doc.pixels.layer_mut(layer, Channel::BaseColor, (size, size)); + for y in 0..size { + for x in 0..size { + let value = ((x * 131 + y * 61) % size * 65535 / size) as u16; + paint.set(x, y, &[value, 65535 - value, 20000, 65535]); + } + } + session + }; + let mut session = build(); + let mut overviews = link(); + overviews.gpu_composite_enabled = true; + overviews.composite_device = Some(device.clone()); + + // A view that composites no layers on the GPU (the mesh map) keeps the set on the CPU + let view = Some(AuxView::MeshMap(BakedMap::AmbientOcclusion)); + let first = overviews.sync(&mut session, view, None, 0, 0.0); + assert!(first.overview.is_none() && first.tiles.is_empty(), "the frame that asks for the overview does not wait for it, its tiles do"); + assert!(overviews.overview_job.is_some()); + let mut late = None; + for _ in 0..6000 { + std::thread::sleep(std::time::Duration::from_millis(5)); + let scene = overviews.sync(&mut session, view, None, 0, 0.0); + if scene.overview.is_some() { + late = Some(scene); + break; + } + assert!(scene.tiles.is_empty(), "the set's tiles wait for its overview"); + } + let late = late.expect("the overview arrives"); + assert!(late.late_overview && device.composited.load(Ordering::Relaxed) > 0, "the overview comes from the device"); + + // The CPU composite at full size, at every overview texel's set texel + let (ts, overview) = late.overview.as_ref().unwrap(); + assert_eq!((*ts, overview.size), (0, (size / 8, size / 8))); + let mut cpu = build(); + cpu.update(); + let cache = &cpu.caches[0]; + let empty = Default::default(); + let ao_mixing = cpu.doc.project.texture_sets[0].ao_mixing; + let padding = texturecraft_engine::session::DISPLAY_PADDING; + let island = size / 4 - padding..size * 3 / 4 + padding; + for (kind, map) in &overview.maps { + let stride = kind.bytes_per_texel(); + let (mut differing, mut compared) = (0, 0); + for y in 0..size / 8 { + for x in 0..size / 8 { + let (sx, sy) = (x * 8, y * 8); + + // The island and its padding: the CPU leaves the texels past it uncomposited + if !(island.contains(&sx) && island.contains(&sy)) { + continue; + } + compared += 1; + let tile = tile_bytes(&cache.composite, &empty, ao_mixing, *kind, sx / TILE, sy / TILE); + let at = (((sy % TILE) * TILE + sx % TILE) as usize) * stride; + let gpu_texel = &map[((y * size / 8 + x) as usize) * stride..][..stride]; + differing += usize::from(gpu_texel.iter().zip(&tile[at..at + stride]).any(|(g, c)| g.abs_diff(*c) > 2)); + } + } + assert!(differing * 100 <= compared, "{kind:?}: {differing} of {compared} texels differ"); + } + + // A composite that reached the set first keeps its full-size textures + let mut late = late; + late.tiles.clear(); + let mut on_gpu = link(); + on_gpu.gpu_composite_enabled = true; + on_gpu.sync(&mut session, None, None, 0, 0.0).apply_display(&mut gpu.renderer, &gpu.device, &gpu.queue); + late.apply_display(&mut gpu.renderer, &gpu.device, &gpu.queue); + let base = &gpu.renderer.display_textures()[0][DisplayKind::BaseColor as usize]; + assert_eq!((base.width(), base.height()), (size, size), "the late overview does not replace the composite"); + } + + /// A set the GPU composites shows its material overview from the composite device while its + /// first composite still waits for its pipelines + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_gpu_composited_set_shows_its_overview_before_its_composite() { + let Some(mut gpu) = Headless::for_required_tests() else { return }; + let device = Arc::new(HeadlessPreviews::new(&gpu)); + let size = 1024; + let mut session = Session::new_project("overview", primitives::plane(1.0, 1), "builtin:plane", None, size).unwrap(); + execute(&mut session, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0]})).unwrap(); + let mut link = link(); + link.gpu_composite_enabled = true; + link.composite_device = Some(device.clone()); + + // The renderer answers every composite "pipelines pending", as while they compile + let mut frame = |link: &mut GpuLink, session: &mut Session| { + let mut scene = link.sync(session, None, None, 0, 0.0); + assert!(scene.composites.iter().all(|submission| submission.ts == 0 && !submission.program.is_neutral())); + for submission in std::mem::take(&mut scene.composites) { + submission.pending.store(true, Ordering::Release); + } + scene.apply_display(&mut gpu.renderer, &gpu.device, &gpu.queue); + scene.overview.is_some() + }; + let mut arrived = frame(&mut link, &mut session); + assert!(link.compositors[0].uses_gpu() && link.overview_job.is_some(), "the GPU set's overview starts on the device"); + for _ in 0..6000 { + if arrived { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + arrived = frame(&mut link, &mut session); + } + assert!(arrived && device.composited.load(Ordering::Relaxed) > 0, "the overview arrives from the device"); + let base = &gpu.renderer.display_textures()[0][DisplayKind::BaseColor as usize]; + assert_eq!((base.width(), base.height()), (size / 8, size / 8), "the set shows the overview before its composite"); + + // Then its composite replaces the overview + for _ in 0..6000 { + link.sync(&mut session, None, None, 0, 0.0).apply_display(&mut gpu.renderer, &gpu.device, &gpu.queue); + if gpu.renderer.display_textures()[0][DisplayKind::BaseColor as usize].width() == size { + break; + } + std::thread::sleep(std::time::Duration::from_millis(5)); + } + let base = &gpu.renderer.display_textures()[0][DisplayKind::BaseColor as usize]; + assert_eq!((base.width(), base.height()), (size, size), "the composite replaces the overview"); + + // An overview still waiting once the composite is accepted is dropped + link.pending_overviews.insert(0); + link.sync(&mut session, None, None, 0, 0.0); + assert!(link.overview_job.is_none() && !link.pending_overviews.contains(&0), "no overview waits once the composite is accepted"); + } + + /// With the clone or smudge tool picked, the frame asks the renderer to compile the active + /// GPU set's live pickup variant ahead; other tools and CPU sets do not + #[test] + fn a_pickup_tool_prewarms_the_active_gpu_sets_live_variant() { + let mut session = Session::new_project("prewarm", primitives::plane(1.0, 1), "builtin:plane", None, 256).unwrap(); + execute(&mut session, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0]})).unwrap(); + let mut link = link(); + link.gpu_composite_enabled = true; + for (tool, prewarmed) in + [(texturecraft_engine::Tool::Paint, None), (texturecraft_engine::Tool::Clone, Some(0)), (texturecraft_engine::Tool::Smudge, Some(0))] + { + session.tool.tool = tool; + assert_eq!(link.sync(&mut session, None, None, 0, 0.0).prewarm_pickup, prewarmed, "{tool:?}"); + } + link.gpu_composite_enabled = false; + assert_eq!(link.sync(&mut session, None, None, 0, 0.0).prewarm_pickup, None, "a CPU set has no GPU variant"); + } + + /// The previews' composite device and the resize's stroke-replay brush follow the GPU + /// compositing settings: CPU selected or an adapter that refuses gives neither + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn preview_and_resize_devices_follow_the_gpu_compositing_settings() { + let Some(gpu) = Headless::for_required_tests() else { return }; + let mut link = link(); + link.composite_device = Some(Arc::new(HeadlessPreviews::new(&gpu))); + link.brush_device = Some(Arc::new(HeadlessBrush(Mutex::new(gpu)))); + for (enabled, preferred, on) in [(true, true, true), (false, true, false), (true, false, false)] { + (link.gpu_composite_enabled, link.prefer_gpu_layers) = (enabled, preferred); + assert_eq!((link.composite_device().is_some(), link.resize_brush_device().is_some()), (on, on), "enabled {enabled}, preferred {preferred}"); + } + } + + /// Dropping an overview job (a reset, a shift change, the preview turned off, the set's + /// composite accepted) stops its worker before it composites + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_dropped_overview_job_stops_before_it_composites() { + use texturecraft_engine::composite_device::{CompositeDevice, CompositeJob, DisplayMaps}; + use texturecraft_engine::gpu_failure::GpuFailure; + + /// The test GPU's previews behind a gate: a composite starts only once the test opens it + struct Watched(HeadlessPreviews, Mutex>, Arc); + impl CompositeDevice for Watched { + fn display_maps(&self, job: &CompositeJob, kinds: &[DisplayKind]) -> Result { + let _ = self.1.lock().unwrap().recv(); + let maps = self.0.display_maps(job, kinds); + if maps.is_ok() { + self.2.fetch_add(1, Ordering::Relaxed); + } + maps + } + + fn thumbnail( + &self, + job: &CompositeJob, + output: texturecraft_engine::compose::ThumbOutput, + ) -> Result { + self.0.thumbnail(job, output) + } + } + + let Some(gpu) = Headless::for_required_tests() else { return }; + let (open, gate) = std::sync::mpsc::channel(); + let composited = Arc::new(AtomicUsize::new(0)); + let device = Arc::new(Watched(HeadlessPreviews::new(&gpu), Mutex::new(gate), composited.clone())); + let worker = Arc::downgrade(&device); + let mut session = Session::new_project("overview", primitives::plane(1.0, 1), "builtin:plane", None, 512).unwrap(); + execute(&mut session, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0]})).unwrap(); + let job = OverviewJob::start(0, session.overview_snapshot(0, 128).unwrap(), device); + + // The worker waits at the gate until the job is gone; its device goes when it exits + drop(job); + drop(open); + let started = std::time::Instant::now(); + while worker.strong_count() > 0 { + assert!(started.elapsed() < std::time::Duration::from_secs(600), "the worker exits"); + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert_eq!(composited.load(Ordering::Relaxed), 0, "the dropped job does not composite"); + } + + /// A GPU aux view that failed to draw is not taken as current: the next frame draws it once + /// more, and a second failure keeps the error until the view changes + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_failed_aux_view_is_drawn_once_more() { + let Some(mut headless) = texturecraft_render::headless::Headless::for_required_tests() else { return }; + let mut link = link(); + link.real_gpu = true; + let mut session = session(false); + let view = Some(AuxView::MeshMap(BakedMap::AmbientOcclusion)); + let first = link.sync(&mut session, None, None, 0, 0.0); + let (_, errors, _) = first.apply_display(&mut headless.renderer, &headless.device, &headless.queue); + assert!(errors.is_empty(), "{errors:?}"); + + let mut draws = Vec::new(); + for _ in 0..3 { + let scene = link.sync(&mut session, view, None, 0, 0.0); + draws.push(scene.aux_views.iter().any(|(ts, _)| *ts == 0)); + + // Two failures outlast the renderer's one retry + headless.renderer.fail_next_gpu_attempts(2); + scene.apply_display(&mut headless.renderer, &headless.device, &headless.queue); + headless.renderer.fail_next_gpu_attempts(0); + } + assert_eq!(draws, [true, true, false], "a failed view is drawn once more, then waits for a change"); + } + + /// The GPU memory budget setting reaches the preview renderer (thumbnails, overviews, shelf + /// and orb previews) as it reaches the viewport's + #[test] + fn the_preview_renderer_follows_the_memory_budget_setting() { + let mut link = link(); + let mut session = session(false); + link.memory_budget_mb = 512; + drop(link.sync(&mut session, None, None, 0, 0.0)); + assert_eq!(link.preview_memory_budget_mb.load(Ordering::Relaxed), 512); + } + + /// A removed set's running overview gives up the one overview slot for the remaining sets + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_removed_sets_overview_job_is_dropped() { + let mut link = link(); + let mut session = session(false); + drop(link.sync(&mut session, None, None, 0, 0.0)); + + // The GPU still has a second set whose overview runs + link.sets.push(link.sets[0]); + let (_running, result) = std::sync::mpsc::channel(); + link.overview_job = Some(OverviewJob { ts: 1, result, cancel: Arc::default() }); + drop(link.sync(&mut session, None, None, 0, 0.0)); + assert!(link.overview_job.is_none(), "the removed set's overview job is dropped"); + } + + /// A stroke on the active set stops an overview that started before it: the overview would + /// hold the set's tile uploads, the focused tile's included, until it finished + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_brush_stops_the_active_sets_running_overview() { + let mut link = link(); + let mut s = session(false); + execute(&mut s, "layer.add.paint", &json!({})).unwrap(); + drop(link.sync(&mut s, None, None, 0, 0.0)); + let (_running, result) = std::sync::mpsc::channel(); + link.overview_job = Some(OverviewJob { ts: s.ts(), result, cancel: Arc::default() }); + drop(link.sync(&mut s, None, None, 0, 0.0)); + assert!(link.overview_job.is_some(), "without a brush the overview keeps running"); + + s.begin_stroke_uv(Vec2::splat(0.5), 1.0).unwrap(); + drop(link.sync(&mut s, None, None, 0, 0.0)); + assert!(link.overview_job.is_none(), "the stroke's set stops its overview"); + } + + /// Layer-panel thumbnails of a 4K stack composited on the test GPU (the engine's + /// `bench_layer_thumbs_4k` with a device): each kind of picture after a warm-up pass + #[cfg(not(target_arch = "wasm32"))] + #[test] + #[ignore] + fn bench_gpu_layer_thumbs_4k() { + use texturecraft_engine::compose::ThumbTarget; + use texturecraft_engine::thumbs::{GbufCache, ThumbSnapshot}; + + let Some(gpu) = Headless::for_required_tests() else { return }; + let mut s = Session::new_project("perf", primitives::sphere(1.0, 64, 32), "builtin:sphere", None, 4096).unwrap(); + s.viewport = Vec2::new(800.0, 800.0); + let run = |s: &mut Session, id: &str, params: serde_json::Value| execute(s, id, ¶ms).unwrap(); + run(&mut s, "layer.add.fill", json!({"color": [0.6, 0.5, 0.4], "roughness": 0.6})); + run(&mut s, "layer.fill.set", json!({"channel": "baseColor", "procedural": "clouds", "low": [0.2, 0.2, 0.2], "high": [0.8, 0.7, 0.6]})); + run(&mut s, "layer.fill.set", json!({"channel": "height", "procedural": "cells", "low": [-0.2, -0.2, -0.2], "high": [0.2, 0.2, 0.2]})); + run(&mut s, "layer.add.fill", json!({"color": [0.1, 0.3, 0.6]})); + run(&mut s, "layer.fill.set", json!({"channel": "roughness", "procedural": "grunge"})); + run(&mut s, "mask.add.black", json!(null)); + run(&mut s, "effect.add.generator", json!({"generator": "position", "level": 0.5})); + run(&mut s, "effect.add.filter", json!({"filter": "blur", "radius": 8})); + run(&mut s, "layer.add.fill", json!({"roughness": 0.3})); + run(&mut s, "layer.fill.set", json!({"channel": "baseColor", "procedural": "wood"})); + run(&mut s, "layer.fill.projection", json!({"projection": "triplanar", "scale": 2})); + run(&mut s, "mask.add.black", json!(null)); + run(&mut s, "effect.add.fill", json!({"procedural": "scratches", "scale": 6})); + run(&mut s, "layer.add.fill", json!({"color": [0.2, 0.2, 0.2], "metallic": 1.0})); + run(&mut s, "mask.add.black", json!(null)); + run(&mut s, "effect.add.generator", json!({"generator": "dirt"})); + run(&mut s, "layer.add.fill", json!({"roughness": 0.8})); + run(&mut s, "layer.fill.set", json!({"channel": "roughness", "procedural": "marble"})); + run(&mut s, "layer.add.group", json!(null)); + run(&mut s, "layer.add.fill", json!({"color": [0.9, 0.9, 0.2]})); + run(&mut s, "mask.add.black", json!(null)); + run(&mut s, "effect.add.generator", json!({"generator": "direction"})); + run(&mut s, "effect.add.levels", json!({"inLow": 0.3, "inHigh": 0.7})); + let top_layer = s.doc.project.texture_sets[0].stack.last().copied().unwrap(); + run(&mut s, "layer.select", json!({"layer": top_layer.0})); + run(&mut s, "layer.add.paint", json!(null)); + run(&mut s, "tool.brush", json!({"size": 6, "hardness": 80})); + run(&mut s, "tool.stroke", json!({"points": [[200, 300], [600, 500]]})); + run(&mut s, "layer.add.paint", json!(null)); + + // A layer painted over the whole set in two channels (the stroke above covers little) + let painted = s.selected_layer().unwrap(); + for channel in [Channel::BaseColor, Channel::Roughness] { + let paint = s.doc.pixels.layer_mut(painted, channel, (4096, 4096)); + let components = if channel == Channel::BaseColor { 4 } else { 2 }; + for y in 0..4096 { + for x in 0..4096 { + let value = ((x * 131 + y * 61) % 4096 * 16) as u16; + paint.set(x, y, &[value, 65535, value, 65535][..components]); + } + } + } + s.update(); + + let device: Arc = Arc::new(HeadlessPreviews::new(&gpu)); + let snap = ThumbSnapshot::new(&s, s.ts(), &mut GbufCache::default(), Some(device)).unwrap(); + let p = &s.doc.project; + let mut targets = Vec::new(); + for l in p.layers.values() { + let kind = if l.id == painted { "painted" } else { "content" }; + targets.push((kind, ThumbTarget::Content { layer: l.id, channel: Channel::BaseColor })); + if l.mask.is_some() { + targets.push(("mask", ThumbTarget::Mask { layer: l.id })); + } + for e in l.mask.iter().flat_map(|m| m.effects.iter()).chain(l.content_effects.iter()) { + targets.push(("stage", ThumbTarget::Stage { effect: e.id, channel: Channel::BaseColor })); + } + } + let warm = std::time::Instant::now(); + for (_, target) in &targets { + snap.render(*target).unwrap(); + } + eprintln!("GPU layer thumbnails, 4096 set, {} layers: warm-up (pipelines) {:.0} ms", p.layers.len(), warm.elapsed().as_secs_f64() * 1e3); + let mut per: BTreeMap<&str, (f64, usize, f64)> = BTreeMap::new(); + let all = std::time::Instant::now(); + for (kind, target) in &targets { + let t = std::time::Instant::now(); + snap.render(*target).unwrap(); + let ms = t.elapsed().as_secs_f64() * 1e3; + let entry = per.entry(kind).or_default(); + *entry = (entry.0 + ms, entry.1 + 1, entry.2.max(ms)); + } + for (kind, (sum, n, max)) in per { + eprintln!(" {kind:8} {n:3} x avg {:.2} ms, max {max:.2} ms", sum / n as f64); + } + eprintln!(" every target once: {:.1} ms ({} pictures)", all.elapsed().as_secs_f64() * 1e3, targets.len()); + } + + /// The preview compositor on the test GPU (asynchronous, as the app's), counting the display + /// maps it composited + #[cfg(not(target_arch = "wasm32"))] + pub(crate) struct HeadlessPreviews { + gpu: (wgpu::Device, wgpu::Queue), + compositor: Mutex, + pub(crate) composited: AtomicUsize, + } + + #[cfg(not(target_arch = "wasm32"))] + impl HeadlessPreviews { + pub(crate) fn new(gpu: &Headless) -> HeadlessPreviews { + let compositor = Mutex::new(texturecraft_render::gpu_preview::PreviewCompositor::asynchronous()); + HeadlessPreviews { gpu: (gpu.device.clone(), gpu.queue.clone()), compositor, composited: AtomicUsize::new(0) } + } + } + + #[cfg(not(target_arch = "wasm32"))] + impl texturecraft_engine::composite_device::CompositeDevice for HeadlessPreviews { + fn display_maps( + &self, + job: &texturecraft_engine::composite_device::CompositeJob, + kinds: &[DisplayKind], + ) -> Result { + let maps = preview_composite_device::display_maps(&self.compositor, (&self.gpu.0, &self.gpu.1), job, kinds)?; + self.composited.fetch_add(1, Ordering::Relaxed); + Ok(maps) + } + + fn thumbnail( + &self, + job: &texturecraft_engine::composite_device::CompositeJob, + output: texturecraft_engine::compose::ThumbOutput, + ) -> Result { + preview_composite_device::thumbnail(&self.compositor, (&self.gpu.0, &self.gpu.1), job, output) + } + } + + /// Every library filter's shelf preview composites on the GPU as on the CPU, at a size of + /// partial tiles; a refused filter composites on the CPU + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn filter_previews_composite_on_the_gpu_as_on_the_cpu() { + let Some(gpu) = Headless::for_required_tests() else { return }; + let device = HeadlessPreviews::new(&gpu); + let size = 72; + for library_filter in texturecraft_engine::filter_lib::FILTERS { + let id = library_filter.id; + let on_gpu = texturecraft_engine::preview::filter(id, size, Some(&device)).unwrap().unwrap(); + let on_cpu = texturecraft_engine::preview::filter(id, size, None).unwrap().unwrap(); + let differing = on_gpu + .iter() + .zip(&on_cpu) + .filter(|(gpu, cpu)| match (gpu, cpu) { + (Some(gpu), Some(cpu)) => { + let base = gpu.base.iter().zip(&cpu.base).any(|(g, c)| (g - c).abs() > 0.02); + base || (gpu.metallic - cpu.metallic).abs() > 0.01 + || (gpu.roughness - cpu.roughness).abs() > 0.01 + || (gpu.height - cpu.height).abs() > 0.01 + } + (gpu, cpu) => gpu.is_some() != cpu.is_some(), + }) + .count(); + assert!(differing * 100 <= on_cpu.len(), "{id}: {differing} of {} pixels differ", on_cpu.len()); + } + let composited = device.composited.load(Ordering::Relaxed); + eprintln!("{composited} of {} filter previews composited on the GPU", texturecraft_engine::filter_lib::FILTERS.len()); + assert!(composited > 0); + } + + /// A GPU brush start that runs out of memory frees the cached inputs and tries once more; a + /// second failure fails the stroke instead of painting it on the CPU + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_gpu_brush_start_retries_once_then_fails_the_stroke() { + let Some(gpu) = Headless::for_required_tests() else { return }; + let brush = Arc::new(HeadlessBrush(Mutex::new(gpu))); + let mut s = Session::new_project("GPU brush", primitives::plane(1.0, 1), "builtin:plane", None, 128).unwrap(); + execute(&mut s, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); + let mut link = link(); + link.gpu_composite_enabled = true; + link.brush_device = Some(brush.clone()); + link.sync(&mut s, None, None, 0, 0.0); + s.brush_device = link.brush_device(&s); + let layer = s.selected_layer().unwrap(); + + brush.0.lock().unwrap().renderer.fail_next_gpu_attempts(1); + s.begin_stroke_uv(Vec2::splat(0.5), 1.0).unwrap(); + assert!(s.device_stroke().is_some(), "the retry starts the stroke on the GPU"); + s.cancel_stroke(); + + brush.0.lock().unwrap().renderer.fail_next_gpu_attempts(2); + let error = s.begin_stroke_uv(Vec2::splat(0.5), 1.0).unwrap_err().to_string(); + assert!(error.contains("The stroke was not applied") && error.contains("simulated"), "{error}"); + assert!(!s.stroke_active(), "no CPU stroke stands in for the GPU"); + assert!(s.doc.pixels.layer(layer, Channel::BaseColor).is_none()); + } + + /// A 3D path with a control point the camera no longer sees paints on the GPU brush as on + /// the CPU: its surface samples skip the view test, its screen samples keep it + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_3d_path_with_a_hidden_point_paints_on_the_gpu_as_on_the_cpu() { + /// Counts the strokes the GPU brush started + struct Started(HeadlessBrush, std::sync::atomic::AtomicUsize); + + impl brush_device::BrushDevice for Started { + fn start(&self, surface: brush_device::BrushSurface) -> Result, texturecraft_engine::gpu_failure::GpuFailure> { + let stroke = self.0.start(surface)?; + self.1.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + Ok(stroke) + } + } + + let Some(gpu) = Headless::for_required_tests() else { return }; + let started = Arc::new(Started(HeadlessBrush(Mutex::new(gpu)), Default::default())); + let paint = |device: Option>| { + let mut session = Session::new_project("GPU path", primitives::sphere(1.0, 32, 16), "builtin:sphere", None, 128).unwrap(); + session.update(); + execute(&mut session, "layer.add.paint", &json!({})).unwrap(); + execute(&mut session, "tool.material", &json!({"channel": "baseColor", "solo": true, "color": [1.0, 0.0, 0.0]})).unwrap(); + execute(&mut session, "tool.brush", &json!({"size": 10, "hardness": 60})).unwrap(); + let viewport = Vec2::splat(400.0); + let points: Vec<_> = [140.0, 200.0, 260.0].map(|x| session.pick(Vec2::new(x, 200.0), viewport).unwrap().pos).into(); + + // Turned so the last point lies on the sphere's far side + session.camera.set_angles(session.camera.yaw - 1.4, session.camera.pitch); + session.brush_device = device.map(|device| brush_device::BrushBackend { device, surface: Arc::downgrade(&session.caches[0].gbuf) }); + session.tool.path.points = points; + let report = execute(&mut session, "tool.path", &json!({"viewport": [400, 400], "commit": true})).unwrap(); + let effect = texturecraft_engine::core::LayerId(report["committed"]["effect"].as_u64().unwrap()); + assert!( + !session.log.entries().iter().any(|entry| entry.message.starts_with("Brush: CPU") || entry.message.starts_with("GPU brush could not start")), + "{:?}", + session.log.entries().iter().map(|entry| entry.message.clone()).collect::>() + ); + session.doc.pixels.layer(effect, Channel::BaseColor).unwrap().clone() + }; + + let cpu = paint(None); + let gpu = paint(Some(started.clone())); + assert!(started.1.load(std::sync::atomic::Ordering::Relaxed) > 0, "the path paints on the GPU brush"); + let (mut covered, mut differing) = (0, 0); + for y in 0..128 { + for x in 0..128 { + let (expected, actual) = (cpu.get(x, y), gpu.get(x, y)); + covered += usize::from(expected.iter().chain(&actual).any(|&value| value != 0)); + differing += usize::from(expected.iter().zip(&actual).any(|(a, b)| a.abs_diff(*b) > 257)); + } + } + assert!(covered > 100, "the path paints ({covered} texels)"); + assert!(differing * 100 <= covered, "{differing} of {covered} texels differ"); + } + + /// A resize repaints recorded world and texture-space strokes on the GPU brush as the CPU + /// replay does + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn recorded_strokes_repaint_on_the_gpu_as_on_the_cpu() { + /// Counts the strokes the GPU brush started + struct Started(HeadlessBrush, std::sync::atomic::AtomicUsize); + + impl brush_device::BrushDevice for Started { + fn start(&self, surface: brush_device::BrushSurface) -> Result, texturecraft_engine::gpu_failure::GpuFailure> { + let stroke = self.0.start(surface)?; + self.1.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + Ok(stroke) + } + } + + let Some(gpu) = Headless::for_required_tests() else { return }; + let started = Arc::new(Started(HeadlessBrush(Mutex::new(gpu)), Default::default())); + let brush: Arc = started.clone(); + let paint = || { + let mut session = Session::new_project("GPU replay", primitives::sphere(1.0, 32, 16), "builtin:sphere", None, 128).unwrap(); + execute(&mut session, "layer.add.paint", &json!({})).unwrap(); + execute(&mut session, "tool.material", &json!({"channel": "baseColor", "solo": true, "color": [1.0, 0.0, 0.0]})).unwrap(); + let viewport = Vec2::splat(400.0); + session.stroke_points(&[viewport * 0.4, viewport * 0.6], viewport).unwrap(); + session.begin_stroke_uv(Vec2::new(0.2, 0.3), 1.0).unwrap(); + session.continue_stroke_uv(Vec2::new(0.4, 0.35), 0.6); + session.end_stroke().unwrap(); + session + }; + + let [cpu, gpu] = [None, Some(brush)].map(|device| { + let mut session = paint(); + let layer = session.selected_layer().unwrap(); + session.brush_device = device.map(|device| brush_device::BrushBackend { device, surface: std::sync::Weak::new() }); + let out = session.resize_task(0, 256).unwrap().run(&texturecraft_engine::bake::Progress::new()).unwrap(); + session.apply_resize(out).unwrap(); + session.doc.pixels.layer(layer, Channel::BaseColor).unwrap().clone() + }); + + let (mut covered, mut differing) = (0, 0); + for y in 0..256 { + for x in 0..256 { + let (expected, actual) = (cpu.get(x, y), gpu.get(x, y)); + covered += usize::from(expected.iter().chain(&actual).any(|&value| value != 0)); + differing += usize::from(expected.iter().zip(&actual).any(|(a, b)| a.abs_diff(*b) > 257)); + } + } + assert_eq!(started.1.load(std::sync::atomic::Ordering::Relaxed), 2, "both strokes repaint on the GPU"); + assert!(covered > 500, "both strokes repaint ({covered} texels)"); + assert!(differing * 200 <= covered, "{differing} of {covered} texels differ"); + } + #[cfg(not(target_arch = "wasm32"))] #[test] fn gpu_brush_previews_empty_layer_and_survives_switch_to_cpu() { @@ -3199,8 +4194,8 @@ pub(crate) mod tests { } } - /// A stroke carrying picked-up values (here the brush material's pattern) rasterises on the - /// CPU, and the GPU compositor shows it live from the pixels its release commits. + /// A stroke carrying picked-up values (here the brush material's pattern) paints its alpha on + /// the GPU brush, and the GPU compositor shows the carried values live as its release commits. #[cfg(not(target_arch = "wasm32"))] #[test] fn a_pickup_stroke_composites_live_on_the_gpu() { @@ -3224,7 +4219,7 @@ pub(crate) mod tests { s.brush_device = link.brush_device(&s); s.begin_stroke_uv(Vec2::splat(0.5), 1.0).unwrap(); - assert!(s.device_stroke().is_none(), "a pickup rasterises on the CPU"); + assert!(s.device_stroke().is_some(), "the brush material's pattern paints on the GPU brush"); let live = display(&mut link, &mut s); assert_eq!(link.compositor_status().0, "Layers: GPU", "the live pickup stroke composites on the GPU"); s.end_stroke().unwrap(); @@ -3241,7 +4236,7 @@ pub(crate) mod tests { fn a_2d_view_projection_stroke_previews_its_stencil_on_the_gpu() { let Ok(gpu) = Headless::for_tests() else { return }; let brush = Arc::new(HeadlessBrush(Mutex::new(gpu))); - let (mut session, layer) = projection_session(128, false); + let (mut session, layer) = projection_session(128, false, "tool.projection"); let uvs = [144.0, 200.0, 256.0].map(|x| session.pick(Vec2::new(x, 200.0), session.viewport).unwrap().uv); let mut link = link(); link.gpu_composite_enabled = true; @@ -3394,7 +4389,7 @@ pub(crate) mod tests { assert!(errors.is_empty(), "{size}²: {errors:?}"); let _ = reset; for (ts, extent, bytes) in &scene.aux { - gpu.renderer.upload_aux_sized(&gpu.device, &gpu.queue, *ts, *extent, bytes); + gpu.renderer.upload_aux(&gpu.device, &gpu.queue, *ts, *extent, bytes); } let tex = if inspect_aux { gpu.renderer.aux_texture(0).unwrap() } else { gpu.renderer.display_textures()[0][0] }; [center, outside].map(|uv| { @@ -3494,7 +4489,7 @@ pub(crate) mod tests { } #[cfg(not(target_arch = "wasm32"))] - fn projection_session(size: u32, mask_view: bool) -> (Session, LayerId) { + fn projection_session(size: u32, mask_view: bool, tool: &str) -> (Session, LayerId) { let mut session = Session::new_project("GPU projection", primitives::plane(1.0, 1), "builtin:plane", None, size).unwrap(); session.camera.set_angles(0.0, 1.45); session.camera.ortho = true; @@ -3521,7 +4516,7 @@ pub(crate) mod tests { stencil.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); let name = session.import_resource_bytes("projection-bands.png", png).unwrap(); assert!(session.images[&name].srgb); - execute(&mut session, "tool.projection", &json!({})).unwrap(); + execute(&mut session, tool, &json!({})).unwrap(); execute(&mut session, "tool.stencil", &json!({"image": name, "scale": 0.48, "rotation": 15, "center": [0.04, -0.02]})).unwrap(); execute(&mut session, "tool.material", &json!({"channel": "baseColor", "solo": true, "color": [0.25, 0.8, 1.0], "maskValue": 0.65})).unwrap(); execute(&mut session, "tool.brush", &json!({"size": 12, "hardness": 100, "opacity": 83, "spacing": 20})).unwrap(); @@ -3529,7 +4524,9 @@ pub(crate) mod tests { } #[cfg(not(target_arch = "wasm32"))] - fn check_gpu_projection_stroke(size: u32, gpu: Headless, cpu_oracle: bool) { + /// `tool` paints through the stencil: the Projection tool paints its colors, the Paint tool + /// its own color scaled by the stencil's stored gray times alpha. + fn check_gpu_projection_stroke(size: u32, gpu: Headless, cpu_oracle: bool, tool: &str) { use texturecraft_engine::texel::TILE; let brush = Arc::new(HeadlessBrush(Mutex::new(gpu))); @@ -3545,7 +4542,7 @@ pub(crate) mod tests { (pixel.x.min(extent - 1), pixel.y.min(extent - 1)) }; for mask_view in [false, true] { - let (mut session, layer) = projection_session(size, mask_view); + let (mut session, layer) = projection_session(size, mask_view, tool); let uvs = screen.map(|point| session.pick(point, session.viewport).unwrap().uv); let aux = mask_view.then_some(AuxView::Mask(layer)); let mut link = link(); @@ -3585,8 +4582,10 @@ pub(crate) mod tests { if mask_view { assert!(live[2][0] > live[1][0] && live[1][0] > live[0][0], "mask coverage follows stencil alpha"); assert!(live.into_iter().all(|[r, g, b, _]| r == g && r == b)); - } else { + } else if tool == "tool.projection" { assert!(live[1][0] > live[1][1] && live[2][1] > live[2][0], "the material takes the stencil's two ink colors"); + } else { + assert!(live[2] != baseline[2] && live[2][2] > live[2][0], "the tool's color shows through the stencil: {live:?}"); } session.cancel_stroke(); @@ -3608,7 +4607,7 @@ pub(crate) mod tests { compare_pixels(committed, live); if cpu_oracle { - let (mut cpu, layer) = projection_session(size, mask_view); + let (mut cpu, layer) = projection_session(size, mask_view, tool); dab(&mut cpu); assert!(cpu.device_stroke().is_none()); cpu.end_stroke().unwrap(); @@ -3649,7 +4648,261 @@ pub(crate) mod tests { #[test] fn gpu_projection_previews_cancels_commits_and_undoes_in_both_views() { let Ok(gpu) = Headless::for_tests() else { return }; - check_gpu_projection_stroke(128, gpu, true); + check_gpu_projection_stroke(128, gpu, true, "tool.projection"); + } + + /// A plane with soft paint (or, in the mask view, a soft mask blob) at screen x 144 to clone + /// from, and the layer the clone paints on. `pattern`: the Paint tool with a brush material + /// paints instead, its pattern carried like a clone. + #[cfg(not(target_arch = "wasm32"))] + fn clone_session(size: u32, mask_view: bool, from_layer: bool, pattern: bool) -> (Session, LayerId) { + let mut session = Session::new_project("GPU clone", primitives::plane(1.0, 1), "builtin:plane", None, size).unwrap(); + session.camera.set_angles(0.0, 1.45); + session.camera.ortho = true; + session.camera.distance = 1.8; + session.viewport = Vec2::splat(400.0); + if mask_view { + execute(&mut session, "layer.add.fill", &json!({"color": [1.0, 0.0, 0.0]})).unwrap(); + execute(&mut session, "mask.add.black", &json!({})).unwrap(); + } else { + execute(&mut session, "layer.add.paint", &json!({})).unwrap(); + } + execute(&mut session, "tool.paint", &json!({})).unwrap(); + execute(&mut session, "tool.material", &json!({"channel": "baseColor", "solo": true, "color": [0.9, 0.3, 0.1], "maskValue": 0.8})).unwrap(); + execute(&mut session, "tool.brush", &json!({"size": 10, "hardness": 30, "opacity": 90, "spacing": 20})).unwrap(); + assert!(session.begin_stroke(Vec2::new(144.0, 200.0), session.viewport, 1.0).unwrap()); + session.end_stroke().unwrap(); + if !mask_view && !from_layer { + execute(&mut session, "layer.add.paint", &json!({})).unwrap(); + } + let layer = session.selected_layer().unwrap(); + if mask_view { + session.view = ViewMode::Mask(layer); + } + if pattern { + execute(&mut session, "tool.material", &json!({"material": "cobblestone"})).unwrap(); + execute(&mut session, "tool.brush", &json!({"size": 8, "hardness": 60, "opacity": 85, "spacing": 20})).unwrap(); + return (session, layer); + } + execute(&mut session, "tool.clone", &json!({})).unwrap(); + let from = if from_layer { "layer" } else { "composite" }; + execute(&mut session, "tool.brush", &json!({"size": 8, "hardness": 60, "opacity": 85, "spacing": 20, "cloneSource": from})).unwrap(); + execute(&mut session, "tool.cloneSource", &json!({"x": 140.0, "y": 200.0})).unwrap(); + (session, layer) + } + + /// Clone strokes paint their alpha on the GPU brush and show the source's values live and + /// committed as the CPU clone does: from the composite, from one layer (its soft coverage + /// weighs every dab), on a mask, and the brush material's pattern. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn gpu_clone_strokes_match_the_cpu() { + use texturecraft_engine::texel::TILE; + + let Ok(gpu) = Headless::for_tests() else { return }; + let brush = Arc::new(HeadlessBrush(Mutex::new(gpu))); + let size = 128; + let screen = [250.0, 256.0, 262.0].map(|x| Vec2::new(x, 200.0)); + let probes: Vec = (0..15).map(|i| Vec2::new(240.0 + i as f32 * 3.0, 200.0)).collect(); + for (mask_view, from_layer, pattern) in [(false, false, false), (false, true, false), (true, false, false), (false, false, true)] { + let case = format!("mask view {mask_view}, from layer {from_layer}, pattern {pattern}"); + let stroke = |session: &mut Session| { + assert!(session.begin_stroke(screen[0], session.viewport, 1.0).unwrap()); + for point in &screen[1..] { + assert!(session.continue_stroke(*point, 1.0)); + } + }; + let (mut session, layer) = clone_session(size, mask_view, from_layer, pattern); + let texels: Vec<(u32, u32)> = probes + .iter() + .map(|point| { + let pixel = (session.pick(*point, session.viewport).unwrap().uv * size as f32).as_uvec2(); + (pixel.x.min(size - 1), pixel.y.min(size - 1)) + }) + .collect(); + let aux = mask_view.then_some(AuxView::Mask(layer)); + let mut link = link(); + link.gpu_composite_enabled = true; + link.brush_device = Some(brush.clone()); + let display = |link: &mut GpuLink, session: &mut Session| -> Vec<[u8; 4]> { + let scene = link.sync(session, aux, None, 0, 0.0); + let gpu = &mut *brush.0.lock().unwrap(); + if let Some((mesh, id)) = &scene.mesh { + gpu.renderer.set_mesh(&gpu.device, &gpu.queue, mesh, *id); + } + let (_, errors, _) = scene.apply_display(&mut gpu.renderer, &gpu.device, &gpu.queue); + assert!(errors.is_empty(), "{case}: {errors:?}"); + let texture = if mask_view { gpu.renderer.aux_texture(0).unwrap() } else { gpu.renderer.display_textures()[0][0] }; + texels.iter().map(|&(x, y)| read_pixel(gpu, texture, x, y)).collect() + }; + let baseline = display(&mut link, &mut session); + session.brush_device = link.brush_device(&session); + stroke(&mut session); + assert!(session.device_stroke().is_some(), "{case}: the clone runs on the GPU brush"); + let cpu_source = session.log.entries().iter().any(|entry| entry.message.starts_with("GPU clone or smudge source composited on the CPU")); + assert!(!cpu_source, "{case}: the GPU compositor writes the source"); + let live = display(&mut link, &mut session); + session.end_stroke().unwrap(); + let committed = display(&mut link, &mut session); + assert_ne!(live, baseline, "{case}: the clone shows live"); + + let (mut cpu, layer) = clone_session(size, mask_view, from_layer, pattern); + stroke(&mut cpu); + assert!(cpu.device_stroke().is_none()); + cpu.end_stroke().unwrap(); + cpu.update(); + let expected: Vec<[u8; 4]> = if mask_view { + let rgba = cpu.mask_view_rgba(layer, (size, size)).unwrap(); + texels.iter().map(|&(x, y)| rgba[((y * size + x) * 4) as usize..][..4].try_into().unwrap()).collect() + } else { + texels + .iter() + .map(|&(x, y)| { + let tile = display_tile_bytes( + &cpu.caches[0].composite, + &Default::default(), + AoMixing::Multiply, + DisplayKind::BaseColor, + x / TILE, + y / TILE, + 0, + ); + tile[((y % TILE * TILE + x % TILE) * 4) as usize..][..4].try_into().unwrap() + }) + .collect() + }; + for (index, ((live, committed), expected)) in live.iter().zip(&committed).zip(&expected).enumerate() { + let near = |actual: &[u8; 4]| actual.iter().zip(expected).all(|(a, b)| a.abs_diff(*b) <= 2); + assert!(near(live) && near(committed), "{case}, probe {index}: live {live:?}, committed {committed:?}, CPU {expected:?}"); + } + } + } + + /// Smudge strokes drag the composite on the GPU brush, stamp by stamp, and show live and + /// committed what the CPU smudge does: across the edge of a soft blob, with symmetry, where + /// every copy drags its own trail, and on a mask. The GPU compositor writes the source. The + /// stroke runs along a texel edge, where each stamp's center is a tie. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn gpu_smudge_strokes_match_the_cpu() { + use texturecraft_engine::texel::TILE; + + let Ok(gpu) = Headless::for_tests() else { return }; + let brush = Arc::new(HeadlessBrush(Mutex::new(gpu))); + let size = 128; + let screen: Vec = (0..9).map(|i| Vec2::new(132.0 + i as f32 * 4.0, 200.0)).collect(); + let probes: Vec = (0..15).flat_map(|i| [Vec2::new(128.0 + i as f32 * 4.0, 200.0), Vec2::new(272.0 - i as f32 * 4.0, 200.0)]).collect(); + // A Normal layer's smudge drags its own paint with its soft coverage, a Pass through + // layer's smears the stack (the GPU compositor writes that source) + for (symmetry, switch, mask_view, pass_through) in + [(false, false, false, false), (true, false, false, false), (true, true, false, false), (false, false, true, false), (false, false, false, true)] + { + let case = format!("symmetry {symmetry}, switch to the CPU {switch}, mask view {mask_view}, pass through {pass_through}"); + let smudge_session = || { + let (mut session, _) = clone_session(size, mask_view, true, false); + if pass_through { + execute(&mut session, "layer.blend", &json!({"channel": "all", "mode": "passthrough"})).unwrap(); + } + execute(&mut session, "tool.smudge", &json!({})).unwrap(); + execute(&mut session, "tool.brush", &json!({"size": 8, "hardness": 60, "spacing": 10, "smudgeStrength": 80, "symmetryX": symmetry})).unwrap(); + session + }; + // Switching halfway, the CPU continues the device's trails + let stroke = |session: &mut Session| { + assert!(session.begin_stroke(screen[0], session.viewport, 1.0).unwrap()); + for (index, point) in screen[1..].iter().enumerate() { + if switch && index == 4 { + session.materialize_device_stroke(Some("test")); + } + assert!(session.continue_stroke(*point, 1.0)); + } + }; + let mut session = smudge_session(); + let layer = session.selected_layer().unwrap(); + let aux = mask_view.then_some(AuxView::Mask(layer)); + let texels: Vec<(u32, u32)> = probes + .iter() + .map(|point| { + let pixel = (session.pick(*point, session.viewport).unwrap().uv * size as f32).as_uvec2(); + (pixel.x.min(size - 1), pixel.y.min(size - 1)) + }) + .collect(); + let mut link = link(); + link.gpu_composite_enabled = true; + link.brush_device = Some(brush.clone()); + let display = |link: &mut GpuLink, session: &mut Session| -> Vec<[u8; 4]> { + let scene = link.sync(session, aux, None, 0, 0.0); + let gpu = &mut *brush.0.lock().unwrap(); + if let Some((mesh, id)) = &scene.mesh { + gpu.renderer.set_mesh(&gpu.device, &gpu.queue, mesh, *id); + } + let (_, errors, _) = scene.apply_display(&mut gpu.renderer, &gpu.device, &gpu.queue); + assert!(errors.is_empty(), "{case}: {errors:?}"); + let texture = if mask_view { gpu.renderer.aux_texture(0).unwrap() } else { gpu.renderer.display_textures()[0][0] }; + texels.iter().map(|&(x, y)| read_pixel(gpu, texture, x, y)).collect() + }; + let baseline = display(&mut link, &mut session); + session.brush_device = link.brush_device(&session); + stroke(&mut session); + assert_eq!(session.device_stroke().is_some(), !switch, "{case}: the smudge runs on the GPU brush"); + let cpu_source = session.log.entries().iter().any(|entry| entry.message.starts_with("GPU clone or smudge source composited on the CPU")); + assert!(!cpu_source, "{case}: the GPU compositor writes the source"); + let live = display(&mut link, &mut session); + session.end_stroke().unwrap(); + let committed = display(&mut link, &mut session); + assert_ne!(live, baseline, "{case}: the smudge shows live"); + + let mut cpu = smudge_session(); + stroke(&mut cpu); + assert!(cpu.device_stroke().is_none()); + cpu.end_stroke().unwrap(); + cpu.update(); + let expected: Vec<[u8; 4]> = if mask_view { + let rgba = cpu.mask_view_rgba(layer, (size, size)).unwrap(); + texels.iter().map(|&(x, y)| rgba[((y * size + x) * 4) as usize..][..4].try_into().unwrap()).collect() + } else { + texels + .iter() + .map(|&(x, y)| { + let tile = display_tile_bytes( + &cpu.caches[0].composite, + &Default::default(), + AoMixing::Multiply, + DisplayKind::BaseColor, + x / TILE, + y / TILE, + 0, + ); + tile[((y % TILE * TILE + x % TILE) * 4) as usize..][..4].try_into().unwrap() + }) + .collect() + }; + assert_ne!(expected, baseline, "{case}: the CPU smudge changes the probes"); + + // Every committed texel, off the probes' rows too, within 2/255 + let target = |session: &Session| { + let image = if mask_view { session.doc.pixels.masks.values().next() } else { session.doc.pixels.layer(layer, Channel::BaseColor) }; + image.cloned().unwrap() + }; + let (gpu_pixels, cpu_pixels) = (target(&session), target(&cpu)); + for (x, y) in (0..size).flat_map(|y| (0..size).map(move |x| (x, y))) { + let (gpu_value, cpu_value) = (gpu_pixels.get(x, y), cpu_pixels.get(x, y)); + let near = gpu_value.iter().zip(&cpu_value).all(|(a, b)| a.abs_diff(*b) <= 2 * 257); + assert!(near, "{case}: committed texel ({x}, {y}) {gpu_value:?}, CPU {cpu_value:?}"); + } + for (index, ((live, committed), expected)) in live.iter().zip(&committed).zip(&expected).enumerate() { + let near = |actual: &[u8; 4]| actual.iter().zip(expected).all(|(a, b)| a.abs_diff(*b) <= 2); + assert!(near(live) && near(committed), "{case}, probe {index}: live {live:?}, committed {committed:?}, CPU {expected:?}"); + } + } + } + + /// Any other brush tool paints through the stencil's gray on the GPU brush, as on the CPU. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn gpu_mask_stencil_strokes_match_the_cpu_in_both_views() { + let Ok(gpu) = Headless::for_tests() else { return }; + check_gpu_projection_stroke(128, gpu, true, "tool.paint"); } #[cfg(not(target_arch = "wasm32"))] @@ -3657,7 +4910,7 @@ pub(crate) mod tests { #[ignore = "native 4K/8K GPU regression; requires an adapter with sufficient VRAM"] fn smoke_gpu_projection_at_4k_and_8k() { for size in [4096, 8192] { - check_gpu_projection_stroke(size, Headless::for_tests().unwrap(), false); + check_gpu_projection_stroke(size, Headless::for_tests().unwrap(), false, "tool.projection"); } } diff --git a/crates/ui-egui/src/gpu/composite_submission.rs b/crates/ui-egui/src/gpu/composite_submission.rs index 6bb651792..4e367cc22 100644 --- a/crates/ui-egui/src/gpu/composite_submission.rs +++ b/crates/ui-egui/src/gpu/composite_submission.rs @@ -1,4 +1,7 @@ -use std::sync::{Arc, atomic::AtomicBool}; +use std::sync::{ + Arc, + atomic::{AtomicBool, Ordering}, +}; use texturecraft_render::gpu_composite::CompositeProgram; @@ -9,4 +12,13 @@ pub(super) struct CompositeSubmission { pub(super) failed: Arc, pub(super) pending: Arc, pub(super) underlay_drawn: Option>, + /// Set when the renderer accepted the composite (not refused, pending or failed on the device) + pub(super) written: AtomicBool, +} + +impl CompositeSubmission { + /// Whether the renderer accepted this composite, so its display kinds were written + pub(super) fn written(&self) -> bool { + self.written.load(Ordering::Acquire) + } } diff --git a/crates/ui-egui/src/gpu/device_stroke.rs b/crates/ui-egui/src/gpu/device_stroke.rs index c023a4fe7..2f54aefcd 100644 --- a/crates/ui-egui/src/gpu/device_stroke.rs +++ b/crates/ui-egui/src/gpu/device_stroke.rs @@ -1,6 +1,13 @@ use super::{BrushInput, GpuBrushStroke, Renderer, Stamp, TileImage, UvStamp, brush_device, wgpu}; +use texturecraft_engine::gpu_failure::GpuFailure; -pub(super) struct DeviceStroke(pub(super) GpuBrushStroke); +/// Frees the compositor's cached GPU inputs before a readback's one retry after running out of GPU memory +pub(super) type ReleaseInputs = Box; + +pub(super) struct DeviceStroke { + stroke: GpuBrushStroke, + release: Option, +} impl DeviceStroke { pub(super) fn start( @@ -8,31 +15,80 @@ impl DeviceStroke { device: &wgpu::Device, queue: &wgpu::Queue, surface: brush_device::BrushSurface, - ) -> Result, String> { - let brush_device::BrushSurface { mesh, bvh, uv, material, depth, settings, alpha_image, stencil, limit } = surface; - let stroke = renderer.start_gpu_brush(device, queue, BrushInput { mesh, bvh, uv, material, depth, settings, alpha_image, stencil, limit })?; - Ok(Box::new(Self(stroke))) + release: Option, + ) -> Result, GpuFailure> { + let begin = |renderer: &mut Renderer, surface: brush_device::BrushSurface| { + let brush_device::BrushSurface { mesh, bvh, uv, material, depth, settings, alpha_image, stencil, limit, clone, smudge } = surface; + renderer.start_gpu_brush(device, queue, BrushInput { mesh, bvh, uv, material, depth, settings, alpha_image, stencil, limit, clone, smudge }) + }; + + // One more try after freeing the compositor's cached inputs when the GPU ran out of memory + let stroke = match begin(renderer, surface.clone()) { + Err(error) if texturecraft_render::gpu_memory::is_out_of_memory(&error) => { + log::warn!("GPU brush start ran out of memory, freeing cached GPU inputs and retrying: {error}"); + renderer.release_all_composite_inputs(); + begin(renderer, surface) + } + result => result, + }; + match stroke { + Ok(stroke) => Ok(Box::new(Self { stroke, release })), + Err(error) if texturecraft_render::gpu_memory::is_device_error(&error) => Err(GpuFailure::Device(error)), + Err(reason) => Err(GpuFailure::Refused(reason)), + } + } + + /// `read`, once more after freeing the compositor's cached inputs when the GPU ran out of memory + fn read(&self, read: impl Fn(&GpuBrushStroke) -> Result) -> Result { + match read(&self.stroke) { + Err(error) if texturecraft_render::gpu_memory::is_out_of_memory(&error) && self.release.is_some() => { + log::warn!("GPU brush readback ran out of memory, freeing cached GPU inputs and retrying: {error}"); + if let Some(release) = &self.release { + release(); + } + read(&self.stroke) + } + result => result, + } } } impl brush_device::DeviceStroke for DeviceStroke { - fn append_world(&mut self, stamps: &[Stamp]) -> Result { - self.0.append_world(stamps) + fn append_world(&mut self, stamps: &[Stamp], use_view: bool) -> Result { + self.stroke.append_world_with(stamps, use_view) } fn append_uv(&mut self, stamps: &[UvStamp]) -> Result { - self.0.append_uv(stamps) + self.stroke.append_uv(stamps) } fn read_alpha(&self, tiles: &brush_device::BrushTiles) -> Result { - self.0.read_alpha(tiles) + self.read(|stroke| stroke.read_alpha(tiles)) } fn read_projection(&self, tiles: &brush_device::BrushTiles) -> Result { - self.0.read_projection(tiles) + self.read(|stroke| stroke.read_projection(tiles)) + } + + fn read_carried( + &self, + tiles: &brush_device::BrushTiles, + ) -> Result<(TileImage, std::collections::BTreeMap), String> { + self.read(|stroke| stroke.read_carried(tiles)) + } + + fn read_channel_alphas( + &self, + tiles: &brush_device::BrushTiles, + ) -> Result, String> { + self.read(|stroke| stroke.read_channel_alphas(tiles)) + } + + fn read_smudge_lanes(&self, tiles: &brush_device::BrushTiles) -> Result, String> { + self.read(|stroke| stroke.read_smudge_lanes(tiles)) } fn as_any(&self) -> &dyn std::any::Any { - &self.0 + &self.stroke } } diff --git a/crates/ui-egui/src/gpu/preview_composite_device.rs b/crates/ui-egui/src/gpu/preview_composite_device.rs new file mode 100644 index 000000000..6dfff4487 --- /dev/null +++ b/crates/ui-egui/src/gpu/preview_composite_device.rs @@ -0,0 +1,97 @@ +use std::sync::atomic::{AtomicU32, Ordering}; +use std::sync::{Arc, Mutex, PoisonError}; + +use texturecraft_engine::compose::{DisplayKind, ThumbImage, ThumbOutput}; +use texturecraft_engine::composite_device::{CompositeDevice, CompositeJob}; +use texturecraft_engine::gpu_failure::GpuFailure; +use texturecraft_render::gpu_memory::GpuMemoryBudget; +use texturecraft_render::gpu_preview::{PreparedPreview, PreviewCompositor, PreviewFailure, PreviewInputs, PreviewResult, run_until_ready}; + +use super::{egui_wgpu, wgpu}; + +/// The viewport's device compositing shelf and orb previews, layer thumbnails and the material +/// overview with a renderer of their own. Each preview compiles its program before taking the +/// compositor, and the compositor compiles new pipelines on worker threads: a worker holds the +/// lock only while it composites. +pub(super) struct PreviewCompositeDevice { + pub(super) render_state: egui_wgpu::RenderState, + pub(super) compositor: Mutex, + /// The GPU memory budget setting in megabytes (0: automatic), which caps the preview + /// renderer's cached inputs as it caps the viewport's + memory_budget_mb: Arc, +} + +impl PreviewCompositeDevice { + pub(super) fn new(render_state: egui_wgpu::RenderState, memory_budget_mb: Arc) -> PreviewCompositeDevice { + PreviewCompositeDevice { render_state, compositor: Mutex::new(PreviewCompositor::asynchronous()), memory_budget_mb } + } + + /// Apply the current budget setting before a preview composites + fn follow_budget(&self) { + let budget = GpuMemoryBudget::from_megabytes(self.memory_budget_mb.load(Ordering::Relaxed)); + self.compositor.lock().unwrap_or_else(PoisonError::into_inner).set_memory_budget(budget); + } +} + +impl CompositeDevice for PreviewCompositeDevice { + fn display_maps(&self, job: &CompositeJob, kinds: &[DisplayKind]) -> Result { + self.follow_budget(); + display_maps(&self.compositor, (&self.render_state.device, &self.render_state.queue), job, kinds) + } + + fn thumbnail(&self, job: &CompositeJob, output: ThumbOutput) -> Result { + self.follow_budget(); + thumbnail(&self.compositor, (&self.render_state.device, &self.render_state.queue), job, output) + } +} + +fn inputs<'a>(job: &CompositeJob<'a>) -> PreviewInputs<'a> { + let CompositeJob { project, ts, pixels, mesh, gbuf, baked, images, shift, padding, cancel: _ } = *job; + PreviewInputs { project, ts, pixels, mesh, gbuf, baked, images, shift, padding } +} + +fn failure(failure: PreviewFailure) -> GpuFailure { + match failure { + PreviewFailure::Refused(reason) => GpuFailure::Refused(reason), + PreviewFailure::Device(error) => GpuFailure::Device(error), + PreviewFailure::Cancelled => GpuFailure::Device("the preview was cancelled".into()), + } +} + +/// Run `prepared` on `compositor`, locking it only for each composite, until `job` is cancelled +fn run( + compositor: &Mutex, + (device, queue): (&wgpu::Device, &wgpu::Queue), + job: &CompositeJob, + prepared: &PreparedPreview, +) -> Result { + run_until_ready(prepared, job.cancel, |prepared| compositor.lock().unwrap_or_else(PoisonError::into_inner).run(device, queue, prepared)).map_err(failure) +} + +/// [`CompositeDevice::display_maps`] on `compositor` +pub(super) fn display_maps( + compositor: &Mutex, + gpu: (&wgpu::Device, &wgpu::Queue), + job: &CompositeJob, + kinds: &[DisplayKind], +) -> Result { + let prepared = PreparedPreview::maps(&inputs(job), kinds).map_err(failure)?; + match run(compositor, gpu, job, &prepared)? { + PreviewResult::Maps(maps) => Ok(maps), + PreviewResult::Thumbnail(..) => Err(GpuFailure::Refused("the preview is not display maps".into())), + } +} + +/// [`CompositeDevice::thumbnail`] on `compositor` +pub(super) fn thumbnail( + compositor: &Mutex, + gpu: (&wgpu::Device, &wgpu::Queue), + job: &CompositeJob, + output: ThumbOutput, +) -> Result { + let prepared = PreparedPreview::thumbnail(&inputs(job), output).map_err(failure)?; + match run(compositor, gpu, job, &prepared)? { + PreviewResult::Thumbnail(width, height, rgba) => Ok(ThumbImage { width, height, rgba }), + PreviewResult::Maps(_) => Err(GpuFailure::Refused("the preview is not a thumbnail".into())), + } +} diff --git a/crates/ui-egui/src/gpu/set_compositor.rs b/crates/ui-egui/src/gpu/set_compositor.rs index b045e747f..00168bcdd 100644 --- a/crates/ui-egui/src/gpu/set_compositor.rs +++ b/crates/ui-egui/src/gpu/set_compositor.rs @@ -2,7 +2,7 @@ use super::{GpuBrushStroke, LiveBrush, LiveBrushTarget, PaintTarget}; use super::{ - Arc, AtomicBool, CompositeKey, CompositeProgram, CompositeRegion, CompositeSubmission, GPU_COMPOSITE_ERROR, LayerId, LitEnvironment, NO_COVERED_TEXELS, + Arc, AtomicBool, CompositeKey, CompositeProgram, CompositeRegion, CompositeSubmission, GPU_COMPOSITE_REFUSED, LayerId, LitEnvironment, NO_COVERED_TEXELS, Ordering, Session, n_, view_project, }; @@ -30,7 +30,14 @@ pub(super) struct SetCompositor { impl SetCompositor { pub(super) fn submission(&self, ts: usize, program: CompositeProgram) -> CompositeSubmission { - CompositeSubmission { ts, program, failed: self.failed.clone(), pending: self.pending.clone(), underlay_drawn: self.underlay_drawn.clone() } + CompositeSubmission { + ts, + program, + failed: self.failed.clone(), + pending: self.pending.clone(), + underlay_drawn: self.underlay_drawn.clone(), + written: Default::default(), + } } pub(super) fn uses_gpu(&self) -> bool { @@ -80,7 +87,7 @@ impl SetCompositor { if self.failed_key == Some(key) { self.drop_underlay(); - return Err(GPU_COMPOSITE_ERROR); + return Err(GPU_COMPOSITE_REFUSED); } if mask.is_none() && cache.dilation.needs_seam_padding() { @@ -223,9 +230,17 @@ impl SetCompositor { LiveBrushTarget::Layer { layer, values: channels.into_iter().map(|channel| (channel, [0.0; 3])).collect() } } PaintTarget::Layer(layer) => LiveBrushTarget::Layer { layer, values: brush.values.clone() }, - PaintTarget::Mask(effect) => LiveBrushTarget::Mask { effect, value: brush.mask_value, image: brush.mask_image.map(str::to_owned) }, + // A clone or smudge paints its carried values, not the tool's mask image + PaintTarget::Mask(effect) => { + let image = brush.mask_image.filter(|_| !brush.pickup).map(str::to_owned); + LiveBrushTarget::Mask { effect, value: brush.mask_value, image } + } }; - Some(LiveBrush { target, opacity: brush.opacity, erase: brush.erase, alpha: coverage.view(), stencil: coverage.stencil() }) + let carried = coverage.carried(); + if brush.pickup && carried.is_none() { + return Err(n_("This painting tool uses CPU compositing.")); + } + Some(LiveBrush { target, opacity: brush.opacity, erase: brush.erase, alpha: coverage.view(), stencil: coverage.stencil(), carried }) } else { None }; diff --git a/crates/ui-egui/src/gpu/tests/headless_brush.rs b/crates/ui-egui/src/gpu/tests/headless_brush.rs index 9547860d8..91393af73 100644 --- a/crates/ui-egui/src/gpu/tests/headless_brush.rs +++ b/crates/ui-egui/src/gpu/tests/headless_brush.rs @@ -3,8 +3,8 @@ use super::{DeviceStroke, Headless, Mutex, brush_device}; pub(super) struct HeadlessBrush(pub(super) Mutex); impl brush_device::BrushDevice for HeadlessBrush { - fn start(&self, surface: brush_device::BrushSurface) -> Result, String> { + fn start(&self, surface: brush_device::BrushSurface) -> Result, texturecraft_engine::gpu_failure::GpuFailure> { let Headless { renderer, device, queue, .. } = &mut *self.0.lock().unwrap(); - DeviceStroke::start(renderer, device, queue, surface) + DeviceStroke::start(renderer, device, queue, surface, None) } } diff --git a/crates/ui-egui/src/gpu/viewport_brush_device.rs b/crates/ui-egui/src/gpu/viewport_brush_device.rs index 7aa17ca75..57e364962 100644 --- a/crates/ui-egui/src/gpu/viewport_brush_device.rs +++ b/crates/ui-egui/src/gpu/viewport_brush_device.rs @@ -1,11 +1,18 @@ use super::{DeviceStroke, GpuState, brush_device, egui_wgpu}; +use texturecraft_engine::gpu_failure::GpuFailure; pub(super) struct ViewportBrushDevice(pub(super) egui_wgpu::RenderState); impl brush_device::BrushDevice for ViewportBrushDevice { - fn start(&self, surface: brush_device::BrushSurface) -> Result, String> { + fn start(&self, surface: brush_device::BrushSurface) -> Result, GpuFailure> { + let render_state = self.0.clone(); + let release = Box::new(move || { + if let Some(gpu) = render_state.renderer.write().callback_resources.get_mut::() { + gpu.renderer.release_all_composite_inputs(); + } + }); let mut renderer = self.0.renderer.write(); - let gpu = renderer.callback_resources.get_mut::().ok_or("GPU renderer unavailable")?; - DeviceStroke::start(&mut gpu.renderer, &self.0.device, &self.0.queue, surface) + let gpu = renderer.callback_resources.get_mut::().ok_or_else(|| GpuFailure::Refused("GPU renderer unavailable".into()))?; + DeviceStroke::start(&mut gpu.renderer, &self.0.device, &self.0.queue, surface, Some(release)) } } diff --git a/crates/ui-egui/src/gpu/viewport_depth_device.rs b/crates/ui-egui/src/gpu/viewport_depth_device.rs new file mode 100644 index 000000000..7cce22562 --- /dev/null +++ b/crates/ui-egui/src/gpu/viewport_depth_device.rs @@ -0,0 +1,38 @@ +use std::sync::OnceLock; + +use texturecraft_engine::depth_device::DepthDevice; +use texturecraft_engine::geom::{Mesh, OrbitCamera}; +use texturecraft_engine::paint::EyeDepth; +use texturecraft_render::gpu_eye_depth::GpuEyeDepth; + +use super::{GpuState, egui_wgpu}; + +/// The viewport's device rasterizing the paint camera's depth, its passes compiled on first use +pub(super) struct ViewportDepthDevice { + pub(super) render_state: egui_wgpu::RenderState, + pub(super) passes: OnceLock>, +} + +impl DepthDevice for ViewportDepthDevice { + fn eye_depth( + &self, + mesh: &Mesh, + camera: &OrbitCamera, + size: (u32, u32), + record_triangles: bool, + include: &dyn Fn(usize) -> bool, + ) -> Result { + let (device, queue) = (&self.render_state.device, &self.render_state.queue); + let passes = self.passes.get_or_init(|| GpuEyeDepth::new(device)).as_ref().map_err(Clone::clone)?; + match passes.render((device, queue), mesh, camera, size, record_triangles, include) { + // Out of GPU memory: free the compositor's cached inputs and try once more + Err(error) if texturecraft_render::gpu_memory::is_out_of_memory(&error) => { + if let Some(gpu) = self.render_state.renderer.write().callback_resources.get_mut::() { + gpu.renderer.release_all_composite_inputs(); + } + passes.render((device, queue), mesh, camera, size, record_triangles, include) + } + result => result, + } + } +} diff --git a/crates/ui-egui/src/layer_panel.rs b/crates/ui-egui/src/layer_panel.rs index cb0c546ed..bad854e1a 100644 --- a/crates/ui-egui/src/layer_panel.rs +++ b/crates/ui-egui/src/layer_panel.rs @@ -77,6 +77,7 @@ impl LayerPanel { if !self.pictures_begun { self.pictures_begun = true; self.frame += 1; + self.service.set_composite_device(crate::preview_device::current()); self.service.begin_frame(session, now); } } @@ -114,6 +115,9 @@ impl LayerPanel { if self.service.poll(session) { ctx.request_repaint_after(Duration::from_millis(POLL_INTERVAL_MS)); } + for error in self.service.take_errors() { + log::error!("{error}"); + } if self.textures.len() > CACHE_ENTRIES * 2 { let frame = self.frame; self.textures.retain(|_, (_, _, used)| *used + 1 >= frame); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index e47f41a90..8413f0ddc 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -140,6 +140,7 @@ mod placement; mod pointer_lock; mod popup_drag; mod press_edit; +mod preview_device; mod preview_dots; mod preview_image; mod preview_request; @@ -244,6 +245,7 @@ pub use control::ControlRequest; pub use high_poly_job::HighPolyJob; pub use running_bake::RunningBake; pub use state::UiState; +pub use texturecraft_render::gpu_memory; /// The app as the updater knows it: its releases, and the icon and color of its update prompt. #[cfg(not(target_arch = "wasm32"))] @@ -1138,6 +1140,9 @@ impl TextureCraftApp { match self.session.resize_task_to(ts, width, height) { Ok(task) => { + // Recorded strokes repaint on the GPU brush in every view and mode while GPU compositing is on + #[cfg(not(target_arch = "wasm32"))] + let task = task.with_brush_device(self.gpu.as_ref().filter(|_| self.ui.prefs.gpu_compositing).and_then(gpu::GpuLink::resize_brush_device)); let progress = Arc::new(Progress::new()); let p = progress.clone(); #[cfg(not(target_arch = "wasm32"))] @@ -1421,6 +1426,16 @@ impl eframe::App for TextureCraftApp { } else { None }; + self.session.depth_device = if self.ui.prefs.gpu_compositing { self.gpu.as_ref().and_then(gpu::GpuLink::depth_device) } else { None }; + preview_device::set(if self.ui.prefs.gpu_compositing { self.gpu.as_ref().and_then(gpu::GpuLink::composite_device) } else { None }); + + // A preview that failed on the GPU stays empty (no CPU preview stands in): say why + for error in preview_device::take_errors() { + let text = i18n::trf("GPU error: {error}", &[("error", &error)]); + if !self.toasts.iter().any(|toast| toast.text == text) { + self.toast(text, true); + } + } } control::poll(self, ctx); shelf_updates::tick(self, ctx); diff --git a/crates/ui-egui/src/preview_device.rs b/crates/ui-egui/src/preview_device.rs new file mode 100644 index 000000000..b9bff3b45 --- /dev/null +++ b/crates/ui-egui/src/preview_device.rs @@ -0,0 +1,79 @@ +//! The device the preview workers composite shelf and orb material previews on, set by the app +//! each frame (None: GPU compositing off or no GPU, the previews composite on the CPU) + +use std::collections::BTreeSet; +use std::sync::{Arc, Mutex, PoisonError, RwLock}; + +use texturecraft_engine::composite_device::CompositeDevice; + +type Device = Option>; + +static DEVICE: RwLock = RwLock::new(None); + +/// The preview GPU errors logged since the device was set +static REPORTED: Mutex> = Mutex::new(BTreeSet::new()); + +/// Reported preview GPU errors the UI has not shown yet ([`take_errors`]) +static PENDING: Mutex> = Mutex::new(Vec::new()); + +/// Composite the next previews on `device` +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +pub(crate) fn set(device: Device) { + let same = |a: &Device, b: &Device| match (a, b) { + (Some(a), Some(b)) => Arc::ptr_eq(a, b), + (None, None) => true, + _ => false, + }; + if !same(&DEVICE.read().unwrap_or_else(PoisonError::into_inner), &device) { + *DEVICE.write().unwrap_or_else(PoisonError::into_inner) = device; + + // A new device reports its own errors + REPORTED.lock().unwrap_or_else(PoisonError::into_inner).clear(); + } +} + +/// The device previews composite on now +pub(crate) fn current() -> Device { + DEVICE.read().unwrap_or_else(PoisonError::into_inner).clone() +} + +/// Log the GPU error of preview `id` and hand it to the UI ([`take_errors`]), once per distinct +/// error: when the device fails, every preview reports the same error. True when it was new. +pub(crate) fn report_error(id: &str, error: &str) -> bool { + let new = REPORTED.lock().unwrap_or_else(PoisonError::into_inner).insert(error.to_string()); + if new { + let message = format!("The preview of {id} failed on the GPU: {error}"); + log::error!("{message}"); + PENDING.lock().unwrap_or_else(PoisonError::into_inner).push(message); + } + new +} + +/// The preview GPU errors reported since the last call, for the UI to show (no preview falls +/// back to the CPU, so the user learns why it stays empty) +#[cfg_attr(target_arch = "wasm32", allow(dead_code))] +pub(crate) fn take_errors() -> Vec { + std::mem::take(&mut *PENDING.lock().unwrap_or_else(PoisonError::into_inner)) +} + +#[cfg(test)] +mod tests { + /// The same GPU error from several previews is logged once; another error is logged too + #[test] + fn a_preview_gpu_error_is_logged_once() { + assert!(super::report_error("filter:a", "test device lost")); + assert!(!super::report_error("filter:b", "test device lost")); + assert!(super::report_error("filter:b", "test out of memory")); + } + + /// A reported preview error reaches the UI once + #[test] + fn a_preview_gpu_error_reaches_the_ui() { + assert!(super::report_error("material:a", "test adapter lost")); + assert!(!super::report_error("material:b", "test adapter lost")); + let shown = super::take_errors(); + let message = "The preview of material:a failed on the GPU: test adapter lost"; + assert_eq!(shown.iter().filter(|error| error.as_str() == message).count(), 1, "{shown:?}"); + assert!(!super::take_errors().iter().any(|error| error == message), "an error is shown once"); + } +} diff --git a/crates/ui-egui/src/preview_request.rs b/crates/ui-egui/src/preview_request.rs index 2da02d5cd..bec45dae0 100644 --- a/crates/ui-egui/src/preview_request.rs +++ b/crates/ui-egui/src/preview_request.rs @@ -32,7 +32,17 @@ impl PreviewRequest { ShelfPreview::GeneratorSet { generator, images } => { Some(mask_preview_image(self.size_px, &shape.get()?.generator_reading(generator.as_ref().clone(), images, self.size_px)?)) } - ShelfPreview::SmartMaterial(id) => Some(material_preview_image(self.size_px, &shape.get()?.material(id, self.size_px)?)), + ShelfPreview::SmartMaterial(id) => { + let orb = shape.get()?; + orb.set_composite_device(crate::preview_device::current()); + match orb.material(id, self.size_px) { + Ok(pixels) => Some(material_preview_image(self.size_px, &pixels?)), + Err(error) => { + crate::preview_device::report_error(id, &error.to_string()); + None + } + } + } preview => preview.image(self.size_px), } } diff --git a/crates/ui-egui/src/render_mode.rs b/crates/ui-egui/src/render_mode.rs index 25f52fee6..b89d35076 100644 --- a/crates/ui-egui/src/render_mode.rs +++ b/crates/ui-egui/src/render_mode.rs @@ -235,8 +235,11 @@ type Geometry = (String, Arc, Arc); pub struct RenderView { job: Option, gpu: Option, - /// Why the GPU tracer failed on the scene of this key (the CPU renders it instead). + /// Why the GPU tracer cannot take the scene of this key (a limit: the CPU renders it instead). gpu_error: Option<(String, String)>, + /// The error the GPU reported while tracing the scene of this key: shown, and nothing renders + /// until the scene changes (the CPU does not redo GPU work). + gpu_failure: Option<(String, String)>, texture: Option, motion: Motion, shown: Option<(u32, u32, Vec)>, @@ -530,6 +533,27 @@ fn show_gpu(app: &mut TextureCraftApp, ui: &Ui, rect: Rect) -> bool { return false; } + if app.render.gpu_failure.as_ref().is_some_and(|(k, _)| *k == scene_key) { + let shown = app.render.gpu.as_ref().filter(|view| view.has_image).map(|view| view.held.unwrap_or(view.texture)); + paint(ui, rect, shown); + + // No more samples are traced, but "Save render..." still reads the retained image back + if let Some(view) = app.render.gpu.take() { + let mut read = view.read.lock().unwrap_or_else(PoisonError::into_inner); + if matches!(*read, Read::Wanted) { + let mut encoder = render_state.device.create_command_encoder(&wgpu::CommandEncoderDescriptor { label: Some("tc_render_save") }); + *read = Read::Copied(Readback::new(&render_state.device, &mut encoder, &view.out)); + render_state.queue.submit([encoder.finish()]); + } + drop(read); + if poll_read(app, &render_state.device, &view) { + ui.ctx().request_repaint(); + } + app.render.gpu = Some(view); + } + return true; + } + if app.session.doc.project.display.displacement && !prepare_cpu_materials(&mut app.session, true) { let shown = app.render.gpu.as_ref().filter(|view| view.has_image).map(|view| view.held.unwrap_or(view.texture)); paint(ui, rect, shown); @@ -539,6 +563,7 @@ fn show_gpu(app: &mut TextureCraftApp, ui: &Ui, rect: Rect) -> bool { let scene_key = gpu_scene_key(&app.session); app.render.gpu_error = None; + app.render.gpu_failure = None; if app.render.job.take().is_some() { app.render.texture = None; app.render.shown = None; @@ -632,8 +657,19 @@ fn show_gpu(app: &mut TextureCraftApp, ui: &Ui, rect: Rect) -> bool { (status.samples, status.error.take()) }; + // An error belongs to the scene the view traced: a scene changed since then renders + let error = error.filter(|_| view.scene_key == scene_key); if let Some(error) = error { - log::warn!("GPU path tracing failed, rendering on the CPU: {error}"); + if texturecraft_render::gpu_memory::is_device_error(&error) { + log::error!("GPU path tracing failed: {error}"); + app.toast(trf("The GPU couldn't render this scene: {error}", &[("error", &error)]), true); + app.render.gpu_failure = Some((scene_key, error)); + paint(ui, rect, show_image(view.has_image, samples).then_some(view.held.unwrap_or(view.texture))); + app.render.gpu = Some(view); + return true; + } + + log::warn!("GPU path tracing cannot take this scene, rendering on the CPU: {error}"); app.render.gpu_error = Some((scene_key, error)); app.render.gpu = Some(view); return false; @@ -811,8 +847,20 @@ impl CallbackTrait for TraceCallback { None => GpuTracer::new(device).map(|tracer| TraceState { tracer, scene: None, key: String::new(), resolved: None, last_sync: f64::MIN }), }; let result = state.and_then(|mut st| { - let r = match resources.get::() { - Some(gpu) => self.run(&mut st, device, queue, encoder, &gpu.renderer), + let r = match resources.get_mut::() { + Some(gpu) => match self.run(&mut st, device, queue, encoder, &gpu.renderer) { + // Out of GPU memory: free the compositor's cached inputs and the traced scene, then try once more + Err(error) if texturecraft_render::gpu_memory::is_out_of_memory(&error) => { + log::warn!("GPU path tracing ran out of memory, freeing cached GPU inputs and retrying: {error}"); + gpu.renderer.release_all_composite_inputs(); + st.tracer.release(); + (st.scene, st.resolved) = (None, None); + st.key.clear(); + st.last_sync = f64::MIN; + self.run(&mut st, device, queue, encoder, &gpu.renderer) + } + result => result, + }, None => Err("the viewport renderer is missing".into()), }; let samples = st.tracer.samples(); @@ -875,6 +923,9 @@ fn overlay(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, on_gpu: bool) { if let Some((_, e)) = app.render.gpu_error.as_ref().filter(|_| !on_gpu && !app.ui.render.cpu) { line.on_hover_text(trf("The GPU couldn't render this scene: {error}", &[("error", e)])); } + if let Some((_, e)) = app.render.gpu_failure.as_ref().filter(|_| on_gpu) { + ui.label(RichText::new(trf("The GPU couldn't render this scene: {error}", &[("error", e)])).size(11.0).color(tk.danger)); + } ui.add(egui::ProgressBar::new(app.render.samples as f32 / max as f32).desired_height(4.0)); ui.horizontal(|ui| { ui.label(tr("Samples")); diff --git a/crates/ui-egui/src/render_mode/tests.rs b/crates/ui-egui/src/render_mode/tests.rs index 3bee43b92..494d1c6eb 100644 --- a/crates/ui-egui/src/render_mode/tests.rs +++ b/crates/ui-egui/src/render_mode/tests.rs @@ -154,6 +154,66 @@ fn settling_after_the_first_gpu_frame_keeps_its_image() { assert_eq!(view.held, Some(previous_texture)); } +/// An error the GPU reports while tracing is shown and the scene stays off the CPU tracer, until it changes. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_gpu_trace_error_is_shown_without_a_cpu_render() { + let Some(mut app) = gpu_app() else { return }; + + let context = egui::Context::default(); + draw_gpu(&mut app, &context, 0.0).drop_without_applying_deltas(); + let error = "The GPU reported an error in GPU path tracing: a test"; + app.render.gpu.as_ref().unwrap().status.lock().unwrap().error = Some(error.into()); + + for frame in 1..=2 { + draw_gpu(&mut app, &context, f64::from(frame) * 0.01).drop_without_applying_deltas(); + assert!(app.render.job.is_none(), "frame {frame}: no CPU render"); + assert_eq!(app.render.gpu_failure.as_ref().map(|(_, shown)| shown.as_str()), Some(error)); + } + assert!(app.toasts.iter().any(|toast| toast.text.contains(error))); +} + +/// After a GPU error the retained image can still be saved: the save reads it back although +/// no more samples are traced +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_failed_gpu_render_still_reads_its_image_back_for_saving() { + let Some(mut app) = gpu_app() else { return }; + + let context = egui::Context::default(); + draw_gpu(&mut app, &context, 0.0).drop_without_applying_deltas(); + let error = "The GPU reported an error in GPU path tracing: a test"; + app.render.gpu.as_ref().unwrap().status.lock().unwrap().error = Some(error.into()); + draw_gpu(&mut app, &context, 0.01).drop_without_applying_deltas(); + assert!(app.render.gpu_failure.is_some()); + + // "Save render..." asks for the copy + *app.render.gpu.as_ref().unwrap().read.lock().unwrap() = super::Read::Wanted; + draw_gpu(&mut app, &context, 0.02).drop_without_applying_deltas(); + assert!(!matches!(*app.render.gpu.as_ref().unwrap().read.lock().unwrap(), super::Read::Wanted), "the failed render copies its image for the save"); +} + +/// An error of the scene traced before a change is not held against the changed scene, +/// which renders on the GPU +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_gpu_trace_error_of_a_previous_scene_is_discarded() { + let Some(mut app) = gpu_app() else { return }; + + let context = egui::Context::default(); + draw_gpu(&mut app, &context, 0.0).drop_without_applying_deltas(); + let error = "The GPU reported an error in GPU path tracing: a test"; + app.render.gpu.as_ref().unwrap().status.lock().unwrap().error = Some(error.into()); + + // The scene changes before the next frame reads the error + texturecraft_engine::execute(&mut app.session, "textureSet.settings", &serde_json::json!({"heightStrength": 5.0})).unwrap(); + app.session.update(); + draw_gpu(&mut app, &context, 0.01).drop_without_applying_deltas(); + assert!(app.render.gpu_failure.is_none() && app.render.gpu_error.is_none(), "the changed scene is not refused"); + assert!(app.render.job.is_none(), "no CPU render"); + assert_eq!(app.render.gpu.as_ref().unwrap().scene_key, gpu_scene_key(&app.session), "the changed scene is traced"); +} + /// A finished low-sample render must wake again to release its retained preview. #[cfg(not(target_arch = "wasm32"))] #[test] diff --git a/crates/ui-egui/src/settings_window.rs b/crates/ui-egui/src/settings_window.rs index 79ffc3655..c33434e4c 100644 --- a/crates/ui-egui/src/settings_window.rs +++ b/crates/ui-egui/src/settings_window.rs @@ -295,6 +295,9 @@ fn not_available(response: Response) -> Response { response.on_disabled_hover_text(tr(NOT_AVAILABLE)) } +/// The GPU memory budget a user starts from when turning Auto off +const CHOSEN_GPU_MEMORY_START_MB: u32 = 4096; + /// A row of a section: `label` on the left, `control` beside it. fn row(ui: &mut Ui, label: &str, control: impl FnOnce(&mut Ui, egui::Id) -> R) -> R { ui.horizontal(|ui| { @@ -459,6 +462,21 @@ fn general( .on_hover_text(tr("GPU uses the CPU on unsupported devices or layer stacks. CPU forces software composition.")); }); + row(ui, tr("GPU memory budget"), |ui, label| { + let mut automatic = prefs.gpu_memory_budget_mb == 0; + ui.checkbox(&mut automatic, tr("Auto")).labelled_by(label).on_hover_text(tr( + "How much GPU memory cached layer inputs (baked maps, images, Micro Details) may hold. Auto keeps them until the GPU refuses more memory (on Direct3D 12, and on Vulkan with memory budget support, at 90% of the system's GPU memory budget; elsewhere when an allocation fails), then frees them and composites again on the GPU. A number in megabytes frees those of the least recently used texture sets once they hold that much.", + )); + prefs.gpu_memory_budget_mb = match (automatic, prefs.gpu_memory_budget_mb) { + (true, _) => 0, + (false, 0) => CHOSEN_GPU_MEMORY_START_MB, + (false, chosen) => chosen, + }; + if !automatic { + ui.add(egui::DragValue::new(&mut prefs.gpu_memory_budget_mb).range(1..=u32::MAX).suffix(" MB")).labelled_by(label); + } + }); + row(ui, tr("Low-resolution material preview"), |ui, label| { ui.checkbox(&mut prefs.material_start_preview, "").labelled_by(label).on_hover_text(tr( "Show a quick preview while detailed CPU tiles are prepared after opening or resizing. Sets composited on the GPU skip it. Turn off to see the finished tiles as they arrive.", diff --git a/crates/ui-egui/src/shelf_preview.rs b/crates/ui-egui/src/shelf_preview.rs index ba8e4d00d..f9f427edd 100644 --- a/crates/ui-egui/src/shelf_preview.rs +++ b/crates/ui-egui/src/shelf_preview.rs @@ -129,7 +129,13 @@ impl ShelfPreview { | ShelfPreview::Curvature { .. } | ShelfPreview::GeneratorSet { .. } | ShelfPreview::SmartMaterial(_) => None, - ShelfPreview::Filter(id) => Some(sphere_image(size, &preview::filter(id, size)?)), + ShelfPreview::Filter(id) => match preview::filter(id, size, crate::preview_device::current().as_deref()) { + Ok(samples) => Some(sphere_image(size, &samples?)), + Err(error) => { + crate::preview_device::report_error(id, &error.to_string()); + None + } + }, ShelfPreview::Procedural(kind) => Some(procedural_image(*kind, size)), ShelfPreview::Alpha(alpha) => Some(alpha_image(alpha, size)), ShelfPreview::Brush(preset) => Some(stroke_preview(&preset.applied(&BrushSettings::default()), size, None)), @@ -258,7 +264,7 @@ mod tests { samples.iter().flatten().all(|sample| sample.base.into_iter().chain([sample.metallic, sample.roughness, sample.height]).all(f32::is_finite)) }; assert!(finite(preview::material(MATERIALS[0].id, BIG_PX).unwrap_or_default())); - assert!(finite(preview::filter(FILTERS[0].id, BIG_PX).unwrap_or_default())); + assert!(finite(preview::filter(FILTERS[0].id, BIG_PX, None).unwrap().unwrap_or_default())); assert!(ShelfPreview::SmartMask("edges_sharp").image(BIG_PX).is_none(), "smart masks need the baked orb"); assert!(ShelfPreview::SmartMaterial("steel_painted_worn").image(BIG_PX).is_none(), "smart materials need the baked orb"); } diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 8f455bff1..56e0c4371 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -157,6 +157,8 @@ pub struct Prefs { pub viewport_texture: u8, /// Prefer GPU layer compositing in the material viewport where available. pub gpu_compositing: bool, + /// Megabytes of GPU memory cached layer inputs may hold (0: Auto, no limit until the GPU refuses an allocation). + pub gpu_memory_budget_mb: u32, /// Show a coarse view of the whole material before its detailed CPU tiles arrive. pub material_start_preview: bool, /// Interface brightness (the views keep their own background). @@ -225,6 +227,7 @@ impl Default for Prefs { language: crate::i18n::SYSTEM_LANGUAGE.into(), viewport_texture: 0, gpu_compositing: true, + gpu_memory_budget_mb: 0, material_start_preview: true, brightness: crate::theme::Brightness::default(), accent: crate::theme::Accent::default(), diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 3a80fd329..4999f8ada 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -504,6 +504,7 @@ impl PendingSync { .zip(app.session.caches.get(app.session.ts())) .map(|(size, cache)| visible_uv_bounds(size, cache.size, app.ui.uv_zoom, app.ui.uv_pan, app.ui.uv_rotation)); gpu.prefer_gpu_layers = app.ui.prefs.gpu_compositing; + gpu.memory_budget_mb = app.ui.prefs.gpu_memory_budget_mb; gpu.material_start_preview = app.ui.prefs.material_start_preview; let scene = gpu.sync_view( &mut app.session,