From 07fec78a5386f1fc2bfd783914f1088daae544c6 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 3 Nov 2026 22:07:05 +0100 Subject: [PATCH 01/64] Compress project file entries on several threads Saving compressed every zip entry one after the other with deflate level 6 on a single thread; the baked maps were about three quarters of the time. The entries are independent, so native builds now compress them on up to 8 worker threads (one core is left to the UI) and copy the finished entries into the file in the original order with raw_copy_file. Entry names, order, methods, CRCs and sizes are unchanged, the format is unchanged, older versions open the files. Memory stays bounded: a worker only starts an entry while the estimated size of the entries started and not yet written is under 3 GiB, and baked maps and pixel tiles stream into the compressor instead of building a raw copy first. wasm and single-core machines keep the serial writer. The atomic tmp + fsync + rename path is unchanged. Refs #200, fixes #214 Co-Authored-By: Claude Sonnet 5.5 --- crates/formats/src/project_file/entries.rs | 174 +++++++++++++++++++++ crates/formats/src/project_file/mod.rs | 107 +++++++++---- crates/formats/src/project_file/tests.rs | 126 +++++++++++++++ 3 files changed, 375 insertions(+), 32 deletions(-) create mode 100644 crates/formats/src/project_file/entries.rs diff --git a/crates/formats/src/project_file/entries.rs b/crates/formats/src/project_file/entries.rs new file mode 100644 index 00000000..a04eab51 --- /dev/null +++ b/crates/formats/src/project_file/entries.rs @@ -0,0 +1,174 @@ +//! Writing the zip entries of a project file. +//! +//! Compressing the baked maps dominates a save (deflate level 6 over gigabytes of `f32`), and every +//! entry is independent, so on native targets the entries are compressed on several threads. Each +//! worker builds a one-entry zip in memory with the same options the serial writer uses; the writing +//! thread copies those entries into the real file in the original order with +//! [`ZipWriter::raw_copy_file`]. The compressed bytes of every entry and the entry order are +//! therefore the same as in a serial save. +//! +//! Memory stays bounded: a worker only starts an entry while the entries started but not yet written +//! have an estimated compressed size under [`IN_FLIGHT_BUDGET`] (a single entry larger than that runs +//! alone), and entry bodies stream into the compressor instead of building a raw copy first. + +use std::io::{Seek, Write}; + +use zip::ZipWriter; +use zip::write::SimpleFileOptions; + +use super::zip_err; +use crate::Result; + +/// Produces the uncompressed bytes of one entry into the zip writer. +pub(super) type Body<'a> = Box std::io::Result<()> + Send + 'a>; + +pub(super) struct Entry<'a> { + pub name: String, + pub options: SimpleFileOptions, + /// Upper bound of the compressed size in bytes (the uncompressed size is a safe choice). + pub weight: u64, + pub body: Body<'a>, +} + +/// Compressed bytes (estimated) that may be held in memory at once while entries are in flight. +#[cfg(not(target_arch = "wasm32"))] +const IN_FLIGHT_BUDGET: u64 = 3 << 30; +/// More workers than this do not help: a project has a handful of large entries. +#[cfg(not(target_arch = "wasm32"))] +const MAX_WORKERS: usize = 8; + +/// Write `entries` in order: in parallel where threads exist, else one after the other. +pub(super) fn write_entries(zip: &mut ZipWriter, entries: Vec>) -> Result<()> { + #[cfg(not(target_arch = "wasm32"))] + { + // Leave one core to the UI: an autosave runs while the user keeps painting. + let cpus = std::thread::available_parallelism().map_or(1, usize::from); + let workers = cpus.saturating_sub(1).clamp(1, MAX_WORKERS).min(entries.len()); + if workers > 1 { + return parallel::write(zip, entries, workers, IN_FLIGHT_BUDGET); + } + } + write_serial(zip, entries) +} + +/// One entry after the other straight into `zip`. +pub(super) fn write_serial(zip: &mut ZipWriter, entries: Vec>) -> Result<()> { + for e in entries { + zip.start_file(e.name, e.options).map_err(zip_err)?; + (e.body)(zip)?; + } + Ok(()) +} + +#[cfg(not(target_arch = "wasm32"))] +pub(super) mod parallel { + use std::collections::BTreeMap; + use std::io::{Cursor, Seek, Write}; + use std::panic::{AssertUnwindSafe, catch_unwind}; + use std::sync::{Condvar, Mutex, MutexGuard}; + + use zip::{ZipArchive, ZipWriter}; + + use super::Entry; + use crate::project_file::zip_err; + use crate::{FormatError, Result}; + + struct State { + /// Next entry to start. + next: usize, + /// Estimated bytes of the entries started and not yet written. + in_flight: u64, + /// Finished entries (one-entry zips) waiting for their turn. + ready: BTreeMap>>, + /// The writer failed: start nothing more. + stop: bool, + } + + fn lock(m: &Mutex) -> MutexGuard<'_, T> { + m.lock().unwrap_or_else(|e| e.into_inner()) + } + + fn wait<'a>(cv: &Condvar, g: MutexGuard<'a, State>) -> MutexGuard<'a, State> { + cv.wait(g).unwrap_or_else(|e| e.into_inner()) + } + + /// Compress one entry into a zip of its own. + fn compress(e: Entry<'_>) -> Result> { + let mut z = ZipWriter::new(Cursor::new(Vec::new())); + z.start_file(e.name, e.options).map_err(zip_err)?; + (e.body)(&mut z)?; + Ok(z.finish().map_err(zip_err)?.into_inner()) + } + + fn worker(slots: &[Mutex>>], weights: &[u64], budget: u64, state: &Mutex, cv: &Condvar) { + loop { + let i = { + let mut st = lock(state); + loop { + if st.stop || st.next >= slots.len() { + return; + } + let w = weights.get(st.next).copied().unwrap_or(0); + // The first entry in line always starts, however large. + if st.in_flight == 0 || st.in_flight.saturating_add(w) <= budget { + let i = st.next; + st.next += 1; + st.in_flight = st.in_flight.saturating_add(w); + break i; + } + st = wait(cv, st); + } + }; + let entry = slots.get(i).and_then(|s| lock(s).take()); + let res = match entry { + Some(e) => { + catch_unwind(AssertUnwindSafe(|| compress(e))).unwrap_or_else(|_| Err(FormatError::Invalid("compressing a project entry failed".into()))) + } + None => Err(FormatError::Invalid("project entry missing".into())), + }; + lock(state).ready.insert(i, res); + cv.notify_all(); + } + } + + /// Copy the compressed entry of a one-entry zip into `zip` without recompressing. + fn copy_entry(zip: &mut ZipWriter, bytes: Vec) -> Result<()> { + let mut a = ZipArchive::new(Cursor::new(bytes)).map_err(zip_err)?; + let f = a.by_index_raw(0).map_err(zip_err)?; + zip.raw_copy_file(f).map_err(zip_err) + } + + pub(in crate::project_file) fn write(zip: &mut ZipWriter, entries: Vec>, workers: usize, budget: u64) -> Result<()> { + let weights: Vec = entries.iter().map(|e| e.weight).collect(); + let slots: Vec>>> = entries.into_iter().map(|e| Mutex::new(Some(e))).collect(); + let state = Mutex::new(State { next: 0, in_flight: 0, ready: BTreeMap::new(), stop: false }); + let cv = Condvar::new(); + std::thread::scope(|s| { + for _ in 0..workers { + s.spawn(|| worker(&slots, &weights, budget, &state, &cv)); + } + let res = (|| -> Result<()> { + for (i, w) in weights.iter().enumerate() { + let done = { + let mut st = lock(&state); + loop { + if let Some(r) = st.ready.remove(&i) { + st.in_flight = st.in_flight.saturating_sub(*w); + cv.notify_all(); + break r; + } + st = wait(&cv, st); + } + }; + copy_entry(zip, done?)?; + } + Ok(()) + })(); + if res.is_err() { + lock(&state).stop = true; + cv.notify_all(); + } + res + }) + } +} diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index a42afdb9..bf8c4b53 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -28,8 +28,11 @@ use texturecraft_texel::{TILE_AREA, TileImage}; use zip::write::SimpleFileOptions; use zip::{CompressionMethod, ZipArchive, ZipWriter}; +use self::entries::{Body, Entry}; use crate::{FormatError, MAX_IMAGE_SIZE, Result, malformed}; +mod entries; + const KIND: &str = "project file"; const MAGIC: &[u8; 4] = b"TCTX"; /// Version of the `.bin` layout. @@ -164,47 +167,75 @@ fn unique_entry_name(dir: &str, name: &str, used: &mut HashSet) -> Strin entry } -fn write_project(out: W, pf: &ProjectFile) -> Result<()> { - let mut zip = ZipWriter::new(out); +/// Floats converted to bytes at a time when a baked map streams into the compressor. +const BAKED_CHUNK: usize = 1 << 16; + +fn write_baked(w: &mut dyn Write, res: u32, h: u32, comps: usize, data: &[f32]) -> std::io::Result<()> { + w.write_all(&header(res, h, comps, 0))?; + let mut buf = Vec::with_capacity(BAKED_CHUNK * 4); + for chunk in data.chunks(BAKED_CHUNK) { + buf.clear(); + buf.extend(chunk.iter().flat_map(|v| v.to_le_bytes())); + w.write_all(&buf)?; + } + Ok(()) +} + +/// The zip entries of a project file, in file order. Bodies run later, possibly on other threads. +fn entries(pf: &ProjectFile) -> Result>> { let deflate = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated).large_file(true); let stored = SimpleFileOptions::default().compression_method(CompressionMethod::Stored); let json = serde_json::to_vec_pretty(&pf.project).map_err(|e| FormatError::Invalid(e.to_string()))?; - zip.start_file("project.json", deflate).map_err(zip_err)?; - zip.write_all(&json)?; + let mut out = vec![Entry { name: "project.json".into(), options: deflate, weight: json.len() as u64, body: Box::new(move |w| w.write_all(&json)) }]; if let Some((ext, bytes)) = &pf.mesh { - zip.start_file(format!("mesh.{}", sanitize_ext(ext)), deflate).map_err(zip_err)?; - zip.write_all(bytes)?; + out.push(Entry { + name: format!("mesh.{}", sanitize_ext(ext)), + options: deflate, + weight: bytes.len() as u64, + body: Box::new(move |w| w.write_all(bytes)), + }); } let mut used = HashSet::new(); for (dir, (name, bytes)) in pf.high_poly.iter().map(|m| ("highpoly", m)).chain(pf.cage.iter().map(|m| ("cage", m))) { - zip.start_file(unique_entry_name(dir, name, &mut used), deflate).map_err(zip_err)?; - zip.write_all(bytes)?; + out.push(Entry { + name: unique_entry_name(dir, name, &mut used), + options: deflate, + weight: bytes.len() as u64, + body: Box::new(move |w| w.write_all(bytes)), + }); } if let Some(k) = pf.skew.as_ref().filter(|k| k.width > 0 && k.height > 0 && k.values.len() as u64 == u64::from(k.width) * u64::from(k.height)) { - zip.start_file("skew.bin", deflate).map_err(zip_err)?; - let mut b = SKEW_MAGIC.to_vec(); - b.extend_from_slice(&BIN_VERSION.to_le_bytes()); - for v in [k.width, k.height] { - b.extend_from_slice(&v.to_le_bytes()); - } - for v in [k.edge_distance, k.edge_contrast] { - b.extend_from_slice(&v.to_le_bytes()); - } - b.push(u8::from(k.per_triangle)); - b.extend(k.values.iter().flat_map(|v| v.to_le_bytes())); - zip.write_all(&b)?; + let body: Body<'_> = Box::new(move |w| { + let mut b = SKEW_MAGIC.to_vec(); + b.extend_from_slice(&BIN_VERSION.to_le_bytes()); + for v in [k.width, k.height] { + b.extend_from_slice(&v.to_le_bytes()); + } + for v in [k.edge_distance, k.edge_contrast] { + b.extend_from_slice(&v.to_le_bytes()); + } + b.push(u8::from(k.per_triangle)); + b.extend(k.values.iter().flat_map(|v| v.to_le_bytes())); + w.write_all(&b) + }); + out.push(Entry { name: "skew.bin".into(), options: deflate, weight: k.values.len() as u64 * 4, body }); } let mut layers: Vec<_> = pf.pixels.layers.iter().collect(); layers.sort_by_key(|(k, _)| **k); for ((id, c), img) in layers { - zip.start_file(format!("pixels/layer_{}_{}.bin", id.0, c.id()), deflate).map_err(zip_err)?; - write_tiles(&mut zip, img)?; + let weight = (img.allocated_count() * (TILE_AREA * img.comps() * 2 + 8)) as u64; + out.push(Entry { + name: format!("pixels/layer_{}_{}.bin", id.0, c.id()), + options: deflate, + weight, + body: Box::new(move |mut w| write_tiles(&mut w, img)), + }); } let mut masks: Vec<_> = pf.pixels.masks.iter().collect(); masks.sort_by_key(|(k, _)| **k); for (id, img) in masks { - zip.start_file(format!("pixels/mask_{}.bin", id.0), deflate).map_err(zip_err)?; - write_tiles(&mut zip, img)?; + let weight = (img.allocated_count() * (TILE_AREA * img.comps() * 2 + 8)) as u64; + out.push(Entry { name: format!("pixels/mask_{}.bin", id.0), options: deflate, weight, body: Box::new(move |mut w| write_tiles(&mut w, img)) }); } for (ts, maps) in &pf.baked { let r = maps.resolution; @@ -214,21 +245,33 @@ fn write_project(out: W, pf: &ProjectFile) -> Result<()> { if h == 0 || data.len() != (r as usize) * (h as usize) * m.components() { continue; } - zip.start_file(format!("baked/{ts}_{}.bin", m.id()), deflate).map_err(zip_err)?; - zip.write_all(&header(r, h, m.components(), 0))?; - let bytes: Vec = data.iter().flat_map(|v| v.to_le_bytes()).collect(); - zip.write_all(&bytes)?; + let comps = m.components(); + out.push(Entry { + name: format!("baked/{ts}_{}.bin", m.id()), + options: deflate, + weight: data.len() as u64 * 4, + body: Box::new(move |w| write_baked(w, r, h, comps, data)), + }); } } if let Some(png) = &pf.thumbnail { - zip.start_file("thumbnail.png", stored).map_err(zip_err)?; - zip.write_all(png)?; + out.push(Entry { name: "thumbnail.png".into(), options: stored, weight: png.len() as u64, body: Box::new(move |w| w.write_all(png)) }); } used.clear(); for (name, bytes) in &pf.resources { - zip.start_file(unique_entry_name("resources", name, &mut used), stored).map_err(zip_err)?; - zip.write_all(bytes)?; + out.push(Entry { + name: unique_entry_name("resources", name, &mut used), + options: stored, + weight: bytes.len() as u64, + body: Box::new(move |w| w.write_all(bytes)), + }); } + Ok(out) +} + +fn write_project(out: W, pf: &ProjectFile) -> Result<()> { + let mut zip = ZipWriter::new(out); + entries::write_entries(&mut zip, entries(pf)?)?; zip.finish().map_err(zip_err)?; Ok(()) } diff --git a/crates/formats/src/project_file/tests.rs b/crates/formats/src/project_file/tests.rs index 5832d53c..eacc939a 100644 --- a/crates/formats/src/project_file/tests.rs +++ b/crates/formats/src/project_file/tests.rs @@ -211,3 +211,129 @@ fn duplicate_entry_names_are_made_unique_on_save() { res.sort(); assert_eq!(res, vec![vec![3], vec![4]]); } + +/// Every entry of a zip in file order: (name, method, crc, sizes, the compressed bytes as stored). +/// The zip headers around them (version fields, zip64 size placeholders) are not part of this: +/// copying an entry between zips rewrites them. +#[allow(clippy::type_complexity)] +fn payloads(zip: &[u8]) -> Vec<(String, CompressionMethod, u32, u64, u64, Vec)> { + let mut a = ZipArchive::new(Cursor::new(zip)).unwrap(); + (0..a.len()) + .map(|i| { + let mut f = a.by_index_raw(i).unwrap(); + let mut raw = Vec::new(); + f.read_to_end(&mut raw).unwrap(); + (f.name().unwrap().into_owned(), f.compression(), f.crc32(), f.size(), f.compressed_size(), raw) + }) + .collect() +} + +/// A project with several baked maps and pixel layers, big enough that entries stream in chunks. +fn big_sample() -> ProjectFile { + let mut s = sample(); + let mut x = 12345u32; + let mut noise = |n: usize| -> Vec { + (0..n) + .map(|i| { + x = x.wrapping_mul(1664525).wrapping_add(1013904223); + (i as f32 * 0.001).sin() * 0.5 + 0.5 + (x >> 24) as f32 * 1e-4 + }) + .collect() + }; + let r = 300usize; + let maps = [BakedMap::AmbientOcclusion, BakedMap::Normal, BakedMap::Curvature, BakedMap::Position] + .into_iter() + .map(|m| (m, Arc::new(noise(r * r * m.components())))) + .collect(); + s.pf.baked.insert(1, BakedMaps { resolution: r as u32, maps }); + s.pf.mesh = Some(("obj".into(), noise(5000).iter().map(|v| (v * 200.0) as u8).collect())); + s.pf +} + +fn serial_bytes(pf: &ProjectFile) -> Vec { + let mut zip = ZipWriter::new(Cursor::new(Vec::new())); + entries::write_serial(&mut zip, entries(pf).unwrap()).unwrap(); + zip.finish().unwrap().into_inner() +} + +fn parallel_bytes(pf: &ProjectFile, workers: usize, budget: u64) -> Vec { + let mut zip = ZipWriter::new(Cursor::new(Vec::new())); + entries::parallel::write(&mut zip, entries(pf).unwrap(), workers, budget).unwrap(); + zip.finish().unwrap().into_inner() +} + +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn parallel_save_writes_the_same_entries_as_serial() { + let pf = big_sample(); + let serial = serial_bytes(&pf); + let want = payloads(&serial); + assert!(want.len() > 10); + for (workers, budget) in [(2, u64::MAX), (4, u64::MAX), (8, 1), (3, 100_000)] { + let got = parallel_bytes(&pf, workers, budget); + assert!(payloads(&got) == want, "{workers} workers, budget {budget}"); + assert_same(&pf, &load_project_bytes(&got).unwrap()); + } + // The public entry point (threads chosen by the machine) agrees too, and loads back. + assert!(payloads(&save_project_bytes(&pf).unwrap()) == want); + assert_same(&pf, &load_project_bytes(&serial).unwrap()); +} + +/// The files written before entries were compressed in parallel: each entry written in one go. +fn reference_one_shot(pf: &ProjectFile) -> Vec { + let deflate = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated).large_file(true); + let mut zip = ZipWriter::new(Cursor::new(Vec::new())); + zip.start_file("project.json", deflate).unwrap(); + zip.write_all(&serde_json::to_vec_pretty(&pf.project).unwrap()).unwrap(); + for (ts, maps) in &pf.baked { + for (m, data) in &maps.maps { + zip.start_file(format!("baked/{ts}_{}.bin", m.id()), deflate).unwrap(); + zip.write_all(&header(maps.resolution, maps.height(*m), m.components(), 0)).unwrap(); + let bytes: Vec = data.iter().flat_map(|v| v.to_le_bytes()).collect(); + zip.write_all(&bytes).unwrap(); + } + } + zip.finish().unwrap().into_inner() +} + +/// Streaming a baked map into the compressor in chunks may place deflate block boundaries a few +/// bytes differently than one big write, so the stored bytes can differ slightly; what the entry +/// holds (name, method, CRC, size) must not, and the compressed size stays within 0.01%. +#[test] +fn baked_entries_hold_what_the_one_shot_writer_wrote() { + let mut pf = big_sample(); + (pf.mesh, pf.high_poly, pf.cage, pf.skew, pf.thumbnail, pf.resources) = (None, vec![], None, None, None, BTreeMap::new()); + pf.pixels = PixelStore::default(); + let (new, old) = (payloads(&save_project_bytes(&pf).unwrap()), payloads(&reference_one_shot(&pf))); + assert_eq!(new.len(), old.len()); + for (n, o) in new.iter().zip(&old) { + assert_eq!((&n.0, n.1, n.2, n.3), (&o.0, o.1, o.2, o.3)); + assert!(n.4.abs_diff(o.4) <= 64 + o.4 / 10_000, "{}: {} vs {}", n.0, n.4, o.4); + } +} + +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn a_failing_entry_is_an_error_not_a_hang() { + let opts = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated); + for fail_at in [0usize, 3, 9] { + let list: Vec> = (0..10) + .map(|i| Entry { + name: format!("e{i}"), + options: opts, + weight: 10, + body: Box::new(move |w| { + if i == fail_at { + return Err(std::io::Error::other("boom")); + } + if i == 5 && fail_at == 9 { + panic!("worker panic"); + } + w.write_all(&[i as u8; 100]) + }), + }) + .collect(); + let mut zip = ZipWriter::new(Cursor::new(Vec::new())); + assert!(entries::parallel::write(&mut zip, list, 4, 25).is_err(), "fail at {fail_at}"); + } +} From 11d672661fcb300606414041ff2c2cae35e8be4e Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 3 Nov 2026 22:09:19 +0100 Subject: [PATCH 02/64] Parallel save: fall back when threads cannot start; release entry share after copy Co-Authored-By: Claude Sonnet 5.5 --- crates/formats/src/project_file/entries.rs | 25 ++++++++++++++++++---- 1 file changed, 21 insertions(+), 4 deletions(-) diff --git a/crates/formats/src/project_file/entries.rs b/crates/formats/src/project_file/entries.rs index a04eab51..a068e9b9 100644 --- a/crates/formats/src/project_file/entries.rs +++ b/crates/formats/src/project_file/entries.rs @@ -26,6 +26,7 @@ pub(super) struct Entry<'a> { pub name: String, pub options: SimpleFileOptions, /// Upper bound of the compressed size in bytes (the uncompressed size is a safe choice). + #[cfg_attr(target_arch = "wasm32", allow(dead_code))] pub weight: u64, pub body: Body<'a>, } @@ -144,23 +145,39 @@ pub(super) mod parallel { let state = Mutex::new(State { next: 0, in_flight: 0, ready: BTreeMap::new(), stop: false }); let cv = Condvar::new(); std::thread::scope(|s| { + let mut started = 0; for _ in 0..workers { - s.spawn(|| worker(&slots, &weights, budget, &state, &cv)); + // Thread creation can fail (process limits); the workers that did start drain the queue. + if std::thread::Builder::new().spawn_scoped(s, || worker(&slots, &weights, budget, &state, &cv)).is_ok() { + started += 1; + } } let res = (|| -> Result<()> { for (i, w) in weights.iter().enumerate() { + if started == 0 { + // No thread at all: compress here, one entry after the other. + let entry = slots.get(i).and_then(|s| lock(s).take()); + let bytes = compress(entry.ok_or_else(|| FormatError::Invalid("project entry missing".into()))?)?; + copy_entry(zip, bytes)?; + continue; + } let done = { let mut st = lock(&state); loop { if let Some(r) = st.ready.remove(&i) { - st.in_flight = st.in_flight.saturating_sub(*w); - cv.notify_all(); break r; } st = wait(&cv, st); } }; - copy_entry(zip, done?)?; + let copied = done.and_then(|bytes| copy_entry(zip, bytes)); + // Release the entry's share only once its bytes are gone. + { + let mut st = lock(&state); + st.in_flight = st.in_flight.saturating_sub(*w); + } + cv.notify_all(); + copied?; } Ok(()) })(); From 52505ecbc206b654ce78f195303f47a0581a3f6e Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 3 Nov 2026 22:17:06 +0100 Subject: [PATCH 03/64] Refuse to save a project that could not be opened again Opening a project file stops at 8 GiB of decompressed data (MAX_TOTAL), but saving had no matching check, so a too big project saved fine and then failed to open. Saving now counts the bytes the loader would count and refuses before the temporary file is created, with an error that names the size and the limit; the existing file stays as it was. The limit itself is unchanged. A test checks that the count equals what load counts for a real file. Fixes #215. Refs #200 Co-Authored-By: Claude Sonnet 5.5 --- crates/formats/src/project_file/mod.rs | 60 +++++++++++++++++++++++- crates/formats/src/project_file/tests.rs | 46 ++++++++++++++++++ 2 files changed, 105 insertions(+), 1 deletion(-) diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index a42afdb9..0b8ca754 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -88,6 +88,7 @@ pub fn sanitize_resource_name(name: &str) -> String { // Save. pub fn save_project_bytes(pf: &ProjectFile) -> Result> { + check_loadable(pf, MAX_TOTAL)?; let mut out = Cursor::new(Vec::new()); write_project(&mut out, pf)?; Ok(out.into_inner()) @@ -96,6 +97,14 @@ pub fn save_project_bytes(pf: &ProjectFile) -> Result> { /// Save atomically: `.tmp` first, then rename over `path`. #[cfg(not(target_arch = "wasm32"))] pub fn save_project(path: &std::path::Path, pf: &ProjectFile) -> Result<()> { + save_project_limited(path, pf, MAX_TOTAL) +} + +/// [`save_project`] with the size [`load`] would accept as a parameter (tests lower it). +#[cfg(not(target_arch = "wasm32"))] +fn save_project_limited(path: &std::path::Path, pf: &ProjectFile, limit: u64) -> Result<()> { + // Before the temp file exists, so a refusal leaves the file on disk as it was. + check_loadable(pf, limit)?; let mut tmp = path.as_os_str().to_owned(); tmp.push(".tmp"); let tmp = std::path::PathBuf::from(tmp); @@ -112,6 +121,50 @@ pub fn save_project(path: &std::path::Path, pf: &ProjectFile) -> Result<()> { res } +/// Decompressed bytes that [`load`] counts against [`MAX_TOTAL`] when it reads `pf` back: the +/// payload of every entry it reads, without the `.bin` headers. Keep in step with `load` +/// (`load_size_matches_what_load_counts` checks it). Pixels of layers that are in no stack are +/// dropped by `load` without counting, so they are not counted here either. +fn load_size(pf: &ProjectFile) -> Result { + let json = serde_json::to_vec_pretty(&pf.project).map_err(|e| FormatError::Invalid(e.to_string()))?; + let mut n = json.len() as u64; + n += pf.mesh.iter().map(|(_, b)| b.len() as u64).sum::(); + n += pf.high_poly.iter().map(|(_, b)| b.len() as u64).sum::(); + n += pf.cage.iter().map(|(_, b)| b.len() as u64).sum::(); + n += pf.thumbnail.iter().map(|b| b.len() as u64).sum::(); + n += pf.resources.values().map(|b| b.len() as u64).sum::(); + if let Some(k) = pf.skew.as_ref().filter(|k| k.width > 0 && k.height > 0 && k.values.len() as u64 == u64::from(k.width) * u64::from(k.height)) { + n += k.values.len() as u64 * 4; + } + let tiles = |img: &TileImage| (img.allocated_count() as u64) * (TILE_AREA * img.comps() * 2) as u64; + n += pf.pixels.layers.iter().filter(|((id, _), _)| texture_set_of(&pf.project, *id).is_some()).map(|(_, img)| tiles(img)).sum::(); + n += pf.pixels.masks.iter().filter(|(id, _)| texture_set_of(&pf.project, **id).is_some()).map(|(_, img)| tiles(img)).sum::(); + for maps in pf.baked.values() { + for (m, data) in &maps.maps { + let h = maps.height(*m); + if h != 0 && data.len() == (maps.resolution as usize) * (h as usize) * m.components() { + n += data.len() as u64 * 4; + } + } + } + Ok(n) +} + +/// Refuse to save a project that [`load`] would reject as too large, before anything is written. +fn check_loadable(pf: &ProjectFile, limit: u64) -> Result<()> { + let size = load_size(pf)?; + if size > limit { + let gib = |b: u64| b as f64 / (1u64 << 30) as f64; + return Err(FormatError::TooLarge(format!( + "the project holds {:.1} GiB of data once unpacked, but TextureCraft opens project files only up to {:.1} GiB, so it was not saved and the file on disk is unchanged. \ + Remove paint layers or baked maps, or lower the texture resolution", + gib(size), + gib(limit) + ))); + } + Ok(()) +} + fn zip_err(e: zip::result::ZipError) -> FormatError { match e { zip::result::ZipError::Io(e) => FormatError::Io(e), @@ -375,6 +428,11 @@ fn texture_set_of(project: &Project, id: LayerId) -> Option { } fn load(reader: R) -> Result { + load_counted(reader).map(|(pf, _)| pf) +} + +/// [`load`], also returning the decompressed bytes it counted against [`MAX_TOTAL`]. +fn load_counted(reader: R) -> Result<(ProjectFile, u64)> { let mut zip = ZipArchive::new(reader).map_err(zip_err)?; if zip.len() > MAX_ENTRIES { return Err(FormatError::TooLarge(format!("project file has more than {MAX_ENTRIES} entries"))); @@ -464,7 +522,7 @@ fn load(reader: R) -> Result { } // Other entries (from newer minor revisions) are ignored. } - Ok(pf) + Ok((pf, budget.0)) } #[cfg(test)] diff --git a/crates/formats/src/project_file/tests.rs b/crates/formats/src/project_file/tests.rs index 5832d53c..5ae008f8 100644 --- a/crates/formats/src/project_file/tests.rs +++ b/crates/formats/src/project_file/tests.rs @@ -211,3 +211,49 @@ fn duplicate_entry_names_are_made_unique_on_save() { res.sort(); assert_eq!(res, vec![vec![3], vec![4]]); } + +#[test] +fn load_size_matches_what_load_counts() { + let s = sample(); + let mut tiled = sample().pf; + tiled.project.texture_sets[0].uv_tiles = vec![1001, 1002]; + tiled.pixels = PixelStore::default(); + tiled.baked = [(0, BakedMaps { resolution: 32, maps: [(BakedMap::AmbientOcclusion, Arc::new(vec![0.25; 32 * 16]))].into() })].into(); + for pf in [&s.pf, &tiled] { + let bytes = save_project_bytes(pf).unwrap(); + let (_, counted) = load_counted(Cursor::new(bytes)).unwrap(); + assert!(counted > 1000); + assert_eq!(load_size(pf).unwrap(), counted); + } +} + +#[test] +fn a_project_too_big_to_reopen_is_not_saved() { + let s = sample(); + let size = load_size(&s.pf).unwrap(); + assert!(check_loadable(&s.pf, size).is_ok()); + let err = check_loadable(&s.pf, size - 1).unwrap_err(); + assert!(matches!(err, FormatError::TooLarge(_))); + assert!(err.to_string().contains("not saved"), "{err}"); +} + +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_refused_save_leaves_the_existing_file_alone() { + let s = sample(); + let dir = std::env::temp_dir().join(format!("tc-formats-toobig-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("demo.tcraft"); + save_project(&path, &s.pf).unwrap(); + let before = std::fs::read(&path).unwrap(); + let mut changed = s.pf.clone(); + changed.project.name = "Changed".into(); + assert!(matches!(save_project_limited(&path, &changed, 10), Err(FormatError::TooLarge(_)))); + assert_eq!(std::fs::read(&path).unwrap(), before); + assert!(!dir.join("demo.tcraft.tmp").exists()); + // A path that does not exist yet stays absent. + let fresh = dir.join("new.tcraft"); + assert!(save_project_limited(&fresh, &changed, 10).is_err()); + assert!(!fresh.exists() && !dir.join("new.tcraft.tmp").exists()); + std::fs::remove_dir_all(&dir).unwrap(); +} From b99ebf73210efa7ae065ea5bfd7709f547da17d7 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 3 Nov 2026 22:17:57 +0100 Subject: [PATCH 04/64] Save size check: skip orphan baked sets, clearer message, wider test Co-Authored-By: Claude Sonnet 5.5 --- crates/formats/src/project_file/mod.rs | 7 ++++--- crates/formats/src/project_file/tests.rs | 12 ++++++++++-- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index 0b8ca754..e9513793 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -139,7 +139,8 @@ fn load_size(pf: &ProjectFile) -> Result { let tiles = |img: &TileImage| (img.allocated_count() as u64) * (TILE_AREA * img.comps() * 2) as u64; n += pf.pixels.layers.iter().filter(|((id, _), _)| texture_set_of(&pf.project, *id).is_some()).map(|(_, img)| tiles(img)).sum::(); n += pf.pixels.masks.iter().filter(|(id, _)| texture_set_of(&pf.project, **id).is_some()).map(|(_, img)| tiles(img)).sum::(); - for maps in pf.baked.values() { + // `load` skips the baked maps of a texture set that no longer exists. + for maps in pf.baked.iter().filter(|(ts, _)| **ts < pf.project.texture_sets.len()).map(|(_, m)| m) { for (m, data) in &maps.maps { let h = maps.height(*m); if h != 0 && data.len() == (maps.resolution as usize) * (h as usize) * m.components() { @@ -156,8 +157,8 @@ fn check_loadable(pf: &ProjectFile, limit: u64) -> Result<()> { if size > limit { let gib = |b: u64| b as f64 / (1u64 << 30) as f64; return Err(FormatError::TooLarge(format!( - "the project holds {:.1} GiB of data once unpacked, but TextureCraft opens project files only up to {:.1} GiB, so it was not saved and the file on disk is unchanged. \ - Remove paint layers or baked maps, or lower the texture resolution", + "the project holds {:.2} GiB of data once unpacked, but TextureCraft opens project files only up to {:.2} GiB, so nothing was saved and an existing file is unchanged. \ + Remove paint layers or baked maps to make it smaller", gib(size), gib(limit) ))); diff --git a/crates/formats/src/project_file/tests.rs b/crates/formats/src/project_file/tests.rs index 5ae008f8..44fd17cf 100644 --- a/crates/formats/src/project_file/tests.rs +++ b/crates/formats/src/project_file/tests.rs @@ -219,7 +219,15 @@ fn load_size_matches_what_load_counts() { tiled.project.texture_sets[0].uv_tiles = vec![1001, 1002]; tiled.pixels = PixelStore::default(); tiled.baked = [(0, BakedMaps { resolution: 32, maps: [(BakedMap::AmbientOcclusion, Arc::new(vec![0.25; 32 * 16]))].into() })].into(); - for pf in [&s.pf, &tiled] { + // The branches where the count could drift: pixels of a layer in no stack, a baked map of a + // set that does not exist, and a baked map whose size does not match (not written). + let mut odd = sample().pf; + odd.pixels.layer_mut(LayerId(999), Channel::BaseColor, (128, 128)).set(1, 1, &[1, 2, 3, 4]); + odd.pixels.mask_mut(LayerId(998), (64, 64)).set(1, 1, &[1, 2]); + odd.baked.insert(7, BakedMaps { resolution: 16, maps: [(BakedMap::AmbientOcclusion, Arc::new(vec![0.5; 256]))].into() }); + odd.baked.entry(1).or_default().resolution = 8; + odd.baked.get_mut(&1).unwrap().maps.insert(BakedMap::Curvature, Arc::new(vec![0.5; 13])); + for pf in [&s.pf, &tiled, &odd] { let bytes = save_project_bytes(pf).unwrap(); let (_, counted) = load_counted(Cursor::new(bytes)).unwrap(); assert!(counted > 1000); @@ -234,7 +242,7 @@ fn a_project_too_big_to_reopen_is_not_saved() { assert!(check_loadable(&s.pf, size).is_ok()); let err = check_loadable(&s.pf, size - 1).unwrap_err(); assert!(matches!(err, FormatError::TooLarge(_))); - assert!(err.to_string().contains("not saved"), "{err}"); + assert!(err.to_string().contains("nothing was saved"), "{err}"); } #[cfg(not(target_arch = "wasm32"))] From d7ae9891ef079ef0aa6e2bba406306eec01b5df5 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 4 Nov 2026 00:45:24 +0100 Subject: [PATCH 05/64] Parallel save: stream entries when no worker thread starts Review point: with no worker thread the fallback built a whole in-memory zip per entry; it now writes each entry straight into the file like the serial writer, and the test covers that path. Co-Authored-By: Claude Sonnet 5.5 --- crates/formats/src/project_file/entries.rs | 8 ++++---- crates/formats/src/project_file/tests.rs | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/formats/src/project_file/entries.rs b/crates/formats/src/project_file/entries.rs index a068e9b9..9e4c6d03 100644 --- a/crates/formats/src/project_file/entries.rs +++ b/crates/formats/src/project_file/entries.rs @@ -155,10 +155,10 @@ pub(super) mod parallel { let res = (|| -> Result<()> { for (i, w) in weights.iter().enumerate() { if started == 0 { - // No thread at all: compress here, one entry after the other. - let entry = slots.get(i).and_then(|s| lock(s).take()); - let bytes = compress(entry.ok_or_else(|| FormatError::Invalid("project entry missing".into()))?)?; - copy_entry(zip, bytes)?; + // No thread at all: stream the entry into the file like the serial writer does. + let entry = slots.get(i).and_then(|s| lock(s).take()).ok_or_else(|| FormatError::Invalid("project entry missing".into()))?; + zip.start_file(entry.name, entry.options).map_err(zip_err)?; + (entry.body)(zip)?; continue; } let done = { diff --git a/crates/formats/src/project_file/tests.rs b/crates/formats/src/project_file/tests.rs index eacc939a..48045f5d 100644 --- a/crates/formats/src/project_file/tests.rs +++ b/crates/formats/src/project_file/tests.rs @@ -269,7 +269,7 @@ fn parallel_save_writes_the_same_entries_as_serial() { let serial = serial_bytes(&pf); let want = payloads(&serial); assert!(want.len() > 10); - for (workers, budget) in [(2, u64::MAX), (4, u64::MAX), (8, 1), (3, 100_000)] { + for (workers, budget) in [(0, 1), (2, u64::MAX), (4, u64::MAX), (8, 1), (3, 100_000)] { let got = parallel_bytes(&pf, workers, budget); assert!(payloads(&got) == want, "{workers} workers, budget {budget}"); assert_same(&pf, &load_project_bytes(&got).unwrap()); From 715baf47609f689eb5ab0676825869639820a3e3 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 4 Nov 2026 01:36:12 +0100 Subject: [PATCH 06/64] Use as_chunks where the chunk size is a constant Clippy 1.99 flags chunks_exact and chunks_exact_mut with a constant chunk size (chunks_exact_to_as_chunks). Switch those call sites to as_chunks / as_chunks_mut. Behaviour is unchanged: the trailing partial chunk was already dropped. Fixes #233 Co-Authored-By: Claude Sonnet 5.5 --- crates/bake/src/maps.rs | 2 +- crates/bake/src/tests.rs | 2 +- crates/compose/src/display.rs | 4 ++-- crates/compose/src/eval.rs | 2 +- crates/engine/src/quick_mask.rs | 2 +- crates/engine/tests/auto_rebake.rs | 2 +- crates/engine/tests/bake.rs | 2 +- crates/formats/src/fonts.rs | 4 ++-- crates/formats/src/mesh_export.rs | 2 +- crates/formats/src/mesh_export/usd.rs | 2 +- crates/formats/src/mesh_import/abc/mod.rs | 18 +++++++++--------- crates/formats/src/mesh_import/fbx.rs | 10 +++++----- crates/formats/src/mesh_import/gltf.rs | 4 ++-- crates/formats/src/mesh_import/mod.rs | 4 ++-- crates/formats/src/mesh_import/obj.rs | 8 ++++---- crates/formats/src/mesh_import/usd/usdc.rs | 4 ++-- crates/formats/src/project_file/mod.rs | 6 +++--- crates/geom/src/mesh.rs | 10 +++++----- crates/render/src/subdivide.rs | 4 ++-- 19 files changed, 46 insertions(+), 46 deletions(-) diff --git a/crates/bake/src/maps.rs b/crates/bake/src/maps.rs index 5aa60ba1..72d6e45c 100644 --- a/crates/bake/src/maps.rs +++ b/crates/bake/src/maps.rs @@ -389,7 +389,7 @@ fn vertex_curvature(mesh: &Mesh, diag: f32, strength: f32) -> Vec { let (weld, pos, nrm) = welded(mesh, diag); let (mut ksum, mut kcnt) = (vec![0.0f32; pos.len()], vec![0u32; pos.len()]); let (mut edge_sum, mut edge_cnt) = (0.0f64, 0u64); - for t in mesh.indices.chunks_exact(3) { + for t in mesh.indices.as_chunks::<3>().0 { for (a, b) in [(0, 1), (1, 2), (2, 0), (1, 0), (2, 1), (0, 2)] { let (Some(&wa), Some(&wb)) = (t.get(a).and_then(|v| weld.get(*v as usize)), t.get(b).and_then(|v| weld.get(*v as usize))) else { continue }; let (Some(pa), Some(pb), Some(na)) = (pos.get(wa as usize), pos.get(wb as usize), nrm.get(wa as usize)) else { continue }; diff --git a/crates/bake/src/tests.rs b/crates/bake/src/tests.rs index cb81e4a9..17baa8b7 100644 --- a/crates/bake/src/tests.rs +++ b/crates/bake/src/tests.rs @@ -59,7 +59,7 @@ fn open_quad_is_unoccluded() { #[test] fn inside_of_a_closed_box_is_occluded() { let mut m = primitives::cube(2.0); - for t in m.indices.chunks_exact_mut(3) { + for t in m.indices.as_chunks_mut::<3>().0.iter_mut() { t.swap(1, 2); } for n in &mut m.normals { diff --git a/crates/compose/src/display.rs b/crates/compose/src/display.rs index 56a4d4e1..6ab98ed4 100644 --- a/crates/compose/src/display.rs +++ b/crates/compose/src/display.rs @@ -131,7 +131,7 @@ pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u3 } DisplayKind::Lobes => { let lanes = [Channel::CoatWeight, Channel::CoatRoughness, Channel::AnisotropyLevel, Channel::AnisotropyAngle].map(scalar8); - for (i, px) in out.chunks_exact_mut(4).enumerate() { + for (i, px) in out.as_chunks_mut::<4>().0.iter_mut().enumerate() { for (d, lane) in px.iter_mut().zip(&lanes) { *d = lane(i); } @@ -143,7 +143,7 @@ pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u3 let snorm = |v: u16| (128.0 + 127.0 * (v as f32 / 65535.0 * 2.0 - 1.0)).round().clamp(0.0, 255.0) as u8; // A TILE never straddles two atlas blocks. let scale = (-32.0 * comp.block_scales.at(tx * TILE, ty * TILE).log2()).round().clamp(0.0, 255.0) as u8; - for (i, px) in out.chunks_exact_mut(4).enumerate() { + for (i, px) in out.as_chunks_mut::<4>().0.iter_mut().enumerate() { for (k, d) in px.iter_mut().take(2).enumerate() { *d = n.and_then(|t| t.get(i * 3 + k)).map_or(128, |v| snorm(*v)); } diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index de26d5bd..22f44442 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -2002,7 +2002,7 @@ pub fn flatten_layer(inp: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Option< n.chans.iter().filter_map(|c| Channel::ALL.get(c.ch).map(|ch| (*ch, vec![0u16; TILE_AREA * (c.comps + 1)], false))).collect(); for (ch, buf, _) in &mut bufs { if ch.kind() == ChannelKind::Signed { - for px in buf.chunks_exact_mut(2) { + for px in buf.as_chunks_mut::<2>().0.iter_mut() { px[0] = to_u16_signed(0.0); } } diff --git a/crates/engine/src/quick_mask.rs b/crates/engine/src/quick_mask.rs index 304ab3c9..92d00962 100644 --- a/crates/engine/src/quick_mask.rs +++ b/crates/engine/src/quick_mask.rs @@ -115,7 +115,7 @@ impl Session { let mut out = vec![255u8; size as usize * size as usize * 4]; out.par_chunks_mut(size as usize * 4).enumerate().for_each(|(y, row)| { let ty = (y as u64 * u64::from(h) / u64::from(size)) as u32; - for (x, px) in row.chunks_exact_mut(4).enumerate() { + for (x, px) in row.as_chunks_mut::<4>().0.iter_mut().enumerate() { let tx = (x as u64 * u64::from(w) / u64::from(size)) as u32; let mut m = from_u16(mask.get(tx, ty)[0]); if let Some((alpha, opacity, erase)) = live { diff --git a/crates/engine/tests/auto_rebake.rs b/crates/engine/tests/auto_rebake.rs index e6a37275..c95c026d 100644 --- a/crates/engine/tests/auto_rebake.rs +++ b/crates/engine/tests/auto_rebake.rs @@ -14,7 +14,7 @@ fn baked_session(tag: &str) -> (Session, std::path::PathBuf) { for p in &mesh.positions { obj += &format!("v {} {} {}\n", p.x, p.y + 0.002, p.z); } - for t in mesh.indices.chunks_exact(3) { + for t in mesh.indices.as_chunks::<3>().0 { obj += &format!("f {} {} {}\n", t[0] + 1, t[1] + 1, t[2] + 1); } let dir = std::env::temp_dir().join(format!("tc_auto_rebake_{tag}_{}", std::process::id())); diff --git a/crates/engine/tests/bake.rs b/crates/engine/tests/bake.rs index 8f592937..db08f0f0 100644 --- a/crates/engine/tests/bake.rs +++ b/crates/engine/tests/bake.rs @@ -17,7 +17,7 @@ fn obj(mesh: &Mesh, dy: f32, max_x: f32, rgb: [f32; 3]) -> String { for p in &mesh.positions { s += &format!("v {} {} {} {} {} {}\n", p.x.min(max_x), p.y + dy, p.z, rgb[0], rgb[1], rgb[2]); } - for t in mesh.indices.chunks_exact(3) { + for t in mesh.indices.as_chunks::<3>().0 { s += &format!("f {} {} {}\n", t[0] + 1, t[1] + 1, t[2] + 1); } s diff --git a/crates/formats/src/fonts.rs b/crates/formats/src/fonts.rs index b047ba49..ca7db930 100644 --- a/crates/formats/src/fonts.rs +++ b/crates/formats/src/fonts.rs @@ -91,7 +91,7 @@ pub fn faces_of(path: &Path) -> std::io::Result> { for (index, offset) in offsets.into_iter().enumerate() { let dir = at(offset, 12)?; let tables = at(offset + 12, 16 * usize::from(u16_at(&dir, 4).unwrap_or(0)))?; - let Some(rec) = tables.chunks_exact(16).find(|r| r.get(..4) == Some(b"name")) else { continue }; + let Some(rec) = tables.as_chunks::<16>().0.iter().find(|r| r.get(..4) == Some(b"name")) else { continue }; let (Some(off), Some(len)) = (u32_at(rec, 8), u32_at(rec, 12)) else { continue }; let names = at(u64::from(off), len.min(MAX_NAME_TABLE) as usize)?; let name = |ids: [u16; 2]| ids.iter().find_map(|id| name_string(&names, *id)); @@ -125,7 +125,7 @@ fn name_string(t: &[u8], id: u16) -> Option { } let (rank, s) = match platform { 3 | 0 => { - let s = String::from_utf16_lossy(&bytes.chunks_exact(2).map(|c| u16::from_be_bytes([c[0], c[1]])).collect::>()); + let s = String::from_utf16_lossy(&bytes.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes([c[0], c[1]])).collect::>()); (if language == 0x409 { 0 } else { 1 }, s) } 1 => (if language == 0 { 2 } else { 3 }, bytes.iter().map(|b| char::from(*b)).collect()), diff --git a/crates/formats/src/mesh_export.rs b/crates/formats/src/mesh_export.rs index 49b1ef81..454ceffd 100644 --- a/crates/formats/src/mesh_export.rs +++ b/crates/formats/src/mesh_export.rs @@ -93,7 +93,7 @@ fn obj_text(mesh: &Mesh, name: &str, mtllib: Option<&str>) -> String { let material = materials.get(sm.material).map_or("default", String::as_str); let _ = writeln!(s, "g {}\nusemtl {material}", token(&sm.name)); let (a, b) = (sm.start as usize, sm.start as usize + sm.count as usize); - for tri in mesh.indices.get(a..b).unwrap_or_default().chunks_exact(3) { + for tri in mesh.indices.get(a..b).unwrap_or_default().as_chunks::<3>().0 { s.push('f'); for i in tri { let i = i + 1; diff --git a/crates/formats/src/mesh_export/usd.rs b/crates/formats/src/mesh_export/usd.rs index 77d0d5ad..25c8f04c 100644 --- a/crates/formats/src/mesh_export/usd.rs +++ b/crates/formats/src/mesh_export/usd.rs @@ -184,7 +184,7 @@ fn scene(mesh: &Mesh, name: &str, files: &[Vec<(usize, String)>]) -> Result> = vec![Vec::new(); mesh.materials.len()]; for sm in parts(mesh, name) { let range = mesh.indices.get(sm.start as usize..(sm.start as usize).saturating_add(sm.count as usize)).unwrap_or_default(); - for t in range.chunks_exact(3) { + for t in range.as_chunks::<3>().0 { if let Some(f) = faces_of.get_mut(sm.material) { f.push(i32::try_from(tris.len() / 3).map_err(|_| FormatError::TooLarge("triangle count".into()))?); } diff --git a/crates/formats/src/mesh_import/abc/mod.rs b/crates/formats/src/mesh_import/abc/mod.rs index 6730b334..00c5ce02 100644 --- a/crates/formats/src/mesh_import/abc/mod.rs +++ b/crates/formats/src/mesh_import/abc/mod.rs @@ -227,14 +227,14 @@ impl<'a> Ogawa<'a> { Ok(match p.pod { 0 | 1 => raw.iter().map(|v| *v as f64).collect(), 2 => raw.iter().map(|v| *v as i8 as f64).collect(), - 3 => raw.chunks_exact(2).map(|c| u16::from_le_bytes(le(c)) as f64).collect(), - 4 => raw.chunks_exact(2).map(|c| i16::from_le_bytes(le(c)) as f64).collect(), - 5 => raw.chunks_exact(4).map(|c| u32::from_le_bytes(le(c)) as f64).collect(), - 6 => raw.chunks_exact(4).map(|c| i32::from_le_bytes(le(c)) as f64).collect(), - 7 => raw.chunks_exact(8).map(|c| u64::from_le_bytes(le(c)) as f64).collect(), - 8 => raw.chunks_exact(8).map(|c| i64::from_le_bytes(le(c)) as f64).collect(), - 10 => raw.chunks_exact(4).map(|c| f32::from_le_bytes(le(c)) as f64).collect(), - _ => raw.chunks_exact(8).map(|c| f64::from_le_bytes(le(c))).collect(), + 3 => raw.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(le(c)) as f64).collect(), + 4 => raw.as_chunks::<2>().0.iter().map(|c| i16::from_le_bytes(le(c)) as f64).collect(), + 5 => raw.as_chunks::<4>().0.iter().map(|c| u32::from_le_bytes(le(c)) as f64).collect(), + 6 => raw.as_chunks::<4>().0.iter().map(|c| i32::from_le_bytes(le(c)) as f64).collect(), + 7 => raw.as_chunks::<8>().0.iter().map(|c| u64::from_le_bytes(le(c)) as f64).collect(), + 8 => raw.as_chunks::<8>().0.iter().map(|c| i64::from_le_bytes(le(c)) as f64).collect(), + 10 => raw.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(le(c)) as f64).collect(), + _ => raw.as_chunks::<8>().0.iter().map(|c| f64::from_le_bytes(le(c))).collect(), }) } @@ -502,7 +502,7 @@ impl Walk<'_, '_> { let indices = get(&mut self.o, ".faceIndices")?; let counts = get(&mut self.o, ".faceCounts")?; check_vertices(p.len() / 3)?; - let points: Vec = p.chunks_exact(3).map(|c| world.transform_point3(Vec3::new(c[0] as f32, c[1] as f32, c[2] as f32))).collect(); + let points: Vec = p.as_chunks::<3>().0.iter().map(|c| world.transform_point3(Vec3::new(c[0] as f32, c[1] as f32, c[2] as f32))).collect(); let n = [points.len(), counts.len(), indices.len()]; let normals = self.param(&props, "N", n)?; let uvs = self.param(&props, "uv", n)?; diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index d7dd46fc..d1d2e121 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -283,10 +283,10 @@ impl<'a> Binary<'a> { <[u8; N]>::try_from(c).unwrap_or([0; N]) } Ok(match ty { - b'd' => raw.chunks_exact(8).map(|c| f64::from_le_bytes(le(c))).collect(), - b'l' => raw.chunks_exact(8).map(|c| i64::from_le_bytes(le(c)) as f64).collect(), - b'f' => raw.chunks_exact(4).map(|c| f32::from_le_bytes(le(c)) as f64).collect(), - b'i' => raw.chunks_exact(4).map(|c| i32::from_le_bytes(le(c)) as f64).collect(), + b'd' => raw.as_chunks::<8>().0.iter().map(|c| f64::from_le_bytes(le(c))).collect(), + b'l' => raw.as_chunks::<8>().0.iter().map(|c| i64::from_le_bytes(le(c)) as f64).collect(), + b'f' => raw.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(le(c)) as f64).collect(), + b'i' => raw.as_chunks::<4>().0.iter().map(|c| i32::from_le_bytes(le(c)) as f64).collect(), _ => raw.iter().map(|b| *b as f64).collect(), }) } @@ -786,7 +786,7 @@ impl Layer<'_> { fn add_geometry(sink: &mut PolygonSink, g: &Node, m: Mat4, slots: &[String]) -> Result<()> { let verts = g.child("Vertices").map(Node::arr).unwrap_or_default(); check_vertices(verts.len() / 3)?; - let points: Vec = verts.chunks_exact(3).map(|c| m.transform_point3(Vec3::new(c[0] as f32, c[1] as f32, c[2] as f32))).collect(); + let points: Vec = verts.as_chunks::<3>().0.iter().map(|c| m.transform_point3(Vec3::new(c[0] as f32, c[1] as f32, c[2] as f32))).collect(); let pvi = g.child("PolygonVertexIndex").map(Node::arr).unwrap_or_default(); let normals = Layer::read(g, "LayerElementNormal", "Normals", "NormalsIndex"); let uvs = Layer::read(g, "LayerElementUV", "UV", "UVIndex"); diff --git a/crates/formats/src/mesh_import/gltf.rs b/crates/formats/src/mesh_import/gltf.rs index bf1f88e0..92f64077 100644 --- a/crates/formats/src/mesh_import/gltf.rs +++ b/crates/formats/src/mesh_import/gltf.rs @@ -169,7 +169,7 @@ fn add_primitive(raw: &mut RawMesh, attrs: &mut Attrs, prim: &gltf::Primitive, m attrs.uvs.extend((0..n).map(uv_of)); attrs.colors.extend((0..n).map(color_of)); let group = raw.group(&name, part); - for t in indices.chunks_exact(3) { + for t in indices.as_chunks::<3>().0 { let (a, b, c) = (t[0] + base, t[1] + base, t[2] + base); group.extend_from_slice(&if flip { [a, c, b] } else { [a, b, c] }); } @@ -177,7 +177,7 @@ fn add_primitive(raw: &mut RawMesh, attrs: &mut Attrs, prim: &gltf::Primitive, m None => { // glTF: flat normals when none are given, so every triangle gets its own corners. let mut tris = Vec::with_capacity(indices.len()); - for t in indices.chunks_exact(3) { + for t in indices.as_chunks::<3>().0 { let order = if flip { [t[0], t[2], t[1]] } else { [t[0], t[1], t[2]] }; let p = order.map(|i| world.get(i as usize).copied().unwrap_or_default()); let face = (p[1] - p[0]).cross(p[2] - p[0]).try_normalize().unwrap_or(Vec3::Y); diff --git a/crates/formats/src/mesh_import/mod.rs b/crates/formats/src/mesh_import/mod.rs index 3daff3c2..7fd9b113 100644 --- a/crates/formats/src/mesh_import/mod.rs +++ b/crates/formats/src/mesh_import/mod.rs @@ -403,7 +403,7 @@ fn geometry(raw: RawMesh) -> Result<(Mesh, Vec, Option>)> { } if !diagonals.is_empty() { let diagonal = |a: u32, b: u32| diagonals.contains(&(a.min(b), a.max(b))); - mesh.diagonals = mesh.indices.chunks_exact(3).map(|t| (0..3).map(|i| u8::from(diagonal(t[i], t[(i + 1) % 3])) << i).sum()).collect(); + mesh.diagonals = mesh.indices.as_chunks::<3>().0.iter().map(|t| (0..3).map(|i| u8::from(diagonal(t[i], t[(i + 1) % 3])) << i).sum()).collect(); } if let Some(bad) = mesh.indices.iter().find(|i| **i as usize >= mesh.positions.len()) { return Err(FormatError::Invalid(format!("vertex index {bad} out of range ({} vertices)", mesh.positions.len()))); @@ -484,7 +484,7 @@ fn orbit_cameras(raw: &[RawCamera], mesh: &Mesh) -> Vec Vec { let weld = weld_ids(&mesh.positions); let mut acc = vec![Vec3::ZERO; mesh.positions.len()]; - for t in mesh.indices.chunks_exact(3) { + for t in mesh.indices.as_chunks::<3>().0 { let p = |i: u32| mesh.positions.get(i as usize).copied().unwrap_or_default(); let face = (p(t[1]) - p(t[0])).cross(p(t[2]) - p(t[0])); for v in t { diff --git a/crates/formats/src/mesh_import/obj.rs b/crates/formats/src/mesh_import/obj.rs index f9002ad0..d6cc9eb8 100644 --- a/crates/formats/src/mesh_import/obj.rs +++ b/crates/formats/src/mesh_import/obj.rs @@ -44,10 +44,10 @@ fn read_inner(bytes: &[u8]) -> Result { let arities: Vec = if m.face_arities.is_empty() { vec![3; m.indices.len() / 3] } else { m.face_arities.iter().map(|a| *a as usize).collect() }; check_triangles(raw.triangle_count(), arities.iter().map(|a| a.saturating_sub(2)).sum())?; let base = raw.positions.len() as u32; - raw.positions.extend(m.positions.chunks_exact(3).map(|p| Vec3::new(p[0], p[1], p[2]))); + raw.positions.extend(m.positions.as_chunks::<3>().0.iter().map(|p| Vec3::new(p[0], p[1], p[2]))); if m.normals.len() == n * 3 { if let Some(v) = &mut normals { - v.extend(m.normals.chunks_exact(3).map(|p| Vec3::new(p[0], p[1], p[2]))); + v.extend(m.normals.as_chunks::<3>().0.iter().map(|p| Vec3::new(p[0], p[1], p[2]))); } } else { normals = None; @@ -55,7 +55,7 @@ fn read_inner(bytes: &[u8]) -> Result { if m.texcoords.len() == n * 2 { if let Some(v) = &mut uvs { // OBJ UVs have their origin bottom-left. - v.extend(m.texcoords.chunks_exact(2).map(|t| Vec2::new(t[0], 1.0 - t[1]))); + v.extend(m.texcoords.as_chunks::<2>().0.iter().map(|t| Vec2::new(t[0], 1.0 - t[1]))); } } else { partial_uvs |= n > 0 && !m.indices.is_empty(); @@ -63,7 +63,7 @@ fn read_inner(bytes: &[u8]) -> Result { } // `v x y z r g b`: objects without colors are white. match m.vertex_color.len() == n * 3 { - true => colors.extend(m.vertex_color.chunks_exact(3).map(|c| Vec4::new(c[0], c[1], c[2], 1.0))), + true => colors.extend(m.vertex_color.as_chunks::<3>().0.iter().map(|c| Vec4::new(c[0], c[1], c[2], 1.0))), false => colors.extend(std::iter::repeat_n(Vec4::ONE, n)), } let name = match m.material_id { diff --git a/crates/formats/src/mesh_import/usd/usdc.rs b/crates/formats/src/mesh_import/usd/usdc.rs index 61874c67..9d3cc55d 100644 --- a/crates/formats/src/mesh_import/usd/usdc.rs +++ b/crates/formats/src/mesh_import/usd/usdc.rs @@ -134,7 +134,7 @@ fn is_quat(t: u8) -> bool { /// Quaternions are stored imaginary first; values keep USD's text order (real first). fn quat_order(t: u8, v: &mut [f64]) { if is_quat(t) { - for q in v.chunks_exact_mut(4) { + for q in v.as_chunks_mut::<4>().0 { q.rotate_right(1); } } @@ -234,7 +234,7 @@ impl<'a> Crate<'a> { if reps.len() != n * 8 { return Err(malformed(KIND, "field values are truncated")); } - self.fields = tokens.iter().zip(reps.chunks_exact(8)).map(|(t, r)| (*t as u32, u64::from_le_bytes(r.try_into().unwrap_or_default()))).collect(); + self.fields = tokens.iter().zip(reps.as_chunks::<8>().0.iter()).map(|(t, r)| (*t as u32, u64::from_le_bytes(*r))).collect(); Ok(()) } diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index a42afdb9..4639c4b6 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -320,7 +320,7 @@ fn read_tiles(r: &mut impl Read, size: (u32, u32), comps: usize, budget: &mut Bu } read_exact(r, &mut buf, what)?; budget.take(buf.len() as u64)?; - let data: Vec = buf.chunks_exact(2).map(|b| u16::from_le_bytes([b[0], b[1]])).collect(); + let data: Vec = buf.as_chunks::<2>().0.iter().map(|b| u16::from_le_bytes([b[0], b[1]])).collect(); img.set_tile(tx, ty, Some(Arc::new(data))); } expect_end(r, what)?; @@ -338,7 +338,7 @@ fn read_baked(r: &mut impl Read, comps: usize, budget: &mut Budget, what: &str) let mut bytes = vec![0u8; len * 4]; read_exact(r, &mut bytes, what)?; expect_end(r, what)?; - Ok((w, h, bytes.chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect())) + Ok((w, h, bytes.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect())) } /// The skew map entry: header, then the values. @@ -363,7 +363,7 @@ fn read_skew(r: &mut impl Read, budget: &mut Budget, what: &str) -> Result = bytes.chunks_exact(4).map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect(); + let values: Vec = bytes.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect(); // A map with a stray number is dropped by the caller's validation; here only the shape is checked. Ok(SkewData { width: w, height: ht, values, edge_distance, edge_contrast, per_triangle }) } diff --git a/crates/geom/src/mesh.rs b/crates/geom/src/mesh.rs index 95d66b4e..419eb32a 100644 --- a/crates/geom/src/mesh.rs +++ b/crates/geom/src/mesh.rs @@ -156,8 +156,8 @@ impl Mesh { /// Area-weighted smooth normals over the index buffer. pub fn compute_normals(&mut self) { let mut n = vec![Vec3::ZERO; self.positions.len()]; - for t in self.indices.chunks_exact(3) { - let (a, b, c) = (t[0] as usize, t[1] as usize, t[2] as usize); + for &[a, b, c] in self.indices.as_chunks::<3>().0 { + let (a, b, c) = (a as usize, b as usize, c as usize); let (Some(pa), Some(pb), Some(pc)) = (self.positions.get(a), self.positions.get(b), self.positions.get(c)) else { continue }; let face = (*pb - *pa).cross(*pc - *pa); for v in [a, b, c] { @@ -194,8 +194,8 @@ impl Mesh { fn simple_tangents(&mut self) { let mut acc = vec![Vec3::ZERO; self.positions.len()]; - for t in self.indices.chunks_exact(3) { - let (a, b, c) = (t[0] as usize, t[1] as usize, t[2] as usize); + for &[a, b, c] in self.indices.as_chunks::<3>().0 { + let (a, b, c) = (a as usize, b as usize, c as usize); let (Some(pa), Some(pb), Some(pc)) = (self.positions.get(a), self.positions.get(b), self.positions.get(c)) else { continue }; let (Some(ua), Some(ub), Some(uc)) = (self.uvs.get(a), self.uvs.get(b), self.uvs.get(c)) else { continue }; let (e1, e2) = (*pb - *pa, *pc - *pa); @@ -244,7 +244,7 @@ impl Mesh { } } let mut shared = vec![false; self.positions.len()]; - for (_, tri) in self.indices.chunks_exact(3).enumerate().filter(|(t, _)| !is_mine.get(*t).copied().unwrap_or(false)) { + for (_, tri) in self.indices.as_chunks::<3>().0.iter().enumerate().filter(|(t, _)| !is_mine.get(*t).copied().unwrap_or(false)) { for v in tri { if let Some(s) = shared.get_mut(*v as usize) { *s = true; diff --git a/crates/render/src/subdivide.rs b/crates/render/src/subdivide.rs index d08a82f2..3da5e465 100644 --- a/crates/render/src/subdivide.rs +++ b/crates/render/src/subdivide.rs @@ -71,7 +71,7 @@ pub(crate) fn subdivide(verts: &[Vertex], indices: &[u32], draws: &[Draw], level for &(start, count, material) in draws { let first = out_i.len() as u32; let tris = indices.get(start as usize..(start as usize).saturating_add(count as usize)).unwrap_or_default(); - for t in tris.chunks_exact(3) { + for t in tris.as_chunks::<3>().0 { let (Some(a), Some(b), Some(c)) = (verts.get(t[0] as usize), verts.get(t[1] as usize), verts.get(t[2] as usize)) else { continue }; let base = out_v.len() as u32; // Grid point (i, j), i + j <= n, row by row: row j holds n + 1 - j points. Points on @@ -118,7 +118,7 @@ pub(crate) fn subdivide(verts: &[Vertex], indices: &[u32], draws: &[Draw], level /// far a height change moves the surface for the slope height-to-normal shows. pub(crate) fn world_per_uv(verts: &[Vertex], indices: &[u32]) -> Option { let (mut world, mut uv) = (0.0f64, 0.0f64); - for t in indices.chunks_exact(3) { + for t in indices.as_chunks::<3>().0 { let (Some(a), Some(b), Some(c)) = (verts.get(t[0] as usize), verts.get(t[1] as usize), verts.get(t[2] as usize)) else { continue }; let d = |p: [f32; 3], q: [f32; 3]| [f64::from(q[0] - p[0]), f64::from(q[1] - p[1]), f64::from(q[2] - p[2])]; let (e1, e2) = (d(a.pos, b.pos), d(a.pos, c.pos)); From bc563f504a65c3040932603a6aaf07f2eba06172 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Wed, 4 Nov 2026 01:40:30 +0100 Subject: [PATCH 07/64] Fix the remaining Rust 1.99 clippy findings Use slice fill in the particles test (manual_slice_fill) and AtomicUsize::try_update, the renamed fetch_update, in the connection limiter. Both are behaviour-neutral. Refs #233 Co-Authored-By: Claude Sonnet 5.5 --- crates/automation/src/security.rs | 2 +- crates/paint/src/particles.rs | 4 +--- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/crates/automation/src/security.rs b/crates/automation/src/security.rs index 0f5e6ab5..7613ecd5 100644 --- a/crates/automation/src/security.rs +++ b/crates/automation/src/security.rs @@ -179,7 +179,7 @@ pub struct Permit(Arc); impl ConnectionLimiter { pub fn try_acquire(&self, max: usize) -> Option { - self.0.fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| (n < max).then_some(n + 1)).ok().map(|_| Permit(self.0.clone())) + self.0.try_update(Ordering::AcqRel, Ordering::Acquire, |n| (n < max).then_some(n + 1)).ok().map(|_| Permit(self.0.clone())) } } diff --git a/crates/paint/src/particles.rs b/crates/paint/src/particles.rs index 64ec2dde..ad81732e 100644 --- a/crates/paint/src/particles.rs +++ b/crates/paint/src/particles.rs @@ -83,9 +83,7 @@ mod tests { for p in &mut m.positions { *p = Vec3::new(p.x, -p.z, 0.0); } - for n in &mut m.normals { - *n = Vec3::Z; - } + m.normals.fill(Vec3::Z); let bvh = Bvh::new(&m); let cam = OrbitCamera::default(); let ctx = PickCtx { mesh: &m, bvh: &bvh, camera: &cam, viewport: Vec2::new(100.0, 100.0) }; From 1f07beeb431e68d979a37da156a1e1d64800eee4 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Thu, 5 Nov 2026 02:44:41 +0100 Subject: [PATCH 08/64] Drop unused Body import after merge Co-Authored-By: Claude Sonnet 5.5 --- crates/formats/src/project_file/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index f9cad66d..7a8a39fa 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -28,7 +28,7 @@ use texturecraft_texel::{TILE_AREA, TileImage}; use zip::write::SimpleFileOptions; use zip::{CompressionMethod, ZipArchive, ZipWriter}; -use self::entries::{Body, Entry}; +use self::entries::Entry; use crate::{FormatError, MAX_IMAGE_SIZE, Result, malformed}; mod entries; From 8eb2c83e04a4185cc1f6276e0e03a3124bd2e6ac Mon Sep 17 00:00:00 2001 From: vangel76 Date: Thu, 5 Nov 2026 02:57:27 +0100 Subject: [PATCH 09/64] Restore #[test] attribute lost in merge Co-Authored-By: Claude Sonnet 5.5 --- crates/formats/src/project_file/tests.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/crates/formats/src/project_file/tests.rs b/crates/formats/src/project_file/tests.rs index 93863a5f..b16d2f02 100644 --- a/crates/formats/src/project_file/tests.rs +++ b/crates/formats/src/project_file/tests.rs @@ -232,6 +232,7 @@ fn load_size_matches_what_load_counts() { } } +#[test] fn bake_model_options_survive_the_project_archive() { use texturecraft_core::{BackfaceMode, CageType, HeightNormalization}; From d4ea67703de986eb907138148751d9561ed84f7b Mon Sep 17 00:00:00 2001 From: MistyMystery Date: Wed, 4 Nov 2026 22:17:59 +0400 Subject: [PATCH 10/64] Add an asynchronous thumbnail service for layer contents, masks and effect stages The compositor renders a one-layer cut of the stack at 64 px (content in a channel, mask, or the stack up to an effect); the engine keeps an immutable snapshot, a worker thread, an LRU cache and stale-result rejection. --- crates/compose/src/lib.rs | 2 + crates/compose/src/thumb.rs | 155 +++++++++++++ crates/engine/src/lib.rs | 1 + crates/engine/src/thumbs.rs | 396 ++++++++++++++++++++++++++++++++++ crates/engine/tests/thumbs.rs | 294 +++++++++++++++++++++++++ 5 files changed, 848 insertions(+) create mode 100644 crates/compose/src/thumb.rs create mode 100644 crates/engine/src/thumbs.rs create mode 100644 crates/engine/tests/thumbs.rs diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 5e34945c..a72c0922 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -12,6 +12,7 @@ pub mod display; pub mod eval; pub mod pattern; pub mod store; +pub mod thumb; pub use below::{BelowCache, StackKey}; pub use display::{DisplayKind, tile_bytes}; @@ -20,3 +21,4 @@ pub use eval::{ mask_image, pad_tiles, }; pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore}; +pub use thumb::{THUMB_TEXELS, ThumbImage, ThumbTarget}; diff --git a/crates/compose/src/thumb.rs b/crates/compose/src/thumb.rs new file mode 100644 index 00000000..a5a817e0 --- /dev/null +++ b/crates/compose/src/thumb.rs @@ -0,0 +1,155 @@ +//! Small previews of one layer's content, one mask, or one effect stage, computed without +//! touching the main composite. +//! +//! Every thumbnail is the ordinary compositor run on a *cut* copy of the project: the texture +//! set's stack is replaced by the one layer, the layer is forced visible at Normal / 100 %, and +//! the layer's effect list is truncated after the effect being previewed. The evaluator is the +//! same code the viewport uses (just on a small G-buffer), so a thumbnail always agrees with +//! what the stack really computes. Nothing here mutates the caller's project. + +use texturecraft_core::{BlendMode, Channel, ChannelBlend, ChannelKind, LayerId, Project}; +use texturecraft_texel::linear_to_srgb; + +use crate::eval::{Composite, Inputs, all_tiles, composite_tiles, mask_image}; + +/// Edge length (texels) the thumbnails are computed at. +pub const THUMB_TEXELS: u32 = 64; + +/// What a thumbnail shows. +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum ThumbTarget { + /// The content of a layer (content effects included, mask ignored) in `channel`. + Content { layer: LayerId, channel: Channel }, + /// The mask of a layer (an instance without its own mask shows its source's). + Mask { layer: LayerId }, + /// The result up to and including `effect`, in the layer's content (`channel`) or in its + /// mask (the channel is ignored). An effect that is hidden shows the bypassed result. + Stage { effect: LayerId, channel: Channel }, +} + +/// An 8-bit RGBA thumbnail. Alpha is 0 where the mesh does not cover the texture (the view +/// paints its own background there) and 255 elsewhere. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ThumbImage { + pub width: u32, + pub height: u32, + pub rgba: Vec, +} + +/// 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. +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)) } + } + } +} + +/// `project` cut down to the single layer `id` of texture set `ts`: only that layer is drawn, +/// visible, Normal at full opacity in `channel` (when given). +fn solo(project: &Project, ts: usize, id: LayerId, channel: Option) -> Option { + let mut cut = project.clone(); + cut.texture_sets.get_mut(ts)?.stack = vec![id]; + let l = cut.layers.get_mut(&id)?; + l.visible = true; + if let Some(c) = channel { + *l.channels.get_mut(&c)? = ChannelBlend { mode: BlendMode::Normal, opacity: 1.0 }; + } + Some(cut) +} + +/// Keep the effects of `list` up to and including `last`. +fn truncate_after(list: &mut Vec, last: LayerId) -> bool { + match list.iter().position(|e| e.id == last) { + Some(k) => { + list.truncate(k + 1); + true + } + None => false, + } +} + +fn content(inp: &Inputs, layer: LayerId, channel: Channel, upto: Option) -> Option { + let set = inp.project.texture_set(inp.ts).ok()?; + if !set.channel_list().contains(&channel) { + return None; + } + // The layer whose content is drawn: an instance draws its source's effects. + let mut cut = solo(inp.project, inp.ts, layer, Some(channel))?; + let owner = cut.content_layer(layer)?.id; + for id in [layer, owner] { + let l = cut.layers.get_mut(&id)?; + l.mask = None; + l.visible = true; + if let Some(b) = l.channels.get_mut(&channel) { + *b = ChannelBlend { mode: BlendMode::Normal, opacity: 1.0 }; + } + } + if let Some(effect) = upto + && !truncate_after(&mut cut.layers.get_mut(&owner)?.content_effects, effect) + { + return None; + } + let cut_inp = Inputs { project: &cut, preview: None, ..*inp }; + let (w, h) = (inp.gbuf.width, inp.gbuf.height); + let mut comp = Composite::with_size(&set.channel_list(), w, h); + composite_tiles(&cut_inp, &mut comp, &all_tiles(w, h)); + Some(encode_channel(&comp, channel, inp)) +} + +fn mask(inp: &Inputs, layer: LayerId, upto: Option) -> Option { + let mut cut = solo(inp.project, inp.ts, layer, None)?; + let owner = cut.mask_owner(layer); + let m = cut.layers.get_mut(&owner)?.mask.as_mut()?; + m.enabled = true; + if let Some(effect) = upto + && !truncate_after(&mut m.effects, effect) + { + return None; + } + let cut_inp = Inputs { project: &cut, preview: None, ..*inp }; + let (w, h) = (inp.gbuf.width, inp.gbuf.height); + let gray = mask_image(&cut_inp, layer, w)?; + let mut rgba = Vec::with_capacity((w * h) as usize * 4); + for y in 0..h { + for x in 0..w { + let i = (y * w + x) as usize; + let g = gray.get(i).copied().unwrap_or(0); + rgba.extend_from_slice(&[g, g, g, if inp.gbuf.covered(i) { 255 } else { 0 }]); + } + } + Some(ThumbImage { width: w, height: h, rgba }) +} + +/// Encode the composited `channel` for display: colors linear → sRGB, signed values 0 → mid +/// gray, normal maps and scalars as stored (data channels raw). +fn encode_channel(comp: &Composite, channel: Channel, inp: &Inputs) -> ThumbImage { + let (w, h) = (comp.resolution, comp.height); + let mut rgba = Vec::with_capacity((w * h) as usize * 4); + for y in 0..h { + for x in 0..w { + let v = comp.value(channel, x, y); + let px = match channel.kind() { + ChannelKind::Color => v.map(|c| to_byte(linear_to_srgb(c.clamp(0.0, 1.0)))), + ChannelKind::Signed => v.map(|c| to_byte(c * 0.5 + 0.5)), + ChannelKind::Scalar | ChannelKind::NormalMap => v.map(to_byte), + }; + let covered = inp.gbuf.covered((y * w + x) as usize); + rgba.extend_from_slice(&[px[0], px[1], px[2], if covered { 255 } else { 0 }]); + } + } + ThumbImage { width: w, height: h, rgba } +} + +fn to_byte(v: f32) -> u8 { + if v.is_finite() { (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8 } else { 0 } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ed07d645..20aa19f9 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -44,6 +44,7 @@ pub mod set_cmds; pub mod smart_masks; pub mod template_cmds; pub mod text_cmds; +pub mod thumbs; pub mod tool_cmds; pub mod uv_tile_cmds; pub mod view_cmds; diff --git a/crates/engine/src/thumbs.rs b/crates/engine/src/thumbs.rs new file mode 100644 index 00000000..6ee7dda4 --- /dev/null +++ b/crates/engine/src/thumbs.rs @@ -0,0 +1,396 @@ +//! Asynchronous layer-panel thumbnails. +//! +//! The panel asks for small previews of layer contents, masks and effect stages +//! ([`ThumbTarget`]). The work never runs on the UI thread and never touches the main composite: +//! +//! * A **snapshot** ([`ThumbSnapshot`]) is an immutable copy of what the compositor reads (the +//! 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. +//! * 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. +//! * Only targets requested during the current frame are rendered: a row that scrolled away +//! before its turn is dropped from the queue. + +use std::collections::{HashMap, HashSet, VecDeque}; +use std::sync::Arc; + +use texturecraft_compose::{BakedMaps, ImageStore, Inputs, PixelStore, THUMB_TEXELS, ThumbImage, ThumbTarget, thumb}; +use texturecraft_core::Project; +use texturecraft_geom::glam::Vec3; +use texturecraft_geom::{Mesh, UvGBuffer}; + +use crate::Session; + +/// Thumbnails kept. +pub const CACHE_ENTRIES: usize = 96; +/// Seconds between checks for a changed document while it keeps changing. +pub const DEBOUNCE: f64 = 0.12; +/// Jobs handed to the worker at once (the rest wait here, where they can still be dropped). +const IN_FLIGHT: usize = 2; + +/// An immutable copy of everything the thumbnails of one texture set read. +pub struct ThumbSnapshot { + ts: usize, + mesh_id: u64, + project: Project, + pixels: PixelStore, + baked: BakedMaps, + images: ImageStore, + mesh: Arc, + gbuf: Arc, + bounds: (Vec3, Vec3), +} + +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 { + let material = s.doc.project.texture_set(ts).ok()?.material; + let gbuf = gbufs.get(&s.mesh, s.mesh_id, material); + Some(ThumbSnapshot { + ts, + mesh_id: s.mesh_id, + project: s.doc.project.clone(), + pixels: s.doc.pixels.clone(), + baked: s.doc.baked.get(&ts).cloned().unwrap_or_default(), + images: s.images.clone(), + mesh: s.mesh.clone(), + gbuf, + bounds: s.mesh.bounds(), + }) + } + + /// Whether `s` would give the same thumbnails as this snapshot. + fn matches(&self, s: &Session, ts: usize) -> bool { + let same_pixels = self.pixels.layers.len() == s.doc.pixels.layers.len() + && self.pixels.masks.len() == s.doc.pixels.masks.len() + && self.pixels.layers.iter().all(|(k, v)| s.doc.pixels.layers.get(k) == Some(v)) + && self.pixels.masks.iter().all(|(k, v)| s.doc.pixels.masks.get(k) == Some(v)); + let none = BakedMaps::default(); + let baked = s.doc.baked.get(&ts).unwrap_or(&none); + self.ts == ts + && self.mesh_id == s.mesh_id + && self.project == s.doc.project + && same_pixels + && self.baked == *baked + && self.images.len() == s.images.len() + && self.images.iter().all(|(k, v)| s.images.get(k).is_some_and(|o| Arc::ptr_eq(o, v))) + } + + /// Render `target`: the work of one job. + pub fn render(&self, target: ThumbTarget) -> Option { + let inp = Inputs { + project: &self.project, + ts: self.ts, + mesh: &self.mesh, + gbuf: &self.gbuf, + pixels: &self.pixels, + baked: &self.baked, + preview: None, + images: &self.images, + bounds: self.bounds, + }; + thumb::render(&inp, target) + } + + /// Whether the layer or effect `target` shows still exists in the snapshot's project. + fn has(&self, target: ThumbTarget) -> bool { + has_target(&self.project, target) + } +} + +fn has_target(p: &Project, target: ThumbTarget) -> bool { + match target { + ThumbTarget::Content { layer, .. } | ThumbTarget::Mask { layer } => p.layers.contains_key(&layer), + ThumbTarget::Stage { effect, .. } => p.effect(effect).is_some(), + } +} + +/// The 64 px G-buffers built so far, per mesh and material (rasterizing is the one part of a +/// snapshot that is not just copying handles). +#[derive(Default)] +pub struct GbufCache { + map: HashMap<(u64, usize), Arc>, +} + +impl GbufCache { + fn get(&mut self, mesh: &Mesh, mesh_id: u64, material: usize) -> Arc { + if self.map.len() > 16 { + self.map.clear(); + } + self.map.entry((mesh_id, material)).or_insert_with(|| Arc::new(UvGBuffer::new(mesh, material, THUMB_TEXELS, THUMB_TEXELS))).clone() + } +} + +struct Entry { + /// None: the target has nothing to show (a layer without that channel). + image: Option>, + /// Snapshot generation it was rendered from. + generation: u64, + /// Changes whenever `image` does (views key their GPU textures on it). + version: u64, + used: u64, +} + +/// What the panel draws for one target. +#[derive(Clone)] +pub struct ThumbView { + pub image: Option>, + /// Identifies `image`; changes when a new picture arrives. + pub version: u64, + /// A newer picture is on its way. + pub pending: bool, +} + +struct Job { + snapshot: Arc, + generation: u64, + target: ThumbTarget, +} + +struct Done { + generation: u64, + target: ThumbTarget, + image: Option, +} + +#[cfg(not(target_arch = "wasm32"))] +struct Worker { + tx: std::sync::mpsc::Sender, + rx: std::sync::mpsc::Receiver, +} + +#[cfg(not(target_arch = "wasm32"))] +fn spawn_worker() -> Option { + let (tx, jobs) = std::sync::mpsc::channel::(); + let (done_tx, rx) = std::sync::mpsc::channel::(); + std::thread::Builder::new() + .name("layer-thumbs".into()) + .spawn(move || { + while let Ok(job) = jobs.recv() { + let image = job.snapshot.render(job.target); + if done_tx.send(Done { generation: job.generation, target: job.target, image }).is_err() { + break; + } + } + }) + .ok()?; + Some(Worker { tx, rx }) +} + +/// The thumbnail cache and its worker. One lives in the UI; see the module documentation. +pub struct ThumbService { + snapshot: Option>, + /// Bumps whenever the snapshot's content changes; entries and jobs carry it. + generation: u64, + /// The session revision the snapshot was last compared with. + seen: Option, + last_check: f64, + cache: HashMap, + tick: u64, + versions: u64, + queue: VecDeque, + in_flight: HashSet, + wanted: HashSet, + gbufs: GbufCache, + #[cfg(not(target_arch = "wasm32"))] + worker: Option, + #[cfg(not(target_arch = "wasm32"))] + spawned: bool, + /// Jobs run inline (wasm32, or no worker thread could start). + inline: VecDeque, + /// Pictures computed (tests, benchmarks). + pub rendered: u64, +} + +impl Default for ThumbService { + fn default() -> Self { + ThumbService { + snapshot: None, + generation: 0, + seen: None, + last_check: f64::NEG_INFINITY, + cache: HashMap::new(), + tick: 0, + versions: 0, + queue: VecDeque::new(), + in_flight: HashSet::new(), + wanted: HashSet::new(), + gbufs: GbufCache::default(), + #[cfg(not(target_arch = "wasm32"))] + worker: None, + #[cfg(not(target_arch = "wasm32"))] + spawned: false, + inline: VecDeque::new(), + rendered: 0, + } + } +} + +impl ThumbService { + pub fn new() -> ThumbService { + ThumbService::default() + } + + /// Start of a frame: forget what the last frame asked for and notice document changes. + pub fn begin_frame(&mut self, s: &Session, now: f64) { + self.wanted.clear(); + let ts = s.ts(); + if self.seen == Some(s.revision) && self.snapshot.as_ref().is_some_and(|sn| sn.ts == ts && sn.mesh_id == s.mesh_id) { + return; + } + // While the document keeps changing, compare at the debounce pace (the first look is immediate). + if self.snapshot.is_some() && now - self.last_check < DEBOUNCE { + return; + } + self.last_check = now; + if self.snapshot.as_ref().is_some_and(|sn| sn.matches(s, ts)) { + self.seen = Some(s.revision); + return; + } + self.snapshot = ThumbSnapshot::new(s, ts, &mut self.gbufs).map(Arc::new); + self.seen = Some(s.revision); + self.generation += 1; + // Jobs of the old snapshot are not worth running (those in flight are dropped on arrival). + self.queue.clear(); + self.inline.clear(); + self.in_flight.clear(); + if let Some(sn) = &self.snapshot { + self.cache.retain(|t, _| sn.has(*t)); + } else { + self.cache.clear(); + } + } + + /// Whether the displayed pictures wait for a document comparison that is still debounced. + fn checked(&self, s: &Session) -> bool { + self.seen == Some(s.revision) + } + + /// The picture for `target` (call for the rows on screen only). Queues work when the + /// picture is missing or out of date. + pub fn get(&mut self, s: &Session, target: ThumbTarget) -> ThumbView { + self.wanted.insert(target); + self.tick += 1; + let fresh = self.cache.get(&target).is_some_and(|e| e.generation == self.generation); + let checked = self.checked(s); + if !fresh && checked && self.snapshot.is_some() && !self.in_flight.contains(&target) && !self.queue.contains(&target) { + self.queue.push_back(target); + } + let tick = self.tick; + match self.cache.get_mut(&target) { + Some(e) => { + e.used = tick; + ThumbView { image: e.image.clone(), version: e.version, pending: !(fresh && checked) } + } + None => ThumbView { image: None, version: 0, pending: true }, + } + } + + /// End of a frame: take finished pictures, drop queued rows nobody asked for, hand the worker + /// its next jobs. Returns whether more work is outstanding (ask for another frame). + pub fn poll(&mut self, s: &Session) -> bool { + self.collect(); + let wanted = &self.wanted; + self.queue.retain(|t| wanted.contains(t)); + self.dispatch(); + self.trim(); + !self.queue.is_empty() || !self.in_flight.is_empty() || !self.inline.is_empty() || !self.checked(s) + } + + fn dispatch(&mut self) { + let Some(snapshot) = self.snapshot.clone() else { return }; + while self.in_flight.len() + self.inline.len() < IN_FLIGHT { + let Some(target) = self.queue.pop_front() else { break }; + let job = Job { snapshot: snapshot.clone(), generation: self.generation, target }; + self.in_flight.insert(target); + if !self.send(job) { + break; + } + } + } + + #[cfg(not(target_arch = "wasm32"))] + fn send(&mut self, job: Job) -> bool { + if !self.spawned { + self.spawned = true; + self.worker = spawn_worker(); + } + match &self.worker { + Some(w) => match w.tx.send(job) { + Ok(()) => true, + Err(e) => { + // The worker is gone: run this and the rest here. + self.worker = None; + self.inline.push_back(e.0); + true + } + }, + None => { + self.inline.push_back(job); + true + } + } + } + + #[cfg(target_arch = "wasm32")] + fn send(&mut self, job: Job) -> bool { + self.inline.push_back(job); + true + } + + fn collect(&mut self) { + let mut done: Vec = Vec::new(); + #[cfg(not(target_arch = "wasm32"))] + if let Some(w) = &self.worker { + while let Ok(d) = w.rx.try_recv() { + done.push(d); + } + } + // Without a thread one job runs per frame, so the interface keeps its pace. + if let Some(job) = self.inline.pop_front() { + let image = job.snapshot.render(job.target); + done.push(Done { generation: job.generation, target: job.target, image }); + } + for d in done { + self.rendered += 1; + // A picture of an older snapshot never replaces a newer one. + if d.generation != self.generation { + continue; + } + self.in_flight.remove(&d.target); + if !self.snapshot.as_ref().is_some_and(|sn| sn.has(d.target)) { + continue; + } + self.versions += 1; + let entry = Entry { image: d.image.map(Arc::new), generation: d.generation, version: self.versions, used: self.tick }; + self.cache.insert(d.target, entry); + } + } + + fn trim(&mut self) { + while self.cache.len() > CACHE_ENTRIES { + let Some(oldest) = self.cache.iter().filter(|(t, _)| !self.wanted.contains(t)).min_by_key(|(_, e)| e.used).map(|(t, _)| *t) else { break }; + self.cache.remove(&oldest); + } + } + + /// Entries held (tests). + pub fn cached(&self) -> usize { + self.cache.len() + } + + /// Whether `target` has a picture of the current snapshot (tests). + pub fn is_fresh(&self, target: ThumbTarget) -> bool { + self.cache.get(&target).is_some_and(|e| e.generation == self.generation) + } + + /// Whether any work is queued or running (tests). + pub fn busy(&self) -> bool { + !self.queue.is_empty() || !self.in_flight.is_empty() || !self.inline.is_empty() + } +} diff --git a/crates/engine/tests/thumbs.rs b/crates/engine/tests/thumbs.rs new file mode 100644 index 00000000..05fb52ba --- /dev/null +++ b/crates/engine/tests/thumbs.rs @@ -0,0 +1,294 @@ +//! Layer-panel thumbnails: they equal a plain CPU evaluation of the same sub-stack at 64 px, +//! follow edits, drop stale and vanished work, and only render what was asked for. + +use std::time::{Duration, Instant}; + +use serde_json::{Value, json}; +use texturecraft_engine::compose::{Composite, Inputs, ThumbImage, ThumbTarget, all_tiles, composite_tiles, mask_image}; +use texturecraft_engine::core::{Channel, ChannelKind, LayerId}; +use texturecraft_engine::geom::UvGBuffer; +use texturecraft_engine::geom::primitives; +use texturecraft_engine::texel::linear_to_srgb; +use texturecraft_engine::thumbs::{CACHE_ENTRIES, ThumbService}; +use texturecraft_engine::{Session, execute}; + +const N: u32 = 64; + +fn session() -> Session { + Session::new_project("t", primitives::sphere(1.0, 32, 16), "builtin:sphere", None, 256).unwrap() +} + +fn id(v: Value, key: &str) -> LayerId { + LayerId(v[key].as_u64().unwrap()) +} + +/// A fill layer with two content effects (invert, then posterize) and a masked generator. +struct Stack { + layer: LayerId, + invert: LayerId, + posterize: LayerId, + gen_: LayerId, +} + +fn stack(s: &mut Session) -> Stack { + let layer = id(execute(s, "layer.add.fill", &json!({"color": "#336699", "roughness": 0.2})).unwrap(), "layer"); + let invert = id(execute(s, "effect.add.filter", &json!({"target": "content", "filter": "invert"})).unwrap(), "effect"); + let posterize = id(execute(s, "effect.add.filter", &json!({"target": "content", "filter": "posterize"})).unwrap(), "effect"); + execute(s, "mask.add.black", &Value::Null).unwrap(); + let gen_ = id(execute(s, "effect.add.generator", &json!({"generator": "position", "level": 0.5})).unwrap(), "effect"); + Stack { layer, invert, posterize, gen_ } +} + +fn inputs<'a>(s: &'a Session, project: &'a texturecraft_engine::core::Project, gbuf: &'a UvGBuffer) -> Inputs<'a> { + let none = Default::default(); + // Leaked: the oracle only lives for the test. + let baked: &'a _ = Box::leak(Box::new(s.doc.baked.get(&0).cloned().unwrap_or(none))); + Inputs { project, ts: 0, mesh: &s.mesh, gbuf, pixels: &s.doc.pixels, baked, preview: None, images: &s.images, bounds: s.mesh.bounds() } +} + +/// The reference: the same sub-stack built by hand and composited at 64 px with the ordinary +/// evaluator, then encoded for display. +fn oracle(s: &Session, target: ThumbTarget) -> ThumbImage { + let gbuf = UvGBuffer::new(&s.mesh, 0, N, N); + let mut p = s.doc.project.clone(); + let (layer, upto, channel) = match target { + ThumbTarget::Content { layer, channel } => (layer, None, channel), + ThumbTarget::Mask { layer } => (layer, None, Channel::BaseColor), + ThumbTarget::Stage { effect, channel } => (p.effect(effect).unwrap().0, Some(effect), channel), + }; + p.texture_sets[0].stack = vec![layer]; + let l = p.layers.get_mut(&layer).unwrap(); + l.visible = true; + let in_mask = upto.is_some_and(|e| l.mask.as_ref().is_some_and(|m| m.effects.iter().any(|x| x.id == e))) || matches!(target, ThumbTarget::Mask { .. }); + if in_mask { + let m = l.mask.as_mut().unwrap(); + m.enabled = true; + if let Some(e) = upto { + let k = m.effects.iter().position(|x| x.id == e).unwrap(); + m.effects.truncate(k + 1); + } + let gray = mask_image(&inputs(s, &p, &gbuf), layer, N).unwrap(); + let rgba = gray.iter().enumerate().flat_map(|(i, g)| [*g, *g, *g, if gbuf.covered(i) { 255 } else { 0 }]).collect(); + return ThumbImage { width: N, height: N, rgba }; + } + l.mask = None; + l.channels.insert(channel, texturecraft_engine::core::ChannelBlend::default()); + if let Some(e) = upto { + let k = l.content_effects.iter().position(|x| x.id == e).unwrap(); + l.content_effects.truncate(k + 1); + } + let channels = p.texture_set(0).unwrap().channel_list(); + let mut comp = Composite::new(&channels, N); + composite_tiles(&inputs(s, &p, &gbuf), &mut comp, &all_tiles(N, N)); + let byte = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + let mut rgba = Vec::new(); + for y in 0..N { + for x in 0..N { + let v = comp.value(channel, x, y); + let px = match channel.kind() { + ChannelKind::Color => v.map(|c| byte(linear_to_srgb(c.clamp(0.0, 1.0)))), + ChannelKind::Signed => v.map(|c| byte(c * 0.5 + 0.5)), + _ => v.map(byte), + }; + rgba.extend_from_slice(&[px[0], px[1], px[2], if gbuf.covered((y * N + x) as usize) { 255 } else { 0 }]); + } + } + ThumbImage { width: N, height: N, rgba } +} + +/// Frames of `svc` until every target is current (or a timeout). +fn settle(svc: &mut ThumbService, s: &Session, targets: &[ThumbTarget], clock: &mut f64) { + let t0 = Instant::now(); + loop { + *clock += 0.2; + svc.begin_frame(s, *clock); + for t in targets { + svc.get(s, *t); + } + svc.poll(s); + if targets.iter().all(|t| svc.is_fresh(*t)) { + return; + } + assert!(t0.elapsed() < Duration::from_secs(60), "thumbnails never settled"); + std::thread::sleep(Duration::from_millis(2)); + } +} + +fn image(svc: &mut ThumbService, s: &Session, t: ThumbTarget) -> ThumbImage { + (*svc.get(s, t).image.expect("a picture")).clone() +} + +#[test] +fn thumbnails_equal_a_cpu_evaluation_of_the_same_sub_stack() { + let mut s = session(); + let st = stack(&mut s); + let base = Channel::BaseColor; + let targets = [ + ThumbTarget::Content { layer: st.layer, channel: base }, + ThumbTarget::Content { layer: st.layer, channel: Channel::Roughness }, + ThumbTarget::Mask { layer: st.layer }, + ThumbTarget::Stage { effect: st.invert, channel: base }, + ThumbTarget::Stage { effect: st.posterize, channel: base }, + ThumbTarget::Stage { effect: st.gen_, channel: base }, + ]; + let (mut svc, mut clock) = (ThumbService::new(), 0.0); + settle(&mut svc, &s, &targets, &mut clock); + for t in targets { + assert_eq!(image(&mut svc, &s, t), oracle(&s, t), "{t:?}"); + } + // Sanity on the values themselves: the first stage is #336699 inverted (in linear light). + let inv = image(&mut svc, &s, targets[3]); + let px = inv.rgba.chunks_exact(4).find(|p| p[3] == 255).unwrap(); + let expect = |byte: f32| (linear_to_srgb(1.0 - texturecraft_engine::texel::srgb_to_linear(byte / 255.0)) * 255.0 + 0.5) as i32; + assert!((px[0] as i32 - expect(51.0)).abs() <= 1 && (px[2] as i32 - expect(153.0)).abs() <= 1, "{px:?}"); + // The mask thumbnail is gray and not flat (a position gradient on a black mask). + let m = image(&mut svc, &s, targets[2]); + let grays: Vec = m.rgba.chunks_exact(4).filter(|p| p[3] == 255).map(|p| p[0]).collect(); + assert!(grays.iter().max() != grays.iter().min()); +} + +#[test] +fn earlier_stages_never_show_later_effects_and_hidden_effects_are_bypassed() { + let mut s = session(); + let st = stack(&mut s); + let base = Channel::BaseColor; + let (first, second) = (ThumbTarget::Stage { effect: st.invert, channel: base }, ThumbTarget::Stage { effect: st.posterize, channel: base }); + let (mut svc, mut clock) = (ThumbService::new(), 0.0); + settle(&mut svc, &s, &[first, second], &mut clock); + let (a, b) = (image(&mut svc, &s, first), image(&mut svc, &s, second)); + // Hide the second effect: its stage now shows the first one's result; the first is unchanged. + execute(&mut s, "effect.set", &json!({"effect": st.posterize.0, "visible": false})).unwrap(); + settle(&mut svc, &s, &[first, second], &mut clock); + assert_eq!(image(&mut svc, &s, first), a); + assert_eq!(image(&mut svc, &s, second), a); + assert_ne!(a, b, "posterize should change something for the test to mean anything"); + // And the content thumbnail (everything) follows. + let all = ThumbTarget::Content { layer: st.layer, channel: base }; + settle(&mut svc, &s, &[all], &mut clock); + assert_eq!(image(&mut svc, &s, all), a); +} + +#[test] +fn editing_invalidates_and_unrelated_changes_do_not() { + let mut s = session(); + let st = stack(&mut s); + let t = ThumbTarget::Content { layer: st.layer, channel: Channel::BaseColor }; + let (mut svc, mut clock) = (ThumbService::new(), 0.0); + settle(&mut svc, &s, &[t], &mut clock); + let before = image(&mut svc, &s, t); + let rendered = svc.rendered; + // A camera move changes the session revision but no thumbnail input: nothing is re-rendered. + execute(&mut s, "camera.set", &json!({"yaw": 0.7})).ok(); + s.revision += 1; + for _ in 0..3 { + clock += 0.3; + svc.begin_frame(&s, clock); + svc.get(&s, t); + svc.poll(&s); + } + assert!(svc.is_fresh(t)); + assert_eq!(svc.rendered, rendered, "an unrelated change re-rendered a thumbnail"); + // An edit of the layer re-renders it, and the new picture is the new oracle. + execute(&mut s, "effect.set", &json!({"effect": st.invert.0, "visible": false})).unwrap(); + clock += 0.3; + svc.begin_frame(&s, clock); + assert!(!svc.is_fresh(t)); + settle(&mut svc, &s, &[t], &mut clock); + let after = image(&mut svc, &s, t); + assert_ne!(before, after); + assert_eq!(after, oracle(&s, t)); + // Undo brings the first picture back. + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + settle(&mut svc, &s, &[t], &mut clock); + assert_eq!(image(&mut svc, &s, t), before); +} + +#[test] +fn deleting_a_layer_with_a_pending_thumbnail_is_harmless() { + let mut s = session(); + let st = stack(&mut s); + let (a, b) = (ThumbTarget::Content { layer: st.layer, channel: Channel::BaseColor }, ThumbTarget::Mask { layer: st.layer }); + let mut svc = ThumbService::new(); + // Queue the work and hand it to the worker, then delete the layer before collecting. + svc.begin_frame(&s, 1.0); + svc.get(&s, a); + svc.get(&s, b); + svc.poll(&s); + execute(&mut s, "layer.remove", &json!({"layer": st.layer.0})).unwrap(); + let mut clock = 2.0; + for _ in 0..200 { + clock += 0.2; + svc.begin_frame(&s, clock); + // The row is gone, so nobody asks for it any more; the pending result is dropped. + svc.poll(&s); + std::thread::sleep(Duration::from_millis(2)); + } + assert!(!svc.is_fresh(a) && !svc.is_fresh(b)); + assert_eq!(svc.cached(), 0); + assert!(!svc.busy()); + // Asking for a layer that no longer exists renders nothing and does not panic either. + settle_gone(&mut svc, &s, a, &mut clock); +} + +fn settle_gone(svc: &mut ThumbService, s: &Session, t: ThumbTarget, clock: &mut f64) { + for _ in 0..20 { + *clock += 0.2; + svc.begin_frame(s, *clock); + svc.get(s, t); + svc.poll(s); + std::thread::sleep(Duration::from_millis(2)); + } + assert!(svc.get(s, t).image.is_none()); +} + +#[test] +fn a_result_of_an_older_document_never_replaces_a_newer_one() { + let mut s = session(); + let st = stack(&mut s); + let t = ThumbTarget::Content { layer: st.layer, channel: Channel::BaseColor }; + let mut svc = ThumbService::new(); + svc.begin_frame(&s, 1.0); + svc.get(&s, t); + svc.poll(&s); // the job of the first document is running + execute(&mut s, "effect.set", &json!({"effect": st.invert.0, "visible": false})).unwrap(); + let mut clock = 2.0; + settle(&mut svc, &s, &[t], &mut clock); + // Whatever the first job returned, what is shown is the current document. + assert_eq!(image(&mut svc, &s, t), oracle(&s, t)); +} + +#[test] +fn only_requested_rows_render_and_the_cache_is_bounded() { + let mut s = session(); + let layers: Vec = (0..(CACHE_ENTRIES + 30)).map(|_| id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap(), "layer")).collect(); + let target = |l: LayerId| ThumbTarget::Content { layer: l, channel: Channel::BaseColor }; + let mut svc = ThumbService::new(); + // A frame asks for six rows, the next frame (scrolled) for only one of them. + svc.begin_frame(&s, 1.0); + for l in &layers[..6] { + svc.get(&s, target(*l)); + } + svc.poll(&s); + let mut clock = 2.0; + for _ in 0..300 { + clock += 0.2; + svc.begin_frame(&s, clock); + svc.get(&s, target(layers[0])); + svc.poll(&s); + std::thread::sleep(Duration::from_millis(1)); + } + assert!(svc.is_fresh(target(layers[0]))); + // At most the rows already on their way (the in-flight limit) finished besides it. + let done = layers[..6].iter().filter(|l| svc.is_fresh(target(**l))).count(); + assert!(done <= 3, "{done} of the scrolled-away rows were rendered"); + // Scrolling through every layer keeps the cache within its limit. + for chunk in layers.chunks(12) { + let ts: Vec = chunk.iter().map(|l| target(*l)).collect(); + settle(&mut svc, &s, &ts, &mut clock); + assert!(svc.cached() <= CACHE_ENTRIES + 12, "{}", svc.cached()); + } + clock += 0.2; + svc.begin_frame(&s, clock); + svc.poll(&s); + assert!(svc.cached() <= CACHE_ENTRIES, "{}", svc.cached()); +} From 11d889dbf57c0ffb8e775a9086610e964b1d91a7 Mon Sep 17 00:00:00 2001 From: MistyMystery Date: Wed, 4 Nov 2026 22:17:59 +0400 Subject: [PATCH 11/64] Redesign the Layers panel rows with live thumbnails Layer rows are 48 points tall with alternating shades, hover, an accent edge on the selected row and a divider under each layer. Each row shows its content thumbnail (the layer's own result in the displayed channel) and its mask thumbnail, each selectable on its own; a subtitle names the layer type and effect count; blend mode and opacity stack on the right. Effects hang under their layer on tree lines in "Content effects" and "Mask effects" groups that fold without touching the document, each with a thumbnail of the stack up to and including it (a hidden effect shows what it bypasses, struck through). Folder contents indent with lines. Paint and fill thumbnails show their own coverage over a checkerboard; folders composite their children. Every size derives from layer_panel::layer_preview_size, so a preview size setting plugs in there. New strings are translated in every shipped language. --- crates/compose/src/thumb.rs | 61 ++++- crates/engine/tests/perf.rs | 47 ++++ crates/engine/tests/thumbs.rs | 47 +++- crates/ui-egui/src/dock.rs | 326 ++++++++++++++++++++------- crates/ui-egui/src/i18n/ar.rs | 8 + crates/ui-egui/src/i18n/de.rs | 8 + crates/ui-egui/src/i18n/es.rs | 8 + crates/ui-egui/src/i18n/fr.rs | 8 + crates/ui-egui/src/i18n/it.rs | 8 + crates/ui-egui/src/i18n/ja.rs | 8 + crates/ui-egui/src/i18n/ko.rs | 8 + crates/ui-egui/src/i18n/pt_br.rs | 8 + crates/ui-egui/src/i18n/zh_hans.rs | 8 + crates/ui-egui/src/layer_panel.rs | 87 +++++++ crates/ui-egui/src/lib.rs | 4 + crates/ui-egui/tests/layers_panel.rs | 96 ++++++++ crates/ui-egui/tests/ui_snapshots.rs | 35 ++- docs/architecture.md | 20 ++ 18 files changed, 693 insertions(+), 102 deletions(-) create mode 100644 crates/ui-egui/src/layer_panel.rs create mode 100644 crates/ui-egui/tests/layers_panel.rs diff --git a/crates/compose/src/thumb.rs b/crates/compose/src/thumb.rs index a5a817e0..6a246d79 100644 --- a/crates/compose/src/thumb.rs +++ b/crates/compose/src/thumb.rs @@ -8,9 +8,9 @@ //! what the stack really computes. Nothing here mutates the caller's project. use texturecraft_core::{BlendMode, Channel, ChannelBlend, ChannelKind, LayerId, Project}; -use texturecraft_texel::linear_to_srgb; +use texturecraft_texel::{TILE, from_u16, from_u16_signed, linear_to_srgb}; -use crate::eval::{Composite, Inputs, all_tiles, composite_tiles, mask_image}; +use crate::eval::{Composite, FlatTile, Inputs, all_tiles, composite_tiles, flatten_layer, mask_image}; /// Edge length (texels) the thumbnails are computed at. pub const THUMB_TEXELS: u32 = 64; @@ -27,8 +27,9 @@ pub enum ThumbTarget { Stage { effect: LayerId, channel: Channel }, } -/// An 8-bit RGBA thumbnail. Alpha is 0 where the mesh does not cover the texture (the view -/// paints its own background there) and 255 elsewhere. +/// An 8-bit RGBA thumbnail (straight alpha). Alpha is 0 where the mesh does not cover the +/// texture and, for a paint or fill layer's content, where the layer has nothing; the view +/// paints its own background there. #[derive(Clone, Debug, PartialEq, Eq)] pub struct ThumbImage { pub width: u32, @@ -101,11 +102,57 @@ fn content(inp: &Inputs, layer: LayerId, channel: Channel, upto: Option } let cut_inp = Inputs { project: &cut, preview: None, ..*inp }; let (w, h) = (inp.gbuf.width, inp.gbuf.height); + // A paint or fill layer shows its own coverage (transparent where nothing is painted); a + // folder shows its children composited over the channel's default. + if !cut.layers.get(&owner)?.is_group() { + let flat = flatten_layer(&cut_inp, layer, &all_tiles(w, h))?; + return Some(encode_flat(&flat, channel, w, h)); + } let mut comp = Composite::with_size(&set.channel_list(), w, h); composite_tiles(&cut_inp, &mut comp, &all_tiles(w, h)); Some(encode_channel(&comp, channel, inp)) } +/// Encode the flattened (premultiplied value, coverage) tiles of `channel`: alpha is coverage. +fn encode_flat(flat: &[FlatTile], channel: Channel, w: u32, h: u32) -> ThumbImage { + let mut rgba = vec![0u8; (w * h) as usize * 4]; + let comps = channel.components(); + let signed = channel.kind() == ChannelKind::Signed; + for (c, (tx, ty), buf) in flat { + if *c != channel { + continue; + } + for (o, px) in buf.chunks_exact(comps + 1).enumerate() { + let (x, y) = (tx * TILE + o as u32 % TILE, ty * TILE + o as u32 / TILE); + let a = px.get(comps).map_or(0.0, |v| from_u16(*v)); + if x >= w || y >= h || a <= 0.0 { + continue; + } + let mut v = [0.0f32; 3]; + for (k, slot) in v.iter_mut().enumerate() { + let raw = px.get(k.min(comps - 1)).copied().unwrap_or(0); + *slot = if signed { from_u16_signed(raw) } else { from_u16(raw) } / a; + } + let p = display(channel, v); + let i = ((y * w + x) * 4) as usize; + if let Some(d) = rgba.get_mut(i..i + 4) { + d.copy_from_slice(&[p[0], p[1], p[2], to_byte(a)]); + } + } + } + ThumbImage { width: w, height: h, rgba } +} + +/// A channel value as display bytes: colors linear → sRGB, signed values with 0 at mid gray, +/// normal maps and scalars as stored. +fn display(channel: Channel, v: [f32; 3]) -> [u8; 3] { + match channel.kind() { + ChannelKind::Color => v.map(|c| to_byte(linear_to_srgb(c.clamp(0.0, 1.0)))), + ChannelKind::Signed => v.map(|c| to_byte(c * 0.5 + 0.5)), + ChannelKind::Scalar | ChannelKind::NormalMap => v.map(to_byte), + } +} + fn mask(inp: &Inputs, layer: LayerId, upto: Option) -> Option { let mut cut = solo(inp.project, inp.ts, layer, None)?; let owner = cut.mask_owner(layer); @@ -138,11 +185,7 @@ fn encode_channel(comp: &Composite, channel: Channel, inp: &Inputs) -> ThumbImag for y in 0..h { for x in 0..w { let v = comp.value(channel, x, y); - let px = match channel.kind() { - ChannelKind::Color => v.map(|c| to_byte(linear_to_srgb(c.clamp(0.0, 1.0)))), - ChannelKind::Signed => v.map(|c| to_byte(c * 0.5 + 0.5)), - ChannelKind::Scalar | ChannelKind::NormalMap => v.map(to_byte), - }; + let px = display(channel, v); let covered = inp.gbuf.covered((y * w + x) as usize); rgba.extend_from_slice(&[px[0], px[1], px[2], if covered { 255 } else { 0 }]); } diff --git a/crates/engine/tests/perf.rs b/crates/engine/tests/perf.rs index eeee7662..e4691b6a 100644 --- a/crates/engine/tests/perf.rs +++ b/crates/engine/tests/perf.rs @@ -350,3 +350,50 @@ fn bench_8k_resize() { println!("[resize] dilation {:.2?}", t.elapsed()); drop(d); } + +/// Layer-panel thumbnails on the 4K stack: the snapshot, each kind of picture, and a whole panel. +#[test] +#[ignore] +fn bench_layer_thumbs_4k() { + use texturecraft_engine::compose::ThumbTarget; + use texturecraft_engine::core::Channel; + use texturecraft_engine::thumbs::{GbufCache, ThumbSnapshot}; + let s = stack(4096); + let ts = s.ts(); + let mut gbufs = GbufCache::default(); + let t = Instant::now(); + let snap = ThumbSnapshot::new(&s, ts, &mut gbufs).unwrap(); + let first = t.elapsed(); + let t = Instant::now(); + let _again = ThumbSnapshot::new(&s, ts, &mut gbufs).unwrap(); + let cached = t.elapsed(); + let p = &s.doc.project; + let mut targets = Vec::new(); + for l in p.layers.values() { + targets.push(("content", 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 mut per: std::collections::BTreeMap<&str, (Duration, usize, Duration)> = Default::default(); + let all = Instant::now(); + for (kind, target) in &targets { + let t = Instant::now(); + let _ = snap.render(*target); + let d = t.elapsed(); + let e = per.entry(kind).or_default(); + e.0 += d; + e.1 += 1; + e.2 = e.2.max(d); + } + let total = all.elapsed(); + eprintln!("layer thumbnails, 4096 set, {} layers, 64 px:", p.layers.len()); + eprintln!(" snapshot: {:.2} ms first (with the 64 px G-buffer), {:.2} ms after", first.as_secs_f64() * 1e3, cached.as_secs_f64() * 1e3); + for (kind, (sum, n, max)) in per { + eprintln!(" {kind:8} {n:3} × avg {:.2} ms, max {:.2} ms", sum.as_secs_f64() * 1e3 / n as f64, max.as_secs_f64() * 1e3); + } + eprintln!(" every target once: {:.1} ms ({} pictures)", total.as_secs_f64() * 1e3, targets.len()); +} diff --git a/crates/engine/tests/thumbs.rs b/crates/engine/tests/thumbs.rs index 05fb52ba..ff164cee 100644 --- a/crates/engine/tests/thumbs.rs +++ b/crates/engine/tests/thumbs.rs @@ -4,11 +4,11 @@ use std::time::{Duration, Instant}; use serde_json::{Value, json}; -use texturecraft_engine::compose::{Composite, Inputs, ThumbImage, ThumbTarget, all_tiles, composite_tiles, mask_image}; +use texturecraft_engine::compose::{Inputs, ThumbImage, ThumbTarget, all_tiles, flatten_layer, mask_image}; use texturecraft_engine::core::{Channel, ChannelKind, LayerId}; use texturecraft_engine::geom::UvGBuffer; use texturecraft_engine::geom::primitives; -use texturecraft_engine::texel::linear_to_srgb; +use texturecraft_engine::texel::{from_u16, from_u16_signed, linear_to_srgb}; use texturecraft_engine::thumbs::{CACHE_ENTRIES, ThumbService}; use texturecraft_engine::{Session, execute}; @@ -46,8 +46,8 @@ fn inputs<'a>(s: &'a Session, project: &'a texturecraft_engine::core::Project, g Inputs { project, ts: 0, mesh: &s.mesh, gbuf, pixels: &s.doc.pixels, baked, preview: None, images: &s.images, bounds: s.mesh.bounds() } } -/// The reference: the same sub-stack built by hand and composited at 64 px with the ordinary -/// evaluator, then encoded for display. +/// The reference: the same sub-stack cut by hand and evaluated at 64 px with the ordinary CPU +/// evaluator (the mask with `mask_image`, the content with `flatten_layer`), then encoded. fn oracle(s: &Session, target: ThumbTarget) -> ThumbImage { let gbuf = UvGBuffer::new(&s.mesh, 0, N, N); let mut p = s.doc.project.clone(); @@ -77,20 +77,27 @@ fn oracle(s: &Session, target: ThumbTarget) -> ThumbImage { let k = l.content_effects.iter().position(|x| x.id == e).unwrap(); l.content_effects.truncate(k + 1); } - let channels = p.texture_set(0).unwrap().channel_list(); - let mut comp = Composite::new(&channels, N); - composite_tiles(&inputs(s, &p, &gbuf), &mut comp, &all_tiles(N, N)); + // A paint or fill layer: its own (premultiplied value, coverage), coverage as alpha. + let flat = flatten_layer(&inputs(s, &p, &gbuf), layer, &all_tiles(N, N)).unwrap(); let byte = |v: f32| (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; - let mut rgba = Vec::new(); - for y in 0..N { - for x in 0..N { - let v = comp.value(channel, x, y); + let mut rgba = vec![0u8; (N * N * 4) as usize]; + let comps = channel.components(); + for (_, _, buf) in flat.iter().filter(|(c, _, _)| *c == channel) { + for (i, px) in buf.chunks_exact(comps + 1).enumerate() { + let a = from_u16(px[comps]); + if a <= 0.0 { + continue; + } + let v: [f32; 3] = std::array::from_fn(|k| { + let raw = px[k.min(comps - 1)]; + (if channel.kind() == ChannelKind::Signed { from_u16_signed(raw) } else { from_u16(raw) }) / a + }); let px = match channel.kind() { ChannelKind::Color => v.map(|c| byte(linear_to_srgb(c.clamp(0.0, 1.0)))), ChannelKind::Signed => v.map(|c| byte(c * 0.5 + 0.5)), _ => v.map(byte), }; - rgba.extend_from_slice(&[px[0], px[1], px[2], if gbuf.covered((y * N + x) as usize) { 255 } else { 0 }]); + rgba[i * 4..i * 4 + 4].copy_from_slice(&[px[0], px[1], px[2], byte(a)]); } } ThumbImage { width: N, height: N, rgba } @@ -292,3 +299,19 @@ fn only_requested_rows_render_and_the_cache_is_bounded() { svc.poll(&s); assert!(svc.cached() <= CACHE_ENTRIES, "{}", svc.cached()); } + +#[test] +fn an_empty_paint_layer_is_transparent_and_a_folder_composites_its_children() { + let mut s = session(); + let paint = id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap(), "layer"); + let fill = id(execute(&mut s, "layer.add.fill", &json!({"color": "#336699"})).unwrap(), "layer"); + let folder = id(execute(&mut s, "layer.group", &json!({"layer": fill.0})).unwrap(), "layer"); + let base = Channel::BaseColor; + let (p, f) = (ThumbTarget::Content { layer: paint, channel: base }, ThumbTarget::Content { layer: folder, channel: base }); + let (mut svc, mut clock) = (ThumbService::new(), 0.0); + settle(&mut svc, &s, &[p, f], &mut clock); + assert!(image(&mut svc, &s, p).rgba.chunks_exact(4).all(|px| px[3] == 0), "nothing painted: nothing shown"); + let folder_img = image(&mut svc, &s, f); + let px = folder_img.rgba.chunks_exact(4).find(|px| px[3] == 255).unwrap(); + assert!((px[0] as i32 - 51).abs() <= 1 && (px[2] as i32 - 153).abs() <= 1, "{px:?}"); +} diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 3a74a80b..23b73dcb 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -4,6 +4,7 @@ use egui::{Color32, Rect, RichText, Sense, Stroke, Ui, pos2, vec2}; use egui_phosphor::regular as ic; use serde_json::{Value, json}; +use texturecraft_engine::compose::ThumbTarget; use texturecraft_engine::core::{ BakedMap, BlendMode, Channel, Decal, Effect, EffectKind, Fill, Filter, GeneratorKind, Layer, LayerId, LayerKind, LinkParam, MaterialLink, ProceduralKind, Source, @@ -14,6 +15,7 @@ use texturecraft_engine::{CloneFrom, StackTarget, Tool}; use crate::TextureCraftApp; use crate::i18n::{n_, tr, trf}; +use crate::layer_panel::{effect_preview_size, effect_row_height, layer_preview_size, layer_row_height}; use crate::shelf::{Asset, ShelfDrag}; use crate::state::PropsTab; use crate::theme::{Tokens, caption}; @@ -168,9 +170,12 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { ui.add_space(2.0); let ts = app.session.ts(); let stack: Vec = app.session.doc.project.texture_sets.get(ts).map(|t| t.stack.iter().rev().copied().collect()).unwrap_or_default(); + let now = ui.input(|i| i.time); + app.layer_panel.begin(&app.session, now); egui::ScrollArea::vertical().id_salt("layers_scroll").auto_shrink([false, false]).show(ui, |ui| { + let mut count = 0; for id in stack { - layer_tree(app, ui, id, 0); + layer_tree(app, ui, id, 0, &mut count); } // Click on empty space deselects nothing; the space below the rows drops at the bottom. let free = ui.available_height(); @@ -195,6 +200,7 @@ pub(crate) fn layers(app: &mut TextureCraftApp, ui: &mut Ui) { ui.painter().line_segment([rect.left_top(), rect.right_top()], Stroke::new(2.0, tk.accent)); } }); + app.layer_panel.end(ui.ctx(), &app.session); } /// Whether the selection targets the layer content (the content or one of its effects) rather @@ -252,49 +258,108 @@ fn effect_menu(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer) { }); } -fn layer_tree(app: &mut TextureCraftApp, ui: &mut Ui, id: LayerId, depth: usize) { +/// Layer rows alternate between two shades so neighbours read as separate items. +fn row_shade(tk: &Tokens, index: usize) -> Color32 { + if index.is_multiple_of(2) { tk.row } else { tk.row.lerp_to_gamma(tk.row_hover, 0.45) } +} + +/// Width of the blend mode / opacity column at the right of a layer row. +const RIGHT_COLUMN: f32 = 58.0; +/// Indent per folder level, and per level of the effect tree. +const INDENT: f32 = 14.0; +/// Height of the "Content effects" / "Mask effects" header rows. +const GROUP_HEADER_H: f32 = 20.0; + +/// X of the centre of the eye column at indent `level` in a row spanning from `left`. +fn level_x(left: f32, level: usize) -> f32 { + left + 7.0 + level as f32 * INDENT + 8.0 +} + +fn layer_tree(app: &mut TextureCraftApp, ui: &mut Ui, id: LayerId, depth: usize, count: &mut usize) { let Some(layer) = app.session.doc.project.layers.get(&id).cloned() else { return }; - layer_row(app, ui, &layer, depth); - for e in layer.content_effects.iter().rev() { - effect_row(app, ui, &layer, &layer.content_effects, e, depth + 1, ic::SPHERE); + let index = *count; + *count += 1; + layer_row(app, ui, &layer, depth, index); + let mask_effects = layer.mask.as_ref().map_or(0, |m| m.effects.len()); + if !layer.content_effects.is_empty() { + effect_group(app, ui, &layer, depth, false, mask_effects > 0); } - if let Some(m) = &layer.mask { - for e in m.effects.iter().rev() { - effect_row(app, ui, &layer, &m.effects, e, depth + 1, ic::MAGIC_WAND); - } + if mask_effects > 0 { + effect_group(app, ui, &layer, depth, true, false); } + // A line under the layer and its effects separates it from the next layer. + let tk = Tokens::get(ui.ctx()); + let r = ui.available_rect_before_wrap(); + ui.painter().hline(r.x_range(), r.top() - 0.5, Stroke::new(1.0, tk.separator)); if let LayerKind::Group { children, collapsed } = &layer.kind && !collapsed && depth < 12 { for c in children.iter().rev() { - layer_tree(app, ui, *c, depth + 1); + layer_tree(app, ui, *c, depth + 1, count); } } } -fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize) { +/// The picture for `target` inside `rect` (drawn over the well), whether there is one yet. +fn thumb_box(ui: &Ui, app: &mut TextureCraftApp, rect: Rect, target: ThumbTarget, dim: bool) -> bool { + let tk = Tokens::get(ui.ctx()); + let p = ui.painter(); + p.rect_filled(rect, 2.0, tk.field); + // A checkerboard shows through where the layer has nothing (transparent texels). + let cells = 4; + let cell = rect.width() / cells as f32; + let check = tk.field.lerp_to_gamma(tk.row_hover, 0.6); + for y in 0..cells { + for x in (0..cells).filter(|x| (x + y) % 2 == 0) { + p.rect_filled(Rect::from_min_size(rect.min + vec2(x as f32 * cell, y as f32 * cell), vec2(cell, cell)), 0.0, check); + } + } + // Only rows on screen ask for a picture. + if ui.is_rect_visible(rect) + && let Some(tex) = app.layer_panel.texture(ui.ctx(), &app.session, target) + { + let tint = if dim { Color32::WHITE.gamma_multiply(0.4) } else { Color32::WHITE }; + ui.painter().image(tex, rect, Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)), tint); + return true; + } + false +} + +fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize, index: usize) { let tk = Tokens::get(ui.ctx()); let selected = app.session.selected_layer() == Some(layer.id); - let h = 38.0; + let content_target = selected && targets_content(app); + let size = layer_preview_size(app); + let h = layer_row_height(size); let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), h), Sense::click_and_drag()); resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &layer.name)); let p = ui.painter().clone(); - let bg = if selected && app.session.target == StackTarget::Content { + let bg = if selected { tk.row_selected } else if resp.hovered() { tk.row_hover } else { - tk.row + row_shade(&tk, index) }; - p.rect_filled(rect.shrink2(vec2(0.0, 1.0)), 2.0, bg); + p.rect_filled(rect, 0.0, bg); + // Folder contents hang off lines down the left. + let line = Stroke::new(1.0, tk.button_border.gamma_multiply(0.6)); + for level in 0..depth { + let x = level_x(rect.left(), level); + p.vline(x, rect.y_range(), line); + } + if depth > 0 { + let x = level_x(rect.left(), depth - 1); + p.hline(x..=x + INDENT * 0.5, rect.center().y, line); + } if selected { - p.rect_stroke(rect.shrink2(vec2(0.0, 1.0)), 2.0, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside); + p.rect_filled(Rect::from_min_size(rect.min, vec2(3.0, h)), 0.0, tk.accent); } if let Some(tag) = layer.color_tag.and_then(|t| TAG_COLORS.get(t as usize)) { - p.rect_filled(Rect::from_min_size(rect.min + vec2(0.0, 1.0), vec2(3.0, h - 2.0)), 0.0, *tag); + p.rect_filled(Rect::from_min_size(rect.min + vec2(3.0, 0.0), vec2(3.0, h)), 0.0, *tag); } - let x0 = rect.left() + 6.0 + depth as f32 * 14.0; + let x0 = rect.left() + 7.0 + depth as f32 * INDENT; // Eye. let eye = Rect::from_center_size(pos2(x0 + 8.0, rect.center().y), vec2(18.0, 18.0)); let eye_resp = ui.interact(eye, ui.scope_id().with(("eye", layer.id.0)), Sense::click()).on_hover_text(tr("Show or hide the layer")); @@ -327,29 +392,24 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize } x += 14.0; } - // Thumbnail. - let thumb = Rect::from_min_size(pos2(x, rect.top() + 5.0), vec2(28.0, 28.0)); - p.rect_filled(thumb, 2.0, tk.field); - match &layer.kind { - LayerKind::Fill(f) => { - let c = match f.source(Channel::BaseColor) { - Source::Uniform(v) => v, - Source::Procedural { low, high, .. } => [(low[0] + high[0]) * 0.5, (low[1] + high[1]) * 0.5, (low[2] + high[2]) * 0.5], - Source::Image { .. } | Source::Anchor { .. } => [0.5; 3], - }; - crate::thumbs::paint_sphere(&p, thumb.center(), 12.0, c); - } - LayerKind::Paint => { - p.text(thumb.center(), egui::Align2::CENTER_CENTER, ic::PAINT_BRUSH, egui::FontId::proportional(15.0), tk.text); - } - LayerKind::Group { .. } => { - p.text(thumb.center(), egui::Align2::CENTER_CENTER, ic::FOLDER_SIMPLE, egui::FontId::proportional(16.0), tk.text); - } - LayerKind::Instance { .. } => { - p.text(thumb.center(), egui::Align2::CENTER_CENTER, ic::LINK, egui::FontId::proportional(16.0), tk.accent); - } + // Content thumbnail: the layer's own result in the displayed channel. + let ch = app.ui.layer_channel; + let thumb = Rect::from_min_size(pos2(x, rect.center().y - size * 0.5), vec2(size, size)); + let drawn = thumb_box(ui, app, thumb, ThumbTarget::Content { layer: layer.id, channel: ch }, !layer.visible); + if !drawn { + content_glyph(&p, &tk, thumb, layer); } - x = thumb.right() + 8.0; + p.rect_stroke( + thumb, + 2.0, + Stroke::new(if content_target { 1.5 } else { 1.0 }, if content_target { tk.accent } else { tk.button_border }), + egui::StrokeKind::Outside, + ); + let content_resp = ui.interact(thumb, ui.scope_id().with(("content", layer.id.0)), Sense::click()).on_hover_text(tr("Select the layer content")); + if content_resp.clicked() { + app.run("layer.select", json!({"layer": layer.id.0, "target": "content"})); + } + x = thumb.right() + 4.0; // An instance draws its source's content, blending and (unless it has its own) mask. let project = &app.session.doc.project; let source = layer.instance_source().map(|src| { @@ -357,26 +417,29 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize project.layers.get(&src).map_or_else(|| tr("missing source").to_string(), |l| format!("{} · {set}", l.name)) }); let mask = project.layers.get(&project.mask_owner(layer.id)).and_then(|l| l.mask.clone()); - let blend = project.content_layer(layer.id).and_then(|l| l.blend(app.ui.layer_channel)); - // Mask thumbnail. - let right_w = 46.0; - let mask_rect = Rect::from_min_size(pos2(rect.right() - right_w - 30.0, rect.top() + 7.0), vec2(24.0, 24.0)); + let blend = project.content_layer(layer.id).and_then(|l| l.blend(ch)); + // Mask thumbnail, selectable on its own; or the slot that adds one. + let mask_rect; if let Some(m) = &mask { let mask_sel = selected && !targets_content(app); - p.rect_filled( - mask_rect, - 1.0, - if m.background == texturecraft_engine::core::MaskBackground::White { Color32::from_gray(225) } else { Color32::from_gray(18) }, - ); + mask_rect = Rect::from_min_size(pos2(x, rect.center().y - size * 0.5), vec2(size, size)); + let drawn = thumb_box(ui, app, mask_rect, ThumbTarget::Mask { layer: layer.id }, !layer.visible || !m.enabled); + if !drawn { + p.rect_filled( + mask_rect, + 2.0, + if m.background == texturecraft_engine::core::MaskBackground::White { Color32::from_gray(225) } else { Color32::from_gray(18) }, + ); + if !m.effects.is_empty() { + p.text(mask_rect.center(), egui::Align2::CENTER_CENTER, ic::MAGIC_WAND, egui::FontId::proportional(13.0), tk.text_dim); + } + } p.rect_stroke( mask_rect, - 1.0, + 2.0, Stroke::new(if mask_sel { 1.5 } else { 1.0 }, if mask_sel { tk.accent } else { tk.button_border }), egui::StrokeKind::Outside, ); - if !m.effects.is_empty() { - p.text(mask_rect.center(), egui::Align2::CENTER_CENTER, ic::MAGIC_WAND, egui::FontId::proportional(11.0), tk.text_dim); - } if !m.enabled { p.line_segment([mask_rect.left_top(), mask_rect.right_bottom()], Stroke::new(1.5, tk.danger)); } @@ -392,19 +455,25 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize } } if app.session.view == texturecraft_engine::ViewMode::Mask(layer.id) { - p.rect_stroke(mask_rect.expand(2.0), 1.0, Stroke::new(1.5, tk.warning), egui::StrokeKind::Outside); + p.rect_stroke(mask_rect.expand(2.0), 2.0, Stroke::new(1.5, tk.warning), egui::StrokeKind::Outside); } + x = mask_rect.right() + 8.0; } else { // The empty slot adds a mask to this layer. + mask_rect = Rect::from_center_size(pos2(x + 9.0, rect.center().y), vec2(18.0, 18.0)); let slot = ui.interact(mask_rect, ui.scope_id().with(("mask_slot", layer.id.0)), Sense::click()).on_hover_text(tr("Add mask")); - p.rect_stroke(mask_rect, 1.0, Stroke::new(1.0, if slot.hovered() { tk.accent } else { tk.field_border }), egui::StrokeKind::Inside); + p.rect_stroke(mask_rect, 2.0, Stroke::new(1.0, if slot.hovered() { tk.accent } else { tk.field_border }), egui::StrokeKind::Inside); if slot.hovered() { p.text(mask_rect.center(), egui::Align2::CENTER_CENTER, ic::PLUS, egui::FontId::proportional(12.0), tk.text); } egui::Popup::menu(&slot).show(|ui| add_mask_menu(app, ui, Some(layer.id.0))); + x = mask_rect.right() + 8.0; } - // Name (or rename editor). - let name_rect = Rect::from_min_max(pos2(x, rect.top() + 4.0), pos2(mask_rect.left() - 4.0, rect.bottom() - 4.0)); + // Blend mode and opacity of the displayed channel, stacked at the right. + let blend_rect = Rect::from_min_size(pos2(rect.right() - RIGHT_COLUMN - 4.0, rect.center().y - 18.0), vec2(RIGHT_COLUMN, 17.0)); + let op_rect = Rect::from_min_size(pos2(rect.right() - RIGHT_COLUMN - 4.0, rect.center().y + 1.0), vec2(RIGHT_COLUMN, 17.0)); + // Name (or rename editor) with the quieter subtitle under it. + let name_rect = Rect::from_min_max(pos2(x, rect.top() + 4.0), pos2((blend_rect.left() - 4.0).max(x + 20.0), rect.bottom() - 4.0)); let renaming = app.ui.rename.as_ref().is_some_and(|(r, _)| *r == layer.id.0); if renaming { let mut child = ui.new_child(egui::UiBuilder::new().max_rect(name_rect).layout(egui::Layout::left_to_right(egui::Align::Center))); @@ -428,20 +497,29 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize } } } else { - let galley = elided(&p, layer.name.clone(), 12.0, if layer.visible { tk.text_strong } else { tk.text_dim }, name_rect.width()); - let y = if source.is_some() { rect.center().y - 7.0 } else { rect.center().y }; - p.galley(pos2(name_rect.left(), y - galley.size().y * 0.5), galley, tk.text); - if let Some(src) = source { - let src = elided(&p, format!("{} {src}", ic::LINK_SIMPLE), 10.0, tk.text_dim, name_rect.width()); - p.galley(pos2(name_rect.left(), rect.center().y + 7.0 - src.size().y * 0.5), src, tk.text_dim); - } + let galley = elided(&p, layer.name.clone(), 12.5, if layer.visible { tk.text_strong } else { tk.text_dim }, name_rect.width()); + p.galley(pos2(name_rect.left(), rect.center().y - 2.0 - galley.size().y), galley, tk.text); + let kind = tr(match &layer.kind { + LayerKind::Paint => "Paint layer", + LayerKind::Fill(_) => "Fill layer", + LayerKind::Group { .. } => "Folder", + LayerKind::Instance { .. } => "Instance", + }); + let effects = layer.content_effects.len() + mask.as_ref().map_or(0, |m| m.effects.len()); + let subtitle = match (source, effects) { + (Some(src), _) => format!("{kind} · {} {src}", ic::LINK_SIMPLE), + (None, 0) => kind.to_string(), + (None, 1) => format!("{kind} · {}", tr("1 effect")), + (None, n) => format!("{kind} · {}", trf("{count} effects", &[("count", &n)])), + }; + let sub = elided(&p, subtitle, 10.0, tk.text_dim, name_rect.width()); + p.galley(pos2(name_rect.left(), rect.center().y + 2.0), sub, tk.text_dim); } - // Blend mode and opacity of the displayed channel. - let ch = app.ui.layer_channel; - let blend_rect = Rect::from_min_size(pos2(rect.right() - right_w - 2.0, rect.top() + 3.0), vec2(right_w, 16.0)); - let op_rect = Rect::from_min_size(pos2(rect.right() - right_w - 2.0, rect.top() + 19.0), vec2(right_w, 16.0)); if let Some(b) = blend { let br = ui.interact(blend_rect, ui.scope_id().with(("blend", layer.id.0)), Sense::click()).on_hover_text(tr("Blending mode of the displayed channel")); + if br.hovered() { + p.rect_filled(blend_rect, 2.0, tk.row_hover); + } p.text(blend_rect.right_center() - vec2(10.0, 0.0), egui::Align2::RIGHT_CENTER, b.mode.short(), egui::FontId::proportional(11.0), tk.text); p.text(blend_rect.right_center(), egui::Align2::RIGHT_CENTER, ic::CARET_DOWN, egui::FontId::proportional(8.0), tk.text_dim); egui::Popup::menu(&br).show(|ui| { @@ -466,7 +544,7 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize child.spacing_mut().interact_size.y = op_rect.height(); child.spacing_mut().button_padding = vec2(4.0, 0.0); child.style_mut().override_text_style = Some(egui::TextStyle::Small); - let r = child.add(egui::DragValue::new(&mut op).range(0.0..=100.0).speed(0.5).max_decimals(0)); + let r = child.add(egui::DragValue::new(&mut op).range(0.0..=100.0).speed(0.5).max_decimals(0).suffix("%")); if r.changed() { app.run("layer.blend", json!({"layer": layer.id.0, "channel": ch.id(), "opacity": op / 100.0})); } @@ -474,10 +552,11 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize p.text(blend_rect.right_center(), egui::Align2::RIGHT_CENTER, tr("off"), egui::FontId::proportional(11.0), tk.text_dim); } // Interaction: select, rename, drag & drop, context menu. - if resp.clicked() && !eye_resp.clicked() && !renaming { + let on_control = eye_resp.clicked() || content_resp.clicked(); + if resp.clicked() && !on_control && !renaming { app.run("layer.select", json!({"layer": layer.id.0})); } - if resp.double_clicked() && !eye_resp.clicked() && !renaming { + if resp.double_clicked() && !on_control && !renaming { app.ui.rename = Some((layer.id.0, layer.name.clone())); } if resp.drag_started() && !renaming { @@ -523,20 +602,94 @@ fn layer_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize resp.context_menu(|ui| layer_context_menu(app, ui, layer)); } +/// What a content thumbnail shows until its picture arrives (or where the layer has none). +fn content_glyph(p: &egui::Painter, tk: &Tokens, thumb: Rect, layer: &Layer) { + match &layer.kind { + LayerKind::Fill(f) => { + let c = match f.source(Channel::BaseColor) { + Source::Uniform(v) => v, + Source::Procedural { low, high, .. } => [(low[0] + high[0]) * 0.5, (low[1] + high[1]) * 0.5, (low[2] + high[2]) * 0.5], + Source::Image { .. } | Source::Anchor { .. } => [0.5; 3], + }; + crate::thumbs::paint_sphere(p, thumb.center(), thumb.width() * 0.34, c); + } + LayerKind::Paint => { + p.text(thumb.center(), egui::Align2::CENTER_CENTER, ic::PAINT_BRUSH, egui::FontId::proportional(thumb.width() * 0.45), tk.text_dim); + } + LayerKind::Group { .. } => { + p.text(thumb.center(), egui::Align2::CENTER_CENTER, ic::FOLDER_SIMPLE, egui::FontId::proportional(thumb.width() * 0.5), tk.text); + } + LayerKind::Instance { .. } => { + p.text(thumb.center(), egui::Align2::CENTER_CENTER, ic::LINK, egui::FontId::proportional(thumb.width() * 0.45), tk.accent); + } + } +} + +/// The "Content effects" or "Mask effects" header of `layer` and, unless folded, its effect rows +/// hung off tree lines. `more_below`: a second group follows, so the tree line goes on. +fn effect_group(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, depth: usize, mask: bool, more_below: bool) { + let tk = Tokens::get(ui.ctx()); + let stack: &[Effect] = if mask { layer.mask.as_ref().map_or(&[], |m| &m.effects) } else { &layer.content_effects }; + let key = (layer.id.0, mask); + let folded = app.layer_panel.folded.contains(&key); + let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), GROUP_HEADER_H), Sense::click()); + let label = if mask { tr("Mask effects") } else { tr("Content effects") }; + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, label)); + let p = ui.painter().clone(); + p.rect_filled(rect, 0.0, if resp.hovered() { tk.row_hover } else { tk.panel }); + tree_lines(&p, &tk, rect, depth + 1, &[], more_below); + let x = level_x(rect.left(), depth + 1); + p.text( + pos2(x, rect.center().y), + egui::Align2::CENTER_CENTER, + if folded { ic::CARET_RIGHT } else { ic::CARET_DOWN }, + egui::FontId::proportional(10.0), + tk.text_dim, + ); + p.text(pos2(x + 10.0, rect.center().y), egui::Align2::LEFT_CENTER, label, egui::FontId::proportional(10.5), tk.text_dim); + p.text(pos2(rect.right() - 8.0, rect.center().y), egui::Align2::RIGHT_CENTER, stack.len().to_string(), egui::FontId::proportional(10.0), tk.text_dim); + if resp.on_hover_text(tr("Fold or unfold these effects")).clicked() && !app.layer_panel.folded.remove(&key) { + app.layer_panel.folded.insert(key); + } + if folded { + return; + } + let trunks: Vec = if more_below { vec![depth] } else { Vec::new() }; + for (i, e) in stack.iter().rev().enumerate() { + effect_row(app, ui, layer, stack, e, depth + 2, &trunks, i + 1 == stack.len(), mask); + } +} + +/// Tree connector of a row at indent `level`: a line down from the parent's column (to the middle +/// of the row when `more` is false, the row's end otherwise) and a tick towards the row, with +/// lines straight through for the `trunks` of ancestors that continue. +fn tree_lines(p: &egui::Painter, tk: &Tokens, rect: Rect, level: usize, trunks: &[usize], more: bool) { + let stroke = Stroke::new(1.0, tk.button_border); + for t in trunks { + p.vline(level_x(rect.left(), *t), rect.y_range(), stroke); + } + let x = level_x(rect.left(), level.saturating_sub(1)); + let end = if more { rect.bottom() } else { rect.center().y }; + p.vline(x, rect.top()..=end, stroke); + p.hline(x..=x + INDENT * 0.6, rect.center().y, stroke); +} + /// The drag-and-drop payload of an effect row (the effect id). struct EffectDrag(u64); -/// Effect `e` of `stack`, a layer's content (`glyph` sphere) or mask (`glyph` wand) effects. -fn effect_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, stack: &[Effect], e: &Effect, depth: usize, glyph: &str) { +/// Effect `e` of `stack` (a layer's content or, with `in_mask`, mask effects) at indent `level`. +#[allow(clippy::too_many_arguments)] +fn effect_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, stack: &[Effect], e: &Effect, level: usize, trunks: &[usize], last: bool, in_mask: bool) { let tk = Tokens::get(ui.ctx()); let (eid, visible) = (e.id, e.visible); let selected = app.session.selected_layer() == Some(layer.id) && app.session.target == StackTarget::Effect(eid); - let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 22.0), Sense::click_and_drag()); + let size = effect_preview_size(layer_preview_size(app)); + let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), effect_row_height(layer_preview_size(app))), Sense::click_and_drag()); resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::ListItem, true, selected, &e.name)); let p = ui.painter().clone(); p.rect_filled( - rect.shrink2(vec2(0.0, 1.0)), - 2.0, + rect, + 0.0, if selected { tk.row_selected } else if resp.hovered() { @@ -545,15 +698,28 @@ fn effect_row(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, stack: &[Ef tk.panel }, ); + tree_lines(&p, &tk, rect, level, trunks, !last); if selected { - p.rect_stroke(rect.shrink2(vec2(0.0, 1.0)), 2.0, Stroke::new(1.0, tk.accent), egui::StrokeKind::Inside); + p.rect_filled(Rect::from_min_size(rect.min, vec2(3.0, rect.height())), 0.0, tk.accent); } - let x0 = rect.left() + 6.0 + depth as f32 * 14.0; + let x0 = rect.left() + 7.0 + level as f32 * INDENT; let eye = Rect::from_center_size(pos2(x0 + 8.0, rect.center().y), vec2(16.0, 16.0)); let er = ui.interact(eye, ui.scope_id().with(("eff_eye", eid.0)), Sense::click()).on_hover_text(tr("Enable or disable the effect")); p.text(eye.center(), egui::Align2::CENTER_CENTER, if visible { ic::EYE } else { ic::EYE_SLASH }, egui::FontId::proportional(12.0), tk.text_dim); - p.text(pos2(x0 + 22.0, rect.center().y), egui::Align2::LEFT_CENTER, glyph, egui::FontId::proportional(11.0), tk.text_dim); - p.text(pos2(x0 + 38.0, rect.center().y), egui::Align2::LEFT_CENTER, &e.name, egui::FontId::proportional(11.5), tk.text); + // The stack as it is up to and including this effect; a hidden one shows what it bypasses. + let thumb = Rect::from_min_size(pos2(x0 + 22.0, rect.center().y - size * 0.5), vec2(size, size)); + let ch = app.ui.layer_channel; + if !thumb_box(ui, app, thumb, ThumbTarget::Stage { effect: eid, channel: ch }, false) { + let glyph = if in_mask { ic::MAGIC_WAND } else { ic::SPHERE }; + p.text(thumb.center(), egui::Align2::CENTER_CENTER, glyph, egui::FontId::proportional(size * 0.5), tk.text_dim); + } + p.rect_stroke(thumb, 2.0, Stroke::new(1.0, tk.button_border), egui::StrokeKind::Outside); + if !visible { + p.line_segment([thumb.left_bottom(), thumb.right_top()], Stroke::new(1.5, tk.text_dim)); + } + let name_x = thumb.right() + 8.0; + let galley = elided(&p, e.name.clone(), 11.5, if visible { tk.text } else { tk.text_dim }, (rect.right() - name_x - 6.0).max(20.0)); + p.galley(pos2(name_x, rect.center().y - galley.size().y * 0.5), galley, tk.text); if er.clicked() { app.run("effect.set", json!({"effect": eid.0, "visible": !visible})); } else if resp.clicked() { diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 6ef517e9..5e8c266f 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1041,4 +1041,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "الحد الأقصى للقيمة"), ("Value Bounds Min", "الحد الأدنى للقيمة"), ("Vertex Color", "لون الرأس"), + ("Select the layer content", "تحديد محتوى الطبقة"), + ("Paint layer", "طبقة رسم"), + ("Fill layer", "طبقة تعبئة"), + ("1 effect", "تأثير واحد"), + ("{count} effects", "{count} تأثيرات"), + ("Mask effects", "تأثيرات القناع"), + ("Content effects", "تأثيرات المحتوى"), + ("Fold or unfold these effects", "طيّ هذه التأثيرات أو فردها"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index caaabb14..30693118 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1090,4 +1090,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "Maximaler Grenzwert"), ("Value Bounds Min", "Minimaler Grenzwert"), ("Vertex Color", "Scheitelpunktfarbe"), + ("Select the layer content", "Ebeneninhalt auswählen"), + ("Paint layer", "Malebene"), + ("Fill layer", "Füllebene"), + ("1 effect", "1 Effekt"), + ("{count} effects", "{count} Effekte"), + ("Mask effects", "Maskeneffekte"), + ("Content effects", "Inhaltseffekte"), + ("Fold or unfold these effects", "Diese Effekte ein- oder ausklappen"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 6c8ccccb..bc8ace33 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1075,4 +1075,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "Límite máximo"), ("Value Bounds Min", "Límite mínimo"), ("Vertex Color", "Color de vértice"), + ("Select the layer content", "Seleccionar el contenido de la capa"), + ("Paint layer", "Capa de pintura"), + ("Fill layer", "Capa de relleno"), + ("1 effect", "1 efecto"), + ("{count} effects", "{count} efectos"), + ("Mask effects", "Efectos de la máscara"), + ("Content effects", "Efectos del contenido"), + ("Fold or unfold these effects", "Plegar o desplegar estos efectos"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index f10bba8d..336621e9 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1099,4 +1099,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "Borne maximale"), ("Value Bounds Min", "Borne minimale"), ("Vertex Color", "Couleur des sommets"), + ("Select the layer content", "Sélectionner le contenu du calque"), + ("Paint layer", "Calque de peinture"), + ("Fill layer", "Calque de remplissage"), + ("1 effect", "1 effet"), + ("{count} effects", "{count} effets"), + ("Mask effects", "Effets du masque"), + ("Content effects", "Effets du contenu"), + ("Fold or unfold these effects", "Replier ou déplier ces effets"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 1c19d597..8f92b26c 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1084,4 +1084,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "Limite massimo"), ("Value Bounds Min", "Limite minimo"), ("Vertex Color", "Colore dei vertici"), + ("Select the layer content", "Seleziona il contenuto del livello"), + ("Paint layer", "Livello di pittura"), + ("Fill layer", "Livello di riempimento"), + ("1 effect", "1 effetto"), + ("{count} effects", "{count} effetti"), + ("Mask effects", "Effetti della maschera"), + ("Content effects", "Effetti del contenuto"), + ("Fold or unfold these effects", "Comprimi o espandi questi effetti"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 068603b5..52166e4a 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1069,4 +1069,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "値の上限"), ("Value Bounds Min", "値の下限"), ("Vertex Color", "頂点カラー"), + ("Select the layer content", "レイヤーの内容を選択"), + ("Paint layer", "ペイントレイヤー"), + ("Fill layer", "塗りつぶしレイヤー"), + ("1 effect", "エフェクト 1 件"), + ("{count} effects", "エフェクト {count} 件"), + ("Mask effects", "マスクのエフェクト"), + ("Content effects", "コンテンツのエフェクト"), + ("Fold or unfold these effects", "これらのエフェクトを折りたたむ/展開する"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 137d6177..18bf30a6 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1054,4 +1054,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "값 상한"), ("Value Bounds Min", "값 하한"), ("Vertex Color", "정점 색상"), + ("Select the layer content", "레이어 내용 선택"), + ("Paint layer", "페인트 레이어"), + ("Fill layer", "채우기 레이어"), + ("1 effect", "효과 1개"), + ("{count} effects", "효과 {count}개"), + ("Mask effects", "마스크 효과"), + ("Content effects", "콘텐츠 효과"), + ("Fold or unfold these effects", "이 효과들 접기/펼치기"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 99627b25..17d7cc2e 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1072,4 +1072,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "Limite máximo"), ("Value Bounds Min", "Limite mínimo"), ("Vertex Color", "Cor do vértice"), + ("Select the layer content", "Selecionar o conteúdo da camada"), + ("Paint layer", "Camada de pintura"), + ("Fill layer", "Camada de preenchimento"), + ("1 effect", "1 efeito"), + ("{count} effects", "{count} efeitos"), + ("Mask effects", "Efeitos da máscara"), + ("Content effects", "Efeitos do conteúdo"), + ("Fold or unfold these effects", "Recolher ou expandir estes efeitos"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 18623ce3..4bb8705e 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1000,4 +1000,12 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "值上限"), ("Value Bounds Min", "值下限"), ("Vertex Color", "顶点颜色"), + ("Select the layer content", "选择图层内容"), + ("Paint layer", "绘画图层"), + ("Fill layer", "填充图层"), + ("1 effect", "1 个效果"), + ("{count} effects", "{count} 个效果"), + ("Mask effects", "蒙版效果"), + ("Content effects", "内容效果"), + ("Fold or unfold these effects", "折叠或展开这些效果"), ]; diff --git a/crates/ui-egui/src/layer_panel.rs b/crates/ui-egui/src/layer_panel.rs new file mode 100644 index 00000000..a29fa288 --- /dev/null +++ b/crates/ui-egui/src/layer_panel.rs @@ -0,0 +1,87 @@ +//! State behind the Layers panel: the thumbnail service, the GPU textures made from its pictures, +//! which effect groups are folded, and the one place the preview size is decided. + +use std::collections::{HashMap, HashSet}; +use std::time::Duration; + +use egui::{Context, TextureHandle, TextureId, TextureOptions}; +use texturecraft_engine::Session; +use texturecraft_engine::compose::ThumbTarget; +use texturecraft_engine::thumbs::{CACHE_ENTRIES, ThumbService}; + +use crate::TextureCraftApp; + +/// Edge (points) of a layer's content and mask thumbnails. The Layers "Preview size" setting +/// plugs in by changing [`layer_preview_size`]; every row measure below derives from it. +pub(crate) const LAYER_PREVIEW_SIZE: f32 = 36.0; + +/// The thumbnail edge in points, read once per row. +pub(crate) fn layer_preview_size(_app: &TextureCraftApp) -> f32 { + LAYER_PREVIEW_SIZE +} + +/// Height of a layer row for thumbnails of `size`. +pub(crate) fn layer_row_height(size: f32) -> f32 { + (size + 12.0).max(48.0) +} + +/// Edge of an effect's stage thumbnail for layer thumbnails of `size` (18 to 28 points). +pub(crate) fn effect_preview_size(size: f32) -> f32 { + (size * 0.6).clamp(18.0, 28.0) +} + +/// Height of an effect row. +pub(crate) fn effect_row_height(size: f32) -> f32 { + (effect_preview_size(size) + 4.0).max(26.0) +} + +#[derive(Default)] +pub struct LayerPanel { + service: ThumbService, + textures: HashMap, + frame: u64, + /// Folded effect groups: (layer, true for the mask's). A view setting; the document is not touched. + pub(crate) folded: HashSet<(u64, bool)>, +} + +impl LayerPanel { + /// Start drawing the panel for this frame. + pub(crate) fn begin(&mut self, session: &Session, now: f64) { + self.frame += 1; + self.service.begin_frame(session, now); + } + + /// The texture of `target`, queuing its render (call only for rows that are on screen). + pub(crate) fn texture(&mut self, ctx: &Context, session: &Session, target: ThumbTarget) -> Option { + let view = self.service.get(session, target); + let image = view.image?; + let frame = self.frame; + if let Some((version, tex, used)) = self.textures.get_mut(&target) + && *version == view.version + { + *used = frame; + return Some(tex.id()); + } + let pixels = egui::ColorImage::from_rgba_unmultiplied([image.width as usize, image.height as usize], &image.rgba); + let tex = ctx.load_texture("layer-thumb", pixels, TextureOptions::LINEAR); + let id = tex.id(); + self.textures.insert(target, (view.version, tex, frame)); + Some(id) + } + + /// Finish the frame: collect pictures and ask for another frame while work is outstanding. + pub(crate) fn end(&mut self, ctx: &Context, session: &Session) { + if self.service.poll(session) { + ctx.request_repaint_after(Duration::from_millis(40)); + } + if self.textures.len() > CACHE_ENTRIES * 2 { + let frame = self.frame; + self.textures.retain(|_, (_, _, used)| *used + 1 >= frame); + } + } + + /// The service, for tests. + pub fn service(&self) -> &ThumbService { + &self.service + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 8bfc66c9..d82bea69 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -16,6 +16,7 @@ pub mod fonts; pub mod gpu; pub mod i18n; pub mod keymap; +pub mod layer_panel; pub mod menus; pub mod parity; pub mod profile; @@ -85,6 +86,8 @@ pub struct TextureCraftApp { pub resize: Option, pub link_cooks: Vec, pub thumbs: thumbs::Thumbs, + /// The Layers panel's thumbnails and folded groups. + pub layer_panel: layer_panel::LayerPanel, /// Last frame's viewport rect (logical points), for scripted input. pub viewport_rect: egui::Rect, pub fps: f32, @@ -145,6 +148,7 @@ impl TextureCraftApp { resize: None, link_cooks: Vec::new(), thumbs: thumbs::Thumbs::default(), + layer_panel: layer_panel::LayerPanel::default(), viewport_rect: egui::Rect::NOTHING, fps: 0.0, ui_ms: 0.0, diff --git a/crates/ui-egui/tests/layers_panel.rs b/crates/ui-egui/tests/layers_panel.rs new file mode 100644 index 00000000..facf2ab3 --- /dev/null +++ b/crates/ui-egui/tests/layers_panel.rs @@ -0,0 +1,96 @@ +//! The Layers panel rows: content and mask thumbnails select their own target, effect groups +//! fold without touching the document, and the thumbnails arrive from the worker. + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::{Value, json}; +use texturecraft_engine::compose::ThumbTarget; +use texturecraft_engine::core::{Channel, LayerId}; +use texturecraft_engine::{StackTarget, execute}; +use texturecraft_ui_egui::TextureCraftApp; + +fn id(v: Value, key: &str) -> u64 { + v[key].as_u64().unwrap() +} + +/// A session whose top layer, "Masked fill", has one content effect and a mask with one effect. +fn harness() -> (Harness<'static, TextureCraftApp>, LayerId) { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = LayerId(id(execute(&mut session, "layer.add.fill", &json!({"color": "#336699"})).unwrap(), "layer")); + execute(&mut session, "layer.rename", &json!({"layer": layer.0, "name": "Masked fill"})).unwrap(); + execute(&mut session, "effect.add.filter", &json!({"target": "content", "filter": "invert", "name": "Effect A"})).unwrap(); + execute(&mut session, "mask.add.black", &Value::Null).unwrap(); + execute(&mut session, "effect.add.generator", &json!({"generator": "position", "level": 0.5, "name": "Effect M"})).unwrap(); + execute(&mut session, "layer.select", &json!({"layer": layer.0})).unwrap(); + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(4); + (h, layer) +} + +/// Centre of the content (`mask` false) or mask thumbnail of the top-level, non-folder row +/// labelled `name`: after the 7-point edge, the 20-point eye column, then 36-point squares 4 apart. +fn thumb(h: &Harness<'_, TextureCraftApp>, name: &str, mask: bool) -> egui::Pos2 { + let row = h.get_by_label(name).rect(); + let x = row.left() + 7.0 + 20.0 + 18.0 + if mask { 40.0 } else { 0.0 }; + egui::pos2(x, row.center().y) +} + +/// The `label` header that follows the "Masked fill" row (other layers have groups too). +fn header(h: &mut Harness<'_, TextureCraftApp>, label: &str) { + let top = h.get_by_label("Masked fill").rect().top(); + let at = h.get_all_by_label(label).map(|n| n.rect()).filter(|r| r.top() > top).min_by(|a, b| a.top().total_cmp(&b.top())).unwrap().center(); + click(h, at); +} + +fn click(h: &mut Harness<'_, TextureCraftApp>, at: egui::Pos2) { + h.drag_at(at); + h.drop_at(at); + h.run_steps(3); +} + +#[test] +fn mask_and_content_thumbnails_select_their_own_target() { + let (mut h, layer) = harness(); + let at = thumb(&h, "Masked fill", true); + click(&mut h, at); + assert_eq!(h.state().session.selected_layer(), Some(layer)); + assert_eq!(h.state().session.target, StackTarget::Mask, "the mask thumbnail routes to the mask"); + let at = thumb(&h, "Masked fill", false); + click(&mut h, at); + assert_eq!(h.state().session.target, StackTarget::Content, "the content thumbnail routes back"); + // Clicking an effect row still selects that effect. + let r = h.get_by_label("Effect A").rect(); + click(&mut h, egui::pos2(r.right() - 40.0, r.center().y)); + assert!(matches!(h.state().session.target, StackTarget::Effect(_))); +} + +#[test] +fn folding_an_effect_group_hides_its_rows_without_changing_the_document() { + let (mut h, _) = harness(); + let (project, undo) = (h.state().session.doc.project.clone(), h.state().session.revision); + assert!(h.query_by_label("Effect A").is_some() && h.query_by_label("Effect M").is_some()); + header(&mut h, "Content effects"); + assert!(h.query_by_label("Effect A").is_none(), "folded content effects are hidden"); + assert!(h.query_by_label("Effect M").is_some(), "the mask group stays open"); + header(&mut h, "Mask effects"); + assert!(h.query_by_label("Effect M").is_none()); + assert_eq!(h.state().session.doc.project, project); + assert_eq!(h.state().session.revision, undo, "folding is not an edit"); + header(&mut h, "Content effects"); + assert!(h.query_by_label("Effect A").is_some(), "unfolds again"); +} + +#[test] +fn visible_rows_get_their_thumbnails() { + let (mut h, layer) = harness(); + let content = ThumbTarget::Content { layer, channel: Channel::BaseColor }; + let mask = ThumbTarget::Mask { layer }; + let t0 = std::time::Instant::now(); + while !(h.state().layer_panel.service().is_fresh(content) && h.state().layer_panel.service().is_fresh(mask)) { + assert!(t0.elapsed().as_secs() < 60, "thumbnails never arrived"); + h.run_steps(1); + std::thread::sleep(std::time::Duration::from_millis(5)); + } + // Rows, mask, and every effect stage on screen were asked for: well under the cache size. + assert!(h.state().layer_panel.service().cached() >= 4); +} diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 0f42158f..f180af43 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -127,7 +127,40 @@ fn window_snapshots() { texturecraft_engine::execute(session, id, ¶ms).unwrap(); } save(&mut harness, &output_dir, "properties-levels"); - + // Show the Layers panel thumbnails with a hidden content effect, a folder and a mask + let session = &mut harness.state_mut().session; + for (id, params) in [ + ("effect.add.filter", serde_json::json!({"target": "content", "filter": "hsl"})), + ("effect.add.filter", serde_json::json!({"target": "content", "filter": "invert"})), + ("layer.add.paint", serde_json::Value::Null), + ("layer.group", serde_json::Value::Null), + ] { + texturecraft_engine::execute(session, id, ¶ms).unwrap(); + } + let hidden = harness + .state() + .session + .doc + .project + .layers + .values() + .flat_map(|layer| layer.content_effects.iter()) + .find(|effect| effect.name == "Invert") + .map(|effect| effect.id.0); + if let Some(effect) = hidden { + texturecraft_engine::execute(&mut harness.state_mut().session, "effect.set", &serde_json::json!({"effect": effect, "visible": false})).unwrap(); + } + harness.state_mut().ui.dock.focus(Panel::Layers); + harness.set_size(egui::vec2(1600.0, 1400.0)); + for _ in 0..400 { + harness.run_steps(1); + std::thread::sleep(std::time::Duration::from_millis(10)); + if !harness.state().layer_panel.service().busy() { + break; + } + } + save(&mut harness, &output_dir, "panel-layers"); + harness.set_size(egui::vec2(1600.0, 960.0)); // Show the second path selected in Properties let session = &mut harness.state_mut().session; for (id, params) in [ diff --git a/docs/architecture.md b/docs/architecture.md index 5eda226c..2756a942 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -69,6 +69,26 @@ The CPU compositor is the reference for everything users see and export. Export (`formats::export`) reads the same composite, adds height-to-normal (Sobel) combined with the normal channel and baked normals by reoriented normal mapping, and packs channels per preset. +### Layer-panel thumbnails + +The Layers panel shows each layer's content (in the displayed channel), its mask and every effect +stage as small pictures. `compose::thumb::render` runs the same compositor on a *cut* copy of the +project: the set's stack becomes the one layer, forced visible at Normal / 100 %, without its mask +for the content, and with its effect list truncated after the previewed effect (a hidden effect +shows the result it bypasses). Paint and fill layers are flattened to (value, coverage), so empty +texels are transparent; folders composite their children. Colors are encoded linear to sRGB, data +channels raw. Everything is evaluated on a 64 px G-buffer of the mesh (painted tiles are +resampled), never at the set's resolution, and the main composite is never touched. + +`engine::thumbs::ThumbService` runs it off the UI thread: an immutable `ThumbSnapshot` (the +project, copy-on-write pixel tiles, baked maps, images and the cached 64 px G-buffer) is rebuilt +only when the document really differs (compared at most every 120 ms while it keeps changing), a +worker thread renders one job at a time (inline, one per frame, on wasm32), results of an older +snapshot are dropped, and an LRU of 96 pictures keeps the out-of-date picture on screen until its +replacement arrives. Only rows on screen ask for pictures; queued rows that scrolled away are +dropped. On a 4096 set (`perf::bench_layer_thumbs_4k`) a snapshot costs 0.02 ms, a content picture +about 2.5 ms and a whole ten-layer panel (20 pictures) about 42 ms of worker time. + ## Undo `Session::edit` snapshots the `Document` (project + pixels + baked maps + resources) before a From d60fb856c900113f7245a7563d0a549c4e2a4ee6 Mon Sep 17 00:00:00 2001 From: MistyMystery Date: Wed, 4 Nov 2026 22:17:24 +0400 Subject: [PATCH 12/64] Live bake preview: the 3D view shows each mesh map as it finishes A bake started in the app bakes the set's maps one after another (BakeTask::run_streaming, one bake per map, same pixels as a single bake) and streams each finished map from the worker thread. One map is installed per UI poll into the session's bake preview (not the document); the 3D view follows the newest map raw on the model, with maps and sets not baked yet shown neutral, and the bake bar names the stage. The bake bar picks Follow Newest Map, a finished map or Material. The previous view mode comes back when the bake ends, is cancelled or Bake mode is left; painting is paused while a bake is shown. bake.preview, ui.bake.start and ui.bake.cancel expose it on the control channel. New strings are translated in every shipped language. --- crates/engine/src/bake/bake_task.rs | 61 ++++++- crates/engine/src/bake/mod.rs | 2 +- crates/engine/src/bake_preview.rs | 243 +++++++++++++++++++++++++++ crates/engine/src/commands.rs | 1 + crates/engine/src/inspect.rs | 1 + crates/engine/src/lib.rs | 4 +- crates/engine/src/painting.rs | 12 ++ crates/engine/src/session.rs | 3 + crates/engine/src/view_cmds.rs | 8 +- crates/engine/tests/bake_preview.rs | 183 ++++++++++++++++++++ crates/render/src/mesh_maps.rs | 13 ++ crates/ui-egui/src/bake_mode.rs | 43 +++++ crates/ui-egui/src/control.rs | 35 ++++ crates/ui-egui/src/gpu.rs | 15 +- crates/ui-egui/src/i18n/ar.rs | 11 ++ crates/ui-egui/src/i18n/de.rs | 11 ++ crates/ui-egui/src/i18n/es.rs | 11 ++ crates/ui-egui/src/i18n/fr.rs | 11 ++ crates/ui-egui/src/i18n/it.rs | 11 ++ crates/ui-egui/src/i18n/ja.rs | 11 ++ crates/ui-egui/src/i18n/ko.rs | 11 ++ crates/ui-egui/src/i18n/pt_br.rs | 11 ++ crates/ui-egui/src/i18n/zh_hans.rs | 8 + crates/ui-egui/src/lib.rs | 92 ++++++++-- crates/ui-egui/src/viewport.rs | 4 +- crates/ui-egui/tests/bake_preview.rs | 98 +++++++++++ docs/control-protocol.md | 36 +++- docs/features.md | 2 + 28 files changed, 931 insertions(+), 21 deletions(-) create mode 100644 crates/engine/src/bake_preview.rs create mode 100644 crates/engine/tests/bake_preview.rs create mode 100644 crates/ui-egui/tests/bake_preview.rs diff --git a/crates/engine/src/bake/bake_task.rs b/crates/engine/src/bake/bake_task.rs index 831a7abc..efe2a635 100644 --- a/crates/engine/src/bake/bake_task.rs +++ b/crates/engine/src/bake/bake_task.rs @@ -2,7 +2,7 @@ use super::MergedHigh; use crate::{EngineError, Result}; use std::sync::Arc; use texturecraft_bake::{BakeOutput, BakePaintMap, BakeRequest, HighPoly, Progress, bake, bake_on, tracing::Tracer}; -use texturecraft_core::BakeSettings; +use texturecraft_core::{BakeSettings, BakedMap}; use texturecraft_geom::{Bvh, Mesh}; /// A self-contained bake task that can run on another thread. @@ -24,8 +24,65 @@ pub struct BakeTask { pub tracer: Option>, } +/// One finished map of a streamed bake (see [`BakeTask::run_streaming`]). +#[derive(Clone, Debug)] +pub struct StreamedMap { + pub map: BakedMap, + /// Position among the maps this bake makes, from 0, and how many there are. + pub index: usize, + pub total: usize, + /// Width and height in texels. + pub resolution: u32, + pub height: u32, + /// Row-major, `map.components()` floats per texel, padded. + pub data: Arc>, +} + impl BakeTask { + /// The maps this task makes, in the order [`BakeTask::run_streaming`] finishes them. + pub fn maps(&self) -> Vec { + self.settings.maps.enabled().collect() + } + + /// Bake the maps one after another, handing each one to `on_map` as soon as it is padded, + /// and return all of them together. Each map is a bake of its own, so with a high poly + /// the transfer rays are cast once per map: slower than [`BakeTask::run`] with several + /// maps, in exchange for showing them as they land. The pixels are the same as `run`'s. + /// A cancel or an error leaves the maps already handed over whole. + pub fn run_streaming(&self, progress: &Progress, on_map: &mut dyn FnMut(StreamedMap)) -> Result { + let maps = self.maps(); + let total = maps.len(); + let mut combined: Option = None; + for (index, map) in maps.into_iter().enumerate() { + let mut settings = self.settings.clone(); + settings.maps.select([map]); + let mut output = self.run_with(&settings, progress)?; + let Some(data) = output.maps.remove(&map) else { continue }; + let data = Arc::new(data); + on_map(StreamedMap { map, index, total, resolution: output.resolution, height: output.height, data: data.clone() }); + let pixels = Arc::try_unwrap(data).unwrap_or_else(|shared| shared.as_ref().clone()); + match &mut combined { + Some(all) => { + all.maps.insert(map, pixels); + } + None => { + output.maps.clear(); + output.maps.insert(map, pixels); + combined = Some(output); + } + } + } + match combined { + Some(output) => Ok(output), + None => self.run(progress), + } + } + pub fn run(&self, progress: &Progress) -> Result { + self.run_with(&self.settings, progress) + } + + fn run_with(&self, settings: &BakeSettings, progress: &Progress) -> Result { let high = self.high.as_ref().map(|source| HighPoly { file_ids: &source.file_ids, mesh: &source.mesh, bvh: &source.bvh, base_color: &source.base_color }); let request = BakeRequest { @@ -33,7 +90,7 @@ impl BakeTask { mesh: &self.mesh, bvh: &self.bvh, material: self.material, - settings: &self.settings, + settings, high, cage: self.cage.as_deref(), skew: self.skew.as_deref(), diff --git a/crates/engine/src/bake/mod.rs b/crates/engine/src/bake/mod.rs index 075943b3..ef4cffcf 100644 --- a/crates/engine/src/bake/mod.rs +++ b/crates/engine/src/bake/mod.rs @@ -5,7 +5,7 @@ mod merged_high; pub use bake_mesh::BakeMesh; pub use bake_meshes::BakeMeshes; -pub use bake_task::BakeTask; +pub use bake_task::{BakeTask, StreamedMap}; pub use merged_high::MergedHigh; type MaterialColors = std::sync::Arc>>>; diff --git a/crates/engine/src/bake_preview.rs b/crates/engine/src/bake_preview.rs new file mode 100644 index 00000000..4ff8822c --- /dev/null +++ b/crates/engine/src/bake_preview.rs @@ -0,0 +1,243 @@ +//! Live bake preview: while the app bakes, the 3D view shows each mesh map on the model as soon +//! as it is finished ([`crate::BakeTask::run_streaming`]). The streamed maps live here, not in +//! the document: nothing enters the undo history until a texture set's bake is applied +//! ([`Session::apply_bake`]), and a cancelled bake leaves the document as it was. The preview +//! shows one map at a time, raw on the model; maps and texture sets not baked yet show their +//! neutral value. + +use std::collections::BTreeMap; + +use serde_json::{Value, json}; +use texturecraft_compose::BakedMaps; +use texturecraft_core::BakedMap; + +use crate::bake_data::StreamedMap; +use crate::commands::{CommandSpec, always, bad, strp}; +use crate::session::ViewMode; +use crate::{Result, Session, cmd}; + +/// What painting says while a bake preview shows (the app translates it). +pub const PAINTING_PAUSED: &str = "Painting is paused while a bake is shown. Cancel the bake or wait for it to finish."; + +pub fn specs() -> Vec { + vec![cmd!( + "bake.preview", + "Bake preview", + [], + None, + "{show?: \"follow\" (the newest finished map) | \"material\" | \"map:\" (pin a map)} → {active, show, shown, newest, stage, sets}. While the app bakes, the 3D view shows the maps as they finish; `show` picks what it shows. With no bake running {active: false} (setting `show` is then an error)", + always, + preview + )] +} + +/// What the 3D view shows while a bake runs. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PreviewShow { + /// The newest finished map (the first one, still neutral, before any is done). + Follow, + /// One map, pinned: neutral until it is baked. + Pin(BakedMap), + /// The lit material. + Material, +} + +impl PreviewShow { + pub fn id(self) -> String { + match self { + PreviewShow::Follow => "follow".into(), + PreviewShow::Pin(map) => format!("map:{}", map.id()), + PreviewShow::Material => "material".into(), + } + } + + pub fn parse(text: &str) -> Option { + match text { + "follow" => Some(PreviewShow::Follow), + "material" => Some(PreviewShow::Material), + _ => text.strip_prefix("map:").and_then(BakedMap::parse).map(PreviewShow::Pin), + } + } +} + +/// The maps of one texture set streamed so far. +#[derive(Clone, Debug, Default)] +pub struct PreviewSet { + pub baked: BakedMaps, + /// The maps this set's bake makes, in the order they arrive. + pub order: Vec, +} + +/// The map a bake is working on. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Stage { + pub texture_set: usize, + pub map: BakedMap, + /// 1-based position among the set's maps, and how many there are. + pub position: usize, + pub total: usize, +} + +#[derive(Clone, Debug)] +pub struct BakePreview { + /// The view mode to put back when the preview ends. + pub restore: ViewMode, + pub show: PreviewShow, + pub sets: BTreeMap, + /// The texture set being baked. + pub current: Option, + /// The last map that finished. + pub newest: Option, +} + +impl BakePreview { + /// The map the view shows, None for the material. + pub fn shown(&self) -> Option { + match self.show { + PreviewShow::Material => None, + PreviewShow::Pin(map) => Some(map), + PreviewShow::Follow => self + .newest + .or_else(|| self.current_set().and_then(|set| set.order.first().copied())) + .or_else(|| self.sets.values().find_map(|set| set.order.first().copied())), + } + } + + pub fn current_set(&self) -> Option<&PreviewSet> { + self.sets.get(&self.current?) + } + + /// The map being baked now (None between sets and once the set's maps are all in). + pub fn stage(&self) -> Option { + let texture_set = self.current?; + let set = self.sets.get(&texture_set)?; + let done = set.baked.maps.len(); + Some(Stage { texture_set, map: *set.order.get(done)?, position: done + 1, total: set.order.len() }) + } +} + +impl Session { + /// Start showing a bake of `sets` (each with the maps it makes, in order): the 3D view + /// follows the newest map and every set shows neutral values until its maps arrive. The + /// view mode in use comes back with [`Session::bake_preview_end`]. + pub fn bake_preview_begin(&mut self, sets: Vec<(usize, Vec)>) { + let restore = self.bake_preview.as_ref().map_or(self.view, |preview| preview.restore); + let sets = sets.into_iter().map(|(texture_set, order)| (texture_set, PreviewSet { baked: BakedMaps::default(), order })).collect(); + self.bake_preview = Some(BakePreview { restore, show: PreviewShow::Follow, sets, current: None, newest: None }); + self.bake_preview_refresh(); + } + + /// The texture set whose maps stream in now. + pub fn bake_preview_set_current(&mut self, texture_set: usize) { + if let Some(preview) = &mut self.bake_preview { + preview.current = Some(texture_set); + } + self.bake_preview_refresh(); + } + + /// Install one finished map of set `texture_set`. Returns false when no preview shows. + pub fn bake_preview_map(&mut self, texture_set: usize, streamed: StreamedMap) -> bool { + let Some(preview) = &mut self.bake_preview else { return false }; + let set = preview.sets.entry(texture_set).or_default(); + // A new bake of the set starts from nothing (the baker never repeats a map) + if streamed.index == 0 { + set.baked = BakedMaps::default(); + } + set.baked.resolution = streamed.resolution; + set.baked.maps.insert(streamed.map, streamed.data); + preview.newest = Some(streamed.map); + self.bake_preview_refresh(); + true + } + + /// Choose what the view shows (Follow, a pinned map or the material). + pub fn bake_preview_show(&mut self, show: PreviewShow) -> Result<()> { + let Some(preview) = &mut self.bake_preview else { return Err(bad("bake.preview", "no bake is running")) }; + preview.show = show; + self.bake_preview_refresh(); + Ok(()) + } + + /// The user picked a view mode during a bake: a mesh map pins it, any other mode shows + /// the material and is what comes back when the bake ends. + pub(crate) fn bake_preview_user_view(&mut self, view: ViewMode) { + let Some(preview) = &mut self.bake_preview else { return }; + match view { + ViewMode::MeshMap(map) => preview.show = PreviewShow::Pin(map), + other => { + preview.show = PreviewShow::Material; + preview.restore = other; + } + } + self.bake_preview_refresh(); + if !matches!(view, ViewMode::MeshMap(_)) { + self.view = view; + } + } + + /// The bake is over, cancelled or no longer shown: put the previous view mode back. + pub fn bake_preview_end(&mut self) { + if let Some(preview) = self.bake_preview.take() { + self.view = preview.restore; + self.revision = self.revision.wrapping_add(1); + } + } + + pub fn bake_preview_active(&self) -> bool { + self.bake_preview.is_some() + } + + /// The streamed maps of set `texture_set` while a preview shows (empty for a set not baked + /// yet: neutral values), None when the document's baked maps are what shows. + pub fn bake_preview_baked(&self, texture_set: usize) -> Option<&BakedMaps> { + self.bake_preview.as_ref()?.sets.get(&texture_set).map(|set| &set.baked) + } + + /// Why painting is not possible now, when a bake preview shows. + pub fn painting_blocked(&self) -> Option<&'static str> { + self.bake_preview.as_ref().map(|_| PAINTING_PAUSED) + } + + fn bake_preview_refresh(&mut self) { + let Some(preview) = &self.bake_preview else { return }; + self.view = match preview.shown() { + Some(map) => ViewMode::MeshMap(map), + None => ViewMode::Material, + }; + self.revision = self.revision.wrapping_add(1); + } +} + +/// The preview as JSON, for `bake.preview`, `session.inspect` and `ui.inspect`. +pub fn preview_json(session: &Session) -> Value { + let Some(preview) = &session.bake_preview else { return json!({ "active": false }) }; + let stage = preview.stage().map(|stage| json!({ "set": stage.texture_set, "map": stage.map.id(), "n": stage.position, "total": stage.total })); + let sets: Vec = preview + .sets + .iter() + .map(|(texture_set, set)| { + json!({ + "set": texture_set, + "order": set.order.iter().map(|map| map.id()).collect::>(), + "done": set.baked.maps.keys().map(|map| map.id()).collect::>(), + }) + }) + .collect(); + json!({ + "active": true, + "show": preview.show.id(), + "shown": preview.shown().map(|map| map.id()), + "newest": preview.newest.map(|map| map.id()), + "restore": preview.restore.label(), + "stage": stage, + "sets": sets, + }) +} + +fn preview(session: &mut Session, params: &Value) -> Result { + if let Some(show) = strp(params, "show") { + let show = PreviewShow::parse(show).ok_or_else(|| bad("bake.preview", format!("unknown `show` {show:?}: follow, material or map:")))?; + session.bake_preview_show(show)?; + } + Ok(preview_json(session)) +} diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 94bb350c..31d2f692 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -69,6 +69,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(crate::template_cmds::specs()); v.extend(crate::project_cmds::specs()); v.extend(crate::bake_cmds::specs()); + v.extend(crate::bake_preview::specs()); v.extend(crate::bake_paint_cmds::specs()); v.extend(crate::materialx_cmds::specs()); v.extend(crate::file_cmds::specs()); diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 228d37e1..5f40a62c 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -168,6 +168,7 @@ pub fn session(s: &Session) -> Value { "layers": stack(s, ts), "tool": { "tool": s.tool.tool.id(), "brush": crate::tool_cmds::brush_json(s) }, "view": s.view.label(), + "bakePreview": crate::bake_preview::preview_json(s), "camera": crate::view_cmds::camera_json(s), "display": s.doc.project.display, "history": { "undo": s.undo_label(), "redo": s.redo_label(), "depth": s.history_labels().len() }, diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index ed07d645..9478de8f 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -12,6 +12,7 @@ pub mod bake_cmds; #[path = "bake/mod.rs"] mod bake_data; mod bake_paint_cmds; +pub mod bake_preview; pub mod brush_preset_cmds; pub mod camera_cmds; pub mod commands; @@ -48,7 +49,8 @@ pub mod tool_cmds; pub mod uv_tile_cmds; pub mod view_cmds; -pub use bake_data::{BakeMesh, BakeMeshes, BakeTask}; +pub use bake_data::{BakeMesh, BakeMeshes, BakeTask, StreamedMap}; +pub use bake_preview::{BakePreview, PreviewShow}; pub use commands::{CommandSpec, command_specs, execute, find}; pub use path_tool::PathState; pub use project_cmds::sample_session; diff --git a/crates/engine/src/painting.rs b/crates/engine/src/painting.rs index de132ffd..f4e93f40 100644 --- a/crates/engine/src/painting.rs +++ b/crates/engine/src/painting.rs @@ -135,6 +135,7 @@ impl Session { /// Common setup of 3D and 2D strokes. `first_uv` is where the stroke starts on the mesh /// (the Clone tool's destination anchor). fn start_stroke(&mut self, viewport: Vec2, uv_mode: bool, first_uv: Option) -> Result<()> { + self.refuse_while_baking()?; let tool = self.tool.tool; let erase = tool == Tool::Eraser; let quick_mask = self.quick_mask.editing; @@ -276,9 +277,18 @@ impl Session { Some(texturecraft_compose::Stencil { image, view_proj: self.camera.view_proj(aspect), center, half, rotation, tile: st.tile }) } + /// Painting is paused while a bake preview shows the baked maps instead of the material. + fn refuse_while_baking(&self) -> Result<()> { + match self.painting_blocked() { + Some(why) => Err(EngineError::Other(why.into())), + None => Ok(()), + } + } + /// Start a stroke at `screen` (viewport pixels). Returns false when the cursor misses the /// mesh (the stroke starts anyway and resumes when the cursor enters the mesh). pub fn begin_stroke(&mut self, screen: Vec2, viewport: Vec2, pressure: f32) -> Result { + self.refuse_while_baking()?; self.cancel_stroke(); match self.tool.tool { Tool::PolygonFill => return self.polygon_fill(screen, viewport).map(|_| true), @@ -293,6 +303,7 @@ impl Session { /// Start a stroke in the 2D view at texture coordinate `uv`. pub fn begin_stroke_uv(&mut self, uv: Vec2, pressure: f32) -> Result<()> { + self.refuse_while_baking()?; self.cancel_stroke(); if matches!(self.tool.tool, Tool::PolygonFill | Tool::ColorPicker | Tool::GeometryMask) { return Err(EngineError::Other("use this tool in the 3D view".into())); @@ -474,6 +485,7 @@ impl Session { /// Polygon fill: fill the triangle / UV island / whole mesh under `screen`. pub fn polygon_fill(&mut self, screen: Vec2, viewport: Vec2) -> Result { + self.refuse_while_baking()?; let hit = self.pick(screen, viewport).ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?; let ts = self.ts(); let material = self.doc.project.texture_set(ts)?.material; diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 7ec12739..31cd5519 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -334,6 +334,8 @@ pub struct Session { pub target: StackTarget, pub camera: OrbitCamera, pub view: ViewMode, + /// The live bake preview while the app bakes (see [`crate::bake_preview`]). + pub bake_preview: Option, /// Viewport size (pixels) used by scripted strokes. pub viewport: Vec2, pub(crate) stroke: Option, @@ -393,6 +395,7 @@ impl Session { target: StackTarget::Content, camera, view: ViewMode::Material, + bake_preview: None, viewport: Vec2::new(1280.0, 800.0), stroke: None, clipboard: None, diff --git a/crates/engine/src/view_cmds.rs b/crates/engine/src/view_cmds.rs index b39c876d..9fb03ecf 100644 --- a/crates/engine/src/view_cmds.rs +++ b/crates/engine/src/view_cmds.rs @@ -88,7 +88,13 @@ fn frame(s: &mut Session, _: &Value) -> Result { } fn set_view(s: &mut Session, v: ViewMode) -> Result { - s.view = v; + if s.bake_preview.is_some() { + // During a bake the view follows the preview: a mesh map pins it, another mode comes back afterwards + s.bake_preview_user_view(v); + } else { + s.view = v; + } + let v = s.view; s.revision = s.revision.wrapping_add(1); Ok(json!({ "view": v.label() })) } diff --git a/crates/engine/tests/bake_preview.rs b/crates/engine/tests/bake_preview.rs new file mode 100644 index 00000000..b2330721 --- /dev/null +++ b/crates/engine/tests/bake_preview.rs @@ -0,0 +1,183 @@ +//! Live bake preview: maps stream into the view while a bake runs, the view mode comes back, +//! painting is paused, a cancelled bake leaves the document alone, and the streamed pixels are +//! the ones a single bake makes. + +use serde_json::{Value, json}; +use texturecraft_engine::bake::Progress; +use texturecraft_engine::core::{BakeResolution, BakedMap, Channel}; +use texturecraft_engine::geom::glam::Vec2; +use texturecraft_engine::{BakeTask, PreviewShow, Session, ViewMode, execute}; + +const MAPS: [BakedMap; 4] = [BakedMap::Id, BakedMap::AmbientOcclusion, BakedMap::Curvature, BakedMap::Height]; + +fn session() -> Session { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + for texture_set in &mut session.doc.project.texture_sets { + texture_set.bake = Default::default(); + texture_set.bake.common.resolution = BakeResolution::R64; + texture_set.bake.maps.ao.parameters.rays.rays = 8; + texture_set.bake.maps.select(MAPS); + } + session +} + +fn task(session: &Session) -> BakeTask { + let mut task = session.bake_task(0).unwrap(); + task.tracer = None; + task +} + +fn order(session: &Session) -> Vec { + task(session).maps() +} + +#[test] +fn streamed_maps_are_the_pixels_of_one_bake() { + let session = session(); + let task = task(&session); + let whole = task.run(&Progress::new()).unwrap(); + let mut streamed = Vec::new(); + let combined = task.run_streaming(&Progress::new(), &mut |map| streamed.push(map)).unwrap(); + assert_eq!(streamed.iter().map(|map| map.map).collect::>(), order(&session)); + assert_eq!(streamed.iter().map(|map| (map.index, map.total)).collect::>(), (0..MAPS.len()).map(|index| (index, MAPS.len())).collect::>()); + assert_eq!((combined.resolution, combined.height), (whole.resolution, whole.height)); + assert_eq!(combined.maps.keys().collect::>(), whole.maps.keys().collect::>()); + for (map, pixels) in &whole.maps { + assert!(combined.maps[map] == *pixels, "{map:?} differs between a streamed and a single bake"); + } + for map in &streamed { + assert!(*map.data == whole.maps[&map.map], "{:?} handed over differs from the bake", map.map); + } +} + +#[test] +fn the_view_follows_each_map_and_the_previous_mode_comes_back() { + let mut session = session(); + session.view = ViewMode::Channel(Channel::Roughness); + let before = session.view; + let baked_before = session.doc.baked.get(&0).cloned(); + let maps = order(&session); + session.bake_preview_begin(vec![(0, maps.clone())]); + session.bake_preview_set_current(0); + // Nothing is baked yet: the first map shows, neutral + assert_eq!(session.view, ViewMode::MeshMap(maps[0])); + assert!(session.bake_preview_baked(0).is_some_and(|baked| baked.maps.is_empty())); + + let task = task(&session); + let mut shown = Vec::new(); + let mut stages = Vec::new(); + let output = task + .run_streaming(&Progress::new(), &mut |map| { + session.bake_preview_map(0, map); + shown.push(session.view); + stages.push(session.bake_preview.as_ref().and_then(|preview| preview.stage()).map(|stage| (stage.position, stage.total))); + }) + .unwrap(); + assert_eq!(shown, maps.iter().map(|map| ViewMode::MeshMap(*map)).collect::>(), "the view follows the newest map"); + assert_eq!(stages, [Some((2, 4)), Some((3, 4)), Some((4, 4)), None], "the stage names the next map"); + assert_eq!(session.doc.baked.get(&0).cloned(), baked_before, "the document is untouched until the bake is applied"); + let undo_before = session.undo_label().map(str::to_owned); + + session.apply_bake(0, output).unwrap(); + assert_ne!(session.undo_label().map(str::to_owned), undo_before, "applying the bake is one undo step"); + session.bake_preview_end(); + assert_eq!(session.view, before, "the previous view mode is restored"); + assert!(!session.bake_preview_active()); + assert!(maps.iter().all(|map| session.doc.baked[&0].maps.contains_key(map))); +} + +#[test] +fn pinning_material_and_follow() { + let mut session = session(); + let maps = order(&session); + session.bake_preview_begin(vec![(0, maps.clone())]); + session.bake_preview_set_current(0); + let task = task(&session); + let mut count = 0; + task.run_streaming(&Progress::new(), &mut |map| { + session.bake_preview_map(0, map); + count += 1; + match count { + // Pin the finished map: later maps do not take the view + 1 => session.bake_preview_show(PreviewShow::Pin(maps[0])).unwrap(), + 2 => { + assert_eq!(session.view, ViewMode::MeshMap(maps[0])); + session.bake_preview_show(PreviewShow::Material).unwrap(); + } + 3 => { + assert_eq!(session.view, ViewMode::Material); + session.bake_preview_show(PreviewShow::Follow).unwrap(); + assert_eq!(session.view, ViewMode::MeshMap(maps[2])); + } + _ => {} + } + }) + .unwrap(); + // A mesh map picked in the viewport pins it; another mode is what comes back at the end + execute(&mut session, "viewport.view", &json!({ "mode": "map:height" })).unwrap(); + assert_eq!(session.bake_preview.as_ref().map(|preview| preview.show), Some(PreviewShow::Pin(BakedMap::Height))); + execute(&mut session, "viewport.view", &json!({ "mode": "uvChecker" })).unwrap(); + assert_eq!(session.view, ViewMode::UvChecker); + session.bake_preview_end(); + assert_eq!(session.view, ViewMode::UvChecker); +} + +#[test] +fn unbaked_sets_show_neutral_and_the_control_command_reports() { + let mut session = session(); + assert_eq!(execute(&mut session, "bake.preview", &Value::Null).unwrap()["active"], false); + assert!(execute(&mut session, "bake.preview", &json!({ "show": "material" })).is_err(), "nothing to show when no bake runs"); + session.bake_preview_begin(vec![(0, order(&session)), (1, order(&session))]); + session.bake_preview_set_current(0); + assert!(session.bake_preview_baked(1).is_some_and(|baked| baked.maps.is_empty()), "a queued set has nothing yet"); + assert!(session.bake_preview_baked(7).is_none(), "a set outside the bake shows its document maps"); + let reply = execute(&mut session, "bake.preview", &json!({ "show": "map:ambientOcclusion" })).unwrap(); + assert_eq!( + (reply["active"].clone(), reply["show"].clone(), reply["shown"].clone()), + (json!(true), json!("map:ambientOcclusion"), json!("ambientOcclusion")) + ); + assert!(execute(&mut session, "bake.preview", &json!({ "show": "nonsense" })).is_err()); + assert_eq!(texturecraft_engine::inspect::session(&session)["bakePreview"]["active"], true); +} + +#[test] +fn painting_is_refused_while_a_bake_shows() { + let mut session = session(); + session.bake_preview_begin(vec![(0, order(&session))]); + let error = session.begin_stroke(Vec2::new(10.0, 10.0), Vec2::new(100.0, 100.0), 1.0).unwrap_err().to_string(); + assert_eq!(error, texturecraft_engine::bake_preview::PAINTING_PAUSED); + assert!(session.begin_stroke_uv(Vec2::new(0.5, 0.5), 1.0).is_err()); + assert!(session.polygon_fill(Vec2::new(10.0, 10.0), Vec2::new(100.0, 100.0)).is_err()); + assert!(!session.stroke_active()); + session.bake_preview_end(); + assert!(session.painting_blocked().is_none()); +} + +#[test] +fn cancelling_mid_bake_leaves_the_document_and_the_shown_maps_whole() { + let mut session = session(); + let before = session.doc.baked.get(&0).cloned(); + let maps = order(&session); + let full = task(&session).run(&Progress::new()).unwrap(); + session.bake_preview_begin(vec![(0, maps.clone())]); + session.bake_preview_set_current(0); + let progress = Progress::new(); + let task = task(&session); + let result = task.run_streaming(&progress, &mut |map| { + if map.index == 1 { + progress.cancel(); + } + session.bake_preview_map(0, map); + }); + assert!(result.is_err(), "a cancelled bake fails"); + // The two maps that landed are whole and equal to a full bake's; the others are still neutral + let shown = session.bake_preview_baked(0).unwrap(); + assert_eq!(shown.maps.len(), 2); + for (map, data) in &shown.maps { + assert!(**data == full.maps[map], "{map:?}"); + } + // What the app does on cancel: end the preview; the document keeps what it had + session.bake_preview_end(); + assert_eq!(session.doc.baked.get(&0).cloned(), before); + assert!(session.bake_preview_baked(0).is_none()); +} diff --git a/crates/render/src/mesh_maps.rs b/crates/render/src/mesh_maps.rs index bf811478..8c246ee6 100644 --- a/crates/render/src/mesh_maps.rs +++ b/crates/render/src/mesh_maps.rs @@ -25,3 +25,16 @@ pub fn mesh_map_rgba(baked: Option<&BakedMaps>, m: BakedMap, size: u32) -> Vec 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 { + out.extend_from_slice(&[pixel[0], pixel[1], pixel[2], 255]); + } + out +} diff --git a/crates/ui-egui/src/bake_mode.rs b/crates/ui-egui/src/bake_mode.rs index c0397a49..dd47102a 100644 --- a/crates/ui-egui/src/bake_mode.rs +++ b/crates/ui-egui/src/bake_mode.rs @@ -61,16 +61,59 @@ fn edit_settings(app: &mut TextureCraftApp, ui: &mut Ui, scroll_id: &str, conten } } +/// What the 3D view shows while a bake runs: the newest finished map, one finished map or the material +fn preview_control(app: &mut TextureCraftApp, ui: &mut Ui) { + use texturecraft_engine::PreviewShow; + let Some(preview) = app.session.bake_preview.as_ref() else { return }; + let show = preview.show; + // Finished maps of the set baking now can be pinned; the others are still neutral + let rows: Vec<(BakedMap, bool)> = + preview.current_set().map(|set| set.order.iter().map(|&map| (map, set.baked.maps.contains_key(&map))).collect()).unwrap_or_default(); + let text = match show { + PreviewShow::Follow => tr("Follow Newest Map").to_owned(), + PreviewShow::Material => tr("Material").to_owned(), + PreviewShow::Pin(map) => trf("Mesh map: {map}", &[("map", &tr(crate::i18n::baked_map_label(map)))]), + }; + let mut choice = None; + egui::ComboBox::from_id_salt("bake_preview_show") + .selected_text(text) + .show_ui(ui, |ui| { + if ui.selectable_label(show == PreviewShow::Follow, tr("Follow Newest Map")).clicked() { + choice = Some(PreviewShow::Follow); + } + for (map, done) in rows { + let label = trf("Mesh map: {map}", &[("map", &tr(crate::i18n::baked_map_label(map)))]); + if ui.add_enabled(done, egui::Button::selectable(show == PreviewShow::Pin(map), label)).clicked() { + choice = Some(PreviewShow::Pin(map)); + } + } + if ui.selectable_label(show == PreviewShow::Material, tr("Material")).clicked() { + choice = Some(PreviewShow::Material); + } + }) + .response + .on_hover_text(tr( + "What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.", + )); + if let Some(show) = choice { + app.run("bake.preview", json!({ "show": show.id() })); + } +} + pub(crate) fn bake_bar(app: &mut TextureCraftApp, ctx: &egui::Context, viewport: egui::Rect) { egui::Area::new(egui::Id::unique("bake_bar")).constrain_to(viewport).anchor(egui::Align2::CENTER_BOTTOM, vec2(0.0, -16.0)).default_width(0.0).show( ctx, |ui| { + if let Some(status) = app.bake_status() { + ui.vertical_centered(|ui| ui.label(egui::RichText::new(status).strong())); + } ui.horizontal(|ui| { if let Some(progress) = app.bake_progress() { ui.add(egui::ProgressBar::new(progress).desired_width(220.0).show_percentage()); if ui.button(tr("Cancel")).clicked() { app.cancel_bake(); } + preview_control(app, ui); } else { let texture_sets: Vec = app .session diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 167b9754..fa73e485 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -110,9 +110,44 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, p: & "uiMs": app.ui_ms, "titleBar": app.title_bar.name(), "baking": app.bake_progress(), + "bakeStatus": app.bake_status(), + "bakePreview": texturecraft_engine::bake_preview::preview_json(&app.session), "toasts": app.toasts.iter().map(|t| json!({"text": t.text, "error": t.error})).collect::>(), })) } + "ui.bake.start" => { + // Bake in the background like the Bake button: the 3D view shows the maps as they finish + let count = app.session.doc.project.texture_sets.len(); + let sets: Vec = match p.get("ts") { + Some(value) => match serde_json::from_value::>(if value.is_array() { value.clone() } else { json!([value]) }) { + Ok(list) if list.iter().all(|&index| index < count) => list, + _ => return err(format!("`ts` must be texture set indices below {count}")), + }, + None => app + .session + .doc + .project + .texture_sets + .iter() + .enumerate() + .filter(|(_, texture_set)| texture_set.bake.common.is_enabled) + .map(|(index, _)| index) + .collect(), + }; + if app.bake.is_some() { + return err("a bake is already running"); + } + if sets.is_empty() { + return err("no texture set to bake: tick one in Bake mode or pass `ts`"); + } + app.ui.mode = crate::state::Mode::Baking; + app.start_bake(sets); + ok(texturecraft_engine::bake_preview::preview_json(&app.session)) + } + "ui.bake.cancel" => { + app.cancel_bake(); + ok(Value::Null) + } "ui.menu.list" => ok(json!( crate::menus::CATALOG .iter() diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index 77db5727..d33cfad5 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -211,13 +211,22 @@ impl GpuLink { match aux_map { Some(AuxView::MeshMap(m)) => { for ts in 0..s.caches.len() { - let rev = s.doc.baked.get(&ts).and_then(|b| b.maps.get(&m)).map(|d| Arc::as_ptr(d) as u64).unwrap_or(0); - let key = (format!("{m:?}"), rev); + // While a bake shows, its streamed maps (neutral where not baked yet) replace the document's + let preview = s.bake_preview_baked(ts); + let baked = preview.or_else(|| s.doc.baked.get(&ts)); + let have = baked.and_then(|b| b.maps.get(&m)); + let rev = have.map(|d| Arc::as_ptr(d) as u64).unwrap_or(0); + let key = (format!("{m:?}{}", if preview.is_some() { "~" } else { "" }), rev); if self.aux.get(&ts) == Some(&key) { continue; } let res = s.caches.get(ts).map_or(1024, |c| texturecraft_render::aux_size(c.size)); - out.aux.push((ts, res, texturecraft_render::mesh_maps::mesh_map_rgba(s.doc.baked.get(&ts), m, res))); + let rgba = if preview.is_some() && have.is_none() { + texturecraft_render::mesh_maps::neutral_rgba(m, res) + } else { + texturecraft_render::mesh_maps::mesh_map_rgba(baked, m, res) + }; + out.aux.push((ts, res, rgba)); self.aux.insert(ts, key); } } diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 6ef517e9..8d49896a 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1,6 +1,17 @@ //! Arabic UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ("Baking {map} ({n}/{total})", "جارٍ خبز {map} ({n}/{total})"), + ("Baking {map} ({n}/{total}), texture set {set} of {sets}", "جارٍ خبز {map} ({n}/{total})، مجموعة الخامات {set} من {sets}"), + ("Follow Newest Map", "تتبّع أحدث خريطة"), + ( + "Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.", + "الرسم متوقف مؤقتًا أثناء عرض عملية الخبز. ألغِ الخبز أو انتظر حتى ينتهي.", + ), + ( + "What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.", + "ما يعرضه العرض ثلاثي الأبعاد أثناء الخبز: أحدث خريطة مكتملة، أو أي خريطة مكتملة تختارها، أو الخامة. الخرائط التي لم تُخبز بعد تعرض قيمة محايدة.", + ), ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "لا يوجد رسم على \"{layer}\" بعد: يغيّر المرشح ما ترسمه عليها."), ("0 turns autosave off. Copies go to {folder}", "0 يعطل الحفظ التلقائي. تُحفظ النُسخ في {folder}"), ("2D view only", "عرض ثنائي الأبعاد فقط"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index caaabb14..0272179e 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1,6 +1,17 @@ //! German UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ("Baking {map} ({n}/{total})", "{map} wird gebacken ({n}/{total})"), + ("Baking {map} ({n}/{total}), texture set {set} of {sets}", "{map} wird gebacken ({n}/{total}), Texturset {set} von {sets}"), + ("Follow Newest Map", "Neueste Map verfolgen"), + ( + "Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.", + "Das Malen ist pausiert, solange ein Bake angezeigt wird. Brich den Bake ab oder warte, bis er fertig ist.", + ), + ( + "What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.", + "Was die 3D-Ansicht während des Backens zeigt: die zuletzt fertige Map, eine fertige Map deiner Wahl oder das Material. Noch nicht gebackene Maps zeigen einen neutralen Wert.", + ), ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" ist noch nicht bemalt: Der Filter verändert, was du darauf malst."), ("0 turns autosave off. Copies go to {folder}", "0 deaktiviert die automatische Speicherung. Kopien werden in {folder} abgelegt"), ("2D view only", "Nur 2D-Ansicht"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 6c8ccccb..c1b91d79 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1,6 +1,17 @@ //! Spanish UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ("Baking {map} ({n}/{total})", "Horneando {map} ({n}/{total})"), + ("Baking {map} ({n}/{total}), texture set {set} of {sets}", "Horneando {map} ({n}/{total}), conjunto de texturas {set} de {sets}"), + ("Follow Newest Map", "Seguir el mapa más reciente"), + ( + "Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.", + "La pintura está en pausa mientras se muestra un horneado. Cancela el horneado o espera a que termine.", + ), + ( + "What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.", + "Lo que muestra la vista 3D mientras se hornea: el último mapa terminado, un mapa terminado a elección o el material. Los mapas aún sin hornear muestran un valor neutro.", + ), ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" aún no tiene pintura: el filtro cambia lo que pintes en ella."), ("0 turns autosave off. Copies go to {folder}", "0 desactiva el autoguardado. Las copias se guardan en {folder}"), ("2D view only", "Solo vista 2D"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index f10bba8d..e47e5c17 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1,6 +1,17 @@ //! French UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ("Baking {map} ({n}/{total})", "Cuisson de {map} ({n}/{total})"), + ("Baking {map} ({n}/{total}), texture set {set} of {sets}", "Cuisson de {map} ({n}/{total}), jeu de textures {set} sur {sets}"), + ("Follow Newest Map", "Suivre la dernière carte"), + ( + "Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.", + "La peinture est suspendue tant qu'une cuisson est affichée. Annulez la cuisson ou attendez qu'elle se termine.", + ), + ( + "What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.", + "Ce que la vue 3D affiche pendant la cuisson : la dernière carte terminée, une carte terminée au choix ou le matériau. Les cartes pas encore cuites affichent une valeur neutre.", + ), ( "\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" n'a pas encore de peinture : le filtre modifie ce que vous y peignez.", diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 1c19d597..f851dfc5 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1,6 +1,17 @@ //! Italian UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ("Baking {map} ({n}/{total})", "Bake di {map} in corso ({n}/{total})"), + ("Baking {map} ({n}/{total}), texture set {set} of {sets}", "Bake di {map} in corso ({n}/{total}), set di texture {set} di {sets}"), + ("Follow Newest Map", "Segui la mappa più recente"), + ( + "Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.", + "La pittura è in pausa finché viene mostrato un bake. Annulla il bake o attendi che finisca.", + ), + ( + "What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.", + "Cosa mostra la vista 3D durante il bake: l'ultima mappa completata, una mappa completata a scelta o il materiale. Le mappe non ancora create mostrano un valore neutro.", + ), ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" non è ancora dipinto: il filtro modifica ciò che vi dipingi."), ("0 turns autosave off. Copies go to {folder}", "0 disattiva il salvataggio automatico. Le copie vengono salvate in {folder}"), ("2D view only", "Solo vista 2D"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 068603b5..b190dc04 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1,6 +1,17 @@ //! Japanese UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ("Baking {map} ({n}/{total})", "{map} をベイク中 ({n}/{total})"), + ("Baking {map} ({n}/{total}), texture set {set} of {sets}", "{map} をベイク中 ({n}/{total})、テクスチャセット {set}/{sets}"), + ("Follow Newest Map", "最新のマップを追う"), + ( + "Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.", + "ベイクの表示中はペイントを一時停止しています。ベイクをキャンセルするか、終わるまでお待ちください。", + ), + ( + "What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.", + "ベイク中に3Dビューが表示するもの:最後に完成したマップ、完成済みの好きなマップ、またはマテリアル。まだベイクされていないマップは中立値で表示されます。", + ), ( "\"{layer}\" has no paint yet: the filter changes what you paint on it.", "「{layer}」にはまだペイントがありません:フィルターはこのレイヤーにペイントした内容を変化させます。", diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 137d6177..d9d1fcda 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1,6 +1,17 @@ //! Korean UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ("Baking {map} ({n}/{total})", "{map} 베이크 중 ({n}/{total})"), + ("Baking {map} ({n}/{total}), texture set {set} of {sets}", "{map} 베이크 중 ({n}/{total}), 텍스처 세트 {set}/{sets}"), + ("Follow Newest Map", "최신 맵 따라가기"), + ( + "Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.", + "베이크를 표시하는 동안에는 페인팅이 일시 중지됩니다. 베이크를 취소하거나 끝날 때까지 기다리세요.", + ), + ( + "What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.", + "베이크하는 동안 3D 뷰가 보여 주는 것: 가장 최근에 완료된 맵, 완료된 맵 중 선택한 하나, 또는 머티리얼. 아직 베이크되지 않은 맵은 중립 값으로 표시됩니다.", + ), ( "\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\"에 아직 페인트가 없습니다: 필터는 이 레이어에 칠하는 내용을 바꿉니다.", diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 99627b25..ae44b364 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1,6 +1,17 @@ //! Brazilian Portuguese UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ("Baking {map} ({n}/{total})", "Fazendo o bake de {map} ({n}/{total})"), + ("Baking {map} ({n}/{total}), texture set {set} of {sets}", "Fazendo o bake de {map} ({n}/{total}), conjunto de texturas {set} de {sets}"), + ("Follow Newest Map", "Seguir o mapa mais recente"), + ( + "Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.", + "A pintura fica em pausa enquanto um bake é exibido. Cancele o bake ou espere ele terminar.", + ), + ( + "What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.", + "O que a vista 3D mostra durante o bake: o último mapa concluído, um mapa concluído à escolha ou o material. Mapas ainda não gerados mostram um valor neutro.", + ), ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "\"{layer}\" ainda não tem pintura: o filtro altera o que você pintar nela."), ("0 turns autosave off. Copies go to {folder}", "0 desativa o salvamento automático. As cópias vão para {folder}"), ("2D view only", "Apenas vista 2D"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 18623ce3..552242b4 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1,6 +1,14 @@ //! Simplified Chinese UI text: (English key, translation). Keys are the English strings passed to `tr`. pub const TABLE: &[(&str, &str)] = &[ + ("Baking {map} ({n}/{total})", "正在烘焙{map} ({n}/{total})"), + ("Baking {map} ({n}/{total}), texture set {set} of {sets}", "正在烘焙{map} ({n}/{total}),纹理集 {set}/{sets}"), + ("Follow Newest Map", "跟随最新贴图"), + ("Painting is paused while a bake is shown. Cancel the bake or wait for it to finish.", "显示烘焙时已暂停绘制。请取消烘焙,或等待其完成。"), + ( + "What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.", + "烘焙过程中 3D 视图显示的内容:最新完成的贴图、任意已完成的贴图,或材质。尚未烘焙的贴图显示中性值。", + ), ("\"{layer}\" has no paint yet: the filter changes what you paint on it.", "“{layer}”尚未绘制:滤镜会改变你在其上绘制的内容。"), ("0 turns autosave off. Copies go to {folder}", "设为 0 可关闭自动保存。副本保存到 {folder}"), ("2D view only", "仅 2D 视图"), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 8bfc66c9..b4ed93d0 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -47,10 +47,22 @@ pub struct ResizeJob { pub rx: std::sync::mpsc::Receiver>, } +/// The texture set baking on a worker thread: its progress, its result and the maps it finishes +/// on the way (the 3D view shows one per UI poll). +pub struct RunningBake { + pub set_index: usize, + pub progress: Arc, + pub receiver: std::sync::mpsc::Receiver>, + pub maps: std::sync::mpsc::Receiver, + /// Maps finished so far, and how many the set makes. + pub maps_done: Arc, + pub maps_total: usize, +} + /// A background bake of one or more texture sets. pub struct BakeJob { pub queue: Vec, - pub current: Option<(usize, Arc, std::sync::mpsc::Receiver>)>, + pub current: Option, pub total: usize, } @@ -62,6 +74,9 @@ pub struct LinkCook { pub rx: std::sync::mpsc::Receiver>>, } +/// The engine's refusal to paint while a bake shows (translated where it is toasted). +pub const PAINTING_PAUSED: &str = i18n::n_("Painting is paused while a bake is shown. Cancel the bake or wait for it to finish."); + /// The browser build's notice when WebGPU is unavailable and wgpu fell back to WebGL2. pub const WEBGL_NOTICE: &str = i18n::n_( "WebGPU isn't available in this browser, so TextureCraft runs on WebGL2: Rendering mode path traces on the CPU (slower) and large texture sets show at reduced resolution. A current Chrome, Edge or Safari has WebGPU.", @@ -208,6 +223,16 @@ impl TextureCraftApp { return; } let total = sets.len(); + // The 3D view shows the maps landing on the model while they bake + let orders = sets + .iter() + .map(|&set_index| { + let maps = + self.session.doc.project.texture_sets.get(set_index).map(|texture_set| texture_set.bake.maps.enabled().collect()).unwrap_or_default(); + (set_index, maps) + }) + .collect(); + self.session.bake_preview_begin(orders); self.bake = Some(BakeJob { queue: sets, current: None, total }); } @@ -261,13 +286,27 @@ impl TextureCraftApp { } fn poll_bake(&mut self, ctx: &egui::Context) { - let Some(job) = self.bake.as_mut() else { return }; + // Leaving Bake mode puts the view mode back; the bake goes on + if self.session.bake_preview_active() && self.ui.mode != state::Mode::Baking { + self.session.bake_preview_end(); + } + let Some(job) = self.bake.as_mut() else { + // A preview whose bake is gone must not keep the view + self.session.bake_preview_end(); + return; + }; ctx.request_repaint_after(std::time::Duration::from_millis(50)); - if let Some((set_index, _, receiver)) = &job.current { - match receiver.try_recv() { + if let Some(running) = &job.current { + let set_index = running.set_index; + // One streamed map per poll, so each lands on the model in its own frame. The worker + // sends every map before its result, so the last map shows before the bake is applied + if let Ok(map) = running.maps.try_recv() { + self.session.bake_preview_map(set_index, map); + return; + } + match running.receiver.try_recv() { Ok(Ok(output)) => { - let set_index = *set_index; job.current = None; if let Err(error) = self.session.apply_bake(set_index, output) { self.toast(error.to_string(), true); @@ -290,17 +329,28 @@ impl TextureCraftApp { if job.queue.is_empty() { self.bake = None; + self.session.bake_preview_end(); self.toast(i18n::tr("Mesh maps baked"), false); return; } let set_index = job.queue.remove(0); + self.session.bake_preview_set_current(set_index); match self.session.bake_task(set_index) { Ok(task) => { let progress = Arc::new(Progress::new()); let worker_progress = progress.clone(); - let receiver = spawn_worker("texturecraft-bake", move || task.run(&worker_progress)); + let maps_total = task.maps().len(); + let maps_done = Arc::new(std::sync::atomic::AtomicUsize::new(0)); + let worker_done = maps_done.clone(); + let (sender, maps) = std::sync::mpsc::channel(); + let receiver = spawn_worker("texturecraft-bake", move || { + task.run_streaming(&worker_progress, &mut |map| { + worker_done.fetch_add(1, Ordering::Relaxed); + let _ = sender.send(map); + }) + }); if let Some(job) = self.bake.as_mut() { - job.current = Some((set_index, progress, receiver)); + job.current = Some(RunningBake { set_index, progress, receiver, maps, maps_done, maps_total }); } } Err(error) => self.toast(error.to_string(), true), @@ -311,9 +361,11 @@ impl TextureCraftApp { pub fn cancel_bake(&mut self) { let Some(job) = self.bake.take() else { return }; - if let Some((_, progress, _)) = job.current { - progress.cancel.store(true, Ordering::Relaxed); + if let Some(running) = job.current { + running.progress.cancel.store(true, Ordering::Relaxed); } + // The streamed maps were only shown: the document keeps the maps it had + self.session.bake_preview_end(); } /// Resize texture set `ts` to `resolution` on a worker thread (the document changes when @@ -351,10 +403,30 @@ impl TextureCraftApp { } /// Bake progress 0..1 across all queued sets. + pub fn bake_status(&self) -> Option { + let job = self.bake.as_ref()?; + let stage = self.session.bake_preview.as_ref()?.stage()?; + let map = i18n::tr(i18n::baked_map_label(stage.map)); + let (n, total) = (stage.position, stage.total); + if job.total > 1 { + let set = job.total - job.queue.len(); + return Some(i18n::trf( + "Baking {map} ({n}/{total}), texture set {set} of {sets}", + &[("map", &map), ("n", &n), ("total", &total), ("set", &set.max(1)), ("sets", &job.total)], + )); + } + Some(i18n::trf("Baking {map} ({n}/{total})", &[("map", &map), ("n", &n), ("total", &total)])) + } + pub fn bake_progress(&self) -> Option { let job = self.bake.as_ref()?; let done = job.total - job.queue.len() - usize::from(job.current.is_some()); - let cur = job.current.as_ref().map(|(_, p, _)| p.fraction()).unwrap_or(0.0); + // Each map is a bake of its own: its progress runs from 0 to 1 within the set's share + let cur = job + .current + .as_ref() + .map(|running| (running.maps_done.load(Ordering::Relaxed) as f32 + running.progress.fraction()) / running.maps_total.max(1) as f32) + .unwrap_or(0.0); Some(((done as f32 + cur) / job.total.max(1) as f32).clamp(0.0, 1.0)) } } diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index da60a42d..1ce473dd 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -405,7 +405,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } app.last_paint_point = Some(local(p)); } - Err(e) => app.toast(e.to_string(), true), + Err(e) => app.toast(tr(&e.to_string()).to_string(), true), } } if resp.clicked_by(PointerButton::Primary) @@ -1017,7 +1017,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin if let Some(p) = resp.interact_pointer_pos() && let Err(e) = app.session.begin_stroke_uv(to_uv(p), pressure) { - app.toast(e.to_string(), true); + app.toast(tr(&e.to_string()).to_string(), true); } if resp.clicked_by(PointerButton::Primary) && let Err(e) = app.session.end_stroke() diff --git a/crates/ui-egui/tests/bake_preview.rs b/crates/ui-egui/tests/bake_preview.rs new file mode 100644 index 00000000..a24b2352 --- /dev/null +++ b/crates/ui-egui/tests/bake_preview.rs @@ -0,0 +1,98 @@ +//! Bake mode: while a bake runs the 3D view shows the maps landing on the model, the previous view +//! mode comes back when the bake ends, is cancelled or Bake mode is left, and painting is paused. + +use egui_kittest::Harness; +use texturecraft_engine::ViewMode; +use texturecraft_engine::core::{BakeResolution, BakedMap}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::Mode; + +const MAPS: [BakedMap; 3] = [BakedMap::Id, BakedMap::AmbientOcclusion, BakedMap::Height]; + +fn harness() -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + for texture_set in &mut session.doc.project.texture_sets { + texture_set.bake = Default::default(); + texture_set.bake.common.resolution = BakeResolution::R64; + texture_set.bake.maps.ao.parameters.rays.rays = 8; + texture_set.bake.maps.select(MAPS); + } + session.view = ViewMode::UvChecker; + let mut harness = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.mode = Mode::Baking; + harness.run_steps(3); + harness +} + +/// Frames until the bake is gone, with the view mode after each one. +fn run_to_the_end(harness: &mut Harness<'static, TextureCraftApp>) -> Vec { + let mut seen = Vec::new(); + for _ in 0..4000 { + harness.run_steps(1); + seen.push(harness.state().session.view); + if harness.state().bake.is_none() { + return seen; + } + std::thread::sleep(std::time::Duration::from_millis(2)); + } + panic!("the bake did not finish"); +} + +#[test] +fn the_view_shows_each_map_as_it_lands_and_the_previous_mode_comes_back() { + let mut harness = harness(); + harness.state_mut().start_bake(vec![0]); + // Right away: the first map shows, still neutral + assert_eq!(harness.state().session.view, ViewMode::MeshMap(MAPS[0])); + harness.run_steps(1); + assert!(harness.state().bake_status().is_some_and(|status| status.contains("/3")), "the status line names the stage"); + let seen = run_to_the_end(&mut harness); + // Every requested map was shown at some frame, in request order + let mut shown: Vec = Vec::new(); + for view in seen { + if let ViewMode::MeshMap(map) = view + && shown.last() != Some(&map) + { + shown.push(map); + } + } + assert_eq!(shown, MAPS); + assert_eq!(harness.state().session.view, ViewMode::UvChecker, "the mode in use before the bake is back"); + assert!(!harness.state().session.bake_preview_active()); + assert!(MAPS.iter().all(|map| harness.state().session.doc.baked[&0].maps.contains_key(map))); +} + +#[test] +fn cancelling_restores_the_view_and_leaves_the_document_alone() { + let mut harness = harness(); + let before = harness.state().session.doc.baked.get(&0).cloned(); + harness.state_mut().start_bake(vec![0]); + harness.run_steps(2); + assert!(harness.state().session.bake_preview_active()); + let (at, viewport) = (texturecraft_engine::geom::glam::Vec2::new(5.0, 5.0), texturecraft_engine::geom::glam::Vec2::new(100.0, 100.0)); + assert!(harness.state_mut().session.begin_stroke(at, viewport, 1.0).is_err(), "painting is paused"); + harness.state_mut().cancel_bake(); + harness.run_steps(2); + assert_eq!(harness.state().session.view, ViewMode::UvChecker); + assert!(!harness.state().session.bake_preview_active() && harness.state().bake.is_none()); + assert_eq!(harness.state().session.doc.baked.get(&0).cloned(), before); +} + +#[test] +fn leaving_bake_mode_closes_the_preview_but_the_bake_goes_on() { + let mut harness = harness(); + harness.state_mut().start_bake(vec![0]); + harness.run_steps(2); + harness.state_mut().ui.mode = Mode::Painting; + harness.run_steps(2); + assert_eq!(harness.state().session.view, ViewMode::UvChecker); + assert!(!harness.state().session.bake_preview_active()); + run_to_the_end(&mut harness); + assert!(harness.state().session.doc.baked[&0].maps.contains_key(&BakedMap::Height), "the bake finished and was applied"); + assert_eq!(harness.state().session.view, ViewMode::UvChecker); +} + +#[test] +fn the_painting_message_is_a_translated_key() { + assert_eq!(texturecraft_ui_egui::PAINTING_PAUSED, texturecraft_engine::bake_preview::PAINTING_PAUSED); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 3d7c2206..07fd17e5 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -62,9 +62,11 @@ keeps its state in a throwaway file. | `command.run` | `{id, params?}` | the command's JSON result | | `command.list` | `{filter?}` | `[{id, label, menu, shortcut, params, enabled}]` | | `session.inspect` | | project, mesh, texture sets, layer stack, tool, camera, display, history | -| `ui.inspect` | | UI state, viewport rect, fps, bake progress, toasts, `titleBar` (who draws the title bar this run: `app`, `integrated` on macOS, or `system`) | +| `ui.inspect` | | UI state, viewport rect, fps, bake progress (`baking`, 0..1), the running bake's stage (`bakeStatus`, e.g. "Baking Ambient Occlusion (2/4)") and live preview (`bakePreview`, see *Live bake preview*), toasts, `titleBar` (who draws the title bar this run: `app`, `integrated` on macOS, or `system`) | | `ui.menu.list` | | the menu catalog: `{menu, submenu, label, id, shortcut, implemented, enabled}` | | `ui.menu.invoke` | `{id}` | behaves like a menu click (may open a window) | +| `ui.bake.start` | `{ts?: index \| [indices]}` (default: the sets ticked in Bake mode) | Opens Bake mode and bakes in the background like the Bake button: the 3D view shows the maps landing on the model as they finish (see *Live bake preview*). → the `bake.preview` state. Errors when a bake is already running | +| `ui.bake.cancel` | | Stops the running bake; the document keeps the maps it had and the previous view mode comes back | | `ui.set` | fields of the UI state, e.g. `{"layout": "Only3D"}`; `dock` is the panel layout, a craft-ui docking `Workspace` (`{version, layout: {root, floating}, hidden}`; `root` is a tree of `Split`, `Tabs` and `Stack` nodes over the panels `Viewport`, `Assets`, `TextureSetList`, `Layers`, `TextureSetSettings`, `Properties`, `Display`, `Shader`, `History` and `Log`; `hidden` lists where each closed panel was, so reopening it puts it back; a layout that does not read or has no docked `Viewport` becomes the default), `prefs` the settings (`{"language": "ja", "viewport_texture": 1, "brightness": "light", "accent": "blue"}`; missing fields take their defaults; `brightness` is `dark`, `mediumDark` (default), `mediumLight` or `light`, `accent` `copper` (default), `coral`, `blue`, `violet`, `green`, `amber` or `pink`, applied on the next frame; `system_title_bar` `true` has the system draw the title bar from the next start), `keymap` the custom shortcuts (`{"file.save": "F5"}`, `""` unbinds) | `null` | | `viewport.screenshot` | `{view?: "3d" \| "2d"}` | `{width, height, png}` (PNG, base64) | | `ui.screenshot` | | `{width, height, png}` of the whole window, after the next frame | @@ -85,6 +87,38 @@ Example session: < {"id":3,"ok":true,"result":{"width":1210,"height":788,"png":"iVBORw0KGgo…"}} ``` +### Live bake preview + +A bake started in the app (`ui.bake.start`, or the Bake button) makes the mesh maps one after +another, in the `BakedMap` order of the set's enabled maps, and shows each one on the model as +soon as it is finished and padded: the 3D view displays the newest finished map raw (normals as +RGB, scalar maps as gray, ID maps as their colors), maps and texture sets not baked yet show their +neutral value, and the bake bar names the stage (`Baking Ambient Occlusion (2/4)`). Each map is a +bake of its own, so with a high poly the transfer rays are cast once per map; the pixels are the +same as a single bake's. `bake.run` and the CLI bake all maps at once and never show a preview. + +The streamed maps are held by the session, not the document: nothing enters the undo history +until a texture set's bake is applied (one undo step), and a cancelled bake changes nothing. When +the bake ends, is cancelled or Bake mode is left, the view mode that was in use comes back. +**Painting is paused while a bake is shown**: strokes fail with "Painting is paused while a bake +is shown. Cancel the bake or wait for it to finish." + +`bake.preview` `{show?: "follow" \| "material" \| "map:"}` reads and sets what the view shows +(also the control in the bake bar): `follow` (default) the newest finished map, `material` the lit +material, `map:` one map pinned (neutral until it is baked). Picking a mesh map with +`viewport.view` during a bake pins it; any other view mode is kept for when the bake ends. Result, +also `session.inspect`'s `bakePreview`: + +```json +{"active": true, "show": "follow", "shown": "ambientOcclusion", "newest": "ambientOcclusion", + "restore": "Material", "stage": {"set": 0, "map": "curvature", "n": 3, "total": 4}, + "sets": [{"set": 0, "order": ["id", "ambientOcclusion", "curvature", "height"], "done": ["id", "ambientOcclusion"]}]} +``` + +`{"active": false}` when no bake is shown; setting `show` then is an error. Drive a bake with +`ui.bake.start` and poll `ui.inspect`'s `bakeStatus` / `bakePreview` (and `viewport.screenshot`) +until `baking` is `null`. + A minimal client (Python, for illustration): ```python diff --git a/docs/features.md b/docs/features.md index fcbaca5f..a51352da 100644 --- a/docs/features.md +++ b/docs/features.md @@ -103,6 +103,8 @@ Everything TextureCraft does today, by area. What's still missing is in [`ROADMA edited): drop one from the Assets panel on a slot of the Texture Set Settings, or pick it from the slot's menu. A UV-tiled set takes one image per tile, named with its tile number (`ao.1001.png`, `ao.1002.png`…): drop or pick any one of them. +- **Live bake preview:** while the app bakes, each mesh map shows on the model as soon as it is + finished; the bake bar follows the newest map, pins a finished one or shows the material. - **Export presets** for glTF PBR Metal Roughness, Unreal Engine (packed), Unity HDRP (mask map), Unity Standard, Blender (Principled BSDF), Godot 4 (ORM), OpenPBR (with the coat, fuzz, anisotropy, transmission and subsurface maps), separate maps, mesh maps and document channels, in From 4543c858122565b13529299e8715b31fc7c990db Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 10:32:33 +0000 Subject: [PATCH 13/64] Reset icon on each brush section header Each brush section header gets a reset icon at its right end that puts only that section's settings back to their defaults; dimmed and inert while already at them. Docked Properties uses the solid scroll bar so the icon sits flush right. --- crates/ui-egui/src/dock.rs | 191 ++++++++++++-------- crates/ui-egui/src/i18n/ar.rs | 1 + crates/ui-egui/src/i18n/de.rs | 1 + crates/ui-egui/src/i18n/es.rs | 1 + crates/ui-egui/src/i18n/fr.rs | 1 + crates/ui-egui/src/i18n/it.rs | 1 + crates/ui-egui/src/i18n/ja.rs | 1 + crates/ui-egui/src/i18n/ko.rs | 1 + crates/ui-egui/src/i18n/pt_br.rs | 1 + crates/ui-egui/src/i18n/zh_hans.rs | 1 + crates/ui-egui/src/widgets.rs | 56 +++++- crates/ui-egui/tests/brush_section_reset.rs | 123 +++++++++++++ 12 files changed, 300 insertions(+), 79 deletions(-) create mode 100644 crates/ui-egui/tests/brush_section_reset.rs diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 976a3035..2799dbca 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -9,7 +9,7 @@ use texturecraft_engine::core::{ Projection, Source, }; use texturecraft_engine::filter_lib::{FILTERS, scalar_params}; -use texturecraft_engine::paint::{BrushAlpha, alphas}; +use texturecraft_engine::paint::{BrushAlpha, BrushSettings, alphas}; use texturecraft_engine::{CloneFrom, StackTarget, Tool}; use crate::TextureCraftApp; @@ -17,7 +17,8 @@ use crate::i18n::{n_, tr, trf}; use crate::shelf::{Asset, ShelfDrag}; use crate::state::PropsTab; use crate::theme::{Tokens, caption}; -use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, histogram, icon_button, section, slider, slider_edit}; +use crate::toolbar::{MAX_BRUSH_SIZE, MIN_BRUSH_SIZE}; +use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, histogram, icon_button, section, section_with_reset, slider, slider_edit}; const TAG_COLORS: [Color32; 8] = [ Color32::from_rgb(0xc0, 0x40, 0x40), @@ -924,6 +925,8 @@ pub(crate) fn properties_title(app: &TextureCraftApp) -> String { } pub(crate) fn properties(app: &mut TextureCraftApp, ui: &mut Ui) { + // A floating scroll bar would cover the right-aligned slider values and section reset icons + ui.spacing_mut().scroll = egui::style::ScrollStyle::solid(); egui::ScrollArea::vertical().id_salt("props").auto_shrink([false, false]).show(ui, |ui| properties_contents(app, ui)); } @@ -1144,104 +1147,150 @@ fn path_section(app: &mut TextureCraftApp, ui: &mut Ui) { ui.label(RichText::new(hint).size(10.5).color(tk.text_dim)); } +/// Font size of the dim hint line under the Brush caption +const HINT_TEXT_SIZE: f32 = 10.5; + fn brush_section(app: &mut TextureCraftApp, ui: &mut Ui) { - let b = &mut app.session.tool.brush; + let brush = &mut app.session.tool.brush; + let defaults = BrushSettings::default(); ui.label(caption(tr("Brush"))); let hint = tr("Ctrl+right-drag in a view sets the size and hardness, Ctrl+left-drag the flow and angle."); - ui.label(RichText::new(hint).size(10.5).color(Tokens::get(ui.ctx()).text_dim)); - section(ui, "sec_size", tr("Size"), true, |ui| { - let mut size = b.size / 0.25 * 100.0; - if slider(ui, tr("Size"), &mut size, 0.05..=100.0, 1).changed() { - b.size = (size / 100.0 * 0.25).clamp(0.0005, 0.25); + ui.label(RichText::new(hint).size(HINT_TEXT_SIZE).color(Tokens::get(ui.ctx()).text_dim)); + + // Each section's reset puts back only the fields it shows + let size_fields = |settings: &BrushSettings| (settings.size, settings.min_size, settings.screen_space); + if section_with_reset(ui, "sec_size", tr("Size"), true, size_fields(brush) == size_fields(&defaults), |ui| { + let mut size_percent = brush.size / MAX_BRUSH_SIZE * 100.0; + if slider(ui, tr("Size"), &mut size_percent, 0.05..=100.0, 1).changed() { + brush.size = (size_percent / 100.0 * MAX_BRUSH_SIZE).clamp(MIN_BRUSH_SIZE, MAX_BRUSH_SIZE); } - let mut ms = b.min_size * 100.0; - if slider(ui, tr("Minimum size (%)"), &mut ms, 0.0..=100.0, 0).changed() { - b.min_size = ms / 100.0; + + let mut min_size_percent = brush.min_size * 100.0; + if slider(ui, tr("Minimum size (%)"), &mut min_size_percent, 0.0..=100.0, 0).changed() { + brush.min_size = min_size_percent / 100.0; } - ui.checkbox(&mut b.screen_space, tr("Size in screen space")); - }); - section(ui, "sec_flow", tr("Flow and opacity"), true, |ui| { - let mut f = b.flow * 100.0; - if slider(ui, tr("Flow"), &mut f, 0.0..=100.0, 0).changed() { - b.flow = f / 100.0; + + ui.checkbox(&mut brush.screen_space, tr("Size in screen space")); + }) { + (brush.size, brush.min_size, brush.screen_space) = size_fields(&defaults); + } + + let flow_fields = |settings: &BrushSettings| (settings.flow, settings.opacity, settings.spacing, settings.hardness); + if section_with_reset(ui, "sec_flow", tr("Flow and opacity"), true, flow_fields(brush) == flow_fields(&defaults), |ui| { + let mut flow_percent = brush.flow * 100.0; + if slider(ui, tr("Flow"), &mut flow_percent, 0.0..=100.0, 0).changed() { + brush.flow = flow_percent / 100.0; } - let mut o = b.opacity * 100.0; - if slider(ui, tr("Stroke opacity"), &mut o, 0.0..=100.0, 0).changed() { - b.opacity = o / 100.0; + + let mut opacity_percent = brush.opacity * 100.0; + if slider(ui, tr("Stroke opacity"), &mut opacity_percent, 0.0..=100.0, 0).changed() { + brush.opacity = opacity_percent / 100.0; } - let mut s = b.spacing * 100.0; - if slider(ui, tr("Spacing"), &mut s, 1.0..=1000.0, 0).changed() { - b.spacing = s / 100.0; + + let mut spacing_percent = brush.spacing * 100.0; + if slider(ui, tr("Spacing"), &mut spacing_percent, 1.0..=1000.0, 0).changed() { + brush.spacing = spacing_percent / 100.0; } - let mut h = b.hardness * 100.0; - if slider(ui, tr("Hardness"), &mut h, 0.0..=99.9, 0).changed() { - b.hardness = h / 100.0; + + let mut hardness_percent = brush.hardness * 100.0; + if slider(ui, tr("Hardness"), &mut hardness_percent, 0.0..=99.9, 0).changed() { + brush.hardness = hardness_percent / 100.0; } - }); - section(ui, "sec_angle", tr("Angle"), false, |ui| { - slider(ui, tr("Angle"), &mut b.angle, -180.0..=180.0, 0); - ui.checkbox(&mut b.follow_path, tr("Follow path")); - }); - section(ui, "sec_jitter", tr("Jitters"), false, |ui| { - for (label, v) in [(tr("Size jitter"), &mut b.jitter_size), (tr("Angle jitter"), &mut b.jitter_angle), (tr("Flow jitter"), &mut b.jitter_flow)] { - let mut x = *v * 100.0; - if slider(ui, label, &mut x, 0.0..=100.0, 0).changed() { - *v = x / 100.0; + }) { + (brush.flow, brush.opacity, brush.spacing, brush.hardness) = flow_fields(&defaults); + } + + let angle_fields = |settings: &BrushSettings| (settings.angle, settings.follow_path); + if section_with_reset(ui, "sec_angle", tr("Angle"), false, angle_fields(brush) == angle_fields(&defaults), |ui| { + slider(ui, tr("Angle"), &mut brush.angle, -180.0..=180.0, 0); + ui.checkbox(&mut brush.follow_path, tr("Follow path")); + }) { + (brush.angle, brush.follow_path) = angle_fields(&defaults); + } + + let jitter_fields = |settings: &BrushSettings| (settings.jitter_size, settings.jitter_angle, settings.jitter_flow, settings.jitter_position); + if section_with_reset(ui, "sec_jitter", tr("Jitters"), false, jitter_fields(brush) == jitter_fields(&defaults), |ui| { + let jitters = [(tr("Size jitter"), &mut brush.jitter_size), (tr("Angle jitter"), &mut brush.jitter_angle), (tr("Flow jitter"), &mut brush.jitter_flow)]; + for (label, jitter) in jitters { + let mut jitter_percent = *jitter * 100.0; + if slider(ui, label, &mut jitter_percent, 0.0..=100.0, 0).changed() { + *jitter = jitter_percent / 100.0; } } - let mut pj = b.jitter_position * 100.0; - if slider(ui, tr("Position jitter"), &mut pj, 0.0..=400.0, 0).changed() { - b.jitter_position = pj / 100.0; + + let mut position_jitter_percent = brush.jitter_position * 100.0; + if slider(ui, tr("Position jitter"), &mut position_jitter_percent, 0.0..=400.0, 0).changed() { + brush.jitter_position = position_jitter_percent / 100.0; } - }); - section(ui, "sec_align", tr("Alignment and culling"), false, |ui| { + }) { + (brush.jitter_size, brush.jitter_angle, brush.jitter_flow, brush.jitter_position) = jitter_fields(&defaults); + } + + let alignment_fields = |settings: &BrushSettings| (settings.alignment, settings.backface_culling, settings.angle_fade, settings.depth); + if section_with_reset(ui, "sec_align", tr("Alignment and culling"), false, alignment_fields(brush) == alignment_fields(&defaults), |ui| { use texturecraft_engine::paint::Alignment; let alignments = [(Alignment::Tangent, tr("Tangent | Wrap")), (Alignment::Camera, tr("Camera"))]; - let shown = alignments.iter().find(|(a, _)| *a == b.alignment).map_or("", |(_, l)| l); + let shown = alignments.iter().find(|(alignment, _)| *alignment == brush.alignment).map_or("", |(_, label)| label); combo(ui, tr("Alignment"), shown, |ui| { - for (a, l) in alignments { - ui.selectable_value(&mut b.alignment, a, l); + for (alignment, label) in alignments { + ui.selectable_value(&mut brush.alignment, alignment, label); } }); - ui.checkbox(&mut b.backface_culling, tr("Backface culling")); - slider(ui, tr("Angle fade from"), &mut b.angle_fade.0, 0.0..=90.0, 0); - slider(ui, tr("Angle fade to"), &mut b.angle_fade.1, 0.0..=90.0, 0); - slider(ui, tr("Stamp depth"), &mut b.depth, 0.05..=4.0, 2); - }); - section(ui, "sec_particles", tr("Particles"), false, |ui| { - let pt = &mut b.particles; - ui.checkbox(&mut pt.enabled, tr("Particle brush (slides down the surface)")); - let mut count = pt.count as f32; + + ui.checkbox(&mut brush.backface_culling, tr("Backface culling")); + slider(ui, tr("Angle fade from"), &mut brush.angle_fade.0, 0.0..=90.0, 0); + slider(ui, tr("Angle fade to"), &mut brush.angle_fade.1, 0.0..=90.0, 0); + slider(ui, tr("Stamp depth"), &mut brush.depth, 0.05..=4.0, 2); + }) { + (brush.alignment, brush.backface_culling, brush.angle_fade, brush.depth) = alignment_fields(&defaults); + } + + if section_with_reset(ui, "sec_particles", tr("Particles"), false, brush.particles == defaults.particles, |ui| { + let particles = &mut brush.particles; + ui.checkbox(&mut particles.enabled, tr("Particle brush (slides down the surface)")); + + let mut count = particles.count as f32; if slider(ui, tr("Count per stamp"), &mut count, 1.0..=16.0, 0).changed() { - pt.count = count as u32; + particles.count = count as u32; } - let mut life = pt.lifetime as f32; - if slider(ui, tr("Lifetime (steps)"), &mut life, 1.0..=128.0, 0).changed() { - pt.lifetime = life as u32; + + let mut lifetime_steps = particles.lifetime as f32; + if slider(ui, tr("Lifetime (steps)"), &mut lifetime_steps, 1.0..=128.0, 0).changed() { + particles.lifetime = lifetime_steps as u32; } - slider(ui, tr("Gravity"), &mut pt.gravity, 0.0..=2.0, 2); - }); - section(ui, "sec_lazy", tr("Lazy mouse and symmetry"), false, |ui| { - slider(ui, tr("Lazy mouse distance"), &mut b.lazy, 0.0..=200.0, 0); + + slider(ui, tr("Gravity"), &mut particles.gravity, 0.0..=2.0, 2); + }) { + brush.particles = defaults.particles; + } + + let lazy_fields = |settings: &BrushSettings| (settings.lazy, settings.symmetry); + if section_with_reset(ui, "sec_lazy", tr("Lazy mouse and symmetry"), false, lazy_fields(brush) == lazy_fields(&defaults), |ui| { + slider(ui, tr("Lazy mouse distance"), &mut brush.lazy, 0.0..=200.0, 0); ui.horizontal(|ui| { - ui.checkbox(&mut b.symmetry.x, tr("Mirror X")); - ui.checkbox(&mut b.symmetry.y, tr("Mirror Y")); - ui.checkbox(&mut b.symmetry.z, tr("Mirror Z")); + ui.checkbox(&mut brush.symmetry.x, tr("Mirror X")); + ui.checkbox(&mut brush.symmetry.y, tr("Mirror Y")); + ui.checkbox(&mut brush.symmetry.z, tr("Mirror Z")); }); - let mut copies = f32::from(b.symmetry.radial); + + let mut copies = f32::from(brush.symmetry.radial); if slider(ui, tr("Radial copies"), &mut copies, 0.0..=32.0, 0).changed() { - b.symmetry.radial = copies as u8; + brush.symmetry.radial = copies as u8; } - ui.add_enabled_ui(b.symmetry.radial > 1, |ui| { + + ui.add_enabled_ui(brush.symmetry.radial > 1, |ui| { ui.horizontal(|ui| { ui.label(tr("Radial axis")); - for (k, name) in ["X", "Y", "Z"].into_iter().enumerate() { - ui.selectable_value(&mut b.symmetry.axis, k as u8, name); + for (axis_index, name) in ["X", "Y", "Z"].into_iter().enumerate() { + ui.selectable_value(&mut brush.symmetry.axis, axis_index as u8, name); } }); }); - }); - *b = b.sanitized(); + }) { + (brush.lazy, brush.symmetry) = lazy_fields(&defaults); + } + + *brush = brush.sanitized(); } /// One alpha in the picker: a 52×64 tile with the shape drawn by `paint` and a label. diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 21c87eb2..ab5b6dec 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -646,6 +646,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rescan the library folder", "إعادة فحص مجلد المكتبة"), ("Reset UI", "إعادة ضبط واجهة المستخدم"), ("Reset all", "إعادة ضبط الكل"), + ("Reset to defaults", "إعادة الضبط إلى الإعدادات الافتراضية"), ("Reset to {shortcut}", "إعادة الضبط إلى {shortcut}"), ("Resizing", "تغيير الحجم"), ("Restore every default shortcut", "استعادة كل الاختصارات الافتراضية"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index ea536d5e..224275cf 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -685,6 +685,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rescan the library folder", "Bibliotheksordner neu einlesen"), ("Reset UI", "UI zurücksetzen"), ("Reset all", "Alle zurücksetzen"), + ("Reset to defaults", "Auf Standardwerte zurücksetzen"), ("Reset to {shortcut}", "Auf {shortcut} zurücksetzen"), ("Resizing", "Größe wird geändert"), ("Restore every default shortcut", "Alle Standard-Tastenkürzel wiederherstellen"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index de7c76e2..8df454f8 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -673,6 +673,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rescan the library folder", "Volver a examinar la carpeta de la biblioteca"), ("Reset UI", "Restablecer interfaz"), ("Reset all", "Restablecer todo"), + ("Reset to defaults", "Restablecer valores predeterminados"), ("Reset to {shortcut}", "Restablecer a {shortcut}"), ("Resizing", "Redimensionando"), ("Restore every default shortcut", "Restaurar todos los atajos predeterminados"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index fc4b8b11..77df362b 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -688,6 +688,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rescan the library folder", "Réanalyser le dossier de la bibliothèque"), ("Reset UI", "Réinitialiser l'interface"), ("Reset all", "Tout réinitialiser"), + ("Reset to defaults", "Rétablir les valeurs par défaut"), ("Reset to {shortcut}", "Réinitialiser à {shortcut}"), ("Resizing", "Redimensionnement"), ("Restore every default shortcut", "Restaurer tous les raccourcis par défaut"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 67648219..a22f6bd3 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -682,6 +682,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rescan the library folder", "Ripeti la scansione della cartella della libreria"), ("Reset UI", "Ripristina interfaccia"), ("Reset all", "Ripristina tutto"), + ("Reset to defaults", "Ripristina i valori predefiniti"), ("Reset to {shortcut}", "Ripristina {shortcut}"), ("Resizing", "Ridimensionamento"), ("Restore every default shortcut", "Ripristina tutte le scorciatoie predefinite"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index dfbe8a65..d4c52347 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -664,6 +664,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rescan the library folder", "ライブラリフォルダーを再スキャン"), ("Reset UI", "UIをリセット"), ("Reset all", "すべてリセット"), + ("Reset to defaults", "デフォルトに戻す"), ("Reset to {shortcut}", "{shortcut} にリセット"), ("Resizing", "サイズ変更中"), ("Restore every default shortcut", "すべてのショートカットをデフォルトに戻す"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index f81cfe6d..a96df9c3 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -655,6 +655,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rescan the library folder", "라이브러리 폴더를 다시 검색합니다"), ("Reset UI", "UI 초기화"), ("Reset all", "모두 초기화"), + ("Reset to defaults", "기본값으로 초기화"), ("Reset to {shortcut}", "{shortcut}(으)로 초기화"), ("Resizing", "크기 조정 중"), ("Restore every default shortcut", "모든 기본 단축키를 복원합니다"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 7bd3d231..496f3c7c 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -670,6 +670,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rescan the library folder", "Reexaminar a pasta da biblioteca"), ("Reset UI", "Redefinir interface"), ("Reset all", "Redefinir tudo"), + ("Reset to defaults", "Redefinir para o padrão"), ("Reset to {shortcut}", "Redefinir para {shortcut}"), ("Resizing", "Redimensionando"), ("Restore every default shortcut", "Restaurar todos os atalhos padrão"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 7d393f75..bf2c959c 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -616,6 +616,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Rescan the library folder", "重新扫描库文件夹"), ("Reset UI", "重置界面"), ("Reset all", "全部重置"), + ("Reset to defaults", "恢复默认值"), ("Reset to {shortcut}", "重置为 {shortcut}"), ("Resizing", "正在调整大小"), ("Restore every default shortcut", "恢复所有默认快捷键"), diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 79aa7eab..80b7fa90 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -4,6 +4,7 @@ use craft_ui::buttons::{ButtonVisuals, IconButton, IconButtonStyle}; use egui::{Color32, CornerRadius, Response, RichText, Sense, Stroke, Ui, vec2}; +use crate::i18n::tr; use crate::theme::Tokens; /// The drag-and-drop payload of type `T` released on `resp` this frame. Unlike @@ -261,23 +262,62 @@ pub(crate) fn section_chevron(ui: &Ui, is_open: bool) -> RichText { /// A collapsible section header with a chevron pub fn section(ui: &mut Ui, id: &str, title: &str, default_open: bool, body: impl FnOnce(&mut Ui)) { + collapsible_section(ui, id, title, default_open, None, body); +} + +/// A [`section`] whose header ends in a reset icon, inert while `at_default`; true when clicked +pub fn section_with_reset(ui: &mut Ui, id: &str, title: &str, default_open: bool, at_default: bool, body: impl FnOnce(&mut Ui)) -> bool { + collapsible_section(ui, id, title, default_open, Some(at_default), body) +} + +/// Glyph size of a section header's reset icon +const SECTION_RESET_ICON_SIZE: f32 = 14.0; + +/// How much of `text_dim` the reset icon keeps while its section is at its defaults +const SECTION_RESET_AT_DEFAULT_OPACITY: f32 = 0.4; + +/// The header row and body of [`section`]; `reset_at_default` adds the reset icon +fn collapsible_section(ui: &mut Ui, id: &str, title: &str, default_open: bool, reset_at_default: Option, body: impl FnOnce(&mut Ui)) -> bool { let tokens = Tokens::get(ui.ctx()); let id = ui.make_persistent_id(id); let mut collapsing_state = egui::collapsing_header::CollapsingState::load_with_default_open(ui.ctx(), id, default_open); - let response = ui - .horizontal(|ui| { - ui.add(egui::Label::new(section_chevron(ui, collapsing_state.is_open())).selectable(false)); - ui.add(egui::Label::new(RichText::new(title).strong().color(tokens.text_strong)).selectable(false)); - }) - .response - .interact(Sense::click()); - if response.clicked() { + + let mut reset_rect = None; + let header = ui.horizontal(|ui| { + ui.add(egui::Label::new(section_chevron(ui, collapsing_state.is_open())).selectable(false)); + ui.add(egui::Label::new(RichText::new(title).strong().color(tokens.text_strong)).selectable(false)); + if reset_at_default.is_some() { + let icon_size = vec2(SECTION_RESET_ICON_SIZE, SECTION_RESET_ICON_SIZE); + reset_rect = Some(ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| ui.allocate_exact_size(icon_size, Sense::hover()).0).inner); + } + }); + if header.response.interact(Sense::click()).clicked() { collapsing_state.toggle(ui); } + // Registered after the header so the icon, not the header, takes its clicks + let mut reset_clicked = false; + if let (Some(at_default), Some(rect)) = (reset_at_default, reset_rect) { + let response = ui.interact(rect, id.with("reset"), Sense::click()).on_hover_text(tr("Reset to defaults")); + response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, !at_default, tr("Reset to defaults"))); + + let color = if at_default { + tokens.text_dim.gamma_multiply(SECTION_RESET_AT_DEFAULT_OPACITY) + } else if response.hovered() { + tokens.text_strong + } else { + tokens.text_dim + }; + let font = egui::FontId::proportional(SECTION_RESET_ICON_SIZE); + ui.painter().text(rect.center(), egui::Align2::CENTER_CENTER, egui_phosphor::regular::CLOCK_COUNTER_CLOCKWISE, font, color); + reset_clicked = response.clicked() && !at_default; + } + collapsing_state.show_body_unindented(ui, |ui| { ui.indent(id.with("in"), body); }); + + reset_clicked } /// A channel chip ("color", "metal", "rough"…): toggled = the accent-tinted well. diff --git a/crates/ui-egui/tests/brush_section_reset.rs b/crates/ui-egui/tests/brush_section_reset.rs new file mode 100644 index 00000000..198b618c --- /dev/null +++ b/crates/ui-egui/tests/brush_section_reset.rs @@ -0,0 +1,123 @@ +//! Each brush section header has a reset icon that puts only that section's settings back to their defaults + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::paint::{Alignment, BrushSettings, Particles, Symmetry}; +use texturecraft_ui_egui::TextureCraftApp; + +/// The default window; Properties shows only the top of the brush there, so lower headers are scrolled to +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.0); + +/// Frames for the first layout and fonts to settle +const STARTUP_FRAMES: usize = 4; + +/// Frames for a click to reach the brush settings and the panel +const SETTLE_FRAMES: usize = 3; + +/// Puts one section's fields of the first brush back to the second's values +type SectionReset = fn(&mut BrushSettings, &BrushSettings); + +/// A brush that differs from the defaults in every field a section shows, within the valid ranges +fn changed_brush() -> BrushSettings { + BrushSettings { + size: 0.1, + min_size: 0.5, + screen_space: true, + flow: 0.5, + opacity: 0.6, + spacing: 0.5, + hardness: 0.9, + angle: 45.0, + follow_path: true, + jitter_size: 0.5, + jitter_angle: 0.4, + jitter_flow: 0.3, + jitter_position: 1.0, + alignment: Alignment::Camera, + backface_culling: false, + angle_fade: (30.0, 60.0), + depth: 2.0, + particles: Particles { enabled: true, count: 8, lifetime: 12, gravity: 0.5 }, + lazy: 50.0, + symmetry: Symmetry { x: true, y: false, z: true, radial: 4, axis: 2 }, + ..BrushSettings::default() + } +} + +/// The app showing the brush in Properties, set to `brush` +fn app_with_brush(brush: BrushSettings) -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); + harness.state_mut().session.tool.brush = brush; + harness.run_steps(STARTUP_FRAMES); + harness +} + +/// The reset icon on the header row titled `title` +fn reset_icon<'tree>(harness: &'tree Harness<'_, TextureCraftApp>, title: &str) -> egui_kittest::Node<'tree> { + // "Size" and "Angle" also label sliders, so match the title on the icon's row + let on_title_row = |icon: egui::Rect| harness.query_all_by_label(title).any(|label| label.rect().y_range().intersects(icon.y_range())); + harness.query_all_by_label("Reset to defaults").find(|icon| on_title_row(icon.rect())).unwrap_or_else(|| panic!("no reset icon on the {title} header")) +} + +/// Scrolls the header titled `title` into view and clicks its reset icon +fn click_reset(harness: &mut Harness<'_, TextureCraftApp>, title: &str) { + reset_icon(harness, title).scroll_to_me(); + harness.run_steps(SETTLE_FRAMES); + + reset_icon(harness, title).click(); + harness.run_steps(SETTLE_FRAMES); +} + +#[test] +fn each_reset_puts_back_only_its_own_section() { + let defaults = BrushSettings::default(); + let sections: [(&str, SectionReset); 7] = [ + ("Size", |brush, defaults| (brush.size, brush.min_size, brush.screen_space) = (defaults.size, defaults.min_size, defaults.screen_space)), + ("Flow and opacity", |brush, defaults| { + (brush.flow, brush.opacity, brush.spacing, brush.hardness) = (defaults.flow, defaults.opacity, defaults.spacing, defaults.hardness) + }), + ("Angle", |brush, defaults| (brush.angle, brush.follow_path) = (defaults.angle, defaults.follow_path)), + ("Jitters", |brush, defaults| { + (brush.jitter_size, brush.jitter_angle, brush.jitter_flow, brush.jitter_position) = + (defaults.jitter_size, defaults.jitter_angle, defaults.jitter_flow, defaults.jitter_position) + }), + ("Alignment and culling", |brush, defaults| { + (brush.alignment, brush.backface_culling, brush.angle_fade, brush.depth) = + (defaults.alignment, defaults.backface_culling, defaults.angle_fade, defaults.depth) + }), + ("Particles", |brush, defaults| brush.particles = defaults.particles), + ("Lazy mouse and symmetry", |brush, defaults| (brush.lazy, brush.symmetry) = (defaults.lazy, defaults.symmetry)), + ]; + + for (title, reset_section) in sections { + let mut harness = app_with_brush(changed_brush()); + click_reset(&mut harness, title); + + let mut expected = changed_brush(); + reset_section(&mut expected, &defaults); + assert_eq!(harness.state().session.tool.brush, expected, "resetting {title}"); + } +} + +#[test] +fn clicking_the_reset_icon_does_not_fold_or_unfold_the_section() { + let mut harness = app_with_brush(changed_brush()); + + click_reset(&mut harness, "Size"); + assert!(harness.query_by_label("Minimum size (%)").is_some(), "Size starts open and stays open"); + + click_reset(&mut harness, "Jitters"); + assert!(harness.query_by_label("Size jitter").is_none(), "Jitters starts closed and stays closed"); +} + +#[test] +fn at_the_defaults_the_reset_icon_does_nothing() { + let mut harness = app_with_brush(BrushSettings::default()); + + click_reset(&mut harness, "Size"); + assert_eq!(harness.state().session.tool.brush, BrushSettings::default()); + assert!(harness.query_by_label("Minimum size (%)").is_some(), "the click doesn't reach the header"); +} From 3836730030e719f4db76aca7c884e106f6ce9bcf Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 11:43:05 +0000 Subject: [PATCH 14/64] X inverts the mask paint value while painting a mask New command tool.swapMaskValue (mask value becomes 1 - value), default shortcut X, enabled only while the selected layer's mask or one of its mask effects is the paint target. Ctrl+X stays cut. Closes #332. --- crates/engine/src/tool_cmds.rs | 34 +++++++++++++- crates/engine/tests/tools.rs | 35 +++++++++++++- crates/ui-egui/src/i18n/ar.rs | 1 + crates/ui-egui/src/i18n/de.rs | 1 + crates/ui-egui/src/i18n/es.rs | 1 + crates/ui-egui/src/i18n/fr.rs | 1 + crates/ui-egui/src/i18n/it.rs | 1 + crates/ui-egui/src/i18n/ja.rs | 1 + crates/ui-egui/src/i18n/ko.rs | 1 + crates/ui-egui/src/i18n/pt_br.rs | 1 + crates/ui-egui/src/i18n/zh_hans.rs | 1 + crates/ui-egui/tests/mask_value_swap.rs | 61 +++++++++++++++++++++++++ 12 files changed, 136 insertions(+), 3 deletions(-) create mode 100644 crates/ui-egui/tests/mask_value_swap.rs diff --git a/crates/engine/src/tool_cmds.rs b/crates/engine/src/tool_cmds.rs index 7fa5fdab..e4d61f67 100644 --- a/crates/engine/src/tool_cmds.rs +++ b/crates/engine/src/tool_cmds.rs @@ -7,7 +7,7 @@ use texturecraft_geom::glam::Vec2; use texturecraft_paint::{Alignment, BrushAlpha, alphas}; use crate::commands::{CommandSpec, always, bad, boolp, channel_param, color_param, f32p, strp}; -use crate::session::{CloneFrom, CloneSource, FillMode, Tool}; +use crate::session::{CloneFrom, CloneSource, FillMode, StackTarget, Tool}; use crate::{Result, Session, cmd}; pub fn specs() -> Vec { @@ -51,6 +51,15 @@ pub fn specs() -> Vec { always, material ), + cmd!( + "tool.swapMaskValue", + "Invert mask value", + ["Tools"], + Some("X"), + "{} — mask value becomes 1 − value: switch the brush between adding to and removing from the mask", + paints_mask, + swap_mask_value + ), cmd!( "tool.stencil", "Projection stencil", @@ -252,6 +261,29 @@ fn material(s: &mut Session, p: &Value) -> Result { })) } +/// Whether strokes paint the selected layer's mask: the mask itself or one of its effects +fn paints_mask(s: &Session) -> std::result::Result<(), String> { + s.selected_layer().ok_or("no layer selected")?; + + let project = &s.doc.project; + let targets_mask = match s.target { + StackTarget::Content => false, + StackTarget::Mask => true, + StackTarget::Effect(effect_id) => project + .effect(effect_id) + .and_then(|(owner, _)| project.layers.get(&owner)) + .is_some_and(|owner_layer| !owner_layer.content_effects.iter().any(|effect| effect.id == effect_id)), + }; + + if targets_mask { Ok(()) } else { Err("select a mask to paint on".into()) } +} + +fn swap_mask_value(s: &mut Session, _: &Value) -> Result { + s.tool.mask_value = 1.0 - s.tool.mask_value; + s.revision = s.revision.wrapping_add(1); + Ok(json!({ "maskValue": s.tool.mask_value })) +} + fn stencil(s: &mut Session, p: &Value) -> Result { if boolp(p, "clear") == Some(true) { s.tool.stencil = None; diff --git a/crates/engine/tests/tools.rs b/crates/engine/tests/tools.rs index dcd65100..a8130797 100644 --- a/crates/engine/tests/tools.rs +++ b/crates/engine/tests/tools.rs @@ -2,10 +2,10 @@ //! agents paint. use serde_json::{Value, json}; -use texturecraft_engine::core::Channel; +use texturecraft_engine::core::{Channel, LayerId}; use texturecraft_engine::geom::glam::Vec2; use texturecraft_engine::geom::primitives; -use texturecraft_engine::{Session, execute}; +use texturecraft_engine::{Session, StackTarget, execute}; const RES: f32 = 256.0; @@ -180,3 +180,34 @@ fn quick_mask_limits_painting() { dab(&mut s, 150.0, 200.0); assert!(color_at(&s, 150.0, 200.0)[1] > 0.85, "disabled: everything is open"); } + +#[test] +fn swap_mask_value_inverts_only_while_a_mask_is_the_target() { + let mut s = session(); + execute(&mut s, "layer.add.paint", &Value::Null).unwrap(); + let swap = |s: &mut Session| execute(s, "tool.swapMaskValue", &Value::Null); + let effect_target = |v: Value| StackTarget::Effect(LayerId(v["effect"].as_u64().unwrap())); + + assert!(swap(&mut s).is_err(), "painting the layer content: nothing to invert"); + + let content_effect = effect_target(execute(&mut s, "effect.add.paint", &json!({"target": "content"})).unwrap()); + s.target = content_effect; + assert!(swap(&mut s).is_err(), "a content effect is not a mask"); + + execute(&mut s, "mask.add.white", &Value::Null).unwrap(); + s.target = StackTarget::Mask; + s.tool.mask_value = 0.2; + swap(&mut s).unwrap(); + assert_eq!(s.tool.mask_value, 0.8); + + s.tool.mask_value = 1.0; + swap(&mut s).unwrap(); + assert_eq!(s.tool.mask_value, 0.0); + + swap(&mut s).unwrap(); + assert_eq!(s.tool.mask_value, 1.0, "pressing it again goes back"); + + s.target = effect_target(execute(&mut s, "effect.add.paint", &json!({"target": "mask"})).unwrap()); + swap(&mut s).unwrap(); + assert_eq!(s.tool.mask_value, 0.0, "a mask effect paints the mask too"); +} diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 21c87eb2..948b1a66 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -416,6 +416,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert", "عكس"), ("Invert mask", "عكس القناع"), ("Invert mask background", "عكس خلفية القناع"), + ("Invert mask value", "عكس قيمة القناع"), ("Invert quick mask", "عكس القناع السريع"), ("Jitters", "اضطرابات (Jitters)"), ("Join the ArtCraft community on Discord", "انضم إلى مجتمع ArtCraft على Discord"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index ea536d5e..4341e1b5 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -443,6 +443,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert", "Invertieren"), ("Invert mask", "Maske invertieren"), ("Invert mask background", "Maskenhintergrund invertieren"), + ("Invert mask value", "Maskenwert invertieren"), ("Invert quick mask", "Schnellmaske invertieren"), ("Jitters", "Streuung"), ("Join the ArtCraft community on Discord", "Der ArtCraft-Community auf Discord beitreten"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index de7c76e2..50e64695 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -434,6 +434,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert", "Invertir"), ("Invert mask", "Invertir máscara"), ("Invert mask background", "Invertir fondo de la máscara"), + ("Invert mask value", "Invertir valor de máscara"), ("Invert quick mask", "Invertir máscara rápida"), ("Jitters", "Variaciones"), ("Join the ArtCraft community on Discord", "Únete a la comunidad de ArtCraft en Discord"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index fc4b8b11..85f061ae 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -446,6 +446,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert", "Inverser"), ("Invert mask", "Inverser le masque"), ("Invert mask background", "Inverser le fond du masque"), + ("Invert mask value", "Inverser la valeur du masque"), ("Invert quick mask", "Inverser le masque rapide"), ("Jitters", "Variations"), ("Join the ArtCraft community on Discord", "Rejoindre la communauté ArtCraft sur Discord"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 67648219..4a0e374b 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -437,6 +437,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert", "Inverti"), ("Invert mask", "Inverti maschera"), ("Invert mask background", "Inverti sfondo maschera"), + ("Invert mask value", "Inverti valore maschera"), ("Invert quick mask", "Inverti maschera rapida"), ("Jitters", "Variazioni"), ("Join the ArtCraft community on Discord", "Unisciti alla community di ArtCraft su Discord"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index dfbe8a65..d7036576 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -428,6 +428,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert", "反転"), ("Invert mask", "マスクを反転"), ("Invert mask background", "マスクの背景を反転"), + ("Invert mask value", "マスク値を反転"), ("Invert quick mask", "クイックマスクを反転"), ("Jitters", "ジッター"), ("Join the ArtCraft community on Discord", "DiscordでArtCraftコミュニティに参加"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index f81cfe6d..68fc23d2 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -422,6 +422,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert", "반전"), ("Invert mask", "마스크 반전"), ("Invert mask background", "마스크 배경 반전"), + ("Invert mask value", "마스크 값 반전"), ("Invert quick mask", "퀵 마스크 반전"), ("Jitters", "지터"), ("Join the ArtCraft community on Discord", "Discord에서 ArtCraft 커뮤니티에 참여하세요"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 7bd3d231..f1ff8397 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -431,6 +431,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert", "Inverter"), ("Invert mask", "Inverter máscara"), ("Invert mask background", "Inverter fundo da máscara"), + ("Invert mask value", "Inverter valor da máscara"), ("Invert quick mask", "Inverter máscara rápida"), ("Jitters", "Variações"), ("Join the ArtCraft community on Discord", "Participe da comunidade ArtCraft no Discord"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 7d393f75..cd813723 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -389,6 +389,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Invert", "反相"), ("Invert mask", "反相遮罩"), ("Invert mask background", "反相遮罩背景"), + ("Invert mask value", "反相遮罩值"), ("Invert quick mask", "反相快速遮罩"), ("Jitters", "抖动"), ("Join the ArtCraft community on Discord", "加入 Discord 上的 ArtCraft 社区"), diff --git a/crates/ui-egui/tests/mask_value_swap.rs b/crates/ui-egui/tests/mask_value_swap.rs new file mode 100644 index 00000000..37f79daf --- /dev/null +++ b/crates/ui-egui/tests/mask_value_swap.rs @@ -0,0 +1,61 @@ +//! X inverts the mask value while a mask is the paint target; Ctrl+X still cuts the layer + +use egui_kittest::Harness; +use texturecraft_engine::StackTarget; +use texturecraft_ui_egui::TextureCraftApp; + +/// The sample session with a white mask on its selected layer, painting that mask +fn harness() -> Harness<'static, TextureCraftApp> { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + texturecraft_engine::execute(&mut session, "mask.add.white", &serde_json::Value::Null).unwrap(); + session.target = StackTarget::Mask; + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.run_steps(4); + h +} + +fn mask_value(h: &Harness<'_, TextureCraftApp>) -> f32 { + h.state().session.tool.mask_value +} + +#[test] +fn x_inverts_the_mask_value_and_back() { + let mut h = harness(); + h.state_mut().session.tool.mask_value = 0.25; + h.key_press(egui::Key::X); + h.run_steps(3); + assert_eq!(mask_value(&h), 0.75); + h.key_press(egui::Key::X); + h.run_steps(3); + assert_eq!(mask_value(&h), 0.25); +} + +#[test] +fn x_does_nothing_while_painting_layer_content() { + let mut h = harness(); + h.state_mut().session.target = StackTarget::Content; + h.state_mut().session.tool.mask_value = 0.25; + h.key_press(egui::Key::X); + h.run_steps(3); + assert_eq!(mask_value(&h), 0.25); +} + +#[test] +fn ctrl_x_still_cuts_the_layer_while_a_mask_is_the_target() { + let mut h = harness(); + let layer = h.state().session.selected_layer().unwrap(); + h.event(egui::Event::Cut); + h.run_steps(3); + assert!(!h.state().session.doc.project.layers.contains_key(&layer), "Ctrl+X removes the layer"); +} + +#[test] +fn ctrl_x_is_not_x() { + let mut h = harness(); + // With cut unbound, nothing else may answer Ctrl+X + h.state_mut().ui.keymap.insert("layer.cut".into(), String::new()); + h.state_mut().session.tool.mask_value = 0.25; + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::X); + h.run_steps(3); + assert_eq!(mask_value(&h), 0.25); +} From ed45aa080705602a8088b63ed2719a68d3a9cb26 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 12:33:01 +0000 Subject: [PATCH 15/64] Levels: edit the input range, gamma and output range on the histogram Drag the input low, gamma and input high handles above the histogram and the output low/high handles under a black-to-white strip; double-click a handle to type its value. Reset, Auto and Invert replace the five sliders. Every drag is one undo step through effect.set. --- crates/ui-egui/src/dock.rs | 49 +--- crates/ui-egui/src/i18n/ar.rs | 3 + crates/ui-egui/src/i18n/de.rs | 3 + crates/ui-egui/src/i18n/es.rs | 3 + crates/ui-egui/src/i18n/fr.rs | 3 + crates/ui-egui/src/i18n/it.rs | 3 + crates/ui-egui/src/i18n/ja.rs | 3 + crates/ui-egui/src/i18n/ko.rs | 3 + crates/ui-egui/src/i18n/pt_br.rs | 3 + crates/ui-egui/src/i18n/zh_hans.rs | 3 + crates/ui-egui/src/levels_editor.rs | 313 ++++++++++++++++++++++++ crates/ui-egui/src/levels_handle.rs | 91 +++++++ crates/ui-egui/src/levels_properties.rs | 130 ++++++++++ crates/ui-egui/src/lib.rs | 3 + crates/ui-egui/src/widgets.rs | 25 -- crates/ui-egui/tests/effect_sliders.rs | 6 +- crates/ui-egui/tests/levels_editor.rs | 247 +++++++++++++++++++ 17 files changed, 816 insertions(+), 75 deletions(-) create mode 100644 crates/ui-egui/src/levels_editor.rs create mode 100644 crates/ui-egui/src/levels_handle.rs create mode 100644 crates/ui-egui/src/levels_properties.rs create mode 100644 crates/ui-egui/tests/levels_editor.rs diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 976a3035..bf24149b 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -17,7 +17,7 @@ use crate::i18n::{n_, tr, trf}; use crate::shelf::{Asset, ShelfDrag}; use crate::state::PropsTab; use crate::theme::{Tokens, caption}; -use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, histogram, icon_button, section, slider, slider_edit}; +use crate::widgets::{chip, color_swatch, combo, dnd_release, elided, icon_button, section, slider, slider_edit}; const TAG_COLORS: [Color32; 8] = [ Color32::from_rgb(0xc0, 0x40, 0x40), @@ -1918,20 +1918,7 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: ); } } - EffectKind::Levels(l) => { - ui.label(caption(tr("Levels"))); - levels_histogram(app, ui, layer, eid, (l.in_low, l.in_high)); - let mut v = [l.in_low, l.in_high, l.gamma, l.out_low, l.out_high]; - let labels = [tr("Input low"), tr("Input high"), tr("Gamma"), tr("Output low"), tr("Output high")]; - let mut edit = None; - for (i, label) in labels.iter().enumerate() { - let range = if i == 2 { 0.1..=5.0 } else { 0.0..=1.0 }; - edit = edit.or(slider_edit(ui, label, &mut v[i], range, 2)); - } - if let Some(merge) = edit { - app.run("effect.set", json!({"effect": id, "inLow": v[0], "inHigh": v[1], "gamma": v[2], "outLow": v[3], "outHigh": v[4], "merge": merge})); - } - } + EffectKind::Levels(l) => crate::levels_properties::levels_properties(app, ui, layer, eid, l), EffectKind::Fill { source, .. } => { ui.label(caption(tr("Fill"))); let anchors = anchors_below(app, layer.id); @@ -2026,38 +2013,6 @@ fn effect_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: } } -/// The histogram of what levels effect `eid` of `layer` remaps (its mask, or a content channel -/// picked here), with the input range marked. Recomputed after a document change once no -/// pointer button is held, so dragging a slider keeps the last one. -fn levels_histogram(app: &TextureCraftApp, ui: &mut Ui, layer: &Layer, eid: LayerId, range: (f32, f32)) { - let mut channel = layer.channels.keys().next().copied().unwrap_or(Channel::BaseColor); - if layer.content_effects.iter().any(|e| e.id == eid) { - let pick = egui::Id::unique(("levels_channel", eid.0)); - let chans: Vec = layer.channels.keys().copied().filter(|c| c.kind() != texturecraft_engine::core::ChannelKind::NormalMap).collect(); - channel = ui.data(|d| d.get_temp(pick)).filter(|c| chans.contains(c)).or(chans.first().copied()).unwrap_or(channel); - combo(ui, tr("Channel"), tr(channel.label()), |ui| { - for c in chans { - if ui.selectable_label(c == channel, tr(c.label())).clicked() { - ui.data_mut(|d| d.insert_temp(pick, c)); - } - } - }); - } - let key = egui::Id::unique(("levels_histogram", eid.0, channel)); - let rev = app.session.revision; - let counts = match ui.data(|d| d.get_temp::<(u64, std::sync::Arc>)>(key)) { - Some((r, h)) if r == rev || ui.input(|i| i.pointer.any_down()) => Some(h), - _ => app.session.effect_histogram(eid, channel, 64).map(|h| { - let h = std::sync::Arc::new(h); - ui.data_mut(|d| d.insert_temp(key, (rev, h.clone()))); - h - }), - }; - if let Some(counts) = counts { - histogram(ui, &counts, range); - } -} - /// The parameters of filter effect `id`. fn filter_properties(app: &mut TextureCraftApp, ui: &mut Ui, id: u64, f: &Filter) { let tk = Tokens::get(ui.ctx()); diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 21c87eb2..26bd6066 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -77,6 +77,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Apply", "تطبيق"), ("ArtCraft website...", "موقع ArtCraft الإلكتروني..."), ("Assets", "الأصول"), + ("Auto", "تلقائي"), ("Automatic (from the mesh UVs)", "تلقائي (من إحداثيات UV للمجسم)"), ("Autosave every", "حفظ تلقائي كل"), ( @@ -308,6 +309,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Filters", "مرشحات"), ("Fine noise", "ضوضاء دقيقة"), ("Fingerprints", "بصمات أصابع"), + ("Fit the input range to the histogram", "ملاءمة نطاق الإدخال مع المدرج التكراري"), ("Flatten layer", "تسطيح الطبقة"), ( "Flips the image's green channel, for normal maps made with Y pointing down", @@ -644,6 +646,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Replacement color", "لون الاستبدال"), ("Report a bug...", "الإبلاغ عن خطأ..."), ("Rescan the library folder", "إعادة فحص مجلد المكتبة"), + ("Reset", "إعادة تعيين"), ("Reset UI", "إعادة ضبط واجهة المستخدم"), ("Reset all", "إعادة ضبط الكل"), ("Reset to {shortcut}", "إعادة الضبط إلى {shortcut}"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index ea536d5e..8906dea3 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -80,6 +80,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Apply", "Anwenden"), ("ArtCraft website...", "ArtCraft-Website..."), ("Assets", "Assets"), + ("Auto", "Auto"), ("Automatic (from the mesh UVs)", "Automatisch (aus den UVs des Meshs)"), ("Autosave every", "Automatisch speichern alle"), ( @@ -332,6 +333,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Filters", "Filter"), ("Fine noise", "Feines Rauschen"), ("Fingerprints", "Fingerabdrücke"), + ("Fit the input range to the histogram", "Eingabebereich an das Histogramm anpassen"), ("Flatten layer", "Ebene reduzieren"), ( "Flips the image's green channel, for normal maps made with Y pointing down", @@ -683,6 +685,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Replacement color", "Ersatzfarbe"), ("Report a bug...", "Fehler melden..."), ("Rescan the library folder", "Bibliotheksordner neu einlesen"), + ("Reset", "Zurücksetzen"), ("Reset UI", "UI zurücksetzen"), ("Reset all", "Alle zurücksetzen"), ("Reset to {shortcut}", "Auf {shortcut} zurücksetzen"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index de7c76e2..319d99ec 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -77,6 +77,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Apply", "Aplicar"), ("ArtCraft website...", "Sitio web de ArtCraft..."), ("Assets", "Recursos"), + ("Auto", "Auto"), ("Automatic (from the mesh UVs)", "Automático (según las UV de la malla)"), ("Autosave every", "Autoguardar cada"), ( @@ -323,6 +324,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Filters", "Filtros"), ("Fine noise", "Ruido fino"), ("Fingerprints", "Huellas dactilares"), + ("Fit the input range to the histogram", "Ajustar el rango de entrada al histograma"), ("Flatten layer", "Acoplar capa"), ( "Flips the image's green channel, for normal maps made with Y pointing down", @@ -671,6 +673,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Replacement color", "Color de reemplazo"), ("Report a bug...", "Informar de un error..."), ("Rescan the library folder", "Volver a examinar la carpeta de la biblioteca"), + ("Reset", "Restablecer"), ("Reset UI", "Restablecer interfaz"), ("Reset all", "Restablecer todo"), ("Reset to {shortcut}", "Restablecer a {shortcut}"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index fc4b8b11..ab69ad41 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -83,6 +83,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Apply", "Appliquer"), ("ArtCraft website...", "Site web d'ArtCraft..."), ("Assets", "Ressources"), + ("Auto", "Auto"), ("Automatic (from the mesh UVs)", "Automatique (d'après les UV du maillage)"), ("Autosave every", "Sauvegarde automatique toutes les"), ( @@ -335,6 +336,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Filters", "Filtres"), ("Fine noise", "Bruit fin"), ("Fingerprints", "Empreintes digitales"), + ("Fit the input range to the histogram", "Ajuster la plage d'entrée à l'histogramme"), ("Flatten layer", "Aplatir le calque"), ( "Flips the image's green channel, for normal maps made with Y pointing down", @@ -686,6 +688,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Replacement color", "Couleur de remplacement"), ("Report a bug...", "Signaler un bug..."), ("Rescan the library folder", "Réanalyser le dossier de la bibliothèque"), + ("Reset", "Réinitialiser"), ("Reset UI", "Réinitialiser l'interface"), ("Reset all", "Tout réinitialiser"), ("Reset to {shortcut}", "Réinitialiser à {shortcut}"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 67648219..19a53171 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -80,6 +80,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Apply", "Applica"), ("ArtCraft website...", "Sito web di ArtCraft..."), ("Assets", "Risorse"), + ("Auto", "Auto"), ("Automatic (from the mesh UVs)", "Automatico (dagli UV della mesh)"), ("Autosave every", "Salvataggio automatico ogni"), ( @@ -329,6 +330,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Filters", "Filtri"), ("Fine noise", "Rumore fine"), ("Fingerprints", "Impronte digitali"), + ("Fit the input range to the histogram", "Adatta l'intervallo di input all'istogramma"), ("Flatten layer", "Appiattisci livello"), ( "Flips the image's green channel, for normal maps made with Y pointing down", @@ -680,6 +682,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Replacement color", "Colore sostitutivo"), ("Report a bug...", "Segnala un bug..."), ("Rescan the library folder", "Ripeti la scansione della cartella della libreria"), + ("Reset", "Reimposta"), ("Reset UI", "Ripristina interfaccia"), ("Reset all", "Ripristina tutto"), ("Reset to {shortcut}", "Ripristina {shortcut}"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index dfbe8a65..ed70cda4 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -83,6 +83,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Apply", "適用"), ("ArtCraft website...", "ArtCraft ウェブサイト..."), ("Assets", "アセット"), + ("Auto", "自動"), ("Automatic (from the mesh UVs)", "自動 (メッシュのUVから)"), ("Autosave every", "自動保存の間隔"), ( @@ -320,6 +321,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Filters", "フィルター"), ("Fine noise", "細かいノイズ"), ("Fingerprints", "指紋"), + ("Fit the input range to the histogram", "入力範囲をヒストグラムに合わせる"), ("Flatten layer", "レイヤーを統合"), ("Flips the image's green channel, for normal maps made with Y pointing down", "画像の緑チャンネルを反転します (Y が下向きで作られたノーマルマップ用)"), ("Flow", "フロー"), @@ -662,6 +664,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Replacement color", "置き換え後の色"), ("Report a bug...", "バグを報告..."), ("Rescan the library folder", "ライブラリフォルダーを再スキャン"), + ("Reset", "リセット"), ("Reset UI", "UIをリセット"), ("Reset all", "すべてリセット"), ("Reset to {shortcut}", "{shortcut} にリセット"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index f81cfe6d..4e9cbdfe 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -80,6 +80,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Apply", "적용"), ("ArtCraft website...", "ArtCraft 웹사이트..."), ("Assets", "에셋"), + ("Auto", "자동"), ("Automatic (from the mesh UVs)", "자동 (메시 UV 기준)"), ("Autosave every", "자동 저장 간격"), ( @@ -317,6 +318,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Filters", "필터"), ("Fine noise", "미세 노이즈"), ("Fingerprints", "지문"), + ("Fit the input range to the histogram", "입력 범위를 히스토그램에 맞추기"), ("Flatten layer", "레이어 병합"), ("Flips the image's green channel, for normal maps made with Y pointing down", "이미지의 녹색 채널을 뒤집습니다 (Y가 아래를 향하도록 만든 노멀 맵용)"), ("Flow", "흐름"), @@ -653,6 +655,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Replacement color", "대체 색상"), ("Report a bug...", "버그 신고..."), ("Rescan the library folder", "라이브러리 폴더를 다시 검색합니다"), + ("Reset", "초기화"), ("Reset UI", "UI 초기화"), ("Reset all", "모두 초기화"), ("Reset to {shortcut}", "{shortcut}(으)로 초기화"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 7bd3d231..68676186 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -80,6 +80,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Apply", "Aplicar"), ("ArtCraft website...", "Site da ArtCraft..."), ("Assets", "Recursos"), + ("Auto", "Auto"), ("Automatic (from the mesh UVs)", "Automático (das UVs da malha)"), ("Autosave every", "Salvar automaticamente a cada"), ( @@ -323,6 +324,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Filters", "Filtros"), ("Fine noise", "Ruído fino"), ("Fingerprints", "Impressões digitais"), + ("Fit the input range to the histogram", "Ajustar o intervalo de entrada ao histograma"), ("Flatten layer", "Achatar camada"), ( "Flips the image's green channel, for normal maps made with Y pointing down", @@ -668,6 +670,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Replacement color", "Cor de substituição"), ("Report a bug...", "Relatar um bug..."), ("Rescan the library folder", "Reexaminar a pasta da biblioteca"), + ("Reset", "Redefinir"), ("Reset UI", "Redefinir interface"), ("Reset all", "Redefinir tudo"), ("Reset to {shortcut}", "Redefinir para {shortcut}"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 7d393f75..5f12ab99 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -71,6 +71,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Apply", "应用"), ("ArtCraft website...", "ArtCraft 网站..."), ("Assets", "资产"), + ("Auto", "自动"), ("Automatic (from the mesh UVs)", "自动(基于网格 UV)"), ("Autosave every", "自动保存间隔"), ( @@ -290,6 +291,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Filters", "滤镜"), ("Fine noise", "细噪波"), ("Fingerprints", "指纹"), + ("Fit the input range to the histogram", "使输入范围适合直方图"), ("Flatten layer", "合并图层"), ("Flips the image's green channel, for normal maps made with Y pointing down", "翻转图像的绿色通道,用于 Y 轴朝下制作的法线贴图"), ("Flow", "流量"), @@ -614,6 +616,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Replacement color", "替换后的颜色"), ("Report a bug...", "报告错误..."), ("Rescan the library folder", "重新扫描库文件夹"), + ("Reset", "重置"), ("Reset UI", "重置界面"), ("Reset all", "全部重置"), ("Reset to {shortcut}", "重置为 {shortcut}"), diff --git a/crates/ui-egui/src/levels_editor.rs b/crates/ui-egui/src/levels_editor.rs new file mode 100644 index 00000000..55e2d53d --- /dev/null +++ b/crates/ui-egui/src/levels_editor.rs @@ -0,0 +1,313 @@ +//! The levels editor: draggable handles over a histogram and an output gradient, double-click to type a value + +use egui::{Color32, CornerRadius, CursorIcon, Id, Pos2, Rect, Response, Sense, Stroke, Ui, WidgetInfo, pos2, vec2}; +use texturecraft_engine::core::Levels; + +use crate::levels_handle::LevelsHandle; +use crate::theme::Tokens; + +const HISTOGRAM_HEIGHT: f32 = 56.0; +const HANDLE_HEIGHT: f32 = 11.0; +const HANDLE_HALF_WIDTH: f32 = 5.0; + +/// Height of a handle's straight sides; the rest is its tip pointing at the track +const HANDLE_SIDE_HEIGHT: f32 = 6.0; + +/// Extra width on each side of a handle that still grabs it +const HANDLE_GRAB_MARGIN: f32 = 2.0; + +const GRADIENT_HEIGHT: f32 = 8.0; +const GAP_BELOW_HISTOGRAM: f32 = 3.0; +const VALUE_ROW_HEIGHT: f32 = 16.0; +const VALUE_FONT_SIZE: f32 = 10.5; + +/// Width of the box a value is typed into +const TYPED_VALUE_WIDTH: f32 = 52.0; + +/// Padding of the histogram well around its bars +const WELL_PADDING: f32 = 3.0; + +/// Gray of the gamma handle, between the black input-low and white input-high handles +const GAMMA_HANDLE_GRAY: u8 = 128; + +/// Grid lines across the histogram, at these fractions of its width +const GRID_FRACTIONS: [f32; 3] = [0.25, 0.5, 0.75]; + +/// Decimals of a value typed in or printed beside a handle (printed without trailing zeros) +const VALUE_DECIMALS: usize = 3; + +/// Space kept around a printed value; a value closer to one already printed is left out +const VALUE_SPACING: f32 = 2.0; + +/// Text margin inside the box a value is typed into +const TYPED_VALUE_MARGIN: egui::Vec2 = vec2(2.0, 1.0); + +/// Opacity of the shade over the histogram outside the input range +const OUTSIDE_RANGE_SHADE: f32 = 0.7; + +/// Opacity of the line at gamma, fainter than the input range's accent lines +const GAMMA_LINE_OPACITY: f32 = 0.6; + +/// Edits `levels` over histogram `counts`; `Some(merge)` per change, `merge` true for a drag's later frames +pub fn levels_editor(ui: &mut Ui, id_salt: impl std::hash::Hash + std::fmt::Debug, counts: Option<&[u32]>, levels: &mut Levels) -> Option { + let height = VALUE_ROW_HEIGHT * 2.0 + HANDLE_HEIGHT * 2.0 + HISTOGRAM_HEIGHT + GAP_BELOW_HISTOGRAM + GRADIENT_HEIGHT; + let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), height), Sense::hover()); + let histogram_top = rect.top() + VALUE_ROW_HEIGHT + HANDLE_HEIGHT; + let gradient_top = output_handles_top(rect) - GRADIENT_HEIGHT; + let track = track(rect); + let id = ui.make_persistent_id(("levels_editor", id_salt)); + + // Gamma goes last so it stays grabbable between input handles that close in on it + let handles = [LevelsHandle::InputLow, LevelsHandle::InputHigh, LevelsHandle::Gamma, LevelsHandle::OutputLow, LevelsHandle::OutputHigh]; + let mut edit = None; + let mut responses = Vec::with_capacity(handles.len()); + for handle in handles { + let x = track_x(&track, handle.position(levels)); + let top = handle_top(rect, handle); + let grab_half_width = HANDLE_HALF_WIDTH + HANDLE_GRAB_MARGIN; + let hit = Rect::from_x_y_ranges(x - grab_half_width..=x + grab_half_width, top..=top + HANDLE_HEIGHT); + let response = ui.interact(hit, id.with(handle), Sense::click_and_drag()).on_hover_cursor(CursorIcon::PointingHand); + if response.drag_started() { + ui.data_mut(|data| data.remove_temp::(response.id)); + } + + if response.dragged() + && let Some(pointer) = response.interact_pointer_pos() + { + let mut next = *levels; + handle.set_position(&mut next, track_position(&track, pointer.x)); + if next != *levels { + *levels = next; + edit = Some(continues_drag(ui, response.id)); + } + } + + let value = handle.value(levels); + response.widget_info(|| WidgetInfo::slider(true, f64::from(value), handle.label())); + responses.push((handle, response)); + } + + let typing_id = id.with("typing"); + let double_clicked = responses.iter().find(|(_, response)| response.double_clicked()).map(|(handle, _)| *handle); + if let Some(handle) = double_clicked { + start_typing(ui, typing_id, handle, levels); + } + + let typing = ui.data(|data| data.get_temp::<(LevelsHandle, String)>(typing_id)); + + let well = Rect::from_x_y_ranges(rect.x_range().shrink(HANDLE_HALF_WIDTH), histogram_top..=histogram_top + HISTOGRAM_HEIGHT); + paint_histogram(ui, well, counts.unwrap_or_default(), levels); + paint_output_gradient(ui, Rect::from_x_y_ranges(track, gradient_top..=gradient_top + GRADIENT_HEIGHT)); + paint_handles_and_values(ui, rect, &responses, levels, typing.as_ref().map(|(handle, _)| *handle)); + let typed = typing.and_then(|(handle, text)| typed_value(ui, rect, typing_id, (handle, text), double_clicked.is_some(), levels)); + edit.or(typed) +} + +fn handle_top(rect: Rect, handle: LevelsHandle) -> f32 { + if LevelsHandle::INPUT.contains(&handle) { rect.top() + VALUE_ROW_HEIGHT } else { output_handles_top(rect) } +} + +fn output_handles_top(rect: Rect) -> f32 { + rect.bottom() - VALUE_ROW_HEIGHT - HANDLE_HEIGHT +} + +/// The x range the handles move along in the editor's `rect`, lined up with the histogram bars +fn track(rect: Rect) -> egui::Rangef { + rect.x_range().shrink(HANDLE_HALF_WIDTH + WELL_PADDING) +} + +fn track_x(track: &egui::Rangef, position: f32) -> f32 { + track.min + track.span() * position.clamp(0.0, 1.0) +} + +fn track_position(track: &egui::Rangef, x: f32) -> f32 { + ((x - track.min) / track.span().max(1.0)).clamp(0.0, 1.0) +} + +/// True once the drag of `id` has already changed a value, so its later changes share that undo step +fn continues_drag(ui: &Ui, id: Id) -> bool { + ui.data_mut(|data| std::mem::replace(data.get_temp_mut_or_default::(id), true)) +} + +/// `value` with [`VALUE_DECIMALS`] decimals, trailing zeros dropped ("1", "0.25", "0.634") +fn shown_value(value: f32) -> String { + let fixed = format!("{value:.VALUE_DECIMALS$}"); + fixed.trim_end_matches('0').trim_end_matches('.').to_string() +} + +/// Where `handle`'s value of `size` goes: over an input handle, under an output one, inside `rect` +fn value_rect(rect: Rect, handle: LevelsHandle, levels: &Levels, size: egui::Vec2) -> Rect { + let x = track_x(&track(rect), handle.position(levels)); + let top = handle_top(rect, handle); + let placed = if LevelsHandle::INPUT.contains(&handle) { + egui::Align2::CENTER_BOTTOM.anchor_size(pos2(x, top), size) + } else { + egui::Align2::CENTER_TOP.anchor_size(pos2(x, top + HANDLE_HEIGHT), size) + }; + let shift = (rect.left() - placed.left()).max(0.0) + (rect.right() - placed.right()).min(0.0); + placed.translate(vec2(shift, 0.0)) +} + +/// The histogram in its well: quarter lines, the outside of the input range dimmed, lines at the handles +fn paint_histogram(ui: &Ui, well: Rect, counts: &[u32], levels: &Levels) { + let tokens = Tokens::get(ui.ctx()); + let painter = ui.painter_at(well); + painter.rect(well, CornerRadius::same(tokens.radius), tokens.field, Stroke::new(1.0, tokens.field_border), egui::StrokeKind::Inside); + + let inner = well.shrink(WELL_PADDING); + let vertical_line = |x: f32, color: Color32| painter.line_segment([pos2(x, inner.top()), pos2(x, inner.bottom())], Stroke::new(1.0, color)); + for fraction in GRID_FRACTIONS { + vertical_line(track_x(&inner.x_range(), fraction), tokens.field_border); + } + + let fullest = counts.iter().copied().max().unwrap_or(0).max(1) as f32; + let bar_width = inner.width() / counts.len().max(1) as f32; + for (index, count) in counts.iter().enumerate() { + let bar_height = inner.height() * *count as f32 / fullest; + let x = inner.left() + index as f32 * bar_width; + painter.rect_filled(Rect::from_min_max(pos2(x, inner.bottom() - bar_height), pos2(x + bar_width, inner.bottom())), 0.0, tokens.text_dim); + } + + let x_at = |handle: LevelsHandle| track_x(&inner.x_range(), handle.position(levels)); + let (low, high) = (x_at(LevelsHandle::InputLow), x_at(LevelsHandle::InputHigh)); + let shade = tokens.field.gamma_multiply(OUTSIDE_RANGE_SHADE); + painter.rect_filled(Rect::from_x_y_ranges(inner.left()..=low, inner.y_range()), 0.0, shade); + painter.rect_filled(Rect::from_x_y_ranges(high..=inner.right(), inner.y_range()), 0.0, shade); + vertical_line(low, tokens.accent); + vertical_line(high, tokens.accent); + vertical_line(x_at(LevelsHandle::Gamma), tokens.text_dim.gamma_multiply(GAMMA_LINE_OPACITY)); +} + +/// A black-to-white strip: the output values the output handles pick from +fn paint_output_gradient(ui: &Ui, strip: Rect) { + let mut mesh = egui::Mesh::default(); + for (corner, color) in + [(strip.left_top(), Color32::BLACK), (strip.right_top(), Color32::WHITE), (strip.right_bottom(), Color32::WHITE), (strip.left_bottom(), Color32::BLACK)] + { + mesh.colored_vertex(corner, color); + } + mesh.add_triangle(0, 1, 2); + mesh.add_triangle(0, 2, 3); + + let painter = ui.painter(); + painter.add(mesh); + painter.rect_stroke(strip, 0.0, Stroke::new(1.0, Tokens::get(ui.ctx()).field_border), egui::StrokeKind::Outside); +} + +/// Each handle filled with its gray and its value beside it, the active one first and overlapping values left out +fn paint_handles_and_values(ui: &Ui, rect: Rect, responses: &[(LevelsHandle, Response)], levels: &Levels, typing: Option) { + let track = track(rect); + let tokens = Tokens::get(ui.ctx()); + let painter = ui.painter(); + let font = egui::FontId::proportional(VALUE_FONT_SIZE); + let is_active = |response: &Response| response.dragged() || response.hovered(); + let mut printed: Vec = Vec::new(); + let mut by_priority: Vec<&(LevelsHandle, Response)> = responses.iter().collect(); + by_priority.sort_by_key(|(_, response)| !is_active(response)); + + for &(handle, ref response) in by_priority { + let x = track_x(&track, handle.position(levels)); + let fill = match handle { + LevelsHandle::InputLow => Color32::BLACK, + LevelsHandle::Gamma => Color32::from_gray(GAMMA_HANDLE_GRAY), + LevelsHandle::InputHigh => Color32::WHITE, + LevelsHandle::OutputLow | LevelsHandle::OutputHigh => Color32::from_gray((handle.value(levels).clamp(0.0, 1.0) * 255.0).round() as u8), + }; + let outline = if response.dragged() { + tokens.accent + } else if response.hovered() { + tokens.text_strong + } else { + tokens.text + }; + let points_down = LevelsHandle::INPUT.contains(&handle); + painter.add(egui::Shape::convex_polygon(handle_outline(x, handle_top(rect, handle), points_down), fill, Stroke::new(1.0, outline))); + if typing == Some(handle) { + continue; + } + + let color = if is_active(response) { tokens.text_strong } else { tokens.text_dim }; + let galley = painter.layout_no_wrap(shown_value(handle.value(levels)), font.clone(), color); + let text_rect = value_rect(rect, handle, levels, galley.size()); + if printed.iter().any(|other| other.expand(VALUE_SPACING).intersects(text_rect)) { + continue; + } + + painter.galley(text_rect.min, galley, color); + printed.push(text_rect); + } +} + +/// A pentagon pointer centred on `x`: flat side away from the track, tip touching it +fn handle_outline(x: f32, top: f32, points_down: bool) -> Vec { + let bottom = top + HANDLE_HEIGHT; + let (flat, side_end, tip) = if points_down { (top, top + HANDLE_SIDE_HEIGHT, bottom) } else { (bottom, bottom - HANDLE_SIDE_HEIGHT, top) }; + vec![ + pos2(x - HANDLE_HALF_WIDTH, flat), + pos2(x + HANDLE_HALF_WIDTH, flat), + pos2(x + HANDLE_HALF_WIDTH, side_end), + pos2(x, tip), + pos2(x - HANDLE_HALF_WIDTH, side_end), + ] +} + +/// Opens the box that types `handle`'s value, holding its current value +fn start_typing(ui: &Ui, typing_id: Id, handle: LevelsHandle, levels: &Levels) { + let text = format!("{:.VALUE_DECIMALS$}", handle.value(levels)); + ui.data_mut(|data| data.insert_temp(typing_id, (handle, text))); +} + +/// The floating box a value is typed into: Enter or a click elsewhere applies it as one undo step, Escape drops it +fn typed_value(ui: &Ui, rect: Rect, typing_id: Id, (handle, mut text): (LevelsHandle, String), opened: bool, levels: &mut Levels) -> Option { + let field_id = typing_id.with("field"); + let field = value_rect(rect, handle, levels, vec2(TYPED_VALUE_WIDTH, VALUE_ROW_HEIGHT)); + // Floating over the editor, so opening it never moves the rest of the panel + let response = egui::Area::new(typing_id.with("area")) + .order(egui::Order::Foreground) + .fixed_pos(field.min) + .show(ui.ctx(), |ui| { + let text_edit = egui::TextEdit::singleline(&mut text) + .id(field_id) + .font(egui::FontId::proportional(VALUE_FONT_SIZE)) + .align(egui::Align2::CENTER_CENTER) + .margin(TYPED_VALUE_MARGIN); + ui.add_sized(field.size(), text_edit) + }) + .inner; + + // The app can consume Escape before the box sees it, so read the raw event + let escape = ui.input(|input| input.raw.events.iter().any(|event| matches!(event, egui::Event::Key { key: egui::Key::Escape, pressed: true, .. }))); + + if opened { + // Typing replaces the value; selected only now, as the unfocused box collapses a selection + let mut state = egui::text_edit::TextEditState::load(ui.ctx(), field_id).unwrap_or_default(); + state.cursor.set_char_range(Some(egui::text::CCursorRange::select_all_str(&text))); + state.store(ui.ctx(), field_id); + response.request_focus(); + return None; + } + + if response.has_focus() && !escape { + ui.data_mut(|data| data.insert_temp(typing_id, (handle, text))); + return None; + } + + ui.data_mut(|data| data.remove::<(LevelsHandle, String)>(typing_id)); + ui.memory_mut(|memory| memory.surrender_focus(field_id)); + // A box left open while the editor was hidden is dropped, not applied later + if !response.lost_focus() { + return None; + } + + let typed = text.trim().parse::().ok().filter(|value| value.is_finite()); + let (false, Some(typed)) = (escape, typed) else { return None }; + + let mut next = *levels; + handle.set_value(&mut next, typed); + if next == *levels { + return None; + } + + *levels = next; + Some(false) +} diff --git a/crates/ui-egui/src/levels_handle.rs b/crates/ui-egui/src/levels_handle.rs new file mode 100644 index 00000000..0ac160f6 --- /dev/null +++ b/crates/ui-egui/src/levels_handle.rs @@ -0,0 +1,91 @@ +//! The five handles of the levels editor and how each one reads and moves a [`Levels`] + +use texturecraft_engine::core::Levels; + +use crate::i18n::tr; + +/// Narrowest gap the handles and typed values leave between the low and high handle of a pair +const MIN_HANDLE_GAP: f32 = 0.01; + +/// Gamma range of the handle and typed values: the engine's own, so the handle nearly reaches either input handle +const GAMMA_RANGE: std::ops::RangeInclusive = 0.01..=10.0; + +/// One draggable value of a levels effect +#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] +pub enum LevelsHandle { + InputLow, + Gamma, + InputHigh, + OutputLow, + OutputHigh, +} + +impl LevelsHandle { + /// The handles above the histogram, left to right at the default levels + pub const INPUT: [LevelsHandle; 3] = [LevelsHandle::InputLow, LevelsHandle::Gamma, LevelsHandle::InputHigh]; + + pub fn label(self) -> &'static str { + match self { + LevelsHandle::InputLow => tr("Input low"), + LevelsHandle::Gamma => tr("Gamma"), + LevelsHandle::InputHigh => tr("Input high"), + LevelsHandle::OutputLow => tr("Output low"), + LevelsHandle::OutputHigh => tr("Output high"), + } + } + + pub fn value(self, levels: &Levels) -> f32 { + match self { + LevelsHandle::InputLow => levels.in_low, + LevelsHandle::Gamma => levels.gamma, + LevelsHandle::InputHigh => levels.in_high, + LevelsHandle::OutputLow => levels.out_low, + LevelsHandle::OutputHigh => levels.out_high, + } + } + + /// Where the handle sits along its track (0 left, 1 right); gamma 1 is halfway between the input handles + pub fn position(self, levels: &Levels) -> f32 { + match self { + LevelsHandle::Gamma => levels.in_low + input_span(levels) * 0.5f32.powf(levels.gamma), + _ => self.value(levels), + } + .clamp(0.0, 1.0) + } + + /// Moves the handle to `position` along its track (see [`Self::position`]) + pub fn set_position(self, levels: &mut Levels, position: f32) { + let value = match self { + LevelsHandle::Gamma => { + let span = input_span(levels).max(f32::EPSILON); + let fraction = ((position - levels.in_low) / span).clamp(f32::EPSILON, 1.0 - f32::EPSILON); + fraction.ln() / 0.5f32.ln() + } + _ => position, + }; + self.set_value(levels, value); + } + + /// Sets the handle's value without crossing a neighbour: input low < gamma < input high, outputs keep their sides + pub fn set_value(self, levels: &mut Levels, value: f32) { + if !value.is_finite() { + return; + } + + // The gap keeps each output handle on its side; min/max, not clamp, as a project's bounds can cross + let inverted = levels.out_low > levels.out_high; + match self { + LevelsHandle::InputLow => levels.in_low = value.min(levels.in_high - MIN_HANDLE_GAP).max(0.0), + LevelsHandle::Gamma => levels.gamma = value.clamp(*GAMMA_RANGE.start(), *GAMMA_RANGE.end()), + LevelsHandle::InputHigh => levels.in_high = value.max(levels.in_low + MIN_HANDLE_GAP).min(1.0), + LevelsHandle::OutputLow if inverted => levels.out_low = value.max(levels.out_high + MIN_HANDLE_GAP).min(1.0), + LevelsHandle::OutputLow => levels.out_low = value.min(levels.out_high - MIN_HANDLE_GAP).max(0.0), + LevelsHandle::OutputHigh if inverted => levels.out_high = value.min(levels.out_low - MIN_HANDLE_GAP).max(0.0), + LevelsHandle::OutputHigh => levels.out_high = value.max(levels.out_low + MIN_HANDLE_GAP).min(1.0), + } + } +} + +fn input_span(levels: &Levels) -> f32 { + (levels.in_high - levels.in_low).max(0.0) +} diff --git a/crates/ui-egui/src/levels_properties.rs b/crates/ui-egui/src/levels_properties.rs new file mode 100644 index 00000000..fee6af57 --- /dev/null +++ b/crates/ui-egui/src/levels_properties.rs @@ -0,0 +1,130 @@ +//! Properties of a levels effect: the levels editor, then the channel picker (content), Reset, Auto and Invert + +use std::sync::Arc; + +use egui::Ui; +use serde_json::json; +use texturecraft_engine::core::{Channel, ChannelKind, Layer, LayerId, Levels}; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::levels_editor::levels_editor; +use crate::theme::caption; + +/// Buckets of the histogram, over 0..1 +const HISTOGRAM_BUCKETS: usize = 64; + +/// Share of the counted texels a bucket needs to hold for Auto to keep it in the input range +const AUTO_MIN_SHARE: f64 = 0.001; + +/// The properties of levels effect `effect_id` of `layer`; every edit goes through `effect.set` +pub(crate) fn levels_properties(app: &mut TextureCraftApp, ui: &mut Ui, layer: &Layer, effect_id: LayerId, levels: &Levels) { + ui.label(caption(tr("Levels"))); + let is_content = layer.content_effects.iter().any(|effect| effect.id == effect_id); + let channels: Vec = + if is_content { layer.channels.keys().copied().filter(|channel| channel.kind() != ChannelKind::NormalMap).collect() } else { Vec::new() }; + let picked = egui::Id::unique(("levels_channel", effect_id.0)); + let channel = ui + .data(|data| data.get_temp(picked)) + .filter(|channel| channels.contains(channel)) + .or(channels.first().copied()) + .or(layer.channels.keys().next().copied()) + .unwrap_or(Channel::BaseColor); + let counts = histogram_counts(app, ui, effect_id, channel); + + let mut edited = *levels; + let mut edit = levels_editor(ui, effect_id, counts.as_ref().map(|counts| counts.as_slice()), &mut edited); + ui.horizontal(|ui| { + if !channels.is_empty() { + egui::ComboBox::from_id_salt(picked) + .selected_text(tr(channel.label())) + .show_ui(ui, |ui| { + for option in channels { + if ui.selectable_label(option == channel, tr(option.label())).clicked() { + ui.data_mut(|data| data.insert_temp(picked, option)); + } + } + }) + .response + .on_hover_text(tr("Channel")); + } + + // Right to left: the last button comes first + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(tr("Invert")).clicked() { + std::mem::swap(&mut edited.out_low, &mut edited.out_high); + edit = Some(false); + } + + let auto_range = counts.as_ref().and_then(|counts| auto_input_range(counts)); + let auto = ui.add_enabled(auto_range.is_some(), egui::Button::new(tr("Auto"))).on_hover_text(tr("Fit the input range to the histogram")); + if auto.clicked() + && let Some((low, high)) = auto_range + { + (edited.in_low, edited.in_high) = (low, high); + edit = Some(false); + } + + if ui.add_enabled(edited != Levels::default(), egui::Button::new(tr("Reset"))).clicked() { + edited = Levels::default(); + edit = Some(false); + } + }); + }); + + // Auto or Invert with nothing to change would add an empty undo step + if let Some(merge) = edit + && edited != *levels + { + let Levels { in_low, in_high, gamma, out_low, out_high } = edited; + app.run( + "effect.set", + json!({"effect": effect_id.0, "inLow": in_low, "inHigh": in_high, "gamma": gamma, "outLow": out_low, "outHigh": out_high, "merge": merge}), + ); + } +} + +/// The histogram levels effect `effect_id` remaps, recomputed after a change once no pointer button is held +fn histogram_counts(app: &TextureCraftApp, ui: &Ui, effect_id: LayerId, channel: Channel) -> Option>> { + let key = egui::Id::unique(("levels_histogram", effect_id.0, channel)); + let revision = app.session.revision; + match ui.data(|data| data.get_temp::<(u64, Arc>)>(key)) { + Some((cached, counts)) if cached == revision || ui.input(|input| input.pointer.any_down()) => Some(counts), + _ => app.session.effect_histogram(effect_id, channel, HISTOGRAM_BUCKETS).map(|counts| { + let counts = Arc::new(counts); + ui.data_mut(|data| data.insert_temp(key, (revision, counts.clone()))); + counts + }), + } +} + +/// The input range Auto picks: the first to the last bucket holding more than [`AUTO_MIN_SHARE`] of the texels +fn auto_input_range(counts: &[u32]) -> Option<(f32, f32)> { + let total: u64 = counts.iter().map(|&count| u64::from(count)).sum(); + let holds_enough = |count: &u32| f64::from(*count) > total as f64 * AUTO_MIN_SHARE; + let first = counts.iter().position(holds_enough)?; + let last = counts.iter().rposition(holds_enough)?; + let buckets = counts.len() as f32; + Some((first as f32 / buckets, (last + 1) as f32 / buckets)) +} + +#[cfg(test)] +mod tests { + use super::{HISTOGRAM_BUCKETS, auto_input_range}; + + #[test] + fn auto_skips_buckets_under_the_share() { + let mut counts = vec![0u32; HISTOGRAM_BUCKETS]; + counts[3] = 1; + counts[10] = 5_000; + counts[40] = 5_000; + counts[60] = 1; + assert_eq!(auto_input_range(&counts), Some((10.0 / HISTOGRAM_BUCKETS as f32, 41.0 / HISTOGRAM_BUCKETS as f32))); + } + + #[test] + fn auto_has_nothing_to_fit_in_an_empty_histogram() { + assert_eq!(auto_input_range(&[0; HISTOGRAM_BUCKETS]), None); + assert_eq!(auto_input_range(&[]), None); + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5b5045e6..7367894e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -16,6 +16,9 @@ pub mod fonts; pub mod gpu; pub mod i18n; pub mod keymap; +mod levels_editor; +mod levels_handle; +mod levels_properties; mod mask_preview_image; mod mask_shape; pub mod menus; diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 79aa7eab..64a6f4e2 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -142,31 +142,6 @@ fn track(ui: &Ui, resp: &Response, x: std::ops::RangeInclusive, y: f32, t: p.circle(egui::pos2(xk, y), knob, tk.panel, Stroke::new(1.5, ring)); } -/// A histogram of `counts` (buckets over 0..1, scaled to the fullest) in a field-colored well -/// the width of the panel, the part of 0..1 outside `range` dimmed. -pub fn histogram(ui: &mut Ui, counts: &[u32], range: (f32, f32)) -> Response { - let tk = Tokens::get(ui.ctx()); - let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), 56.0), Sense::hover()); - let p = ui.painter_at(rect); - p.rect(rect, CornerRadius::same(tk.radius), tk.field, Stroke::new(1.0, tk.field_border), egui::StrokeKind::Inside); - let inner = rect.shrink(3.0); - let max = counts.iter().copied().max().unwrap_or(0).max(1) as f32; - let w = inner.width() / counts.len().max(1) as f32; - for (i, c) in counts.iter().enumerate() { - let h = inner.height() * *c as f32 / max; - let x = inner.left() + i as f32 * w; - p.rect_filled(egui::Rect::from_min_max(egui::pos2(x, inner.bottom() - h), egui::pos2(x + w, inner.bottom())), 0.0, tk.text_dim); - } - let x = |t: f32| inner.left() + inner.width() * t.clamp(0.0, 1.0); - let shade = tk.field.gamma_multiply(0.7); - p.rect_filled(egui::Rect::from_x_y_ranges(inner.left()..=x(range.0), inner.y_range()), 0.0, shade); - p.rect_filled(egui::Rect::from_x_y_ranges(x(range.1)..=inner.right(), inner.y_range()), 0.0, shade); - for t in [range.0, range.1] { - p.line_segment([egui::pos2(x(t), inner.top()), egui::pos2(x(t), inner.bottom())], Stroke::new(1.0, tk.accent)); - } - resp -} - /// One line of `text` cut with "…" to fit `max_width`, for list rows that shrink with their panel. pub fn elided(painter: &egui::Painter, text: impl Into, size: f32, color: Color32, max_width: f32) -> std::sync::Arc { let mut job = egui::text::LayoutJob::simple_singleline(text.into(), egui::FontId::proportional(size), color); diff --git a/crates/ui-egui/tests/effect_sliders.rs b/crates/ui-egui/tests/effect_sliders.rs index c5374fb0..a26ac303 100644 --- a/crates/ui-egui/tests/effect_sliders.rs +++ b/crates/ui-egui/tests/effect_sliders.rs @@ -78,10 +78,10 @@ fn dragging_a_generator_slider_applies_live_as_one_undo_step() { assert_eq!(h.state().session.history_labels().len(), steps + 1, "one undo step for the drag"); } -/// The combo box in the row of the "Channel" label. +/// The combo box in the row of the levels editor's Reset button. fn channel_picker<'a>(h: &'a Harness<'_, TextureCraftApp>) -> egui_kittest::Node<'a> { - let row = h.get_by_label("Channel").rect().center().y; - h.get_all(by().role(Role::ComboBox)).find(|n| (n.rect().center().y - row).abs() < 4.0).unwrap() + let row = h.get_by_label("Reset").rect().center().y; + h.get_all(by().role(Role::ComboBox)).find(|node| (node.rect().center().y - row).abs() < 4.0).unwrap() } /// A content levels effect offers a channel for its histogram; picking one keeps it selected. diff --git a/crates/ui-egui/tests/levels_editor.rs b/crates/ui-egui/tests/levels_editor.rs new file mode 100644 index 00000000..c09246c4 --- /dev/null +++ b/crates/ui-egui/tests/levels_editor.rs @@ -0,0 +1,247 @@ +//! The levels editor in Properties: handles, typed values and Reset, Auto and Invert edit the effect + +use egui::accesskit::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable, by}; +use serde_json::{Value, json}; +use texturecraft_engine::core::{Channel, EffectKind, LayerId, Levels}; +use texturecraft_engine::{Session, execute}; +use texturecraft_ui_egui::TextureCraftApp; + +/// Histogram buckets and Auto's share, as in levels_properties.rs +const HISTOGRAM_BUCKETS: usize = 64; +const AUTO_MIN_SHARE: f64 = 0.001; + +/// A clouds mask under a levels effect added by `command` with `params`, selected, and its id +fn levels_harness(command: &str, params: Value) -> (Harness<'static, TextureCraftApp>, LayerId) { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + for (id, params) in [ + ("layer.add.fill", json!({"color": [0.8, 0.3, 0.1]})), + ("mask.add.black", Value::Null), + ("effect.add.fill", json!({"target": "mask", "procedural": "clouds"})), + (command, params), + ] { + execute(&mut session, id, ¶ms).unwrap(); + } + let effect = levels_effect(&session); + open(session, effect) +} + +fn open(mut session: Session, effect: LayerId) -> (Harness<'static, TextureCraftApp>, LayerId) { + let (layer, _) = session.doc.project.effect(effect).unwrap(); + execute(&mut session, "layer.select", &json!({"layer": layer.0, "target": effect.0})).unwrap(); + // Frames of a 60 Hz screen: kittest's default quarter second spreads a double-click past egui's delay + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 1400.0)).with_step_dt(1.0 / 60.0).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.run_steps(4); + (harness, effect) +} + +/// The newest levels effect in the project +fn levels_effect(session: &Session) -> LayerId { + let layers = session.doc.project.layers.values(); + let effects = layers.flat_map(|layer| layer.content_effects.iter().chain(layer.mask.iter().flat_map(|mask| mask.effects.iter()))); + effects.filter(|effect| matches!(effect.kind, EffectKind::Levels(_))).map(|effect| effect.id).max_by_key(|id| id.0).unwrap() +} + +fn levels(harness: &Harness<'_, TextureCraftApp>, effect: LayerId) -> Levels { + match &harness.state().session.doc.project.effect(effect).unwrap().1.kind { + EffectKind::Levels(levels) => *levels, + other => panic!("a levels effect, found {other:?}"), + } +} + +fn undo_steps(harness: &Harness<'_, TextureCraftApp>) -> usize { + harness.state().session.history_labels().len() +} + +fn handle(harness: &Harness<'_, TextureCraftApp>, label: &str) -> egui::Pos2 { + harness.get_by_role_and_label(Role::Slider, label).rect().center() +} + +/// The button labelled `label` (an effect in the stack can share its name) +fn button<'a>(harness: &'a Harness<'_, TextureCraftApp>, label: &'a str) -> egui_kittest::Node<'a> { + harness.get_by_role_and_label(Role::Button, label) +} + +/// Presses at `from`, moves in a few steps to `to` (one frame each, like a hand) and releases +fn drag(harness: &mut Harness<'_, TextureCraftApp>, from: egui::Pos2, to: egui::Pos2) { + harness.drag_at(from); + harness.run_steps(2); + for step in 1..=4 { + harness.hover_at(from + (to - from) * (step as f32 / 4.0)); + harness.run_steps(1); + } + harness.drop_at(to); + harness.run_steps(3); +} + +fn set_levels(harness: &mut Harness<'_, TextureCraftApp>, effect: LayerId, mut params: Value) { + params["effect"] = json!(effect.0); + execute(&mut harness.state_mut().session, "effect.set", ¶ms).unwrap(); + harness.run_steps(3); +} + +#[test] +fn dragging_each_handle_edits_its_value_in_one_undo_step() { + let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask"})); + for (label, offset_x) in [("Input low", 80.0), ("Input high", -80.0), ("Gamma", 30.0), ("Output low", 60.0), ("Output high", -60.0)] { + let before = levels(&harness, effect); + let steps = undo_steps(&harness); + let at = handle(&harness, label); + drag(&mut harness, at, at + egui::vec2(offset_x, 0.0)); + let after = levels(&harness, effect); + let changed: Vec<&str> = [ + ("Input low", before.in_low != after.in_low), + ("Input high", before.in_high != after.in_high), + ("Gamma", before.gamma != after.gamma), + ("Output low", before.out_low != after.out_low), + ("Output high", before.out_high != after.out_high), + ] + .into_iter() + .filter_map(|(name, changed)| changed.then_some(name)) + .collect(); + assert_eq!(changed, [label], "dragging {label} changes only it: {before:?} -> {after:?}"); + assert_eq!(undo_steps(&harness), steps + 1, "dragging {label} is one undo step"); + } + + let dragged = levels(&harness, effect); + assert!(dragged.in_low > 0.0 && dragged.in_high < 1.0 && dragged.out_low > 0.0 && dragged.out_high < 1.0, "{dragged:?}"); + assert!(dragged.gamma < 1.0, "gamma right of the middle darkens: {}", dragged.gamma); +} + +#[test] +fn handles_stop_at_their_neighbours() { + let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask", "inLow": 0.2, "inHigh": 0.6, "outLow": 0.3, "outHigh": 0.7})); + let far_right = egui::vec2(1000.0, 0.0); + for label in ["Input low", "Gamma", "Output low"] { + let at = handle(&harness, label); + drag(&mut harness, at, at + far_right); + } + let edited = levels(&harness, effect); + assert!((edited.in_low - 0.59).abs() < 1e-4, "input low stops below input high: {edited:?}"); + assert_eq!(edited.gamma, 0.01, "gamma stops at its lowest value"); + let gap = handle(&harness, "Input high").x - handle(&harness, "Gamma").x; + assert!((0.0..1.0).contains(&gap), "the gamma handle reaches input high over this narrow range: {gap} pt apart"); + assert!((edited.out_low - 0.69).abs() < 1e-4, "output low stops below output high: {edited:?}"); +} + +#[test] +fn output_handles_keep_their_side_once_inverted() { + let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask", "outLow": 0.2, "outHigh": 0.8})); + button(&harness, "Invert").click(); + harness.run_steps(3); + let inverted = levels(&harness, effect); + assert_eq!((inverted.out_low, inverted.out_high), (0.8, 0.2)); + + let at = handle(&harness, "Output high"); + drag(&mut harness, at, at + egui::vec2(1000.0, 0.0)); + let edited = levels(&harness, effect); + assert!((edited.out_high - 0.79).abs() < 1e-4, "output high stops below output low: {edited:?}"); +} + +#[test] +fn reset_and_invert_are_one_undo_step_each() { + let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask"})); + assert!(button(&harness, "Reset").accesskit_node().is_disabled(), "nothing to reset at the defaults"); + set_levels(&mut harness, effect, json!({"inLow": 0.1, "inHigh": 0.9, "gamma": 2.0, "outLow": 0.2, "outHigh": 0.7})); + + let steps = undo_steps(&harness); + button(&harness, "Invert").click(); + harness.run_steps(3); + assert_eq!(levels(&harness, effect), Levels { in_low: 0.1, in_high: 0.9, gamma: 2.0, out_low: 0.7, out_high: 0.2 }); + assert_eq!(undo_steps(&harness), steps + 1); + + button(&harness, "Reset").click(); + harness.run_steps(3); + assert_eq!(levels(&harness, effect), Levels::default()); + assert_eq!(undo_steps(&harness), steps + 2); +} + +#[test] +fn auto_fits_the_input_range_to_the_histogram() { + let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask", "gamma": 1.5})); + let counts = harness.state().session.effect_histogram(effect, Channel::BaseColor, HISTOGRAM_BUCKETS).unwrap(); + let total: u32 = counts.iter().sum(); + let holds = |count: &u32| f64::from(*count) > f64::from(total) * AUTO_MIN_SHARE; + let low = counts.iter().position(holds).unwrap() as f32 / HISTOGRAM_BUCKETS as f32; + let high = (counts.iter().rposition(holds).unwrap() + 1) as f32 / HISTOGRAM_BUCKETS as f32; + assert!(low > 0.0 || high < 1.0, "the clouds don't fill the whole range: {low}..{high}"); + + button(&harness, "Auto").click(); + harness.run_steps(3); + let edited = levels(&harness, effect); + assert_eq!((edited.in_low, edited.in_high), (low, high)); + assert_eq!(edited.gamma, 1.5, "Auto leaves gamma"); + + let steps = undo_steps(&harness); + button(&harness, "Auto").click(); + harness.run_steps(3); + assert_eq!(undo_steps(&harness), steps, "Auto again changes nothing, so it adds no undo step"); +} + +/// Double-clicks `label`'s handle, then types `text` into the box that opens with the value selected +fn type_value(harness: &mut Harness<'_, TextureCraftApp>, label: &str, text: &str) { + let at = handle(harness, label); + harness.event(egui::Event::PointerMoved(at)); + for pressed in [true, false, true, false] { + harness.event(egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); + } + harness.run_steps(2); + for character in text.chars() { + harness.event(egui::Event::Text(character.to_string())); + harness.run_steps(1); + } +} + +#[test] +fn a_value_typed_after_double_clicking_a_handle_applies() { + let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask"})); + let steps = undo_steps(&harness); + type_value(&mut harness, "Gamma", "2.5"); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + assert_eq!(levels(&harness, effect).gamma, 2.5); + assert_eq!(undo_steps(&harness), steps + 1); +} + +#[test] +fn the_typing_box_moves_nothing_in_the_panel() { + let (mut harness, _) = levels_harness("effect.add.levels", json!({"target": "mask"})); + let buttons = |harness: &Harness<'_, TextureCraftApp>| ["Reset", "Auto", "Invert"].map(|label| button(harness, label).rect()); + let before = buttons(&harness); + type_value(&mut harness, "Output low", ""); + assert!(harness.query_all(by().role(Role::TextInput)).any(|node| node.is_focused()), "the box is open"); + assert_eq!(buttons(&harness), before); +} + +#[test] +fn escape_drops_a_typed_value() { + let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask"})); + let steps = undo_steps(&harness); + type_value(&mut harness, "Output low", "0.4"); + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + assert_eq!(levels(&harness, effect), Levels::default()); + assert_eq!(undo_steps(&harness), steps); + assert!(harness.query_by_value("0.4").is_none(), "the box closed"); +} + +#[test] +fn a_typed_value_keeps_input_low_below_input_high() { + let (mut harness, effect) = levels_harness("effect.add.levels", json!({"target": "mask", "inHigh": 0.5})); + type_value(&mut harness, "Input low", "0.9"); + harness.key_press(egui::Key::Enter); + harness.run_steps(3); + assert!((levels(&harness, effect).in_low - 0.49).abs() < 1e-4, "{:?}", levels(&harness, effect)); +} + +#[test] +fn the_levels_filter_shows_the_same_editor() { + let (harness, _) = levels_harness("effect.add.filter", json!({"target": "mask", "filter": "levels"})); + for label in ["Input low", "Gamma", "Input high", "Output low", "Output high"] { + harness.get_by_role_and_label(Role::Slider, label); + } + for button in ["Reset", "Auto", "Invert"] { + harness.get_by_role_and_label(Role::Button, button); + } +} From 8eeb8e5e7e78d331b18f2ca2d8df6b35b8b36b41 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sat, 7 Nov 2026 16:54:00 +0100 Subject: [PATCH 16/64] Name the exact byte counts in the too-large-to-save error Co-Authored-By: Claude Sonnet 5.5 --- crates/formats/src/project_file/mod.rs | 2 +- crates/formats/src/project_file/tests.rs | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index 92f6ca8a..3319c4f0 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -147,7 +147,7 @@ fn check_loadable(pf: &ProjectFile, limit: u64) -> Result<()> { if size > limit { let gib = |b: u64| b as f64 / (1u64 << 30) as f64; return Err(FormatError::TooLarge(format!( - "the project holds {:.2} GiB of data once unpacked, but TextureCraft opens project files only up to {:.2} GiB, so nothing was saved and an existing file is unchanged. \ + "the project holds {:.2} GiB ({size} bytes) of data once unpacked, but TextureCraft opens project files only up to {:.2} GiB ({limit} bytes), so nothing was saved and an existing file is unchanged. \ Remove paint layers or baked maps to make it smaller", gib(size), gib(limit) diff --git a/crates/formats/src/project_file/tests.rs b/crates/formats/src/project_file/tests.rs index b16d2f02..074566bf 100644 --- a/crates/formats/src/project_file/tests.rs +++ b/crates/formats/src/project_file/tests.rs @@ -358,6 +358,9 @@ fn a_project_too_big_to_reopen_is_not_saved() { let err = check_loadable(&s.pf, size - 1).unwrap_err(); assert!(matches!(err, FormatError::TooLarge(_))); assert!(err.to_string().contains("nothing was saved"), "{err}"); + // Exact byte counts: a size just over the limit does not read as the limit. + let msg = err.to_string(); + assert!(msg.contains(&format!("({size} bytes)")) && msg.contains(&format!("({} bytes)", size - 1)), "{msg}"); } #[cfg(not(target_arch = "wasm32"))] From c827d1b910c0a8eb625d396289989e148244c30d Mon Sep 17 00:00:00 2001 From: Rebornim Date: Fri, 6 Nov 2026 23:48:32 +0000 Subject: [PATCH 17/64] Drop a shelf image on the texture set under the cursor, as a channel or a mask An image dragged over the 3D view highlights the texture set under the cursor, as materials do. A drop opens a menu at the drop point: Mask, then that set's channels. A pick selects the set and places the decal there with the image in the picked channel, or as the gray mask of a new fill layer. A click elsewhere places nothing; the background opens no menu. layer.add.decal takes channel (a channel id, default baseColor, or "mask") and adds the decal to the set under the point, selecting it, as one undo step. layer.decal.set takes effect to edit a mask decal, so the view's frame and handles work on it too, and a new image stays in the channel the decal was placed in. One-value channels and masks read an image's gray instead of its red. --- crates/compose/src/eval.rs | 49 ++++--- crates/engine/src/decal_cmds.rs | 209 +++++++++++++++++++--------- crates/engine/src/set_cmds.rs | 12 +- crates/engine/tests/painter_gaps.rs | 81 +++++++++++ crates/ui-egui/src/decal_drop.rs | 79 +++++++++++ crates/ui-egui/src/i18n/ar.rs | 1 + crates/ui-egui/src/i18n/de.rs | 1 + crates/ui-egui/src/i18n/es.rs | 1 + crates/ui-egui/src/i18n/fr.rs | 1 + crates/ui-egui/src/i18n/it.rs | 1 + crates/ui-egui/src/i18n/ja.rs | 1 + crates/ui-egui/src/i18n/ko.rs | 1 + crates/ui-egui/src/i18n/pt_br.rs | 1 + crates/ui-egui/src/i18n/zh_hans.rs | 1 + crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/shelf.rs | 40 ++++-- crates/ui-egui/src/viewport.rs | 112 +++++++++------ crates/ui-egui/tests/shelf_drop.rs | 71 +++++++++- 18 files changed, 518 insertions(+), 145 deletions(-) create mode 100644 crates/ui-egui/src/decal_drop.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index c2287a4b..308d11c2 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -1129,39 +1129,42 @@ impl<'a, 'b> Texel<'a, 'b> { w * image.map_or(1.0, |img| img.sample(c.uv.x, c.uv.y)[3].clamp(0.0, 1.0)) } - fn source(&mut self, s: &Source, proj: &Projection, kind: ChannelKind) -> [f32; 3] { - match s { - Source::Uniform(v) => *v, + fn source(&mut self, source: &Source, projection: &Projection, kind: ChannelKind) -> [f32; 3] { + match source { + Source::Uniform(value) => *value, Source::Procedural { pattern, low, high } => { - let (c, proj, _) = self.projected(proj); - let t = procedural(pattern, proj, &c); - mix3(*low, *high, t) + let (coords, projection, _) = self.projected(projection); + let amount = procedural(pattern, projection, &coords); + mix3(*low, *high, amount) } Source::Image { name, normal_format } => { - let Some(img) = self.inp.images.get(name) else { return [0.5; 3] }; - let (c, proj, _) = self.projected(proj); - let mut acc = [0.0f32; 4]; - for (uv, w) in image_samples(proj, &c).into_iter().filter(|(_, w)| *w > 0.0) { - let s = img.sample(uv.x, uv.y); - for k in 0..4 { - acc[k] += s[k] * w; + let Some(image) = self.inp.images.get(name) else { return [0.5; 3] }; + + let (coords, projection, _) = self.projected(projection); + let mut sum = [0.0f32; 4]; + for (uv, weight) in image_samples(projection, &coords).into_iter().filter(|(_, weight)| *weight > 0.0) { + for (total, value) in sum.iter_mut().zip(image.sample(uv.x, uv.y)) { + *total += value * weight; } } + + let rgb = [sum[0], sum[1], sum[2]]; match kind { - ChannelKind::Color if img.srgb => [acc[0], acc[1], acc[2]].map(texturecraft_texel::srgb_to_linear), - // Normal channels are OpenGL (+Y up the image): a DirectX image's green flips. - ChannelKind::NormalMap if *normal_format == NormalFormat::DirectX => [acc[0], 1.0 - acc[1], acc[2]], - ChannelKind::Color | ChannelKind::NormalMap => [acc[0], acc[1], acc[2]], - ChannelKind::Scalar => [acc[0]; 3], - ChannelKind::Signed => [acc[0] * 2.0 - 1.0; 3], + ChannelKind::Color if image.srgb => rgb.map(texturecraft_texel::srgb_to_linear), + // Normal channels are OpenGL (+Y up the image): a DirectX image's green flips + ChannelKind::NormalMap if *normal_format == NormalFormat::DirectX => [rgb[0], 1.0 - rgb[1], rgb[2]], + ChannelKind::Color | ChannelKind::NormalMap => rgb, + // A one-value channel or mask reads the image's gray, so a color image works as a mask + ChannelKind::Scalar => [lum(rgb); 3], + ChannelKind::Signed => [lum(rgb) * 2.0 - 1.0; 3], } } Source::Anchor { anchor, channel } => { - // An anchor not evaluated yet (above this layer, hidden) reads the channel default. - let v = self.anchors.iter().rev().find(|(id, _)| id == anchor).and_then(|(_, acc)| acc.get(channel.index()).copied()); - let v = v.unwrap_or_else(|| channel.default_value()); + // An anchor not evaluated yet (above this layer, hidden) reads the channel default + let anchored = self.anchors.iter().rev().find(|(id, _)| id == anchor).and_then(|(_, values)| values.get(channel.index()).copied()); + let value = anchored.unwrap_or_else(|| channel.default_value()); let gray = matches!(channel.kind(), ChannelKind::Color | ChannelKind::NormalMap) && matches!(kind, ChannelKind::Scalar | ChannelKind::Signed); - if gray { [lum(v); 3] } else { v } + if gray { [lum(value); 3] } else { value } } } } diff --git a/crates/engine/src/decal_cmds.rs b/crates/engine/src/decal_cmds.rs index e937b6f5..f3ec8b28 100644 --- a/crates/engine/src/decal_cmds.rs +++ b/crates/engine/src/decal_cmds.rs @@ -2,12 +2,12 @@ //! (a decal fill with a planar projection), as a fill layer with a decal projection. use serde_json::{Value, json}; -use texturecraft_core::{Channel, Decal, Fill, Layer, LayerId, LayerKind, Projection, Source}; +use texturecraft_core::{Channel, Decal, Effect, EffectKind, Fill, Layer, LayerId, LayerKind, Mask, MaskBackground, Projection, Source}; use texturecraft_geom::glam::{Vec2, Vec3}; -use crate::commands::{CommandSpec, always, bad, f32p, has_layer, layer_param, strp}; +use crate::commands::{CommandSpec, always, bad, channel_param, f32p, has_layer, layer_param, strp, u64p}; use crate::tool_cmds::viewport_of; -use crate::{Result, Session, cmd}; +use crate::{Result, Session, StackTarget, cmd}; pub fn specs() -> Vec { vec![ @@ -16,7 +16,7 @@ pub fn specs() -> Vec { "Add decal", [], None, - "{image: resource name, x?, y?: viewport pixels (default: the view center), viewport?: [w,h] | position?: [x,y,z], normal?: [x,y,z], up?: [x,y,z] (the image's up; default the view's up, or the view direction when that is along the normal), size?: height | [w,h] (world units; default a quarter of the mesh), rotation?: degrees, depth?, name?} — a fill layer projecting the image from a frame placed on the surface; seen from the front, the image reads the right way round", + "{image: resource name, channel?: a channel id (default baseColor) | \"mask\" (a new fill layer masked by the image's gray), x?, y?: viewport pixels (default: the view center; a point on another texture set selects it), viewport?: [w,h] | position?: [x,y,z], normal?: [x,y,z], up?: [x,y,z] (the image's up; default the view's up, or the view direction when that is along the normal), size?: height | [w,h] (world units; default a quarter of the mesh), rotation?: degrees, depth?, name?} — a fill layer projecting the image from a frame placed on the surface; seen from the front, the image reads the right way round", always, add ), @@ -25,7 +25,7 @@ pub fn specs() -> Vec { "Edit decal", [], None, - "{layer?, x?, y?, viewport? | position?, normal? (re-place it), up?: [x,y,z], size?: height | [w,h], rotation?: degrees, offset?: [right, up] (world units from where it was placed), depth?, image?, merge?: true continues the previous Edit decal undo step (drags)}", + "{layer? | effect?: a mask fill effect id (a decal placed as a mask), x?, y?, viewport? | position?, normal? (re-place it), up?: [x,y,z], size?: height | [w,h], rotation?: degrees, offset?: [right, up] (world units from where it was placed), depth?, image?, merge?: true continues the previous Edit decal undo step (drags)}", has_layer, set ), @@ -42,43 +42,50 @@ fn vec3(p: &Value, key: &str) -> Option { } } -/// Where a decal goes: a surface point and its normal, from `x`/`y` (viewport pixels, the view -/// center by default) or `position` + `normal`. None when `optional` and neither is given. -fn placement(s: &Session, cmd: &str, p: &Value, optional: bool) -> Result> { - if let Some(pos) = vec3(p, "position") { - let n = vec3(p, "normal").and_then(Vec3::try_normalize).ok_or_else(|| bad(cmd, "`position` needs a non-zero `normal`"))?; - return Ok(Some((pos, n))); +/// Where a decal goes and the texture set it lands on, from `x`/`y` (viewport pixels, the view center by default) or `position` + `normal` (on the active set); None when `optional` and neither is given +fn placement(s: &Session, cmd: &str, p: &Value, optional: bool) -> Result> { + if let Some(position) = vec3(p, "position") { + let normal = vec3(p, "normal").and_then(Vec3::try_normalize).ok_or_else(|| bad(cmd, "`position` needs a non-zero `normal`"))?; + return Ok(Some((position, normal, s.ts()))); } - let vp = viewport_of(s, p); + + let viewport = viewport_of(s, p); let at = match (f32p(p, "x"), f32p(p, "y")) { (Some(x), Some(y)) => Vec2::new(x, y), _ if optional => return Ok(None), - _ => vp * 0.5, + _ => viewport * 0.5, }; - let hit = s.pick(at, vp).ok_or_else(|| bad(cmd, "nothing under that point: place the decal on the mesh"))?; - if s.doc.project.texture_set(s.ts()).ok().map(|t| t.material) != Some(hit.material) { - return Err(bad(cmd, "that surface belongs to another texture set")); - } - Ok(Some((hit.pos, hit.nrm))) + let hit = s.pick(at, viewport).ok_or_else(|| bad(cmd, "nothing under that point: place the decal on the mesh"))?; + let ts = s.texture_set_of_material(hit.material).ok_or_else(|| bad(cmd, "that surface has no texture set"))?; + Ok(Some((hit.pos, hit.nrm, ts))) } +/// A new decal's height, relative to the mesh diagonal +const DEFAULT_HEIGHT: f32 = 0.25; + +/// The smallest decal side or depth, relative to the mesh diagonal +const MIN_SIZE: f32 = 1e-4; + +/// The largest decal side or depth, relative to the mesh diagonal +const MAX_SIZE: f32 = 10.0; + /// The mesh's diagonal (decal sizes are relative to it). fn mesh_size(s: &Session) -> f32 { let (lo, hi) = s.mesh.bounds(); (hi - lo).length().max(1e-3) } -/// Width and height from a `size` param (a height keeping `aspect`, or `[w, h]`). -fn size_param(p: &Value, aspect: f32, diag: f32) -> Option<[f32; 2]> { - let v = p.get("size")?; - let size = match v.as_array() { - Some(a) => [a.first()?.as_f64()? as f32, a.get(1)?.as_f64()? as f32], +/// Width and height from a `size` param (a height keeping `aspect`, or `[w, h]`), within the decal size limits +fn size_param(p: &Value, aspect: f32, mesh_diagonal: f32) -> Option<[f32; 2]> { + let value = p.get("size")?; + let size = match value.as_array() { + Some(pair) => [pair.first()?.as_f64()? as f32, pair.get(1)?.as_f64()? as f32], None => { - let h = v.as_f64()? as f32; - [h * aspect, h] + let height = value.as_f64()? as f32; + [height * aspect, height] } }; - size.iter().all(|x| x.is_finite()).then(|| size.map(|x| x.clamp(diag * 1e-4, diag * 10.0))) + size.iter().all(|side| side.is_finite()).then(|| size.map(|side| side.clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE))) } /// The decal's up direction: `up` when given, else the camera's (decals are placed upright on @@ -96,11 +103,25 @@ fn decal_up(s: &Session, cmd: &str, p: &Value, normal: Vec3) -> Result { fn add(s: &mut Session, p: &Value) -> Result { let cmd = "layer.add.decal"; let image = strp(p, "image").ok_or_else(|| bad(cmd, "`image` is required"))?.to_string(); - let img = s.images.get(&image).ok_or_else(|| bad(cmd, format!("no image resource `{image}` (import it first)")))?; - let aspect = img.width as f32 / img.height.max(1) as f32; - let (center, normal) = placement(s, cmd, p, false)?.ok_or_else(|| bad(cmd, "no placement"))?; - let diag = mesh_size(s); - let size = size_param(p, aspect, diag).unwrap_or([diag * 0.25 * aspect, diag * 0.25]); + let resource = s.images.get(&image).ok_or_else(|| bad(cmd, format!("no image resource `{image}` (import it first)")))?; + let aspect = resource.width as f32 / resource.height.max(1) as f32; + let (center, normal, ts) = placement(s, cmd, p, false)?.ok_or_else(|| bad(cmd, "no placement"))?; + + // None: the image masks a new fill layer + let target = match strp(p, "channel") { + Some("mask") => None, + _ => Some(channel_param(cmd, p, "channel")?.unwrap_or(Channel::BaseColor)), + }; + let set_channels = s.doc.project.texture_set(ts)?.channel_list(); + if let Some(channel) = target + && !set_channels.contains(&channel) + { + return Err(bad(cmd, format!("the texture set has no {} channel", channel.label()))); + } + + let mesh_diagonal = mesh_size(s); + let default_height = mesh_diagonal * DEFAULT_HEIGHT; + let size = size_param(p, aspect, mesh_diagonal).unwrap_or([default_height * aspect, default_height]); let decal = Decal { center: center.to_array(), normal: normal.to_array(), @@ -108,68 +129,130 @@ fn add(s: &mut Session, p: &Value) -> Result { size, rotation: f32p(p, "rotation").unwrap_or(0.0).rem_euclid(360.0), offset: [0.0; 2], - depth: f32p(p, "depth").map_or(size[0].max(size[1]) * 0.5, |d| d.clamp(diag * 1e-4, diag * 10.0)), + // By default it reaches half its larger side into the surface + depth: f32p(p, "depth").map_or(size[0].max(size[1]) * 0.5, |depth| depth.clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE)), }; - let ts = s.ts(); - let base = - strp(p, "name").map(str::to_string).unwrap_or_else(|| std::path::Path::new(&image).file_stem().and_then(|n| n.to_str()).unwrap_or("Decal").to_string()); + + // A decal dropped on another texture set goes there and selects it, as a dropped material does + if ts != s.ts() { + crate::set_cmds::select_set(s, ts); + } + + let base = strp(p, "name") + .map(str::to_string) + .unwrap_or_else(|| std::path::Path::new(&image).file_stem().and_then(|stem| stem.to_str()).unwrap_or("Decal").to_string()); let name = s.doc.project.next_layer_name(ts, &base); - let id = s.edit("Add decal", |s| { + let (id, mask_effect) = s.edit("Add decal", |s| { let id = s.doc.project.alloc_id(); + let Some(channel) = target else { + let effect_id = s.doc.project.alloc_id(); + let mut layer = Layer::new(id, name, LayerKind::Fill(Fill::default()), &set_channels); + let mut mask = Mask::new(MaskBackground::Black); + mask.effects.push(Effect::new(effect_id, EffectKind::Fill { source: Source::image(image.clone()), projection: Projection::Decal(decal) })); + layer.mask = Some(mask); + crate::layer_cmds::insert_selected(s, layer)?; + s.target = StackTarget::Effect(effect_id); + return Ok((id, Some(effect_id))); + }; + let mut fill = Fill { projection: Projection::Decal(decal), ..Fill::default() }; - fill.sources.insert(Channel::BaseColor, Source::image(image.clone())); - crate::layer_cmds::insert_selected(s, Layer::new(id, name, LayerKind::Fill(fill), &[Channel::BaseColor])) + fill.sources.insert(channel, Source::image(image.clone())); + crate::layer_cmds::insert_selected(s, Layer::new(id, name, LayerKind::Fill(fill), &[channel]))?; + Ok((id, None)) })?; - Ok(json!({ "layer": id.0, "decal": decal })) + Ok(json!({ "layer": id.0, "decal": decal, "maskEffect": mask_effect.map(|effect| effect.0) })) } -/// The decal of fill layer `id`. -fn decal_of(s: &Session, cmd: &str, id: LayerId) -> Result { +/// The decal of fill layer `id`, or of mask fill effect `effect` when given +fn decal_of(s: &Session, cmd: &str, id: LayerId, effect: Option) -> Result { + if let Some(effect) = effect { + return match s.doc.project.effect(effect).map(|(_, effect)| &effect.kind) { + Some(EffectKind::Fill { projection: Projection::Decal(decal), .. }) => Ok(*decal), + _ => Err(bad(cmd, "the effect is not a decal (layer.add.decal with channel mask)")), + }; + } + match &s.doc.project.layer(id)?.kind { - LayerKind::Fill(Fill { projection: Projection::Decal(d), .. }) => Ok(*d), + LayerKind::Fill(Fill { projection: Projection::Decal(decal), .. }) => Ok(*decal), _ => Err(bad(cmd, "the layer is not a decal (layer.add.decal)")), } } fn set(s: &mut Session, p: &Value) -> Result { let cmd = "layer.decal.set"; - let id = s.doc.project.content_layer(layer_param(s, cmd, p)?).map(|l| l.id).ok_or_else(|| bad(cmd, "no layer"))?; - let mut d = decal_of(s, cmd, id)?; - let diag = mesh_size(s); - if let Some((center, normal)) = placement(s, cmd, p, true)? { - (d.center, d.normal, d.offset) = (center.to_array(), normal.to_array(), [0.0; 2]); + let effect = u64p(p, "effect").map(LayerId); + let id = match effect { + Some(effect) => s.doc.project.effect(effect).map(|(owner, _)| owner).ok_or_else(|| bad(cmd, format!("no effect {}", effect.0)))?, + None => s.doc.project.content_layer(layer_param(s, cmd, p)?).map(|layer| layer.id).ok_or_else(|| bad(cmd, "no layer"))?, + }; + let mut decal = decal_of(s, cmd, id, effect)?; + let mesh_diagonal = mesh_size(s); + if let Some((center, normal, ts)) = placement(s, cmd, p, true)? { + // A decal layer stays in its texture set + if ts != s.ts() { + return Err(bad(cmd, "that surface belongs to another texture set")); + } + + (decal.center, decal.normal, decal.offset) = (center.to_array(), normal.to_array(), [0.0; 2]); } if p.get("up").is_some() { - d.up = decal_up(s, cmd, p, Vec3::from(d.normal))?.to_array(); + decal.up = decal_up(s, cmd, p, Vec3::from(decal.normal))?.to_array(); } - if let Some(size) = size_param(p, d.size[0] / d.size[1].max(1e-6), diag) { - d.size = size; + if let Some(size) = size_param(p, decal.size[0] / decal.size[1].max(1e-6), mesh_diagonal) { + decal.size = size; } - if let Some(r) = f32p(p, "rotation") { - d.rotation = r.rem_euclid(360.0); + if let Some(rotation) = f32p(p, "rotation") { + decal.rotation = rotation.rem_euclid(360.0); } - if let Some(o) = p.get("offset").and_then(Value::as_array) { - let v: Vec = o.iter().filter_map(Value::as_f64).map(|x| x as f32).filter(|x| x.is_finite()).collect(); - let [x, y] = v.as_slice() else { return Err(bad(cmd, "`offset` must be [right, up]")) }; - d.offset = [x.clamp(-diag, diag), y.clamp(-diag, diag)]; + if let Some(offset) = p.get("offset").and_then(Value::as_array) { + let values: Vec = offset.iter().filter_map(Value::as_f64).map(|value| value as f32).filter(|value| value.is_finite()).collect(); + let [right, up] = values.as_slice() else { return Err(bad(cmd, "`offset` must be [right, up]")) }; + + decal.offset = [right.clamp(-mesh_diagonal, mesh_diagonal), up.clamp(-mesh_diagonal, mesh_diagonal)]; } - if let Some(v) = f32p(p, "depth") { - d.depth = v.clamp(diag * 1e-4, diag * 10.0); + if let Some(depth) = f32p(p, "depth") { + decal.depth = depth.clamp(mesh_diagonal * MIN_SIZE, mesh_diagonal * MAX_SIZE); } + let image = strp(p, "image").map(str::to_string); if let Some(name) = &image && !s.doc.resources.contains_key(name) { return Err(bad(cmd, format!("no image resource `{name}`"))); } + s.edit("Edit decal", |s| { - if let LayerKind::Fill(f) = &mut s.doc.project.layer_mut(id)?.kind { - f.projection = Projection::Decal(d); - if let Some(name) = image { - f.sources.insert(Channel::BaseColor, Source::image(name)); + if let Some(effect) = effect { + if let Some(EffectKind::Fill { source, projection }) = s.doc.project.effect_mut(effect).map(|effect| &mut effect.kind) { + *projection = Projection::Decal(decal); + if let Some(image) = image { + *source = Source::image(image); + } + } + } else if let LayerKind::Fill(fill) = &mut s.doc.project.layer_mut(id)?.kind { + fill.projection = Projection::Decal(decal); + // The new image goes where the decal's image is (the channel it was placed in) + let placed = fill.sources.values().find_map(|source| match source { + Source::Image { name, .. } => Some(name.clone()), + _ => None, + }); + match (image, placed) { + (Some(image), Some(placed)) => { + for source in fill.sources.values_mut() { + if let Source::Image { name, .. } = source + && *name == placed + { + name.clone_from(&image); + } + } + } + (Some(image), None) => { + fill.sources.insert(Channel::BaseColor, Source::image(image)); + } + (None, _) => {} } } Ok(()) })?; - Ok(json!({ "layer": id.0, "decal": d })) + Ok(json!({ "layer": id.0, "decal": decal })) } diff --git a/crates/engine/src/set_cmds.rs b/crates/engine/src/set_cmds.rs index 1d9cc7f0..3f394e23 100644 --- a/crates/engine/src/set_cmds.rs +++ b/crates/engine/src/set_cmds.rs @@ -75,12 +75,20 @@ pub(crate) fn ts_param(s: &Session, p: &Value, cmd: &str) -> Result { } fn select(s: &mut Session, p: &Value) -> Result { - let ts = u64p(p, "ts").map(|t| t as usize).filter(|t| *t < s.set_count()).ok_or_else(|| bad("textureSet.select", "valid `ts` index required"))?; + let ts = u64p(p, "ts") + .map(|index| index as usize) + .filter(|index| *index < s.set_count()) + .ok_or_else(|| bad("textureSet.select", "valid `ts` index required"))?; + select_set(s, ts); + Ok(json!({ "ts": ts })) +} + +/// Make texture set `ts` the active one, on its content stack +pub(crate) fn select_set(s: &mut Session, ts: usize) { s.cancel_stroke(); s.active_set = ts; s.target = StackTarget::Content; s.revision = s.revision.wrapping_add(1); - Ok(json!({ "ts": ts })) } fn resolution(s: &mut Session, p: &Value) -> Result { diff --git a/crates/engine/tests/painter_gaps.rs b/crates/engine/tests/painter_gaps.rs index 814ea08b..c150de79 100644 --- a/crates/engine/tests/painter_gaps.rs +++ b/crates/engine/tests/painter_gaps.rs @@ -34,6 +34,9 @@ fn red(v: [f32; 3]) -> bool { v[0] > 0.85 && v[1] < 0.15 } +/// Distance between the view points searched for a texture set +const SEARCH_STEP: f32 = 10.0; + fn png(w: u32, h: u32, f: impl Fn(u32, u32) -> [u8; 4]) -> Vec { let mut out = Vec::new(); image::RgbaImage::from_fn(w, h, |x, y| image::Rgba(f(x, y))).write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); @@ -345,6 +348,84 @@ fn decal_drags_merge_into_one_undo_step() { assert_eq!(execute(&mut s, "project.inspect", &Value::Null).unwrap()["layers"], start); } +/// A decal dropped on another texture set lands there and selects it, in one undo step +#[test] +fn a_decal_on_another_texture_set_selects_that_set() { + let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 256).unwrap(); + s.viewport = Vec2::new(400.0, 400.0); + s.update(); + let name = s.import_resource_bytes("logo.png", png(8, 8, |_, _| [255, 0, 0, 255])).unwrap(); + let selected = s.ts(); + let (columns, rows) = ((s.viewport.x / SEARCH_STEP) as u32, (s.viewport.y / SEARCH_STEP) as u32); + let other_set_pixel = (0..rows) + .flat_map(|row| (0..columns).map(move |column| Vec2::new(column as f32, row as f32) * SEARCH_STEP)) + .find(|&pixel| s.texture_set_at(pixel, s.viewport).is_some_and(|ts| ts != selected)) + .expect("the material ball shows both of its texture sets"); + let other = s.texture_set_at(other_set_pixel, s.viewport).unwrap(); + let steps = s.history_labels().len(); + + let drop = json!({"image": name, "x": other_set_pixel.x, "y": other_set_pixel.y, "viewport": [s.viewport.x, s.viewport.y]}); + let layer = id(execute(&mut s, "layer.add.decal", &drop).unwrap(), "layer"); + + assert_eq!(s.ts(), other, "the set under the point is selected"); + assert_eq!(s.doc.project.locate(layer).map(|(ts, _, _)| ts), Some(other), "the decal is in that set"); + assert_eq!(s.selected_layer(), Some(layer)); + assert_eq!(s.history_labels().len(), steps + 1, "one undo step"); + + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(s.doc.project.locate(layer).is_none(), "one undo takes the decal away"); + + let background = json!({"image": name, "x": 2, "y": 2, "viewport": [s.viewport.x, s.viewport.y]}); + assert!(s.texture_set_at(Vec2::new(2.0, 2.0), s.viewport).is_none()); + assert!(execute(&mut s, "layer.add.decal", &background).is_err(), "the background still takes nothing"); +} + +/// A decal's image goes in the channel asked for, or masks a new fill layer +#[test] +fn a_decal_image_fills_a_chosen_channel_or_a_mask() { + let mut s = session(); + let name = s.import_resource_bytes("logo.png", png(8, 8, |_, _| [255, 255, 255, 255])).unwrap(); + let place = |channel: &str| json!({"image": name, "channel": channel, "x": 200, "y": 200, "size": 0.5}); + + let rough = id(execute(&mut s, "layer.add.decal", &place("roughness")).unwrap(), "layer"); + assert_eq!(s.doc.project.layer(rough).unwrap().channels.keys().copied().collect::>(), [Channel::Roughness]); + assert!(at(&mut s, Channel::Roughness, 200.0, 200.0)[0] > 0.95, "the white image is full roughness under the decal"); + assert!(execute(&mut s, "layer.add.decal", &place("sparkle")).is_err(), "unknown channel"); + let missing = Channel::ALL.into_iter().find(|channel| !s.doc.project.texture_sets[0].has_channel(*channel)).unwrap(); + assert!(execute(&mut s, "layer.add.decal", &place(missing.id())).is_err(), "a channel the set lacks"); + + let added = execute(&mut s, "layer.add.decal", &place("mask")).unwrap(); + let masked = id(added.clone(), "layer"); + let mask = s.doc.project.layer(masked).unwrap().mask.as_ref().unwrap(); + assert!(matches!(mask.effects.as_slice(), [effect] if matches!(effect.kind, EffectKind::Fill { projection: Projection::Decal(_), .. }))); + assert_eq!(added["maskEffect"], json!(mask.effects[0].id.0)); + execute(&mut s, "layer.fill.set", &json!({"layer": masked.0, "channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); + assert!(red(at(&mut s, Channel::BaseColor, 200.0, 200.0)), "the mask shows the layer under the decal"); + assert!(!red(at(&mut s, Channel::BaseColor, 120.0, 200.0)), "and hides it elsewhere"); + + let effect = &added["maskEffect"]; + execute(&mut s, "layer.decal.set", &json!({"effect": effect, "x": 150, "y": 200})).unwrap(); + assert!(red(at(&mut s, Channel::BaseColor, 150.0, 200.0)), "a mask decal moves like a decal layer"); + assert!(!red(at(&mut s, Channel::BaseColor, 230.0, 200.0))); + assert!(execute(&mut s, "layer.decal.set", &json!({"effect": rough.0, "x": 150, "y": 200})).is_err(), "a layer id is not an effect"); +} + +/// A decal's new image stays in the channel the decal was placed in, read as gray there +#[test] +fn a_channel_decal_reads_its_image_as_gray_and_keeps_its_channel() { + let mut s = session(); + let white = s.import_resource_bytes("white.png", png(8, 8, |_, _| [255, 255, 255, 255])).unwrap(); + let green = s.import_resource_bytes("green.png", png(8, 8, |_, _| [0, 255, 0, 255])).unwrap(); + let place = json!({"image": white, "channel": "roughness", "x": 200, "y": 200, "size": 0.5}); + let layer = id(execute(&mut s, "layer.add.decal", &place).unwrap(), "layer"); + + execute(&mut s, "layer.decal.set", &json!({"layer": layer.0, "image": green})).unwrap(); + + assert_eq!(s.doc.project.layer(layer).unwrap().channels.keys().copied().collect::>(), [Channel::Roughness]); + let roughness = at(&mut s, Channel::Roughness, 200.0, 200.0)[0]; + assert!((roughness - texturecraft_engine::core::lum([0.0, 1.0, 0.0])).abs() < 0.02, "green reads as its gray, not its red: {roughness}"); +} + /// The Geometry mask tool: a click toggles the selected layer on the part under it. #[test] fn geometry_mask_tool_toggles_the_clicked_part() { diff --git a/crates/ui-egui/src/decal_drop.rs b/crates/ui-egui/src/decal_drop.rs new file mode 100644 index 00000000..0bb95f65 --- /dev/null +++ b/crates/ui-egui/src/decal_drop.rs @@ -0,0 +1,79 @@ +//! A shelf image dropped on the 3D view waits for a menu pick at the drop point: a mask, or a channel of the texture set under it + +use egui::{Id, Pos2, Ui, Vec2}; +use serde_json::json; + +use crate::TextureCraftApp; +use crate::i18n::tr; + +/// What the menu offers besides the texture set's channels: a new fill layer masked by the image +const MASK_CHOICE: &str = "mask"; + +/// An image dropped on the 3D view, placed as a decal once the menu at the drop point is picked +#[derive(Clone)] +pub struct DecalDrop { + /// The image resource + pub image: String, + /// The texture set under the drop point + pub texture_set: usize, + /// The drop point in view pixels + pub view_position: Vec2, + /// The 3D view's size in pixels + pub view_size: Vec2, + /// The drop point on screen, where the menu opens + pub screen_position: Pos2, +} + +impl DecalDrop { + fn menu_id() -> Id { + Id::unique("decal_drop_menu") + } + + /// Open the menu for this drop (replacing any other waiting drop): it stays open while the drop waits + pub fn open(self, ui: &Ui) { + ui.ctx().data_mut(|data| data.insert_temp(Self::menu_id(), self)); + } + + /// Show the waiting drop's menu over the 3D view `response`; a pick places the decal, a click elsewhere drops nothing + pub fn show_menu(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response) { + let id = Self::menu_id(); + let Some(drop) = ui.ctx().data(|data| data.get_temp::(id)) else { return }; + + let channels = app.session.doc.project.texture_set(drop.texture_set).map(|set| set.channel_list()).unwrap_or_default(); + let mut picked = None; + let shown = egui::Popup::new(id, ui.ctx().clone(), egui::PopupAnchor::Position(drop.screen_position), response.layer_id) + .kind(egui::PopupKind::Menu) + .layout(egui::Layout::top_down_justified(egui::Align::Min)) + .style(egui::containers::menu::menu_style) + .open(true) + .close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside) + .show(|ui| { + if ui.button(tr("Mask")).clicked() { + picked = Some(MASK_CHOICE); + } + ui.separator(); + for channel in channels { + if ui.button(tr(channel.label())).clicked() { + picked = Some(channel.id()); + } + } + }); + + if picked.is_some() || shown.is_none_or(|menu| menu.response.should_close()) { + ui.ctx().data_mut(|data| data.remove::(id)); + } + + let Some(channel) = picked else { return }; + + app.run( + "layer.add.decal", + json!({ + "image": drop.image, + "channel": channel, + "x": drop.view_position.x, + "y": drop.view_position.y, + "viewport": [drop.view_size.x, drop.view_size.y], + }), + ); + } +} diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 21c87eb2..4c3fb853 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -457,6 +457,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Magenta / green", "أرجواني / أخضر"), ("Main shader", "المظلل الرئيسي"), ("Marble veins", "عروق الرخام"), + ("Mask", "قناع"), ("Mask Editor: Edge wear", "محرر الأقنعة: تآكل الحواف"), ("Mask value (gray)", "قيمة القناع (رمادي)"), ("Mask with height", "قناع بالارتفاع"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index ea536d5e..dda80253 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -484,6 +484,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Magenta / green", "Magenta / Grün"), ("Main shader", "Haupt-Shader"), ("Marble veins", "Marmoradern"), + ("Mask", "Maske"), ("Mask Editor: Edge wear", "Masken-Editor: Kantenabnutzung"), ("Mask value (gray)", "Maskenwert (Grau)"), ("Mask with height", "Mit Höhe maskieren"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index de7c76e2..d5e1edcd 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -475,6 +475,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Magenta / green", "Magenta / verde"), ("Main shader", "Sombreador principal"), ("Marble veins", "Vetas de mármol"), + ("Mask", "Máscara"), ("Mask Editor: Edge wear", "Editor de máscaras: desgaste de bordes"), ("Mask value (gray)", "Valor de máscara (gris)"), ("Mask with height", "Enmascarar con la altura"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index fc4b8b11..39532da0 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -490,6 +490,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Magenta / green", "Magenta / vert"), ("Main shader", "Shader principal"), ("Marble veins", "Veines de marbre"), + ("Mask", "Masque"), ("Mask Editor: Edge wear", "Éditeur de masque : usure des arêtes"), ("Mask value (gray)", "Valeur du masque (gris)"), ("Mask with height", "Masquer avec la hauteur"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 67648219..bfb32ec8 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -481,6 +481,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Magenta / green", "Magenta / verde"), ("Main shader", "Shader principale"), ("Marble veins", "Venature marmo"), + ("Mask", "Maschera"), ("Mask Editor: Edge wear", "Editor maschera: Usura bordi"), ("Mask value (gray)", "Valore maschera (grigio)"), ("Mask with height", "Maschera con altezza"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index dfbe8a65..d053cd61 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -469,6 +469,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Magenta / green", "マゼンタ / グリーン"), ("Main shader", "メインシェーダー"), ("Marble veins", "大理石の筋"), + ("Mask", "マスク"), ("Mask Editor: Edge wear", "マスクエディター: エッジの摩耗"), ("Mask value (gray)", "マスク値 (グレー)"), ("Mask with height", "ハイトでマスク"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index f81cfe6d..f64e9805 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -463,6 +463,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Magenta / green", "마젠타 / 녹색"), ("Main shader", "메인 셰이더"), ("Marble veins", "대리석 무늬"), + ("Mask", "마스크"), ("Mask Editor: Edge wear", "마스크 에디터: 모서리 마모"), ("Mask value (gray)", "마스크 값 (회색)"), ("Mask with height", "높이로 마스크"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 7bd3d231..5b95ce82 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -472,6 +472,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Magenta / green", "Magenta / verde"), ("Main shader", "Shader principal"), ("Marble veins", "Veios de mármore"), + ("Mask", "Máscara"), ("Mask Editor: Edge wear", "Editor de máscara: Desgaste de bordas"), ("Mask value (gray)", "Valor da máscara (cinza)"), ("Mask with height", "Mascarar com altura"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 7d393f75..3b616067 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -430,6 +430,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Magenta / green", "洋红 / 绿色"), ("Main shader", "主着色器"), ("Marble veins", "大理石纹"), + ("Mask", "遮罩"), ("Mask Editor: Edge wear", "遮罩编辑器:边缘磨损"), ("Mask value (gray)", "遮罩值(灰度)"), ("Mask with height", "用高度遮罩"), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5b5045e6..50f886e6 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -9,6 +9,7 @@ pub mod bake_mode; pub mod control; +mod decal_drop; pub mod dock; pub mod docking; pub mod export_templates; diff --git a/crates/ui-egui/src/shelf.rs b/crates/ui-egui/src/shelf.rs index 46ced908..62fd8592 100644 --- a/crates/ui-egui/src/shelf.rs +++ b/crates/ui-egui/src/shelf.rs @@ -2,7 +2,7 @@ //! masks, filters, alphas, procedurals, environments, textures), all built in and procedural. //! Search filters across every tab. Materials (built in and saved), smart masks, filters, alphas //! and textures drag onto the layer stack, a layer row, the viewport or the brush properties -//! ([`ShelfDrag`]); a texture dropped on the 3D view becomes a decal there. +//! ([`ShelfDrag`]); a texture dropped on the 3D view becomes a decal there, in the channel picked from a menu use egui::{Color32, RichText, Sense, Stroke, Ui, vec2}; use egui_phosphor::regular as ic; @@ -20,6 +20,7 @@ use texturecraft_engine::smart_masks::SMART_MASKS; use texturecraft_render::ibl::ENVIRONMENTS; use crate::TextureCraftApp; +use crate::decal_drop::DecalDrop; use crate::i18n::{tr, trf}; use crate::shelf_preview::ShelfPreview; use crate::theme::Tokens; @@ -88,6 +89,11 @@ impl Asset { pub fn is_material(&self) -> bool { matches!(self, Asset::Material(_) | Asset::Library(_)) } + + /// Assets a 3D view drop puts on the texture set under the pointer + pub fn goes_onto_set(&self) -> bool { + self.is_material() || matches!(self, Asset::Texture(_)) + } } /// The drag-and-drop payload of a shelf tile. @@ -143,17 +149,17 @@ pub enum DropZone { Brush, /// The 2D view: alphas and materials. View2d, - /// The 3D view: alphas, materials (on the texture set they drop on) and textures (placed as decals where they drop). + /// The 3D view: alphas, materials (on the texture set they drop on) and textures (decals where they drop, on that set) View3d, } -/// The texture set under the pointer while a shelf material is dragged over the 3D view `response`: the set a drop there applies it to -pub fn material_drop_set(app: &TextureCraftApp, ui: &Ui, response: &egui::Response) -> Option { +/// The texture set under the pointer while a shelf material or image is dragged over the 3D view `response`: the set a drop there goes to +pub fn drop_set(app: &TextureCraftApp, ui: &Ui, response: &egui::Response) -> Option { if app.ui.mode != crate::state::Mode::Painting { return None; } - response.dnd_hover_payload::().filter(|drag| drag.asset.is_material())?; + response.dnd_hover_payload::().filter(|drag| drag.asset.goes_onto_set())?; set_under_pointer(app, ui, response) } @@ -163,12 +169,16 @@ fn set_under_pointer(app: &TextureCraftApp, ui: &Ui, response: &egui::Response) app.session.texture_set_at(Vec2::new(local_position.x, local_position.y), app.session.viewport) } -/// Highlight accepted shelf assets on hover and apply them on drop. In the 3D view a material goes to the texture set under the pointer, highlighted by the view itself ([`material_drop_set`]) +/// Highlight accepted shelf assets on hover and apply them on drop. In the 3D view a material or image goes to the texture set under the pointer, highlighted by the view itself ([`drop_set`]) pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response, zone: DropZone) { if app.ui.mode != crate::state::Mode::Painting { return; } + if zone == DropZone::View3d { + DecalDrop::show_menu(app, ui, response); + } + let tokens = Tokens::get(ui.ctx()); let accepts = |drag: &ShelfDrag| match drag.asset { Asset::Alpha(_) => true, @@ -176,7 +186,7 @@ pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response Asset::Texture(_) => zone == DropZone::View3d, Asset::SmartMask(_) | Asset::Filter(_) => false, }; - let onto_set = |asset: &Asset| zone == DropZone::View3d && asset.is_material(); + let onto_set = |asset: &Asset| zone == DropZone::View3d && asset.goes_onto_set(); if response.dnd_hover_payload::().is_some_and(|drag| accepts(&drag) && !onto_set(&drag.asset)) { ui.painter().rect_stroke(response.rect.shrink(1.0), 3.0, Stroke::new(2.0, tokens.accent), egui::StrokeKind::Inside); } @@ -185,11 +195,19 @@ pub fn drop_target(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response let Some(drag) = dnd_release::(response).filter(|drag| accepts(drag)) else { return }; match (&drag.asset, pointer) { - (Asset::Texture(name), Some(position)) => { - let (local_position, viewport_size) = (position - response.rect.min, response.rect.size()); - app.run("layer.add.decal", json!({"image": name, "x": local_position.x, "y": local_position.y, "viewport": [viewport_size.x, viewport_size.y]})); - } // The background takes nothing + (Asset::Texture(name), Some(position)) => { + let Some(texture_set) = set_under_pointer(app, ui, response) else { return }; + + let drop = DecalDrop { + image: name.clone(), + texture_set, + view_position: position - response.rect.min, + view_size: response.rect.size(), + screen_position: position, + }; + drop.open(ui); + } (asset, _) if onto_set(asset) => { let Some(ts) = set_under_pointer(app, ui, response) else { return }; diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index f20210d4..1855438a 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -223,9 +223,9 @@ fn shade(app: &TextureCraftApp) -> Shade { } } -/// The texture set a shelf material dragged over the 3D view `response` would drop on, its edges drawn in the accent color +/// The texture set a shelf material or image dragged over the 3D view `response` would drop on, its edges drawn in the accent color fn drop_highlight(app: &TextureCraftApp, ui: &Ui, response: &egui::Response) -> Option { - let set = crate::shelf::material_drop_set(app, ui, response)?; + let set = crate::shelf::drop_set(app, ui, response)?; let accent = egui::Rgba::from(Tokens::get(ui.ctx()).viewport_accent); Some(SetHighlight { set, color: [accent.r(), accent.g(), accent.b()] }) @@ -622,7 +622,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin }; add_callback(app, ui, rect, frame, sync); - // Shelf drops: a material goes above the selection of the set under the pointer, an alpha on the brush + // Shelf drops: a material goes above the selection of the set under the pointer, an image opens the decal menu there, an alpha goes on the brush crate::shelf::drop_target(app, ui, &response, crate::shelf::DropZone::View3d); // Brush cursor; while a Ctrl+drag changes the brush it stays where the drag began @@ -691,16 +691,18 @@ impl DecalGrab { } } -/// A decal handle being dragged (kept in egui's memory between frames). +/// A decal handle being dragged (kept in egui's memory between frames) #[derive(Clone, Copy, Debug)] struct DecalDrag { layer: texturecraft_engine::core::LayerId, + /// The mask fill effect holding the decal, when it was placed as a mask + effect: Option, grab: DecalGrab, - /// Where the drag started, the decal's center on screen and the decal then. + /// Where the drag started, the decal's center on screen and the decal then from: Pos2, center: Pos2, start: texturecraft_engine::core::Decal, - /// The drag made its undo step: later updates merge into it. + /// The drag made its undo step: later updates merge into it stepped: bool, } @@ -711,34 +713,51 @@ fn decal_drag_id() -> egui::Id { /// Screen distance from the top edge to the rotation handle (points). const DECAL_KNOB: f32 = 24.0; -/// The selected decal layer (its content, not its mask) as the 3D view shows it. +/// The selected decal (a decal layer's content, or a mask decal effect) as the 3D view shows it struct DecalFrame { layer: texturecraft_engine::core::LayerId, + /// The selected mask fill effect holding the decal, when it was placed as a mask + effect: Option, decal: texturecraft_engine::core::Decal, - /// Top left, top right, bottom right, bottom left. + /// Top left, top right, bottom right, bottom left corners: [Pos2; 4], center: Pos2, - /// The middle of the top edge and the rotation handle above it. + /// The middle of the top edge and the rotation handle above it top: Pos2, knob: Pos2, } impl DecalFrame { fn of(app: &TextureCraftApp, rect: Rect) -> Option { + use texturecraft_engine::StackTarget; use texturecraft_engine::compose::pattern::{decal_axes, decal_corners}; - use texturecraft_engine::core::{Fill, LayerKind, Projection}; - if app.ui.mode != crate::state::Mode::Painting || app.session.target != texturecraft_engine::StackTarget::Content { + use texturecraft_engine::core::{EffectKind, Fill, LayerKind, Projection}; + if app.ui.mode != crate::state::Mode::Painting { return None; } - let p = &app.session.doc.project; - let layer = app.session.selected_layer().and_then(|id| p.content_layer(id))?; - let LayerKind::Fill(Fill { projection: Projection::Decal(decal), .. }) = &layer.kind else { return None }; - let [a, b, c, d] = decal_corners(decal)?.map(|q| project(app, rect, q)); - let corners = [a?, b?, c?, d?]; + + let layers = &app.session.doc.project; + let (layer, effect, decal) = match app.session.target { + StackTarget::Content => { + let layer = app.session.selected_layer().and_then(|id| layers.content_layer(id))?; + let LayerKind::Fill(Fill { projection: Projection::Decal(decal), .. }) = &layer.kind else { return None }; + + (layer.id, None, decal) + } + StackTarget::Effect(effect) => { + let (owner, mask_effect) = layers.effect(effect)?; + let EffectKind::Fill { projection: Projection::Decal(decal), .. } = &mask_effect.kind else { return None }; + + (owner, Some(effect), decal) + } + StackTarget::Mask => return None, + }; + let [top_left, top_right, bottom_right, bottom_left] = decal_corners(decal)?.map(|corner| project(app, rect, corner)); + let corners = [top_left?, top_right?, bottom_right?, bottom_left?]; let center = project(app, rect, decal_axes(decal)?.0)?; let top = corners[0].lerp(corners[1], 0.5); let knob = top + (top - center).normalized() * DECAL_KNOB; - Some(DecalFrame { layer: layer.id, decal: *decal, corners, center, top, knob }) + Some(DecalFrame { layer, effect, decal: *decal, corners, center, top, knob }) } /// The handle under screen point `p`. @@ -759,51 +778,56 @@ impl DecalFrame { } } -/// Drags on the selected decal's frame and handles (one undo step per drag, the decal updates -/// live). Returns whether a decal drag owns the pointer. +/// Drags on the selected decal's frame and handles (one undo step per drag, the decal updates live); returns whether a decal drag owns the pointer fn decal_input(app: &mut TextureCraftApp, ui: &Ui, resp: &egui::Response, rect: Rect) -> bool { let ctx = ui.ctx(); let frame = DecalFrame::of(app, rect); - let mut drag = ctx.data(|d| d.get_temp::(decal_drag_id())).filter(|d| frame.as_ref().is_some_and(|f| f.layer == d.layer)); + let on_frame = |drag: &DecalDrag| frame.as_ref().is_some_and(|frame| frame.layer == drag.layer && frame.effect == drag.effect); + let mut drag = ctx.data(|data| data.get_temp::(decal_drag_id())).filter(on_frame); if resp.drag_started_by(PointerButton::Primary) - && let (Some(f), Some(from)) = (&frame, ctx.input(|i| i.pointer.press_origin())) - && let Some(grab) = f.grab(from) + && let (Some(frame), Some(from)) = (&frame, ctx.input(|input| input.pointer.press_origin())) + && let Some(grab) = frame.grab(from) { - drag = Some(DecalDrag { layer: f.layer, grab, from, center: f.center, start: f.decal, stepped: false }); + drag = Some(DecalDrag { layer: frame.layer, effect: frame.effect, grab, from, center: frame.center, start: frame.decal, stepped: false }); } - let Some(mut d) = drag.filter(|_| resp.dragged_by(PointerButton::Primary) || resp.drag_started_by(PointerButton::Primary)) else { - ctx.data_mut(|m| m.remove::(decal_drag_id())); - if let (Some(f), Some(h)) = (&frame, resp.hover_pos()) - && let Some(g) = f.grab(h) + + let Some(mut drag) = drag.filter(|_| resp.dragged_by(PointerButton::Primary) || resp.drag_started_by(PointerButton::Primary)) else { + ctx.data_mut(|data| data.remove::(decal_drag_id())); + if let (Some(frame), Some(hover)) = (&frame, resp.hover_pos()) + && let Some(grab) = frame.grab(hover) { - ctx.set_cursor_icon(g.cursor(false)); + ctx.set_cursor_icon(grab.cursor(false)); } return false; }; - ctx.set_cursor_icon(d.grab.cursor(true)); - if let Some(p) = resp.interact_pointer_pos().filter(|_| ctx.input(|i| i.pointer.delta() != egui::Vec2::ZERO)) { - let mut params = match d.grab { + + ctx.set_cursor_icon(drag.grab.cursor(true)); + if let Some(pointer) = resp.interact_pointer_pos().filter(|_| ctx.input(|input| input.pointer.delta() != egui::Vec2::ZERO)) { + let mut params = match drag.grab { DecalGrab::Move => { - let q = d.center + (p - d.from) - rect.left_top(); - let vp = app.session.viewport; - json!({"x": q.x, "y": q.y, "viewport": [vp.x, vp.y]}) + let target = drag.center + (pointer - drag.from) - rect.left_top(); + let viewport = app.session.viewport; + json!({"x": target.x, "y": target.y, "viewport": [viewport.x, viewport.y]}) } DecalGrab::Scale => { - let k = (p - d.center).length() / (d.from - d.center).length().max(1.0); - json!({"size": [d.start.size[0] * k, d.start.size[1] * k]}) + let scale = (pointer - drag.center).length() / (drag.from - drag.center).length().max(1.0); + json!({"size": [drag.start.size[0] * scale, drag.start.size[1] * scale]}) } DecalGrab::Rotate => { - // Screen y points down: counter-clockwise angles turn the decal's right toward its up. - let angle = |v: egui::Vec2| (-v.y).atan2(v.x).to_degrees(); - json!({"rotation": d.start.rotation + angle(p - d.center) - angle(d.from - d.center)}) + // Screen y points down: counter-clockwise angles turn the decal's right toward its up + let angle = |offset: egui::Vec2| (-offset.y).atan2(offset.x).to_degrees(); + json!({"rotation": drag.start.rotation + angle(pointer - drag.center) - angle(drag.from - drag.center)}) } }; - params["layer"] = json!(d.layer.0); - params["merge"] = json!(d.stepped); - // Off the mesh while moving: the decal waits where it is. - d.stepped |= texturecraft_engine::execute(&mut app.session, "layer.decal.set", ¶ms).is_ok(); + params["layer"] = json!(drag.layer.0); + if let Some(effect) = drag.effect { + params["effect"] = json!(effect.0); + } + params["merge"] = json!(drag.stepped); + // Off the mesh while moving: the decal waits where it is + drag.stepped |= texturecraft_engine::execute(&mut app.session, "layer.decal.set", ¶ms).is_ok(); } - ctx.data_mut(|m| m.insert_temp(decal_drag_id(), d)); + ctx.data_mut(|data| data.insert_temp(decal_drag_id(), drag)); true } diff --git a/crates/ui-egui/tests/shelf_drop.rs b/crates/ui-egui/tests/shelf_drop.rs index 5b35cc06..7bb94a04 100644 --- a/crates/ui-egui/tests/shelf_drop.rs +++ b/crates/ui-egui/tests/shelf_drop.rs @@ -1,7 +1,9 @@ -//! A shelf material dropped on the 3D view goes to the texture set under the pointer +//! A shelf material or image dropped on the 3D view goes to the texture set under the pointer; an image first asks what it becomes use egui::{Event, Modifiers, PointerButton, Pos2}; use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::core::Channel; use texturecraft_engine::geom::glam::Vec2; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::shelf::{Asset, ShelfDrag}; @@ -9,6 +11,9 @@ use texturecraft_ui_egui::shelf::{Asset, ShelfDrag}; /// Distance between the view points searched for a set or the background const SEARCH_STEP: f32 = 8.0; +/// How far from the drop point the drop menu's items can be +const MENU_REACH: f32 = 60.0; + /// The sample project (Ball = set 0, Base = set 1) with the Ball selected, at 1600 x 960 fn sample_app() -> Harness<'static, TextureCraftApp> { let session = texturecraft_engine::sample_session(256, 64).unwrap(); @@ -33,7 +38,12 @@ fn point_over(harness: &Harness<'_, TextureCraftApp>, set: Option) -> Pos /// Drop a built-in shelf material at `position`, as a drag from the shelf ends there fn drop_material(harness: &mut Harness<'_, TextureCraftApp>, position: Pos2) { - egui::DragAndDrop::set_payload(&harness.ctx, ShelfDrag { asset: Asset::Material("iron_rusted"), label: "Iron".into() }); + drop_asset(harness, Asset::Material("iron_rusted"), position); +} + +/// Drop shelf `asset` at `position`, as a drag from the shelf ends there +fn drop_asset(harness: &mut Harness<'_, TextureCraftApp>, asset: Asset, position: Pos2) { + egui::DragAndDrop::set_payload(&harness.ctx, ShelfDrag { asset, label: "Dragged".into() }); harness.hover_at(position); harness.run_steps(2); @@ -70,3 +80,60 @@ fn a_material_dropped_on_the_background_changes_nothing() { assert_eq!(stack_sizes(&harness), stacks); assert_eq!(harness.state().session.history_labels().len(), history); } + +/// The sample app in English with a white image dropped on texture set `position_over` (the background when `None`) +fn drop_image(position_over: Option) -> (Harness<'static, TextureCraftApp>, Pos2) { + let mut harness = sample_app(); + harness.state_mut().ui.prefs.language = "en".into(); + let mut png = Vec::new(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 255, 255, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let name = harness.state_mut().session.import_resource_bytes("logo.png", png).unwrap(); + harness.run_steps(2); + + let position = point_over(&harness, position_over); + drop_asset(&mut harness, Asset::Texture(name), position); + // The menu's first frame only measures it + harness.run_steps(2); + (harness, position) +} + +#[test] +fn an_image_dropped_on_another_set_asks_for_a_channel_then_goes_to_that_set() { + let (mut harness, position) = drop_image(Some(1)); + let before = stack_sizes(&harness); + + // The menu item nearest the drop point (Properties may show the same name) + let distance = |node: &egui_kittest::Node<'_>| node.rect().center().distance(position); + harness.get_all_by_label("Roughness").min_by(|a, b| distance(a).total_cmp(&distance(b))).unwrap().click(); + harness.run_steps(2); + + let app = harness.state(); + assert_eq!(app.session.ts(), 1, "the set under the drop point is selected"); + assert_eq!(stack_sizes(&harness), vec![before[0], before[1] + 1]); + let layer = app.session.selected_layer().and_then(|id| app.session.doc.project.layer(id).ok()).unwrap(); + assert_eq!(layer.channels.keys().copied().collect::>(), [Channel::Roughness], "the image fills the picked channel"); +} + +/// Whether the drop menu is open at `position` (its Mask item near there) +fn menu_open(harness: &Harness<'_, TextureCraftApp>, position: Pos2) -> bool { + harness.query_all_by_label("Mask").any(|node| node.rect().center().distance(position) < MENU_REACH) +} + +#[test] +fn an_image_drop_places_nothing_until_a_pick_and_nothing_on_the_background() { + let (mut harness, position) = drop_image(Some(1)); + let (stacks, history) = (stack_sizes(&harness), harness.state().session.history_labels().len()); + assert!(menu_open(&harness, position)); + + // A click elsewhere closes the menu + let corner = harness.state().viewport_rect.min + egui::vec2(SEARCH_STEP, SEARCH_STEP); + harness.event(Event::PointerButton { pos: corner, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.event(Event::PointerButton { pos: corner, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + assert!(!menu_open(&harness, position)); + assert_eq!(stack_sizes(&harness), stacks); + assert_eq!(harness.state().session.history_labels().len(), history); + + let (harness, position) = drop_image(None); + assert!(!menu_open(&harness, position), "the background opens no menu"); +} From 508c4bb2aaba8c3a7a5e7af481516fdbff69eeb8 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 02:49:47 +0000 Subject: [PATCH 18/64] Keep the click that dismisses the image drop menu from painting The views don't paint while a dropped image waits for its menu pick, so a click on the mesh outside the menu only closes it. Also document Texel::source and DecalDrop::menu_id. --- crates/compose/src/eval.rs | 1 + crates/ui-egui/src/decal_drop.rs | 6 ++++++ crates/ui-egui/src/viewport.rs | 7 +++++-- crates/ui-egui/tests/shelf_drop.rs | 13 +++++++++---- 4 files changed, 21 insertions(+), 6 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 308d11c2..9dba941a 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -1129,6 +1129,7 @@ impl<'a, 'b> Texel<'a, 'b> { w * image.map_or(1.0, |img| img.sample(c.uv.x, c.uv.y)[3].clamp(0.0, 1.0)) } + /// The value `source` gives this texel through `projection`, read as a channel of `kind` fn source(&mut self, source: &Source, projection: &Projection, kind: ChannelKind) -> [f32; 3] { match source { Source::Uniform(value) => *value, diff --git a/crates/ui-egui/src/decal_drop.rs b/crates/ui-egui/src/decal_drop.rs index 0bb95f65..1dfba5f2 100644 --- a/crates/ui-egui/src/decal_drop.rs +++ b/crates/ui-egui/src/decal_drop.rs @@ -25,6 +25,7 @@ pub struct DecalDrop { } impl DecalDrop { + /// Where the waiting drop and its menu's state are kept fn menu_id() -> Id { Id::unique("decal_drop_menu") } @@ -34,6 +35,11 @@ impl DecalDrop { ui.ctx().data_mut(|data| data.insert_temp(Self::menu_id(), self)); } + /// Whether a drop waits for its menu pick: the views don't paint meanwhile, so the click that dismisses the menu paints nothing + pub fn waiting(ctx: &egui::Context) -> bool { + ctx.data(|data| data.get_temp::(Self::menu_id()).is_some()) + } + /// Show the waiting drop's menu over the 3D view `response`; a pick places the decal, a click elsewhere drops nothing pub fn show_menu(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response) { let id = Self::menu_id(); diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 1855438a..ec58ce89 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -13,6 +13,7 @@ use texturecraft_engine::{Tool, ViewMode}; use texturecraft_render::{Frame, SetHighlight, Shade, ViewKind}; use crate::TextureCraftApp; +use crate::decal_drop::DecalDrop; use crate::gpu::ViewCallback; use crate::i18n::{tr, trf}; use crate::state::ViewLayout; @@ -571,7 +572,8 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && !focus_pick && placing.is_none() && touch.is_none() - && !decal_drag; + && !decal_drag + && !DecalDrop::waiting(ui.ctx()); let path_tool = app.session.tool.tool == Tool::Path; let viewport = app.session.viewport; let show = |app: &TextureCraftApp, point: Vec3| project(app, rect, point); @@ -1236,7 +1238,8 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin crate::properties_popup::open_on_right_click(app, ui, &response, rect, v_held); // Painting in UV space - let painting = app.ui.mode == crate::state::Mode::Painting && app.properties_popup.is_none() && !alt && !adjusting && !v_held; + let painting = + app.ui.mode == crate::state::Mode::Painting && app.properties_popup.is_none() && !alt && !adjusting && !v_held && !DecalDrop::waiting(ui.ctx()); if painting && path_tool { path_input(app, ui, &response, true, |_, pointer| Some(to_uv(pointer).extend(0.0)), show); } else if painting { diff --git a/crates/ui-egui/tests/shelf_drop.rs b/crates/ui-egui/tests/shelf_drop.rs index 7bb94a04..36a89de6 100644 --- a/crates/ui-egui/tests/shelf_drop.rs +++ b/crates/ui-egui/tests/shelf_drop.rs @@ -3,6 +3,7 @@ use egui::{Event, Modifiers, PointerButton, Pos2}; use egui_kittest::Harness; use egui_kittest::kittest::Queryable; +use texturecraft_engine::Tool; use texturecraft_engine::core::Channel; use texturecraft_engine::geom::glam::Vec2; use texturecraft_ui_egui::TextureCraftApp; @@ -125,10 +126,14 @@ fn an_image_drop_places_nothing_until_a_pick_and_nothing_on_the_background() { let (stacks, history) = (stack_sizes(&harness), harness.state().session.history_labels().len()); assert!(menu_open(&harness, position)); - // A click elsewhere closes the menu - let corner = harness.state().viewport_rect.min + egui::vec2(SEARCH_STEP, SEARCH_STEP); - harness.event(Event::PointerButton { pos: corner, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); - harness.event(Event::PointerButton { pos: corner, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + // A click elsewhere on the mesh closes the menu and fills nothing there (a polygon fill click records a step in this harness) + harness.state_mut().session.tool.tool = Tool::PolygonFill; + let elsewhere = point_over(&harness, Some(0)); + harness.hover_at(elsewhere); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: elsewhere, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: elsewhere, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); harness.run_steps(2); assert!(!menu_open(&harness, position)); assert_eq!(stack_sizes(&harness), stacks); From 63fc9936441f4ca70056ccb183f7d0610274620d Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 22:21:43 +0000 Subject: [PATCH 19/64] Tidy the Shader Settings, History and Log panels Shader Settings starts with the shader model; its description moves to the model's tooltip. The height to normal strength stays in the texture set settings only. Subsurface scattering and Transmission are collapsible sections. The History and Log lists fill their panel's height. --- crates/ui-egui/src/windows.rs | 154 +++++++++++++++------------ crates/ui-egui/tests/list_panels.rs | 73 +++++++++++++ crates/ui-egui/tests/shader_panel.rs | 30 ++++++ 3 files changed, 190 insertions(+), 67 deletions(-) create mode 100644 crates/ui-egui/tests/list_panels.rs create mode 100644 crates/ui-egui/tests/shader_panel.rs diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 0c35d957..e9a9e7a6 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -13,7 +13,7 @@ use crate::i18n::LANGUAGES; use crate::i18n::{tr, trf}; use crate::state::Mode; use crate::theme::{Accent, Brightness, Tokens, caption}; -use crate::widgets::{color_swatch, combo, icon_button, primary_button, slider, slider_edit}; +use crate::widgets::{color_swatch, combo, icon_button, primary_button, section, slider}; pub fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { start(app, ctx); @@ -225,18 +225,23 @@ fn cameras(app: &mut TextureCraftApp, ui: &mut Ui) { } } -/// The Shader Settings panel body (a dock tab). +/// Wide enough for the longer shader model name +const SHADER_MODEL_COMBO_WIDTH: f32 = 260.0; + +/// Width of the scatter color swatch +const SCATTER_SWATCH_WIDTH: f32 = 44.0; + +/// Index of refraction slider range: air to well past diamond (2.42) +const INDEX_OF_REFRACTION_RANGE: std::ops::RangeInclusive = 1.0..=3.0; + +/// The Shader Settings panel body (a dock tab) pub(crate) fn shader(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); - let mut d = app.session.doc.project.display.clone(); - let before = d.clone(); - let model = |sg: bool| if sg { tr("TextureCraft PBR - Specular Glossiness") } else { tr("TextureCraft PBR - Metallic Roughness") }; - egui::ComboBox::from_id_salt("shader_model").width(260.0).selected_text(model(d.spec_gloss)).show_ui(ui, |ui| { - for sg in [false, true] { - ui.selectable_value(&mut d.spec_gloss, sg, model(sg)); - } - }); - let channels = if d.spec_gloss { + let tokens = Tokens::get(ui.ctx()); + let mut display = app.session.doc.project.display.clone(); + let before = display.clone(); + + let model_name = |spec_gloss: bool| if spec_gloss { tr("TextureCraft PBR - Specular Glossiness") } else { tr("TextureCraft PBR - Metallic Roughness") }; + let channels = if display.spec_gloss { tr("Base color is the diffuse color, Specular the F0 color and Glossiness 1 - roughness (add these channels in the texture set settings).") } else { tr("Base color, Metallic, Roughness and Specular level.") @@ -247,75 +252,90 @@ pub(crate) fn shader(app: &mut TextureCraftApp, ui: &mut Ui) { let optional = tr( "Optional channels add a clear coat (Coat weight, Coat roughness, Coat normal), sheen (Sheen weight, color, roughness), anisotropy (Anisotropy level, angle), subsurface scattering (Scattering weight) and transmission (Transmission).", ); - ui.label(RichText::new(format!("{model_text} {channels} {optional}")).color(tk.text_dim)); + + egui::ComboBox::from_id_salt("shader_model") + .width(SHADER_MODEL_COMBO_WIDTH) + .selected_text(model_name(display.spec_gloss)) + .show_ui(ui, |ui| { + for spec_gloss in [false, true] { + ui.selectable_value(&mut display.spec_gloss, spec_gloss, model_name(spec_gloss)); + } + }) + .response + .on_hover_text(format!("{model_text} {channels} {optional}")); ui.add_space(6.0); - ui.checkbox(&mut d.parallax, tr("Parallax occlusion (height channel)")) + + ui.checkbox(&mut display.parallax, tr("Parallax occlusion (height channel)")) .on_hover_text(tr("Offsets the textures by the height channel, at the height to normal strength")); - ui.checkbox(&mut d.displacement, tr("Displacement (height channel)")).on_hover_text(tr( + ui.checkbox(&mut display.displacement, tr("Displacement (height channel)")).on_hover_text(tr( "Moves the surface by the height channel on a finer copy of the mesh, at the height to normal strength (viewport only: painting follows the base surface)", )); + slider(ui, tr("AO intensity"), &mut display.ao_intensity, 0.0..=1.0, 2); ui.add_space(6.0); - ui.label(caption(tr("Subsurface scattering"))); - ui.horizontal(|ui| { - ui.label(RichText::new(tr("Scatter color")).color(tk.text)); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| color_swatch(ui, "shader_scatter_color", &mut d.scatter_color, 44.0)) - }) - .response - .on_hover_text(tr("Color of the light that travels under the surface (each channel goes as far as its value)")); - slider(ui, tr("Scatter radius"), &mut d.scatter_radius, 0.0..=1.0, 3) - .on_hover_text(tr("How far light travels under the surface, as a fraction of the mesh size (where the Scattering weight channel is painted)")); - ui.add_space(6.0); - ui.label(caption(tr("Transmission"))); - slider(ui, tr("Index of refraction"), &mut d.ior, 1.0..=3.0, 2) - .on_hover_text(tr("How strongly transmissive surfaces bend light (where the Transmission channel is painted): water 1.33, glass 1.5, diamond 2.42")); - if d != before { - app.session.doc.project.display = d; - } - let ts = app.session.ts(); - if let Some(set) = app.session.doc.project.texture_sets.get(ts) { - let mut hs = set.height_strength; - if let Some(merge) = slider_edit(ui, tr("Height to normal strength"), &mut hs, 0.0..=10.0, 2) { - app.run("textureSet.settings", json!({"ts": ts, "heightStrength": hs, "merge": merge})); - } - } - let mut ao = app.session.doc.project.display.ao_intensity; - if slider(ui, tr("AO intensity"), &mut ao, 0.0..=1.0, 2).changed() { - app.session.doc.project.display.ao_intensity = ao; + + section(ui, "shader_subsurface", tr("Subsurface scattering"), true, |ui| { + ui.horizontal(|ui| { + ui.label(RichText::new(tr("Scatter color")).color(tokens.text)); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + color_swatch(ui, "shader_scatter_color", &mut display.scatter_color, SCATTER_SWATCH_WIDTH) + }) + }) + .response + .on_hover_text(tr("Color of the light that travels under the surface (each channel goes as far as its value)")); + slider(ui, tr("Scatter radius"), &mut display.scatter_radius, 0.0..=1.0, 3) + .on_hover_text(tr("How far light travels under the surface, as a fraction of the mesh size (where the Scattering weight channel is painted)")); + }); + section(ui, "shader_transmission", tr("Transmission"), true, |ui| { + slider(ui, tr("Index of refraction"), &mut display.ior, INDEX_OF_REFRACTION_RANGE, 2).on_hover_text(tr( + "How strongly transmissive surfaces bend light (where the Transmission channel is painted): water 1.33, glass 1.5, diamond 2.42", + )); + }); + + if display != before { + app.session.doc.project.display = display; } } -/// The History panel body (a dock tab). +/// The History panel body (a dock tab) pub(crate) fn history(app: &mut TextureCraftApp, ui: &mut Ui) { - let tk = Tokens::get(ui.ctx()); + let tokens = Tokens::get(ui.ctx()); let (done, undone) = (app.session.history_labels(), app.session.redo_labels()); - // A click on a step goes back (or forward) to it: steps to undo, or to redo when negative. + // A click on a step goes back (or forward) to it: steps to undo, or to redo when negative let mut jump = 0i64; - egui::ScrollArea::vertical().max_height(320.0).show(ui, |ui| { - let n = done.len() as i64; - let rows = std::iter::once(RichText::new(tr("Project opened")).color(tk.text_dim)) - .chain(done.iter().map(RichText::new)) - .chain(undone.iter().map(|l| RichText::new(trf("{action} (undone)", &[("action", l)])).color(tk.text_dim))); - for (i, text) in rows.enumerate() { - // Row i is the state after i steps. - let steps = n - i as i64; - if ui.selectable_label(steps == 0, text).on_hover_text(tr("Return to this step")).clicked() { - jump = steps; + + // Bottom up: the Undo and Redo row keeps its place under a list that fills the rest of the panel + ui.with_layout(egui::Layout::bottom_up(egui::Align::Min), |ui| { + ui.horizontal(|ui| { + if ui.add_enabled(app.session.can_undo(), egui::Button::new(format!("{} {}", ic::ARROW_COUNTER_CLOCKWISE, tr("Undo")))).clicked() { + app.run("edit.undo", json!({})); } - } + if ui.add_enabled(app.session.can_redo(), egui::Button::new(format!("{} {}", ic::ARROW_CLOCKWISE, tr("Redo")))).clicked() { + app.run("edit.redo", json!({})); + } + }); + + ui.with_layout(egui::Layout::top_down(egui::Align::Min), |ui| { + egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| { + let done_count = done.len() as i64; + let rows = std::iter::once(RichText::new(tr("Project opened")).color(tokens.text_dim)) + .chain(done.iter().map(RichText::new)) + .chain(undone.iter().map(|label| RichText::new(trf("{action} (undone)", &[("action", label)])).color(tokens.text_dim))); + for (row, text) in rows.enumerate() { + // Each row is the state after that many steps + let steps = done_count - row as i64; + if ui.selectable_label(steps == 0, text).on_hover_text(tr("Return to this step")).clicked() { + jump = steps; + } + } + }); + }); }); + if jump > 0 { app.run("edit.undo", json!({ "steps": jump })); } else if jump < 0 { app.run("edit.redo", json!({ "steps": -jump })); } - ui.horizontal(|ui| { - if ui.add_enabled(app.session.can_undo(), egui::Button::new(format!("{} {}", ic::ARROW_COUNTER_CLOCKWISE, tr("Undo")))).clicked() { - app.run("edit.undo", json!({})); - } - if ui.add_enabled(app.session.can_redo(), egui::Button::new(format!("{} {}", ic::ARROW_CLOCKWISE, tr("Redo")))).clicked() { - app.run("edit.redo", json!({})); - } - }); } /// What the start window was asked for. @@ -676,11 +696,11 @@ fn about(app: &mut TextureCraftApp, ctx: &egui::Context) { app.ui.windows.about = open; } -/// The Log panel body (a dock tab). +/// The Log panel body (a dock tab) pub(crate) fn log(app: &mut TextureCraftApp, ui: &mut Ui) { - egui::ScrollArea::vertical().max_height(300.0).stick_to_bottom(true).show(ui, |ui| { - for l in &app.session.log { - ui.label(RichText::new(l).monospace()); + egui::ScrollArea::vertical().auto_shrink([false, false]).stick_to_bottom(true).show(ui, |ui| { + for line in &app.session.log { + ui.label(RichText::new(line).monospace()); } }); } diff --git a/crates/ui-egui/tests/list_panels.rs b/crates/ui-egui/tests/list_panels.rs new file mode 100644 index 00000000..7b6ace60 --- /dev/null +++ b/crates/ui-egui/tests/list_panels.rs @@ -0,0 +1,73 @@ +//! The History and Log lists fill their panel instead of stopping at a fixed height + +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::{Dock, Panel}; + +/// The list heights the panels used to stop at +const OLD_HISTORY_HEIGHT: f32 = 320.0; +const OLD_LOG_HEIGHT: f32 = 300.0; + +/// Leaves the left column (where the panel is docked) between 700 and 800 points tall +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 860.0); + +/// Right of the left column (11.5% of the window, about 184 points) and left of every other panel's scroll bar +const LEFT_COLUMN_MAX_X: f32 = 300.0; + +/// Enough rows to overflow the tallest panel +const ROWS: usize = 80; + +/// Small texture and bake sizes keep the sample session fast; the panels don't depend on them +const TEXTURE_RESOLUTION: u32 = 256; +const BAKE_RESOLUTION: u32 = 64; + +/// Frames for the first layout and fonts to settle +const STARTUP_FRAMES: usize = 4; + +/// Dock `panel` in the full-height left column, where the Assets panel is by default +fn dock_in_left_column(harness: &mut Harness<'_, TextureCraftApp>, panel: &str) { + // Each panel name appears once in the saved dock: in the layout or in the hidden list + let saved = serde_json::to_string(&harness.state().ui.dock).unwrap(); + let placeholder = "\"swapped-out\""; + let swapped = saved.replace("\"Assets\"", placeholder).replace(&format!("\"{panel}\""), "\"Assets\"").replace(placeholder, &format!("\"{panel}\"")); + harness.state_mut().ui.dock = Dock::from_value(serde_json::from_str(&swapped).unwrap()); +} + +/// The height of the list's scroll bar, which runs the visible height of the list +fn list_height(harness: &Harness<'_, TextureCraftApp>) -> f32 { + let bar = harness.get_all_by_role(Role::ScrollBar).find(|bar| bar.rect().max.x < LEFT_COLUMN_MAX_X).expect("a scroll bar in the left column"); + bar.rect().height() +} + +#[test] +fn the_history_list_fills_a_tall_panel() { + let mut session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let layer = session.selected_layer().unwrap(); + for step in 0..ROWS { + texturecraft_engine::execute(&mut session, "layer.rename", &json!({"layer": layer.0, "name": format!("Step {step}")})).unwrap(); + } + + let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); + dock_in_left_column(&mut harness, "History"); + harness.run_steps(STARTUP_FRAMES); + + assert!(harness.state().ui.dock.is_visible(Panel::History)); + let height = list_height(&harness); + assert!(height > OLD_HISTORY_HEIGHT, "the history list is {height} points tall"); +} + +#[test] +fn the_log_list_fills_a_tall_panel() { + let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().session.log.extend((0..ROWS).map(|line| format!("Log line {line}"))); + dock_in_left_column(&mut harness, "Log"); + harness.run_steps(STARTUP_FRAMES); + + assert!(harness.state().ui.dock.is_visible(Panel::Log)); + let height = list_height(&harness); + assert!(height > OLD_LOG_HEIGHT, "the log list is {height} points tall"); +} diff --git a/crates/ui-egui/tests/shader_panel.rs b/crates/ui-egui/tests/shader_panel.rs new file mode 100644 index 00000000..805420cb --- /dev/null +++ b/crates/ui-egui/tests/shader_panel.rs @@ -0,0 +1,30 @@ +//! Shader Settings shows each of its settings once: the height strength lives in the texture set settings + +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; + +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.0); + +/// Small texture and bake sizes keep the sample session fast; the panel doesn't depend on them +const TEXTURE_RESOLUTION: u32 = 256; +const BAKE_RESOLUTION: u32 = 64; + +/// Frames for the first layout and fonts to settle +const STARTUP_FRAMES: usize = 4; + +#[test] +fn shader_settings_leave_the_height_strength_to_the_texture_set_settings() { + let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); + harness.state_mut().ui.dock.focus(Panel::Shader); + harness.run_steps(STARTUP_FRAMES); + + assert!(harness.query_by_label("AO intensity").is_some(), "the Shader Settings panel is shown"); + // Texture Set Settings, the slider's other home, sits behind Layers in the default layout, so any match is in Shader Settings + assert!(!harness.state().ui.dock.is_visible(Panel::TextureSetSettings), "Texture Set Settings is behind Layers"); + assert!(harness.query_by_label("Height to normal strength").is_none()); +} From f5d07ced6b4c16721ea9ddae3d122daa1a7ffbf1 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sat, 7 Nov 2026 22:25:41 +0000 Subject: [PATCH 20/64] Pick the display tone mapping from a dropdown The AO intensity is set in Shader Settings, so Display Settings no longer repeats it. --- crates/ui-egui/src/i18n/ar.rs | 1 - crates/ui-egui/src/i18n/de.rs | 1 - crates/ui-egui/src/i18n/es.rs | 1 - crates/ui-egui/src/i18n/fr.rs | 1 - crates/ui-egui/src/i18n/it.rs | 1 - crates/ui-egui/src/i18n/ja.rs | 1 - crates/ui-egui/src/i18n/ko.rs | 1 - crates/ui-egui/src/i18n/pt_br.rs | 1 - crates/ui-egui/src/i18n/zh_hans.rs | 1 - crates/ui-egui/src/windows.rs | 13 +++++++----- crates/ui-egui/tests/display_panel.rs | 30 +++++++++++++++++++++++++++ 11 files changed, 38 insertions(+), 14 deletions(-) create mode 100644 crates/ui-egui/tests/display_panel.rs diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 21c87eb2..9f2bf4f9 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -60,7 +60,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Always", "دائماً"), ("Ambient Occlusion", "الانسداد المحيطي (AO)"), ("Ambient occlusion", "الانسداد المحيطي (AO)"), - ("Ambient occlusion intensity", "شدة الانسداد المحيطي"), ("Amount", "المقدار"), ("Anchor point", "نقطة ارتكاز"), ("Anchor: {name}", "نقطة ارتكاز: {name}"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index ea536d5e..df242dd0 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -63,7 +63,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Always", "Immer"), ("Ambient Occlusion", "Ambient Occlusion"), ("Ambient occlusion", "Ambient occlusion"), - ("Ambient occlusion intensity", "Ambient-Occlusion-Intensität"), ("Amount", "Stärke"), ("Anchor point", "Ankerpunkt"), ("Anchor: {name}", "Anker: {name}"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index de7c76e2..175bc1b0 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -60,7 +60,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Always", "Siempre"), ("Ambient Occlusion", "Oclusión ambiental"), ("Ambient occlusion", "Oclusión ambiental"), - ("Ambient occlusion intensity", "Intensidad de la oclusión ambiental"), ("Amount", "Cantidad"), ("Anchor point", "Punto de anclaje"), ("Anchor: {name}", "Anclaje: {name}"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index fc4b8b11..53a3c001 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -66,7 +66,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Always", "Toujours"), ("Ambient Occlusion", "Occlusion ambiante"), ("Ambient occlusion", "Occlusion ambiante"), - ("Ambient occlusion intensity", "Intensité de l'occlusion ambiante"), ("Amount", "Quantité"), ("Anchor point", "Point d'ancrage"), ("Anchor: {name}", "Ancrage : {name}"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 67648219..89179b4a 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -63,7 +63,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Always", "Sempre"), ("Ambient Occlusion", "Occlusione ambientale"), ("Ambient occlusion", "Occlusione ambientale"), - ("Ambient occlusion intensity", "Intensità occlusione ambientale"), ("Amount", "Quantità"), ("Anchor point", "Punto di ancoraggio"), ("Anchor: {name}", "Ancoraggio: {name}"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index dfbe8a65..74bfdc87 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -66,7 +66,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Always", "常に"), ("Ambient Occlusion", "アンビエントオクルージョン"), ("Ambient occlusion", "アンビエントオクルージョン"), - ("Ambient occlusion intensity", "アンビエントオクルージョンの強度"), ("Amount", "量"), ("Anchor point", "アンカーポイント"), ("Anchor: {name}", "アンカー: {name}"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index f81cfe6d..1ab57f1c 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -63,7 +63,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Always", "항상"), ("Ambient Occlusion", "앰비언트 오클루전"), ("Ambient occlusion", "앰비언트 오클루전"), - ("Ambient occlusion intensity", "앰비언트 오클루전 강도"), ("Amount", "양"), ("Anchor point", "앵커 포인트"), ("Anchor: {name}", "앵커: {name}"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 7bd3d231..7bc898ec 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -63,7 +63,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Always", "Sempre"), ("Ambient Occlusion", "Oclusão de ambiente"), ("Ambient occlusion", "Oclusão de ambiente"), - ("Ambient occlusion intensity", "Intensidade da oclusão de ambiente"), ("Amount", "Quantidade"), ("Anchor point", "Ponto de ancoragem"), ("Anchor: {name}", "Âncora: {name}"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 7d393f75..c161e7f7 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -54,7 +54,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Always", "始终"), ("Ambient Occlusion", "环境光遮蔽"), ("Ambient occlusion", "环境光遮蔽"), - ("Ambient occlusion intensity", "环境光遮蔽强度"), ("Amount", "数量"), ("Anchor point", "锚点"), ("Anchor: {name}", "锚点:{name}"), diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index e9a9e7a6..0d27fa87 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -156,10 +156,14 @@ pub(crate) fn display(app: &mut TextureCraftApp, ui: &mut Ui) { if ui.checkbox(&mut ortho, tr("Orthographic")).changed() { app.run("camera.set", json!({"ortho": ortho})); } - ui.horizontal(|ui| { - ui.label(tr("Tone mapping")); - ui.selectable_value(&mut d.tone_mapping, ToneMapping::Linear, tr("Linear")); - ui.selectable_value(&mut d.tone_mapping, ToneMapping::AcesFilmic, tr("ACES filmic")); + let tone_mapping_name = |tone_mapping: ToneMapping| match tone_mapping { + ToneMapping::Linear => tr("Linear"), + ToneMapping::AcesFilmic => tr("ACES filmic"), + }; + combo(ui, tr("Tone mapping"), tone_mapping_name(d.tone_mapping), |ui| { + for tone_mapping in [ToneMapping::Linear, ToneMapping::AcesFilmic] { + ui.selectable_value(&mut d.tone_mapping, tone_mapping, tone_mapping_name(tone_mapping)); + } }); cameras(app, ui); ui.add_space(6.0); @@ -177,7 +181,6 @@ pub(crate) fn display(app: &mut TextureCraftApp, ui: &mut Ui) { }); ui.add_space(6.0); ui.label(caption(tr("Viewer settings"))); - slider(ui, tr("Ambient occlusion intensity"), &mut d.ao_intensity, 0.0..=1.0, 2); ui.checkbox(&mut app.ui.wireframe_3d, tr("Show wireframe in the 3D view")); ui.checkbox(&mut app.ui.uv_wireframe, tr("Show UV wireframe in the 2D view")); ui.checkbox(&mut d.taa, tr("Temporal anti-aliasing (refines the 3D view while it is still)")); diff --git a/crates/ui-egui/tests/display_panel.rs b/crates/ui-egui/tests/display_panel.rs new file mode 100644 index 00000000..9c72f884 --- /dev/null +++ b/crates/ui-egui/tests/display_panel.rs @@ -0,0 +1,30 @@ +//! Display Settings picks its tone mapping from a dropdown and leaves the AO intensity to Shader Settings + +use egui::Role; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; + +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.0); + +/// Small texture and bake sizes keep the sample session fast; the panel doesn't depend on them +const TEXTURE_RESOLUTION: u32 = 256; +const BAKE_RESOLUTION: u32 = 64; + +/// Frames for the first layout and fonts to settle +const STARTUP_FRAMES: usize = 4; + +#[test] +fn display_picks_the_tone_mapping_from_a_dropdown() { + let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let mut harness = Harness::builder().with_size(WINDOW_SIZE).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); + harness.state_mut().ui.dock.focus(Panel::Display); + harness.run_steps(STARTUP_FRAMES); + + let tone_mapping = harness.get_all_by_role(Role::ComboBox).find(|combo| combo.accesskit_node().value().as_deref() == Some("ACES filmic")); + assert!(tone_mapping.is_some(), "the tone mapping is a dropdown showing ACES filmic"); + assert!(harness.query_by_label("Ambient occlusion intensity").is_none(), "the AO intensity is in Shader Settings"); +} From 1a58c57f64e75699dda1e03a1666dcf3b591f020 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sun, 8 Nov 2026 00:26:23 +0000 Subject: [PATCH 21/64] Section reset: keyboard focus outline, tests over every section The reset icon draws an outline while it has keyboard focus and is left out of Tab order while its section is at its defaults. The tests now run every brush section: enabled and disabled state, the reset folds nothing in either state, and Enter on the focused icon resets. --- crates/ui-egui/src/widgets.rs | 20 ++++- crates/ui-egui/tests/brush_section_reset.rs | 98 +++++++++++++++------ 2 files changed, 87 insertions(+), 31 deletions(-) diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 80b7fa90..d51af0b0 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -276,6 +276,12 @@ const SECTION_RESET_ICON_SIZE: f32 = 14.0; /// How much of `text_dim` the reset icon keeps while its section is at its defaults const SECTION_RESET_AT_DEFAULT_OPACITY: f32 = 0.4; +/// Gap between the reset icon's glyph and its keyboard focus outline +const SECTION_RESET_FOCUS_MARGIN: f32 = 2.0; + +/// Corner radius of the reset icon's keyboard focus outline +const SECTION_RESET_FOCUS_CORNER_RADIUS: u8 = 3; + /// The header row and body of [`section`]; `reset_at_default` adds the reset icon fn collapsible_section(ui: &mut Ui, id: &str, title: &str, default_open: bool, reset_at_default: Option, body: impl FnOnce(&mut Ui)) -> bool { let tokens = Tokens::get(ui.ctx()); @@ -298,18 +304,28 @@ fn collapsible_section(ui: &mut Ui, id: &str, title: &str, default_open: bool, r // Registered after the header so the icon, not the header, takes its clicks let mut reset_clicked = false; if let (Some(at_default), Some(rect)) = (reset_at_default, reset_rect) { - let response = ui.interact(rect, id.with("reset"), Sense::click()).on_hover_text(tr("Reset to defaults")); + // At the defaults the icon is inert, so Tab skips it + let sense = if at_default { Sense::CLICK } else { Sense::click() }; + let response = ui.interact(rect, id.with("reset"), sense).on_hover_text(tr("Reset to defaults")); response.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, !at_default, tr("Reset to defaults"))); + let focused = response.has_focus(); let color = if at_default { tokens.text_dim.gamma_multiply(SECTION_RESET_AT_DEFAULT_OPACITY) - } else if response.hovered() { + } else if response.hovered() || focused { tokens.text_strong } else { tokens.text_dim }; let font = egui::FontId::proportional(SECTION_RESET_ICON_SIZE); ui.painter().text(rect.center(), egui::Align2::CENTER_CENTER, egui_phosphor::regular::CLOCK_COUNTER_CLOCKWISE, font, color); + + // Enter or Space on the focused icon resets, so keyboard focus needs an outline + if focused { + let outline = rect.expand(SECTION_RESET_FOCUS_MARGIN); + ui.painter().rect_stroke(outline, CornerRadius::same(SECTION_RESET_FOCUS_CORNER_RADIUS), ui.visuals().selection.stroke, egui::StrokeKind::Outside); + } + reset_clicked = response.clicked() && !at_default; } diff --git a/crates/ui-egui/tests/brush_section_reset.rs b/crates/ui-egui/tests/brush_section_reset.rs index 198b618c..9df12c7f 100644 --- a/crates/ui-egui/tests/brush_section_reset.rs +++ b/crates/ui-egui/tests/brush_section_reset.rs @@ -1,7 +1,7 @@ //! Each brush section header has a reset icon that puts only that section's settings back to their defaults use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; +use egui_kittest::kittest::{NodeT, Queryable}; use texturecraft_engine::paint::{Alignment, BrushSettings, Particles, Symmetry}; use texturecraft_ui_egui::TextureCraftApp; @@ -17,6 +17,27 @@ const SETTLE_FRAMES: usize = 3; /// Puts one section's fields of the first brush back to the second's values type SectionReset = fn(&mut BrushSettings, &BrushSettings); +/// Each brush section's title, a label shown only while it is open, whether it starts open, and its reset +const SECTIONS: [(&str, &str, bool, SectionReset); 7] = [ + ("Size", "Minimum size (%)", true, |brush, defaults| { + (brush.size, brush.min_size, brush.screen_space) = (defaults.size, defaults.min_size, defaults.screen_space) + }), + ("Flow and opacity", "Stroke opacity", true, |brush, defaults| { + (brush.flow, brush.opacity, brush.spacing, brush.hardness) = (defaults.flow, defaults.opacity, defaults.spacing, defaults.hardness) + }), + ("Angle", "Follow path", false, |brush, defaults| (brush.angle, brush.follow_path) = (defaults.angle, defaults.follow_path)), + ("Jitters", "Size jitter", false, |brush, defaults| { + (brush.jitter_size, brush.jitter_angle, brush.jitter_flow, brush.jitter_position) = + (defaults.jitter_size, defaults.jitter_angle, defaults.jitter_flow, defaults.jitter_position) + }), + ("Alignment and culling", "Backface culling", false, |brush, defaults| { + (brush.alignment, brush.backface_culling, brush.angle_fade, brush.depth) = + (defaults.alignment, defaults.backface_culling, defaults.angle_fade, defaults.depth) + }), + ("Particles", "Gravity", false, |brush, defaults| brush.particles = defaults.particles), + ("Lazy mouse and symmetry", "Lazy mouse distance", false, |brush, defaults| (brush.lazy, brush.symmetry) = (defaults.lazy, defaults.symmetry)), +]; + /// A brush that differs from the defaults in every field a section shows, within the valid ranges fn changed_brush() -> BrushSettings { BrushSettings { @@ -74,26 +95,10 @@ fn click_reset(harness: &mut Harness<'_, TextureCraftApp>, title: &str) { #[test] fn each_reset_puts_back_only_its_own_section() { let defaults = BrushSettings::default(); - let sections: [(&str, SectionReset); 7] = [ - ("Size", |brush, defaults| (brush.size, brush.min_size, brush.screen_space) = (defaults.size, defaults.min_size, defaults.screen_space)), - ("Flow and opacity", |brush, defaults| { - (brush.flow, brush.opacity, brush.spacing, brush.hardness) = (defaults.flow, defaults.opacity, defaults.spacing, defaults.hardness) - }), - ("Angle", |brush, defaults| (brush.angle, brush.follow_path) = (defaults.angle, defaults.follow_path)), - ("Jitters", |brush, defaults| { - (brush.jitter_size, brush.jitter_angle, brush.jitter_flow, brush.jitter_position) = - (defaults.jitter_size, defaults.jitter_angle, defaults.jitter_flow, defaults.jitter_position) - }), - ("Alignment and culling", |brush, defaults| { - (brush.alignment, brush.backface_culling, brush.angle_fade, brush.depth) = - (defaults.alignment, defaults.backface_culling, defaults.angle_fade, defaults.depth) - }), - ("Particles", |brush, defaults| brush.particles = defaults.particles), - ("Lazy mouse and symmetry", |brush, defaults| (brush.lazy, brush.symmetry) = (defaults.lazy, defaults.symmetry)), - ]; - for (title, reset_section) in sections { + for (title, _, _, reset_section) in SECTIONS { let mut harness = app_with_brush(changed_brush()); + assert!(!reset_icon(&harness, title).accesskit_node().is_disabled(), "the {title} reset is enabled once its section changed"); click_reset(&mut harness, title); let mut expected = changed_brush(); @@ -102,22 +107,57 @@ fn each_reset_puts_back_only_its_own_section() { } } +/// Scrolls the header titled `title` into view and clicks the header itself, folding or unfolding it +fn click_header(harness: &mut Harness<'_, TextureCraftApp>, title: &str) { + reset_icon(harness, title).scroll_to_me(); + harness.run_steps(SETTLE_FRAMES); + + let icon = reset_icon(harness, title).rect(); + harness.query_all_by_label(title).find(|label| label.rect().y_range().intersects(icon.y_range())).unwrap_or_else(|| panic!("no {title} header")).click(); + harness.run_steps(SETTLE_FRAMES); +} + #[test] fn clicking_the_reset_icon_does_not_fold_or_unfold_the_section() { - let mut harness = app_with_brush(changed_brush()); + for flip_first in [false, true] { + let mut harness = app_with_brush(changed_brush()); + if flip_first { + for (title, _, _, _) in SECTIONS { + click_header(&mut harness, title); + } + } - click_reset(&mut harness, "Size"); - assert!(harness.query_by_label("Minimum size (%)").is_some(), "Size starts open and stays open"); - - click_reset(&mut harness, "Jitters"); - assert!(harness.query_by_label("Size jitter").is_none(), "Jitters starts closed and stays closed"); + for (title, body_label, starts_open, _) in SECTIONS { + let open = starts_open != flip_first; + click_reset(&mut harness, title); + assert_eq!(harness.query_by_label(body_label).is_some(), open, "{title} stays {}", if open { "open" } else { "closed" }); + } + } } #[test] -fn at_the_defaults_the_reset_icon_does_nothing() { +fn at_the_defaults_the_reset_icons_are_inert() { let mut harness = app_with_brush(BrushSettings::default()); - click_reset(&mut harness, "Size"); - assert_eq!(harness.state().session.tool.brush, BrushSettings::default()); - assert!(harness.query_by_label("Minimum size (%)").is_some(), "the click doesn't reach the header"); + for (title, body_label, starts_open, _) in SECTIONS { + assert!(reset_icon(&harness, title).accesskit_node().is_disabled(), "the {title} reset is disabled at the defaults"); + + click_reset(&mut harness, title); + assert_eq!(harness.query_by_label(body_label).is_some(), starts_open, "the click doesn't reach the {title} header"); + } +} + +#[test] +fn enter_on_the_focused_reset_icon_resets() { + let mut harness = app_with_brush(changed_brush()); + + reset_icon(&harness, "Size").focus(); + harness.run_steps(SETTLE_FRAMES); + assert!(reset_icon(&harness, "Size").is_focused()); + + harness.key_press(egui::Key::Enter); + harness.run_steps(SETTLE_FRAMES); + + let (brush, defaults) = (&harness.state().session.tool.brush, BrushSettings::default()); + assert_eq!((brush.size, brush.min_size, brush.screen_space), (defaults.size, defaults.min_size, defaults.screen_space)); } From 45ab0f42d9b26600f710dbf87e6a74aed7b35bfc Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sun, 8 Nov 2026 01:23:12 +0000 Subject: [PATCH 22/64] Image drop: clearer decal specs, layer/effect check, menu edge cases layer.add.decal's spec says the other-set selection is for x/y only and documents the maskEffect it returns; layer.decal.set's says image keeps the decal's channel or mask and refuses an effect given with another layer. The drop menu's channel list scrolls past 60% of the window. A waiting drop lets go once its menu goes undrawn (the 3D view hidden), and the click that closes the menu no longer moves a decal being placed. --- crates/engine/src/decal_cmds.rs | 10 ++++- crates/engine/tests/painter_gaps.rs | 3 ++ crates/ui-egui/src/decal_drop.rs | 39 +++++++++++++---- crates/ui-egui/src/viewport.rs | 3 +- crates/ui-egui/tests/shelf_drop.rs | 65 +++++++++++++++++++++++++++-- 5 files changed, 105 insertions(+), 15 deletions(-) diff --git a/crates/engine/src/decal_cmds.rs b/crates/engine/src/decal_cmds.rs index f3ec8b28..bd25c185 100644 --- a/crates/engine/src/decal_cmds.rs +++ b/crates/engine/src/decal_cmds.rs @@ -16,7 +16,7 @@ pub fn specs() -> Vec { "Add decal", [], None, - "{image: resource name, channel?: a channel id (default baseColor) | \"mask\" (a new fill layer masked by the image's gray), x?, y?: viewport pixels (default: the view center; a point on another texture set selects it), viewport?: [w,h] | position?: [x,y,z], normal?: [x,y,z], up?: [x,y,z] (the image's up; default the view's up, or the view direction when that is along the normal), size?: height | [w,h] (world units; default a quarter of the mesh), rotation?: degrees, depth?, name?} — a fill layer projecting the image from a frame placed on the surface; seen from the front, the image reads the right way round", + "{image: resource name, channel?: a channel id (default baseColor) | \"mask\" (a new fill layer masked by the image's gray), x?, y?: viewport pixels (default: the view center; a point on another texture set selects it), viewport?: [w,h] | position?: [x,y,z], normal?: [x,y,z] (on the selected texture set), up?: [x,y,z] (the image's up; default the view's up, or the view direction when that is along the normal), size?: height | [w,h] (world units; default a quarter of the mesh), rotation?: degrees, depth?, name?} → {layer, decal, maskEffect: the mask fill effect holding the image with channel \"mask\", else null} — a fill layer projecting the image from a frame placed on the surface; seen from the front, the image reads the right way round", always, add ), @@ -25,7 +25,7 @@ pub fn specs() -> Vec { "Edit decal", [], None, - "{layer? | effect?: a mask fill effect id (a decal placed as a mask), x?, y?, viewport? | position?, normal? (re-place it), up?: [x,y,z], size?: height | [w,h], rotation?: degrees, offset?: [right, up] (world units from where it was placed), depth?, image?, merge?: true continues the previous Edit decal undo step (drags)}", + "{layer? | effect?: a mask fill effect id (a decal placed as a mask; with `layer`, it must be in that layer), x?, y?, viewport? | position?, normal? (re-place it), up?: [x,y,z], size?: height | [w,h], rotation?: degrees, offset?: [right, up] (world units from where it was placed), depth?, image?: replaces the image in the channel or mask it was placed in, merge?: true continues the previous Edit decal undo step (drags)}", has_layer, set ), @@ -185,6 +185,12 @@ fn set(s: &mut Session, p: &Value) -> Result { Some(effect) => s.doc.project.effect(effect).map(|(owner, _)| owner).ok_or_else(|| bad(cmd, format!("no effect {}", effect.0)))?, None => s.doc.project.content_layer(layer_param(s, cmd, p)?).map(|layer| layer.id).ok_or_else(|| bad(cmd, "no layer"))?, }; + if let (Some(effect), Some(layer)) = (effect, u64p(p, "layer")) + && layer != id.0 + { + return Err(bad(cmd, format!("effect {} is not in layer {layer}", effect.0))); + } + let mut decal = decal_of(s, cmd, id, effect)?; let mesh_diagonal = mesh_size(s); if let Some((center, normal, ts)) = placement(s, cmd, p, true)? { diff --git a/crates/engine/tests/painter_gaps.rs b/crates/engine/tests/painter_gaps.rs index c150de79..66f19612 100644 --- a/crates/engine/tests/painter_gaps.rs +++ b/crates/engine/tests/painter_gaps.rs @@ -408,6 +408,9 @@ fn a_decal_image_fills_a_chosen_channel_or_a_mask() { assert!(red(at(&mut s, Channel::BaseColor, 150.0, 200.0)), "a mask decal moves like a decal layer"); assert!(!red(at(&mut s, Channel::BaseColor, 230.0, 200.0))); assert!(execute(&mut s, "layer.decal.set", &json!({"effect": rough.0, "x": 150, "y": 200})).is_err(), "a layer id is not an effect"); + execute(&mut s, "layer.decal.set", &json!({"effect": effect, "layer": masked.0, "size": 0.4})).expect("an effect with its own layer"); + let mismatched = json!({"effect": effect, "layer": rough.0, "size": 0.4}); + assert!(execute(&mut s, "layer.decal.set", &mismatched).is_err(), "an effect with another layer is refused"); } /// A decal's new image stays in the channel the decal was placed in, read as gray there diff --git a/crates/ui-egui/src/decal_drop.rs b/crates/ui-egui/src/decal_drop.rs index 1dfba5f2..4c2fd6db 100644 --- a/crates/ui-egui/src/decal_drop.rs +++ b/crates/ui-egui/src/decal_drop.rs @@ -9,6 +9,9 @@ use crate::i18n::tr; /// What the menu offers besides the texture set's channels: a new fill layer masked by the image const MASK_CHOICE: &str = "mask"; +/// The most of the window's height the channel list takes before it scrolls +const MENU_MAX_HEIGHT_SHARE: f32 = 0.6; + /// An image dropped on the 3D view, placed as a decal once the menu at the drop point is picked #[derive(Clone)] pub struct DecalDrop { @@ -32,18 +35,33 @@ impl DecalDrop { /// Open the menu for this drop (replacing any other waiting drop): it stays open while the drop waits pub fn open(self, ui: &Ui) { - ui.ctx().data_mut(|data| data.insert_temp(Self::menu_id(), self)); + let frame = ui.ctx().cumulative_frame_nr(); + ui.ctx().data_mut(|data| data.insert_temp(Self::menu_id(), (self, frame))); } /// Whether a drop waits for its menu pick: the views don't paint meanwhile, so the click that dismisses the menu paints nothing pub fn waiting(ctx: &egui::Context) -> bool { - ctx.data(|data| data.get_temp::(Self::menu_id()).is_some()) + Self::current(ctx).is_some() + } + + /// The waiting drop; one whose menu went undrawn for a frame (the 3D view was hidden) is dropped instead of blocking the views + fn current(ctx: &egui::Context) -> Option { + let frame = ctx.cumulative_frame_nr(); + let (drop, menu_frame) = ctx.data(|data| data.get_temp::<(DecalDrop, u64)>(Self::menu_id()))?; + if frame > menu_frame + 1 { + ctx.data_mut(|data| data.remove::<(DecalDrop, u64)>(Self::menu_id())); + return None; + } + + Some(drop) } /// Show the waiting drop's menu over the 3D view `response`; a pick places the decal, a click elsewhere drops nothing pub fn show_menu(app: &mut TextureCraftApp, ui: &Ui, response: &egui::Response) { let id = Self::menu_id(); - let Some(drop) = ui.ctx().data(|data| data.get_temp::(id)) else { return }; + let Some(drop) = Self::current(ui.ctx()) else { return }; + let frame = ui.ctx().cumulative_frame_nr(); + ui.ctx().data_mut(|data| data.insert_temp(id, (drop.clone(), frame))); let channels = app.session.doc.project.texture_set(drop.texture_set).map(|set| set.channel_list()).unwrap_or_default(); let mut picked = None; @@ -58,15 +76,20 @@ impl DecalDrop { picked = Some(MASK_CHOICE); } ui.separator(); - for channel in channels { - if ui.button(tr(channel.label())).clicked() { - picked = Some(channel.id()); + + // Many channels scroll instead of running off the window + let max_height = ui.ctx().content_rect().height() * MENU_MAX_HEIGHT_SHARE; + egui::ScrollArea::vertical().max_height(max_height).show(ui, |ui| { + for channel in channels { + if ui.button(tr(channel.label())).clicked() { + picked = Some(channel.id()); + } } - } + }); }); if picked.is_some() || shown.is_none_or(|menu| menu.response.should_close()) { - ui.ctx().data_mut(|data| data.remove::(id)); + ui.ctx().data_mut(|data| data.remove::<(DecalDrop, u64)>(id)); } let Some(channel) = picked else { return }; diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index ec58ce89..f0229e25 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -542,11 +542,12 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin } } - // Decal placement: a click moves the decal being placed there + // Decal placement: a click moves the decal being placed there, unless it dismisses a waiting image drop's menu let placing = app.placing_decal.filter(|_| app.ui.mode == crate::state::Mode::Painting); if let Some(layer) = placing { ui.ctx().set_cursor_icon(egui::CursorIcon::Crosshair); if !alt + && !DecalDrop::waiting(ui.ctx()) && response.clicked_by(PointerButton::Primary) && let Some(pointer) = response.interact_pointer_pos() { diff --git a/crates/ui-egui/tests/shelf_drop.rs b/crates/ui-egui/tests/shelf_drop.rs index 36a89de6..b278a397 100644 --- a/crates/ui-egui/tests/shelf_drop.rs +++ b/crates/ui-egui/tests/shelf_drop.rs @@ -8,6 +8,7 @@ use texturecraft_engine::core::Channel; use texturecraft_engine::geom::glam::Vec2; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::shelf::{Asset, ShelfDrag}; +use texturecraft_ui_egui::state::ViewLayout; /// Distance between the view points searched for a set or the background const SEARCH_STEP: f32 = 8.0; @@ -82,14 +83,20 @@ fn a_material_dropped_on_the_background_changes_nothing() { assert_eq!(harness.state().session.history_labels().len(), history); } -/// The sample app in English with a white image dropped on texture set `position_over` (the background when `None`) -fn drop_image(position_over: Option) -> (Harness<'static, TextureCraftApp>, Pos2) { - let mut harness = sample_app(); - harness.state_mut().ui.prefs.language = "en".into(); +/// Import a small white image and return its resource name +fn import_white_image(harness: &mut Harness<'_, TextureCraftApp>) -> String { let mut png = Vec::new(); image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 255, 255, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); let name = harness.state_mut().session.import_resource_bytes("logo.png", png).unwrap(); harness.run_steps(2); + name +} + +/// The sample app in English with a white image dropped on texture set `position_over` (the background when `None`) +fn drop_image(position_over: Option) -> (Harness<'static, TextureCraftApp>, Pos2) { + let mut harness = sample_app(); + harness.state_mut().ui.prefs.language = "en".into(); + let name = import_white_image(&mut harness); let position = point_over(&harness, position_over); drop_asset(&mut harness, Asset::Texture(name), position); @@ -142,3 +149,53 @@ fn an_image_drop_places_nothing_until_a_pick_and_nothing_on_the_background() { let (harness, position) = drop_image(None); assert!(!menu_open(&harness, position), "the background opens no menu"); } + +#[test] +fn hiding_the_3d_view_lets_go_of_a_waiting_image_drop() { + let (mut harness, position) = drop_image(Some(1)); + assert!(menu_open(&harness, position)); + + // Only the 3D view shows the menu, so a 2D-only layout would otherwise leave the views blocked + harness.state_mut().ui.layout = ViewLayout::Only2D; + harness.run_steps(3); + harness.state_mut().ui.layout = ViewLayout::Split; + harness.run_steps(3); + + assert!(!menu_open(&harness, position), "the drop lapsed while its menu was hidden"); +} + +#[test] +fn the_click_that_closes_the_drop_menu_does_not_move_a_decal_being_placed() { + let (mut harness, position) = drop_image(Some(1)); + let distance = |node: &egui_kittest::Node<'_>| node.rect().center().distance(position); + harness.get_all_by_label("Roughness").min_by(|a, b| distance(a).total_cmp(&distance(b))).unwrap().click(); + harness.run_steps(2); + let decal_layer = harness.state().session.selected_layer().unwrap(); + harness.state_mut().placing_decal = Some(decal_layer); + + let image = import_white_image(&mut harness); + drop_asset(&mut harness, Asset::Texture(image), position); + harness.run_steps(2); + assert!(menu_open(&harness, position)); + let history = harness.state().session.history_labels().len(); + + // A point on the same set, away from the menu + let rect = harness.state().viewport_rect; + let elsewhere = (1..(rect.width() / SEARCH_STEP) as usize) + .map(|step| Pos2::new(rect.max.x - step as f32 * SEARCH_STEP, position.y)) + .find(|point| { + let app = harness.state(); + let local = *point - rect.min; + point.distance(position) > MENU_REACH * 2.0 && app.session.texture_set_at(Vec2::new(local.x, local.y), app.session.viewport) == Some(1) + }) + .unwrap(); + harness.hover_at(elsewhere); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: elsewhere, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: elsewhere, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); + + assert!(!menu_open(&harness, position)); + assert_eq!(harness.state().session.history_labels().len(), history, "the decal wasn't moved"); +} From 8334230ed15d4d5c0e6009a642f94d0ea547e6be Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 8 Nov 2026 02:23:52 +0100 Subject: [PATCH 23/64] test(formats): a late entry error with all earlier entries fine is returned Co-Authored-By: Claude Opus 5.5 --- crates/formats/src/project_file/tests.rs | 26 ++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/crates/formats/src/project_file/tests.rs b/crates/formats/src/project_file/tests.rs index 1f85d26c..e5952be9 100644 --- a/crates/formats/src/project_file/tests.rs +++ b/crates/formats/src/project_file/tests.rs @@ -452,6 +452,32 @@ fn a_failing_entry_is_an_error_not_a_hang() { } } +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn a_late_failing_entry_after_good_ones_is_its_own_error() { + // Only the last entry fails and nothing panics, so the error must come from that entry. + for (workers, budget) in [(4usize, 25u64), (4, u64::MAX), (2, 1)] { + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let opts = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated); + let list: Vec> = (0..10) + .map(|i| Entry { + name: format!("e{i}"), + options: opts, + weight: 10, + body: Box::new(move |w| if i == 9 { Err(std::io::Error::other("late boom")) } else { w.write_all(&[i as u8; 100]) }), + }) + .collect(); + let mut zip = ZipWriter::new(Cursor::new(Vec::new())); + let res = entries::parallel::write(&mut zip, list, workers, budget); + let _ = tx.send(res.map_err(|e| matches!(&e, FormatError::Io(io) if io.to_string() == "late boom"))); + }); + let res = + rx.recv_timeout(std::time::Duration::from_secs(60)).unwrap_or_else(|e| panic!("save did not finish ({e}): {workers} workers, budget {budget}")); + assert_eq!(res, Err(true), "{workers} workers, budget {budget}"); + } +} + #[test] fn recovery_skips_unsupported_baked_map_entries() { let expected = sample().pf; From 6d3f7c216ddf478c8c3cb9227f759604653bf4f1 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sun, 8 Nov 2026 01:26:54 +0000 Subject: [PATCH 24/64] Levels: paint the active handle on top Handles are painted with the dragged or hovered one last, so the handle drawn on top is the one the pointer grabs. Value labels keep the active handle first so its value wins over an overlapping neighbour's. --- crates/ui-egui/src/levels_editor.rs | 19 ++++++++++------ crates/ui-egui/tests/levels_editor.rs | 31 +++++++++++++++++++++++++++ 2 files changed, 44 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/levels_editor.rs b/crates/ui-egui/src/levels_editor.rs index 55e2d53d..575d734e 100644 --- a/crates/ui-egui/src/levels_editor.rs +++ b/crates/ui-egui/src/levels_editor.rs @@ -194,18 +194,17 @@ fn paint_output_gradient(ui: &Ui, strip: Rect) { painter.rect_stroke(strip, 0.0, Stroke::new(1.0, Tokens::get(ui.ctx()).field_border), egui::StrokeKind::Outside); } -/// Each handle filled with its gray and its value beside it, the active one first and overlapping values left out +/// Each handle filled with its gray, the active one on top, and its value beside it, overlapping values left out fn paint_handles_and_values(ui: &Ui, rect: Rect, responses: &[(LevelsHandle, Response)], levels: &Levels, typing: Option) { let track = track(rect); let tokens = Tokens::get(ui.ctx()); let painter = ui.painter(); - let font = egui::FontId::proportional(VALUE_FONT_SIZE); let is_active = |response: &Response| response.dragged() || response.hovered(); - let mut printed: Vec = Vec::new(); - let mut by_priority: Vec<&(LevelsHandle, Response)> = responses.iter().collect(); - by_priority.sort_by_key(|(_, response)| !is_active(response)); - for &(handle, ref response) in by_priority { + // Active handles last, so the one on top is the one the pointer grabs + let mut by_paint_order: Vec<&(LevelsHandle, Response)> = responses.iter().collect(); + by_paint_order.sort_by_key(|(_, response)| is_active(response)); + for &(handle, ref response) in by_paint_order { let x = track_x(&track, handle.position(levels)); let fill = match handle { LevelsHandle::InputLow => Color32::BLACK, @@ -222,6 +221,14 @@ fn paint_handles_and_values(ui: &Ui, rect: Rect, responses: &[(LevelsHandle, Res }; let points_down = LevelsHandle::INPUT.contains(&handle); painter.add(egui::Shape::convex_polygon(handle_outline(x, handle_top(rect, handle), points_down), fill, Stroke::new(1.0, outline))); + } + + // Active values first, so a neighbour's overlapping value gives way to them + let font = egui::FontId::proportional(VALUE_FONT_SIZE); + let mut printed: Vec = Vec::new(); + let mut by_priority: Vec<&(LevelsHandle, Response)> = responses.iter().collect(); + by_priority.sort_by_key(|(_, response)| !is_active(response)); + for &(handle, ref response) in by_priority { if typing == Some(handle) { continue; } diff --git a/crates/ui-egui/tests/levels_editor.rs b/crates/ui-egui/tests/levels_editor.rs index c09246c4..a8aa7fc3 100644 --- a/crates/ui-egui/tests/levels_editor.rs +++ b/crates/ui-egui/tests/levels_editor.rs @@ -12,6 +12,12 @@ use texturecraft_ui_egui::TextureCraftApp; const HISTOGRAM_BUCKETS: usize = 64; const AUTO_MIN_SHARE: f64 = 0.001; +/// Labels of the five handles +const HANDLE_LABELS: [&str; 5] = ["Input low", "Input high", "Gamma", "Output low", "Output high"]; + +/// Corners of a handle's pentagon pointer +const HANDLE_POINTER_CORNERS: usize = 5; + /// A clouds mask under a levels effect added by `command` with `params`, selected, and its id fn levels_harness(command: &str, params: Value) -> (Harness<'static, TextureCraftApp>, LayerId) { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); @@ -245,3 +251,28 @@ fn the_levels_filter_shows_the_same_editor() { harness.get_by_role_and_label(Role::Button, button); } } + +/// Bounds of the handle pointers in paint order, the last one drawn on top +fn painted_handles(harness: &Harness<'_, TextureCraftApp>) -> Vec { + let centres = HANDLE_LABELS.map(|label| handle(harness, label)); + let pointers = harness.output().shapes.iter().filter_map(|clipped| match &clipped.shape { + egui::Shape::Path(path) if path.closed && path.points.len() == HANDLE_POINTER_CORNERS => Some(egui::Rect::from_points(&path.points)), + _ => None, + }); + pointers.filter(|bounds| centres.iter().any(|centre| bounds.expand(1.0).contains(*centre))).collect() +} + +#[test] +fn the_hovered_handle_is_painted_on_top() { + let (mut harness, _) = levels_harness("effect.add.levels", json!({"target": "mask"})); + assert_eq!(painted_handles(&harness).len(), HANDLE_LABELS.len(), "every handle is painted once"); + + for label in HANDLE_LABELS { + let at = handle(&harness, label); + harness.hover_at(at); + harness.run_steps(2); + + let on_top = painted_handles(&harness).last().copied().unwrap(); + assert!(on_top.expand(1.0).contains(at), "{label} is painted last while hovered: {on_top:?} vs {at:?}"); + } +} From aecf9cd7ab4a7cf5c80e1a6703b45d6f8cc4d1b7 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Sun, 8 Nov 2026 02:29:28 +0100 Subject: [PATCH 25/64] Use as_chunks in the bake_tiles tests main added Co-Authored-By: Claude Opus 5.5 --- crates/engine/tests/bake_tiles.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/engine/tests/bake_tiles.rs b/crates/engine/tests/bake_tiles.rs index 3f000321..a7f3f1a0 100644 --- a/crates/engine/tests/bake_tiles.rs +++ b/crates/engine/tests/bake_tiles.rs @@ -57,7 +57,7 @@ fn partial_bake_preserves_unchecked_tiles_and_uses_the_workers_selection() { session.apply_bake(0, output).unwrap(); let pixels = &session.doc.baked[&0].maps[&BakedMap::AmbientOcclusion]; - for row in pixels.chunks_exact(64) { + for row in pixels.as_chunks::<64>().0 { assert!(row[..32].iter().all(|value| *value > 0.99)); assert!(row[32..].iter().all(|value| *value == 0.25)); } @@ -81,7 +81,7 @@ fn partial_bake_resizes_retained_tiles_and_unchecked_map_outputs() { let baked = &session.doc.baked[&0]; assert_eq!((baked.resolution, baked.height(BakedMap::AmbientOcclusion)), (128, 64)); - for row in baked.maps[&BakedMap::AmbientOcclusion].chunks_exact(128) { + for row in baked.maps[&BakedMap::AmbientOcclusion].as_chunks::<128>().0 { assert!(row[..64].iter().all(|value| *value > 0.99)); assert!(row[64..].iter().all(|value| *value == 0.25)); } From b9b5eb4747c774ecd5c9d3f524390a36ecc491eb Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sun, 8 Nov 2026 01:39:59 +0000 Subject: [PATCH 26/64] Symmetry: movable plane, angle span and on/off; copies paint where their source does - Symmetry gets an on/off toggle that keeps its settings, an offset of the mirror planes and radial axis from the mesh center, and a radial angle span; defaults paint exactly as before - tool.brush takes and reports symmetryOn, symmetryOffset and symmetryAngleSpan - A symmetry copy runs the camera checks (hidden, facing away, angle fade) at its source's point, so it paints the mirror of the stroke - The eye-depth test allows for neighbouring pixels of the same surface where it turns away from the camera: strokes reaching the silhouette broke into dots there --- crates/engine/src/commands.rs | 11 ++ crates/engine/src/decal_cmds.rs | 12 +- crates/engine/src/path_tool.rs | 11 +- crates/engine/src/tool_cmds.rs | 22 +++- crates/engine/tests/symmetry.rs | 145 ++++++++++++++++++++++++ crates/engine/tests/tools.rs | 26 +++++ crates/paint/src/brush.rs | 108 ++++++++++++++---- crates/paint/src/lib.rs | 4 +- crates/paint/src/particles.rs | 2 +- crates/paint/src/raster.rs | 49 ++++++-- crates/paint/src/stamp_source.rs | 24 ++++ crates/paint/src/stroke.rs | 184 +++++++++++++++++++++++-------- 12 files changed, 495 insertions(+), 103 deletions(-) create mode 100644 crates/engine/tests/symmetry.rs create mode 100644 crates/paint/src/stamp_source.rs diff --git a/crates/engine/src/commands.rs b/crates/engine/src/commands.rs index 9f0d126b..c91eab37 100644 --- a/crates/engine/src/commands.rs +++ b/crates/engine/src/commands.rs @@ -4,6 +4,7 @@ use serde_json::{Value, json}; use texturecraft_core::{BlendMode, Channel, NormalFormat}; +use texturecraft_geom::glam::Vec3; use crate::{EngineError, Result, Session}; @@ -132,6 +133,16 @@ pub(crate) fn u64p(p: &Value, key: &str) -> Option { p.get(key).and_then(|v| v.as_u64().or_else(|| v.as_f64().filter(|f| f.is_finite() && *f >= 0.0).map(|f| f.round() as u64))) } +/// A `[x, y, z]` param of finite numbers +pub(crate) fn vec3(p: &Value, key: &str) -> Option { + let items = p.get(key)?.as_array()?; + let numbers: Vec = items.iter().filter_map(Value::as_f64).map(|number| number as f32).filter(|number| number.is_finite()).collect(); + match numbers.as_slice() { + [x, y, z] => Some(Vec3::new(*x, *y, *z)), + _ => None, + } +} + pub(crate) fn boolp(p: &Value, key: &str) -> Option { p.get(key).and_then(Value::as_bool) } diff --git a/crates/engine/src/decal_cmds.rs b/crates/engine/src/decal_cmds.rs index e937b6f5..70096409 100644 --- a/crates/engine/src/decal_cmds.rs +++ b/crates/engine/src/decal_cmds.rs @@ -5,7 +5,7 @@ use serde_json::{Value, json}; use texturecraft_core::{Channel, Decal, Fill, Layer, LayerId, LayerKind, Projection, Source}; use texturecraft_geom::glam::{Vec2, Vec3}; -use crate::commands::{CommandSpec, always, bad, f32p, has_layer, layer_param, strp}; +use crate::commands::{CommandSpec, always, bad, f32p, has_layer, layer_param, strp, vec3}; use crate::tool_cmds::viewport_of; use crate::{Result, Session, cmd}; @@ -32,16 +32,6 @@ pub fn specs() -> Vec { ] } -/// A `[x, y, z]` param of finite numbers. -fn vec3(p: &Value, key: &str) -> Option { - let a = p.get(key)?.as_array()?; - let v: Vec = a.iter().filter_map(Value::as_f64).map(|x| x as f32).filter(|x| x.is_finite()).collect(); - match v.as_slice() { - [x, y, z] => Some(Vec3::new(*x, *y, *z)), - _ => None, - } -} - /// Where a decal goes: a surface point and its normal, from `x`/`y` (viewport pixels, the view /// center by default) or `position` + `normal`. None when `optional` and neither is given. fn placement(s: &Session, cmd: &str, p: &Value, optional: bool) -> Result> { diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index 150a103e..8e3db02f 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -452,12 +452,12 @@ impl Session { }) } - /// Fill the inside of `poly`: viewport pixels over the visible surface, or texture - /// coordinates. Returns the touched tiles. + /// Fill the inside of `poly` (viewport pixels over the visible surface, or texture coordinates); returns the touched tiles fn lasso_fill(&mut self, poly: Vec, uv: bool, viewport: Vec2) -> Result { let ts = self.ts(); let (gbuf, mut canvas) = self.fill_canvas(ts)?; let w = gbuf.width.max(1); + if uv { let lasso = Lasso::new(poly.iter().map(|p| *p * Vec2::new(w as f32, gbuf.height as f32)).collect()); fill_coverage(&mut canvas, &gbuf, |i, _| lasso.coverage(Vec2::new((i as u32 % w) as f32 + 0.5, (i as u32 / w) as f32 + 0.5))); @@ -469,15 +469,16 @@ impl Session { // A visible source inside the lasso can paint each symmetry copy let (lo, hi) = mesh.bounds(); - let center = (lo + hi) * 0.5; - let inverses: Vec<_> = self.tool.brush.sanitized().symmetry.transforms().iter().map(|m| m.inverse()).collect(); + let symmetry = self.tool.brush.sanitized().symmetry; + let symmetry_origin = symmetry.origin((lo + hi) * 0.5); + let inverses: Vec<_> = symmetry.transforms().iter().map(|m| m.inverse()).collect(); fill_coverage(&mut canvas, &gbuf, |i, _| { let Some(s) = gbuf.surface(mesh, i) else { return 0.0 }; let mut best = 0.0f32; for m in &inverses { - let pos = center + *m * (s.pos - center); + let pos = symmetry_origin + *m * (s.pos - symmetry_origin); let c = view_proj * pos.extend(1.0); if c.w <= MIN_PROJECTIVE_W { continue; diff --git a/crates/engine/src/tool_cmds.rs b/crates/engine/src/tool_cmds.rs index 7fa5fdab..27f704e2 100644 --- a/crates/engine/src/tool_cmds.rs +++ b/crates/engine/src/tool_cmds.rs @@ -4,9 +4,9 @@ use serde_json::{Value, json}; use texturecraft_core::Channel; use texturecraft_geom::glam::Vec2; -use texturecraft_paint::{Alignment, BrushAlpha, alphas}; +use texturecraft_paint::{Alignment, BrushAlpha, MAX_RADIAL_COPIES, alphas}; -use crate::commands::{CommandSpec, always, bad, boolp, channel_param, color_param, f32p, strp}; +use crate::commands::{CommandSpec, always, bad, boolp, channel_param, color_param, f32p, strp, vec3}; use crate::session::{CloneFrom, CloneSource, FillMode, Tool}; use crate::{Result, Session, cmd}; @@ -34,7 +34,7 @@ pub fn specs() -> Vec { "Brush settings", [], None, - "{size?: 0..100, flow?: 0..100, opacity?: 0..100, spacing?: 1..1000, hardness?: 0..100, angle?, followPath?, alignment?: tangent|camera, lazy?, jitterSize?, jitterAngle?, jitterFlow?, jitterPosition?, alpha?: procedural name | {image: resource name} | {library: id (alpha.list)}, backfaceCulling?, symmetryX?, symmetryY?, symmetryZ?, symmetryRadial?: 0..32 copies around symmetryAxis?: x|y|z (default y), minSize?, smudgeStrength?: 0..100, cloneSource?: composite|layer (what the Clone tool copies), particles?: {enabled?, count?: 1..16, lifetime?: 1..128 steps, gravity?: 0..2}}", + "{size?: 0..100, flow?: 0..100, opacity?: 0..100, spacing?: 1..1000, hardness?: 0..100, angle?, followPath?, alignment?: tangent|camera, lazy?, jitterSize?, jitterAngle?, jitterFlow?, jitterPosition?, alpha?: procedural name | {image: resource name} | {library: id (alpha.list)}, backfaceCulling?, symmetryOn? (the toolbar toggle; off keeps the settings), symmetryX?, symmetryY?, symmetryZ?, symmetryRadial?: 0..32 copies around symmetryAxis?: x|y|z (default y), symmetryOffset?: [x, y, z] (world units from the mesh center, where the mirror planes and radial axis cross), symmetryAngleSpan?: 0..360 degrees the radial copies spread over, minSize?, smudgeStrength?: 0..100, cloneSource?: composite|layer (what the Clone tool copies), particles?: {enabled?, count?: 1..16, lifetime?: 1..128 steps, gravity?: 0..2}}", always, brush ), @@ -98,7 +98,7 @@ fn select(s: &mut Session, p: &Value) -> Result { set_tool(s, t) } -/// Brush values use the UI's 0–100 scales, so agents and the sliders speak the same numbers. +/// Brush values use the UI's 0–100 scales, so agents and the sliders speak the same numbers fn brush(s: &mut Session, p: &Value) -> Result { let b = &mut s.tool.brush; let pct = |k: &str| f32p(p, k).map(|v| v / 100.0); @@ -155,20 +155,23 @@ fn brush(s: &mut Session, p: &Value) -> Result { (b.alpha_image, b.alpha_library) = (Some(name.to_string()), None); } else if let Some(id) = alpha.and_then(|a| a.get("library")).and_then(Value::as_str) { let a = alphas::find(id).ok_or_else(|| bad("tool.brush", format!("unknown library alpha `{id}` (see alpha.list)")))?; - // Render it now rather than on the first stamp. + // Render it now rather than on the first stamp a.image(); (b.alpha_image, b.alpha_library) = (None, Some(a.id.clone())); } if let Some(v) = boolp(p, "backfaceCulling") { b.backface_culling = v; } + if let Some(v) = boolp(p, "symmetryOn") { + b.symmetry.enabled = v; + } for (k, slot) in [("symmetryX", &mut b.symmetry.x), ("symmetryY", &mut b.symmetry.y), ("symmetryZ", &mut b.symmetry.z)] { if let Some(v) = boolp(p, k) { *slot = v; } } if let Some(v) = f32p(p, "symmetryRadial") { - b.symmetry.radial = v.clamp(0.0, 32.0) as u8; + b.symmetry.radial = v.clamp(0.0, f32::from(MAX_RADIAL_COPIES)) as u8; } if let Some(a) = strp(p, "symmetryAxis") { b.symmetry.axis = match a.to_ascii_lowercase().as_str() { @@ -178,6 +181,12 @@ fn brush(s: &mut Session, p: &Value) -> Result { _ => return Err(bad("tool.brush", format!("unknown symmetry axis `{a}` (x, y or z)"))), }; } + if let Some(v) = f32p(p, "symmetryAngleSpan") { + b.symmetry.angle_span = v; + } + if p.get("symmetryOffset").is_some() { + b.symmetry.offset = vec3(p, "symmetryOffset").ok_or_else(|| bad("tool.brush", "`symmetryOffset` must be [x, y, z]"))?.to_array(); + } if let Some(v) = boolp(p, "screenSpace") { b.screen_space = v; } @@ -216,6 +225,7 @@ pub(crate) fn brush_json(s: &Session) -> Value { }, "backfaceCulling": b.backface_culling, "symmetry": [b.symmetry.x, b.symmetry.y, b.symmetry.z], "radialSymmetry": { "copies": b.symmetry.radial, "axis": (["x", "y", "z"].get(b.symmetry.axis as usize)) }, + "symmetryOffset": b.symmetry.offset, "symmetryOn": b.symmetry.enabled, "symmetryAngleSpan": b.symmetry.angle_span, "smudgeStrength": s.tool.smudge_strength * 100.0, "particles": b.particles, "cloneSource": if s.tool.clone_from == CloneFrom::Layer { "layer" } else { "composite" }, }) diff --git a/crates/engine/tests/symmetry.rs b/crates/engine/tests/symmetry.rs new file mode 100644 index 00000000..b1e7c6ef --- /dev/null +++ b/crates/engine/tests/symmetry.rs @@ -0,0 +1,145 @@ +//! Symmetry around a moved plane or axis, driven through engine commands the way agents paint + +use serde_json::json; +use texturecraft_engine::core::Channel; +use texturecraft_engine::geom::glam::{Vec2, Vec3, Vec4}; +use texturecraft_engine::geom::{Mesh, primitives}; +use texturecraft_engine::{Session, execute}; + +const TEXTURE_SIZE: f32 = 256.0; +const VIEWPORT: f32 = 400.0; + +fn session(mesh: Mesh) -> Session { + let mut session = Session::new_project("t", mesh, "builtin:test", None, TEXTURE_SIZE as u32).unwrap(); + session.viewport = Vec2::splat(VIEWPORT); + session.camera.yaw = 0.0; + session.camera.pitch = 0.0; + session.update(); + execute(&mut session, "tool.material", &json!({"channel": "baseColor", "color": [1.0, 0.0, 0.0]})).unwrap(); + execute(&mut session, "tool.brush", &json!({"size": 6, "hardness": 90})).unwrap(); + session +} + +/// A 2×2 wall in the XY plane facing the camera (+Z) +fn wall() -> Mesh { + let mut mesh = primitives::plane(2.0, 8); + for point in &mut mesh.positions { + *point = Vec3::new(point.x, -point.z, 0.0); + } + mesh.normals.iter_mut().for_each(|normal| *normal = Vec3::Z); + mesh.tangents.iter_mut().for_each(|tangent| *tangent = Vec4::new(1.0, 0.0, 0.0, 1.0)); + mesh +} + +/// Viewport pixel of world `point` +fn screen(session: &Session, point: Vec3) -> Vec2 { + let ndc = session.camera.project(point, 1.0).unwrap(); + Vec2::new((ndc.x * 0.5 + 0.5) * VIEWPORT, (0.5 - ndc.y * 0.5) * VIEWPORT) +} + +/// Is the surface at world `point` painted red? +fn red_at(session: &Session, point: Vec3) -> bool { + let hit = session.pick(screen(session, point), session.viewport).unwrap(); + let color = session.caches[0].composite.value(Channel::BaseColor, (hit.uv.x * TEXTURE_SIZE) as u32, (hit.uv.y * TEXTURE_SIZE) as u32); + color[0] > 0.85 && color[1] < 0.15 +} + +/// Where a viewport pixel lands on the mesh +fn surface(session: &Session, x: f32, y: f32) -> Vec3 { + session.pick(Vec2::new(x, y), session.viewport).unwrap().pos +} + +#[test] +fn a_moved_mirror_plane_paints_the_copy_at_the_mirrored_point() { + let mut session = session(wall()); + let reply = execute(&mut session, "tool.brush", &json!({"symmetryX": true, "symmetryOffset": [0.25, 0.0, 0.0]})).unwrap(); + + // Right of the view's center, on the wall + let stroke = surface(&session, 300.0, 200.0); + execute(&mut session, "tool.stroke", &json!({"points": [[300, 200]]})).unwrap(); + session.update(); + + let mirrored = Vec3::new(0.5 - stroke.x, stroke.y, stroke.z); + assert!(red_at(&session, stroke), "the stroke"); + assert!(red_at(&session, mirrored), "its copy across x = 0.25"); + assert!(!red_at(&session, Vec3::new(-stroke.x, stroke.y, stroke.z)), "nothing across the mesh center"); + assert_eq!(reply["symmetryOffset"], json!([0.25, 0.0, 0.0]), "agents read the offset back"); +} + +#[test] +fn radial_copies_turn_around_the_moved_axis() { + let mut session = session(wall()); + let axis = Vec3::new(0.2, -0.1, 0.0); + execute(&mut session, "tool.brush", &json!({"symmetryRadial": 2, "symmetryAxis": "z", "symmetryOffset": axis.to_array()})).unwrap(); + + // Up and right of the view's center, on the wall + let stroke = surface(&session, 290.0, 160.0); + execute(&mut session, "tool.stroke", &json!({"points": [[290, 160]]})).unwrap(); + session.update(); + + // Half a turn around Z through the moved axis + assert!(red_at(&session, stroke), "the stroke"); + assert!(red_at(&session, axis * 2.0 - stroke), "its copy half a turn around the moved axis"); + assert!(!red_at(&session, Vec3::new(-stroke.x, -stroke.y, 0.0)), "nothing around the mesh center"); +} + +#[test] +fn a_closed_path_fill_mirrors_around_the_moved_plane() { + let mut session = session(wall()); + execute(&mut session, "tool.brush", &json!({"symmetryX": true, "symmetryOffset": [-0.2, 0.0, 0.0]})).unwrap(); + + // A small square right of the view's center, on the wall + let square = json!([[250, 180], [280, 180], [280, 220], [250, 220]]); + execute(&mut session, "tool.path", &json!({"points": square, "closed": true, "fill": true, "commit": true})).unwrap(); + + let inside = surface(&session, 265.0, 200.0); + assert!(red_at(&session, inside), "the filled lasso"); + assert!(red_at(&session, Vec3::new(-0.4 - inside.x, inside.y, 0.0)), "its copy across x = -0.2"); + assert!(!red_at(&session, Vec3::new(-inside.x, inside.y, 0.0)), "nothing across the mesh center"); +} + +/// How much redder than green a texel must be to count as painted (faded edges included) +const PAINTED_TINT: f32 = 0.05; + +/// Texels tinted red in the top and bottom half of the texture +fn painted_halves(session: &Session) -> (usize, usize) { + let painted = |x: u32, y: u32| { + let color = session.caches[0].composite.value(Channel::BaseColor, x, y); + color[0] - color[1] > PAINTED_TINT + }; + let half = TEXTURE_SIZE as u32 / 2; + let count = |rows: std::ops::Range| rows.flat_map(|y| (0..TEXTURE_SIZE as u32).map(move |x| (x, y))).filter(|&(x, y)| painted(x, y)).count(); + (count(0..half), count(half..TEXTURE_SIZE as u32)) +} + +#[test] +fn a_mirror_copy_paints_exactly_where_its_stroke_does() { + let mut session = session(primitives::sphere(1.0, 48, 24)); + execute(&mut session, "tool.brush", &json!({"size": 4, "symmetryY": true})).unwrap(); + + // From the middle of the view to past the ball's right edge, above center, where it fades out; the copy below must fade the same way + let points: Vec = (0..40).map(|step| json!([200.0 + step as f32 * 6.0, 165.0])).collect(); + execute(&mut session, "tool.stroke", &json!({"points": points})).unwrap(); + session.update(); + + let (stroke, copy) = painted_halves(&session); + assert!(stroke > 0); + // Within 4%: the ball's texture layout is not exactly symmetric texel for texel + assert!(stroke.abs_diff(copy) * 25 <= stroke, "stroke {stroke} texels, copy {copy}"); +} + +#[test] +fn a_copy_paints_on_a_curved_mesh_across_a_moved_plane() { + let mut session = session(primitives::sphere(1.0, 48, 24)); + execute(&mut session, "tool.brush", &json!({"symmetryX": true, "symmetryOffset": [0.1, 0.0, 0.0]})).unwrap(); + + // Left of the view's center; across x = 0.1 its copy lands where the ball curves away a little more + let stroke = surface(&session, 185.0, 200.0); + execute(&mut session, "tool.stroke", &json!({"points": [[185, 200]]})).unwrap(); + session.update(); + + let mirrored_x = 0.2 - stroke.x; + let on_ball = Vec3::new(mirrored_x, stroke.y, (1.0 - mirrored_x * mirrored_x - stroke.y * stroke.y).sqrt()); + assert!(red_at(&session, stroke), "the stroke"); + assert!(red_at(&session, on_ball), "its copy on the ball across x = 0.1"); +} diff --git a/crates/engine/tests/tools.rs b/crates/engine/tests/tools.rs index dcd65100..ad97433b 100644 --- a/crates/engine/tests/tools.rs +++ b/crates/engine/tests/tools.rs @@ -180,3 +180,29 @@ fn quick_mask_limits_painting() { dab(&mut s, 150.0, 200.0); assert!(color_at(&s, 150.0, 200.0)[1] > 0.85, "disabled: everything is open"); } + +/// How much redder than green a texel must be to count as painted (faded edges included) +const PAINTED_TINT: f32 = 0.05; + +/// Separate painted runs down texture column `x` (base color tinted red) +fn painted_runs(session: &Session, x: u32) -> usize { + let painted = |y: u32| { + let color = session.caches[0].composite.value(Channel::BaseColor, x, y); + color[0] - color[1] > PAINTED_TINT + }; + (0..RES as u32).filter(|&y| painted(y) && (y == 0 || !painted(y - 1))).count() +} + +#[test] +fn a_stroke_to_the_edge_of_the_mesh_fades_without_breaking_into_dots() { + let mut session = session(); + paint_red(&mut session, 4.0); + // From the middle of the view to past the ball's right edge, above center + let points: Vec = (0..40).map(|step| json!([200.0 + step as f32 * 6.0, 165.0])).collect(); + execute(&mut session, "tool.stroke", &json!({"points": points})).unwrap(); + session.update(); + + // The stroke crosses each texture column once, also where the surface turns away from the camera + let broken: Vec = (0..RES as u32).filter(|&x| painted_runs(&session, x) > 1).collect(); + assert!(broken.is_empty(), "columns with gaps: {broken:?}"); +} diff --git a/crates/paint/src/brush.rs b/crates/paint/src/brush.rs index 61313d57..7e7835c7 100644 --- a/crates/paint/src/brush.rs +++ b/crates/paint/src/brush.rs @@ -130,33 +130,82 @@ pub(crate) fn smoothstep(e0: f32, e1: f32, x: f32) -> f32 { t * t * (3.0 - 2.0 * t) } -/// Mirror and radial symmetry through the mesh center. -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)] +/// Largest symmetry offset kept from a command or a file (world units), far beyond any mesh +const MAX_SYMMETRY_OFFSET: f32 = 1.0e6; + +/// Mirror and radial symmetry through the mesh center, optionally moved by `offset` +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] pub struct Symmetry { + /// The toolbar's Symmetry toggle: off keeps the settings below but paints no copies + #[serde(default = "enabled_by_default")] + pub enabled: bool, pub x: bool, pub y: bool, pub z: bool, - /// Radial symmetry: copies spread evenly around `axis` (0 or 1: off; at most 32). + /// Radial copies around `axis`, spread over `angle_span` (0 or 1: off; at most [`MAX_RADIAL_COPIES`]) #[serde(default)] pub radial: u8, - /// Axis of radial symmetry: 0 = X, 1 = Y, 2 = Z. + /// Axis of radial symmetry (0 = X, 1 = Y, 2 = Z), also the one axis the settings popup mirrors on #[serde(default = "radial_axis")] pub axis: u8, + /// Where the mirror planes and the radial axis cross, relative to the mesh center (world units) + #[serde(default)] + pub offset: [f32; 3], + /// Degrees the radial copies spread over: a full turn spaces them evenly, less puts the first and last copy at its ends + #[serde(default = "full_turn")] + pub angle_span: f32, +} + +fn enabled_by_default() -> bool { + true } fn radial_axis() -> u8 { 1 } +fn full_turn() -> f32 { + FULL_TURN_DEGREES +} + +/// [`Symmetry::angle_span`] of a full turn +pub const FULL_TURN_DEGREES: f32 = 360.0; + +/// Most radial copies a brush paints +pub const MAX_RADIAL_COPIES: u8 = 32; + +/// [`Symmetry::axis`] of the last axis, Z +const LAST_AXIS: u8 = 2; + impl Default for Symmetry { fn default() -> Self { - Symmetry { x: false, y: false, z: false, radial: 0, axis: radial_axis() } + Symmetry { enabled: enabled_by_default(), x: false, y: false, z: false, radial: 0, axis: radial_axis(), offset: [0.0; 3], angle_span: full_turn() } } } impl Symmetry { + /// Whether symmetry is on with an axis to mirror on or radial copies pub fn any(&self) -> bool { - self.x || self.y || self.z || self.radial > 1 + self.enabled && (self.x || self.y || self.z || self.radial > 1) + } + + /// Whether radial symmetry is on (see [`Symmetry::radial_on`] for whether it paints copies) + pub fn radial_mode(&self) -> bool { + self.enabled && self.radial > 1 + } + + /// Whether radial copies are painted: with no angle to spread over they would all land on the stroke + pub fn radial_on(&self) -> bool { + self.radial_mode() && self.angle_span > 0.0 + } + + /// Rotation (radians) of radial copy number `copy` (0 = the stroke itself) around the axis + pub fn radial_angle(&self, copy: u8) -> f32 { + if self.angle_span >= FULL_TURN_DEGREES { + f32::from(copy) * std::f32::consts::TAU / f32::from(self.radial.max(1)) + } else { + f32::from(copy) * self.angle_span.to_radians() / f32::from(self.radial.saturating_sub(1).max(1)) + } } /// Mirror scales in stroke order, including identity, without allocating @@ -172,26 +221,39 @@ impl Symmetry { Vec3::NEG_ONE, ] .into_iter() - .filter(|sign| (sign.x > 0.0 || self.x) && (sign.y > 0.0 || self.y) && (sign.z > 0.0 || self.z)) + .filter(|sign| *sign == Vec3::ONE || (self.enabled && (sign.x > 0.0 || self.x) && (sign.y > 0.0 || self.y) && (sign.z > 0.0 || self.z))) } - /// Linear maps (through the mesh center) taking a point to each of its symmetry copies, - /// the identity first. Mirrors come first, then radial rotations of the point and its mirrors. + /// The point the mirror planes and the radial axis pass through, for a mesh centered at `center` + pub fn origin(&self, center: Vec3) -> Vec3 { + center + Vec3::from(self.offset) + } + + /// [`Symmetry::axis`] as an index (0 = X, 1 = Y, 2 = Z), out-of-range values read as Z + pub fn axis_index(&self) -> usize { + usize::from(self.axis.min(LAST_AXIS)) + } + + /// Axis of radial symmetry as a unit vector + pub fn radial_axis(&self) -> Vec3 { + [Vec3::X, Vec3::Y, Vec3::Z][self.axis_index()] + } + + /// Linear maps `m` taking a point to its copies as `origin + m * (p - origin)`: identity, mirrors, then their radial turns pub fn transforms(&self) -> Vec { - let mut out: Vec = self.mirror_signs().map(Mat3::from_diagonal).collect(); + let mut maps: Vec = self.mirror_signs().map(Mat3::from_diagonal).collect(); - if self.radial > 1 { - let axis = [Vec3::X, Vec3::Y, Vec3::Z].get(self.axis as usize).copied().unwrap_or(Vec3::Y); - let base = out.clone(); - out.reserve(base.len().saturating_mul(usize::from(self.radial - 1))); + if self.radial_on() { + let mirrors = maps.clone(); + maps.reserve(mirrors.len().saturating_mul(usize::from(self.radial - 1))); - for k in 1..self.radial { - let r = Mat3::from_axis_angle(axis, f32::from(k) * std::f32::consts::TAU / f32::from(self.radial)); - out.extend(base.iter().map(|m| r * *m)); + for copy in 1..self.radial { + let turn = Mat3::from_axis_angle(self.radial_axis(), self.radial_angle(copy)); + maps.extend(mirrors.iter().map(|mirror| turn * *mirror)); } } - out + maps } } @@ -291,7 +353,7 @@ impl Default for BrushSettings { } impl BrushSettings { - /// Clamp every value into its valid range (input from UI, CLI or agents). + /// Clamp every value into its valid range (input from UI, CLI or agents) pub fn sanitized(&self) -> BrushSettings { let f = |v: f32, lo: f32, hi: f32, d: f32| if v.is_finite() { v.clamp(lo, hi) } else { d }; BrushSettings { @@ -309,7 +371,13 @@ impl BrushSettings { jitter_flow: f(self.jitter_flow, 0.0, 1.0, 0.0), jitter_position: f(self.jitter_position, 0.0, 4.0, 0.0), depth: f(self.depth, 0.05, 4.0, 1.0), - symmetry: Symmetry { radial: self.symmetry.radial.min(32), axis: self.symmetry.axis.min(2), ..self.symmetry }, + symmetry: Symmetry { + radial: self.symmetry.radial.min(MAX_RADIAL_COPIES), + axis: self.symmetry.axis.min(LAST_AXIS), + offset: self.symmetry.offset.map(|v| f(v, -MAX_SYMMETRY_OFFSET, MAX_SYMMETRY_OFFSET, 0.0)), + angle_span: f(self.symmetry.angle_span, 0.0, FULL_TURN_DEGREES, FULL_TURN_DEGREES), + ..self.symmetry + }, particles: Particles { enabled: self.particles.enabled, count: self.particles.count.clamp(1, 16), diff --git a/crates/paint/src/lib.rs b/crates/paint/src/lib.rs index c34415ed..ded26d9e 100644 --- a/crates/paint/src/lib.rs +++ b/crates/paint/src/lib.rs @@ -19,14 +19,16 @@ pub mod path; pub mod pickup; pub mod presets; pub mod raster; +pub mod stamp_source; pub mod stroke; pub mod text; pub mod visibility; -pub use brush::{Alignment, BrushAlpha, BrushSettings, Particles, Shape, Symmetry, image_alpha}; +pub use brush::{Alignment, BrushAlpha, BrushSettings, FULL_TURN_DEGREES, MAX_RADIAL_COPIES, Particles, Shape, Symmetry, image_alpha}; pub use commit::{CommitSource, Staging, TexelFn, commit_coverage, commit_layer, commit_mask}; pub use path::{Lasso, spline}; pub use pickup::{Pickup, PickupMode}; pub use raster::{RasterCtx, StrokeCanvas, UvStamp, fill_coverage, fill_triangles, rasterize, rasterize_uv}; +pub use stamp_source::StampSource; pub use stroke::{PickCtx, Stamp, Stroke, SurfaceHit, pick}; pub use visibility::EyeDepth; diff --git a/crates/paint/src/particles.rs b/crates/paint/src/particles.rs index 64ec2dde..4a0e7660 100644 --- a/crates/paint/src/particles.rs +++ b/crates/paint/src/particles.rs @@ -99,7 +99,7 @@ mod tests { hardness: 0.5, depth: 1.0, seed: 3, - copy: false, + source: None, }; let p = Particles { enabled: true, count: 4, lifetime: 20, gravity: 1.0 }; let a = emit(&ctx, &p, &s); diff --git a/crates/paint/src/raster.rs b/crates/paint/src/raster.rs index f53fd7fc..9c5b4ce9 100644 --- a/crates/paint/src/raster.rs +++ b/crates/paint/src/raster.rs @@ -82,6 +82,29 @@ impl StrokeCanvas { } } +/// Most a texel's eye distance may exceed the nearest surface in its 3×3 pixel neighbourhood, in pixels along the surface +const NEIGHBOUR_REACH: f32 = 1.5; + +/// Facing (cosine) below which the allowance stops growing +const MIN_FACING: f32 = 0.05; + +/// Height of the view in normalized device coordinates (−1 to 1) +const NDC_HEIGHT: f32 = 2.0; + +/// How far toward the eye to test a texel turned `facing` away: at grazing angles the neighbouring pixels of the same surface are much nearer, and the depth test would speckle +fn grazing_allowance(depth: &EyeDepth, point: Vec3, facing: f32) -> f32 { + // Back faces get none, so painting with culling off doesn't reach through thin parts + if facing <= 0.0 { + return 0.0; + } + + let clip_w = (depth.view_proj * point.extend(1.0)).w.max(0.0); + let ndc_per_unit = depth.view_proj.row(1).truncate().length(); + let world_per_pixel = clip_w * NDC_HEIGHT / (depth.height as f32 * ndc_per_unit).max(f32::EPSILON); + let facing = facing.clamp(MIN_FACING, 1.0); + world_per_pixel * NEIGHBOUR_REACH * (1.0 - facing * facing).sqrt() / facing +} + /// What the rasterizer reads. pub struct RasterCtx<'a> { pub mesh: &'a Mesh, @@ -148,7 +171,7 @@ fn scan_triangle(ctx: &RasterCtx, s: &Stamp, t: u32, w: u32, h: u32, fade_lo: f3 let x1 = ((ua.x.max(ub.x).max(uc.x) * w as f32).ceil().max(0.0) as u32).min(w); let y0 = (ua.y.min(ub.y).min(uc.y) * h as f32).floor().max(0.0) as u32; let y1 = ((ua.y.max(ub.y).max(uc.y) * h as f32).ceil().max(0.0) as u32).min(h); - // Stamp radius in texels on this triangle: texel area over world area. + // Stamp radius in texels on this triangle: texel area over world area let uv_area = (*ub - *ua).perp_dot(*uc - *ua).abs() * w as f32 * h as f32; let world_area = (*pb - *pa).cross(*pc - *pa).length(); let shape = ctx.shape.at_radius(s.radius * (uv_area / world_area).sqrt()); @@ -177,22 +200,24 @@ fn scan_triangle(ctx: &RasterCtx, s: &Stamp, t: u32, w: u32, h: u32, fade_lo: f3 center = ([x as f32 + 0.5, y as f32 + 0.5], dist); } let n = (*na * b0 + *nb * b1 + *nc * b2).try_normalize().unwrap_or(s.normal); - let to_eye = (ctx.eye - p).try_normalize().unwrap_or(n); - let facing = n.dot(to_eye); - // Symmetry copies paint where the camera may not see (the back of the model). - let culled = ctx.backface_culling && !s.copy; - if culled && facing <= 0.0 { - continue; - } if n.dot(s.normal) <= 0.0 { continue; } - if let Some(depth) = ctx.depth.filter(|_| !s.copy) - && !depth.visible(p) + + // A copy runs the camera checks at its source's point, up to the stamp's half-depth off the surface on an asymmetric mesh + let (seen, seen_normal) = s.source.map_or((p, n), |source| (source.point(p), source.direction(n))); + let off_surface = if s.source.is_some() { s.radius * s.depth } else { 0.0 }; + let to_eye = (ctx.eye - seen).try_normalize().unwrap_or(seen_normal); + let facing = seen_normal.dot(to_eye); + if ctx.backface_culling && facing <= 0.0 { + continue; + } + if let Some(depth) = ctx.depth + && !depth.visible(seen + to_eye * (grazing_allowance(depth, seen, facing) + off_surface)) { continue; } - let fade = if culled { smoothstep(fade_lo, fade_hi, facing) } else { 1.0 }; + let fade = if ctx.backface_culling { smoothstep(fade_lo, fade_hi, facing) } else { 1.0 }; let a = shape.sample(lx, ly, s.hardness, s.seed) * s.flow * fade; if a > 0.0 { texels.push((x, y, a)); @@ -257,7 +282,7 @@ mod tests { hardness: 0.9, depth: 1.0, seed: 0, - copy: false, + source: None, }; rasterize(&mut canvas, &ctx, &[st]); // Plane is 2 units over 128 texels: radius 0.25 = 16 texels around the center (64, 64). diff --git a/crates/paint/src/stamp_source.rs b/crates/paint/src/stamp_source.rs new file mode 100644 index 00000000..5f56e435 --- /dev/null +++ b/crates/paint/src/stamp_source.rs @@ -0,0 +1,24 @@ +//! Where a symmetry copy of a stamp comes from + +use texturecraft_geom::glam::{Mat3, Vec3}; + +/// The map from a symmetry copy back to its source stamp: a copy paints where its source would be painted +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct StampSource { + /// The point the symmetry maps turn and mirror about + pub origin: Vec3, + /// The inverse of the copy's linear map (mirrors and turns, so its transpose) + pub to_source: Mat3, +} + +impl StampSource { + /// The source's point for a point of the copy + pub fn point(&self, copy_point: Vec3) -> Vec3 { + self.origin + self.to_source * (copy_point - self.origin) + } + + /// The source's direction for a direction of the copy + pub fn direction(&self, copy_direction: Vec3) -> Vec3 { + self.to_source * copy_direction + } +} diff --git a/crates/paint/src/stroke.rs b/crates/paint/src/stroke.rs index 6aacb737..9cc3972b 100644 --- a/crates/paint/src/stroke.rs +++ b/crates/paint/src/stroke.rs @@ -1,11 +1,12 @@ //! From pointer samples to stamps: picking, lazy mouse, spacing along the surface, stamp //! frames, jitter and symmetry. -use texturecraft_geom::glam::{Quat, Vec2, Vec3}; +use texturecraft_geom::glam::{Mat3, Quat, Vec2, Vec3}; use texturecraft_geom::{Bvh, Mesh, OrbitCamera, surface_at}; use texturecraft_texel::noise::pcg3d; use crate::brush::{Alignment, BrushSettings}; +use crate::stamp_source::StampSource; /// Scene access for picking. pub struct PickCtx<'a> { @@ -37,7 +38,20 @@ pub fn pick(ctx: &PickCtx, screen: Vec2) -> Option { Some(SurfaceHit { pos: s.pos, nrm: s.nrm, tri: hit.tri, uv: s.uv, material: ctx.mesh.material_of(hit.tri as usize).unwrap_or(0), screen }) } -/// One brush dab in world space. +/// Random channels of a stamp's jitters (each draws its own number from the stamp's seed) +const JITTER_ANGLE: u32 = 1; +const JITTER_SIZE: u32 = 2; +const JITTER_ACROSS: u32 = 3; +const JITTER_ALONG: u32 = 4; +const JITTER_FLOW: u32 = 5; + +/// Full angle jitter turns a stamp this far either way (degrees) +const HALF_TURN_DEGREES: f32 = 180.0; + +/// Smallest size jitter leaves a stamp, as a fraction of its radius +const MIN_JITTERED_SIZE: f32 = 0.05; + +/// One brush dab in world space #[derive(Clone, Copy, Debug, PartialEq)] pub struct Stamp { pub center: Vec3, @@ -47,12 +61,12 @@ pub struct Stamp { pub radius: f32, pub flow: f32, pub hardness: f32, - /// Half-depth of the stamp volume relative to the radius. + /// Half-depth of the stamp volume relative to the radius pub depth: f32, - /// Varies procedural alphas per stamp. + /// Varies procedural alphas per stamp pub seed: u32, - /// A symmetry copy: it paints where symmetry puts it, whether the camera sees that or not. - pub copy: bool, + /// A symmetry copy's way back to its source: it paints where the source would, mirrored + pub source: Option, } /// An in-progress stroke. @@ -168,66 +182,87 @@ impl Stroke { self.last = Some(hit); } + /// The next stamp at `hit`: oriented to the surface or the camera, then jittered fn stamp(&mut self, ctx: &PickCtx, hit: &SurfaceHit, radius: f32) -> Stamp { - let s = &self.settings; - let n = self.count; + let settings = &self.settings; + let seed = self.count; self.count = self.count.wrapping_add(1); - let jitter = |k: u32, amount: f32| if amount > 0.0 { (rand01(n, k) * 2.0 - 1.0) * amount } else { 0.0 }; - let normal = match s.alignment { + let jitter = |channel: u32, amount: f32| if amount > 0.0 { (rand01(seed, channel) * 2.0 - 1.0) * amount } else { 0.0 }; + + // Frame: the normal, and an up direction from the camera or the stroke's path + let normal = match settings.alignment { Alignment::Tangent => hit.nrm, Alignment::Camera => -ctx.camera.forward(), }; - let cam_up = { - let f = ctx.camera.forward(); - let right = f.cross(Vec3::Y).try_normalize().unwrap_or(Vec3::X); - right.cross(f) + let camera_up = { + let forward = ctx.camera.forward(); + let right = forward.cross(Vec3::Y).try_normalize().unwrap_or(Vec3::X); + right.cross(forward) }; - let up_src = if s.follow_path { self.last_dir.unwrap_or(cam_up) } else { cam_up }; - let up = (up_src - normal * normal.dot(up_src)).try_normalize().unwrap_or_else(|| normal.any_orthonormal_vector()); - let tangent0 = up.cross(normal).try_normalize().unwrap_or_else(|| normal.any_orthonormal_vector()); - let angle = (s.angle + jitter(1, s.jitter_angle) * 180.0).to_radians(); - let q = Quat::from_axis_angle(normal, angle); - let tangent = q * tangent0; + let up_source = if settings.follow_path { self.last_dir.unwrap_or(camera_up) } else { camera_up }; + let up = (up_source - normal * normal.dot(up_source)).try_normalize().unwrap_or_else(|| normal.any_orthonormal_vector()); + let unturned_tangent = up.cross(normal).try_normalize().unwrap_or_else(|| normal.any_orthonormal_vector()); + + // Jitter: angle, size, position and flow + let angle = (settings.angle + jitter(JITTER_ANGLE, settings.jitter_angle) * HALF_TURN_DEGREES).to_radians(); + let turn = Quat::from_axis_angle(normal, angle); + let tangent = turn * unturned_tangent; let bitangent = normal.cross(tangent); - let r = radius * (1.0 + jitter(2, s.jitter_size)).max(0.05); - let offset = (tangent * jitter(3, 1.0) + bitangent * jitter(4, 1.0)) * s.jitter_position * radius; - let flow = (s.flow * (1.0 - jitter(5, s.jitter_flow).abs())).clamp(0.0, 1.0); - Stamp { center: hit.pos + offset, normal, tangent, bitangent, radius: r, flow, hardness: s.hardness, depth: s.depth, seed: n, copy: false } + let jittered_radius = radius * (1.0 + jitter(JITTER_SIZE, settings.jitter_size)).max(MIN_JITTERED_SIZE); + let offset = (tangent * jitter(JITTER_ACROSS, 1.0) + bitangent * jitter(JITTER_ALONG, 1.0)) * settings.jitter_position * radius; + let flow = (settings.flow * (1.0 - jitter(JITTER_FLOW, settings.jitter_flow).abs())).clamp(0.0, 1.0); + + Stamp { + center: hit.pos + offset, + normal, + tangent, + bitangent, + radius: jittered_radius, + flow, + hardness: settings.hardness, + depth: settings.depth, + seed, + source: None, + } } - /// Mirror copies of a stamp for the enabled symmetry axes, then radial copies of it and - /// its mirrors. - fn mirrors(&self, s: &Stamp) -> Vec { - let sym = self.settings.symmetry; - if !sym.any() { + /// Mirror copies of a stamp for the enabled symmetry axes, then radial copies of it and its mirrors + fn mirrors(&self, stamp: &Stamp) -> Vec { + let symmetry = self.settings.symmetry; + if !symmetry.any() { return Vec::new(); } - let mut out = Vec::new(); - for sign in sym.mirror_signs().skip(1) { - let normal = s.normal * sign; - let tangent = s.tangent * sign; - out.push(Stamp { center: self.center + (s.center - self.center) * sign, normal, tangent, bitangent: normal.cross(tangent), copy: true, ..*s }); + let origin = symmetry.origin(self.center); + let mut copies = Vec::new(); + let mut maps = Vec::new(); + for sign in symmetry.mirror_signs().skip(1) { + let normal = stamp.normal * sign; + let tangent = stamp.tangent * sign; + let map = Mat3::from_diagonal(sign); + let source = Some(StampSource { origin, to_source: map.transpose() }); + copies.push(Stamp { center: origin + (stamp.center - origin) * sign, normal, tangent, bitangent: normal.cross(tangent), source, ..*stamp }); + maps.push(map); } - if sym.radial > 1 { - let axis = [Vec3::X, Vec3::Y, Vec3::Z].get(sym.axis as usize).copied().unwrap_or(Vec3::Y); - let base: Vec = std::iter::once(*s).chain(out.iter().copied()).collect(); + if symmetry.radial_on() { + let axis = symmetry.radial_axis(); + let to_turn: Vec<(Stamp, Mat3)> = std::iter::once((*stamp, Mat3::IDENTITY)).chain(copies.iter().copied().zip(maps)).collect(); - for k in 1..sym.radial { - let q = Quat::from_axis_angle(axis, f32::from(k) * std::f32::consts::TAU / f32::from(sym.radial)); - out.extend(base.iter().map(|b| Stamp { - center: self.center + q * (b.center - self.center), - normal: q * b.normal, - tangent: q * b.tangent, - bitangent: q * b.bitangent, - copy: true, - ..*b + for copy in 1..symmetry.radial { + let turn = Quat::from_axis_angle(axis, symmetry.radial_angle(copy)); + copies.extend(to_turn.iter().map(|(base, map)| Stamp { + center: origin + turn * (base.center - origin), + normal: turn * base.normal, + tangent: turn * base.tangent, + bitangent: turn * base.bitangent, + source: Some(StampSource { origin, to_source: (Mat3::from_quat(turn) * *map).transpose() }), + ..*base })); } } - out + copies } pub fn last_hit(&self) -> Option { @@ -296,6 +331,61 @@ mod tests { assert_eq!(s.add(&ctx, Vec2::new(250.0, 180.0), 1.0).len(), 8); } + #[test] + fn symmetry_mirrors_about_the_moved_plane() { + let (mesh, bvh, camera) = ctx_parts(); + let ctx = PickCtx { mesh: &mesh, bvh: &bvh, camera: &camera, viewport: Vec2::new(400.0, 400.0) }; + let mut settings = BrushSettings::default(); + settings.symmetry.x = true; + settings.symmetry.offset = [0.25, 0.0, 0.0]; + let mut stroke = Stroke::new(&settings, &mesh); + let stamps = stroke.add(&ctx, Vec2::new(250.0, 200.0), 1.0); + assert_eq!(stamps.len(), 2, "one stamp and its copy"); + let (painted, copy) = (stamps[0], stamps[1]); + + // Mirrored about x = 0.25 instead of the mesh center (x = 0) + assert!((painted.center.x + copy.center.x - 0.5).abs() < 1e-4, "{} {}", painted.center, copy.center); + assert!((painted.center.y - copy.center.y).abs() < 1e-4 && (painted.center.z - copy.center.z).abs() < 1e-4); + } + + #[test] + fn default_symmetry_copies_match_the_mesh_centered_formula_bit_for_bit() { + let (mesh, bvh, camera) = ctx_parts(); + let ctx = PickCtx { mesh: &mesh, bvh: &bvh, camera: &camera, viewport: Vec2::new(400.0, 400.0) }; + let mut settings = BrushSettings::default(); + settings.symmetry = crate::brush::Symmetry { x: true, y: true, radial: 3, axis: 1, ..settings.symmetry }; + let mut stroke = Stroke::new(&settings, &mesh); + let stamps = stroke.add(&ctx, Vec2::new(250.0, 180.0), 1.0); + + // Copies as painting computed them before the plane could move: mirrors, then radial turns of each + let (lo, hi) = mesh.bounds(); + let center = (lo + hi) * 0.5; + let source = stamps[0].center; + let mirrored = [Vec3::new(-1.0, 1.0, 1.0), Vec3::new(1.0, -1.0, 1.0), Vec3::new(-1.0, -1.0, 1.0)].map(|sign| center + (source - center) * sign); + let to_turn: Vec = std::iter::once(source).chain(mirrored).collect(); + let turned = (1..3u8).flat_map(|copy| { + let turn = Quat::from_axis_angle(Vec3::Y, f32::from(copy) * std::f32::consts::TAU / 3.0); + to_turn.iter().map(move |point| center + turn * (*point - center)).collect::>() + }); + let expected: Vec = mirrored.into_iter().chain(turned).collect(); + + let copies: Vec = stamps[1..].iter().map(|stamp| stamp.center).collect(); + assert_eq!(copies, expected); + } + + #[test] + fn a_zero_angle_span_paints_no_radial_copies() { + let (mesh, bvh, camera) = ctx_parts(); + let ctx = PickCtx { mesh: &mesh, bvh: &bvh, camera: &camera, viewport: Vec2::new(400.0, 400.0) }; + let mut settings = BrushSettings::default(); + settings.symmetry.radial = 6; + settings.symmetry.angle_span = 0.0; + let mut stroke = Stroke::new(&settings, &mesh); + + // Six copies with no angle between them would all paint over the stroke + assert_eq!(stroke.add(&ctx, Vec2::new(250.0, 180.0), 1.0).len(), 1); + } + #[test] fn radial_symmetry_spreads_copies_around_the_axis() { let (m, b, c) = ctx_parts(); From 74c9afcad9e944f0f70bed136ae477255a7e0062 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sun, 8 Nov 2026 01:39:59 +0000 Subject: [PATCH 27/64] Renderer: see-through overlay quads drawn after the mesh Frames carry quads the 3D view draws depth-tested after the mesh (no depth writes), so the mesh hides them per pixel; used for the symmetry plane, axis and the line where the plane cuts the mesh. --- crates/automation/src/render.rs | 10 +++++- crates/render/src/lib.rs | 2 ++ crates/render/src/overlay_quad.rs | 11 ++++++ crates/render/src/renderer.rs | 53 +++++++++++++++++++++++++++++ crates/render/src/set_highlight.rs | 21 +++++++----- crates/render/src/shaders/mesh.wgsl | 20 +++++++++++ crates/render/tests/headless.rs | 3 +- 7 files changed, 110 insertions(+), 10 deletions(-) create mode 100644 crates/render/src/overlay_quad.rs diff --git a/crates/automation/src/render.rs b/crates/automation/src/render.rs index c61fce50..e390c239 100644 --- a/crates/automation/src/render.rs +++ b/crates/automation/src/render.rs @@ -85,7 +85,15 @@ impl Gpu { /// 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); - let frame = Frame { view_id: 1, size, kind, camera, shade: shade(s), visible: s.doc.project.texture_sets.iter().map(|t| t.visible).collect() }; + let frame = Frame { + view_id: 1, + size, + kind, + camera, + shade: shade(s), + visible: s.doc.project.texture_sets.iter().map(|t| t.visible).collect(), + overlay: Vec::new(), + }; self.h.render(&frame) } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index c5ca2221..83cec6fc 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -21,12 +21,14 @@ pub mod gpu_trace; pub mod headless; pub mod ibl; pub mod mesh_maps; +pub mod overlay_quad; pub mod readback; pub mod renderer; pub mod set_highlight; mod subdivide; pub mod trace; +pub use overlay_quad::OverlayQuad; pub use renderer::{COLOR_FORMAT, Frame, MSAA, Renderer, Shade, ViewKind, aux_size, uv_view_scale}; pub use set_highlight::SetHighlight; pub use wgpu; diff --git a/crates/render/src/overlay_quad.rs b/crates/render/src/overlay_quad.rs new file mode 100644 index 00000000..c813bb42 --- /dev/null +++ b/crates/render/src/overlay_quad.rs @@ -0,0 +1,11 @@ +//! See-through quads drawn into the 3D view and hidden where the mesh is in front (the symmetry plane and lines) + +use texturecraft_geom::glam::Vec3; + +/// A flat quad with its corners in order, in a screen color (linear RGB) and opacity +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct OverlayQuad { + pub corners: [Vec3; 4], + pub color: [f32; 3], + pub opacity: f32, +} diff --git a/crates/render/src/renderer.rs b/crates/render/src/renderer.rs index 4ce9dac3..d0805f2d 100644 --- a/crates/render/src/renderer.rs +++ b/crates/render/src/renderer.rs @@ -32,6 +32,7 @@ use texturecraft_texel::TILE; use crate::gpu_trace::{Checked, checked}; use crate::ibl; +use crate::overlay_quad::OverlayQuad; use crate::set_highlight::SetHighlight; use crate::subdivide::{self, Vertex}; @@ -282,6 +283,8 @@ pub struct Frame { pub shade: Shade, /// Visibility per texture set. pub visible: Vec, + /// See-through quads in the 3D view, hidden behind the mesh + pub overlay: Vec, } struct Tex { @@ -492,6 +495,9 @@ struct ViewTargets { behind: Option, blit_buf: wgpu::Buffer, blit_bg: wgpu::BindGroup, + /// The frame's overlay triangles and how many vertices of the buffer they use + overlay: Option, + overlay_vertices: u32, /// Set by [`Renderer::prepare`]: the view has content to blit. ready: bool, } @@ -528,6 +534,7 @@ pub struct Renderer { uv_pipeline: wgpu::RenderPipeline, wire_pipeline: wgpu::RenderPipeline, wire3d_pipeline: wgpu::RenderPipeline, + overlay_pipeline: wgpu::RenderPipeline, /// The highlighted set's mesh edges, wider and in the highlight color highlight_pipeline: wgpu::RenderPipeline, bg_pipeline: wgpu::RenderPipeline, @@ -904,6 +911,7 @@ impl Renderer { let wire_pipeline = pipeline(device, "tc_wire", &layout, &module, "vs_uv", &vb, hdr("fs_wire", blend), MSAA, always()); let wire3d_depth = Some(depth_state(false, wgpu::CompareFunction::LessEqual)); let wire3d_pipeline = pipeline(device, "tc_wire3d", &layout, &module, "vs_wire3d", &vb, hdr("fs_wire3d", blend), MSAA, wire3d_depth.clone()); + let overlay_pipeline = pipeline(device, "tc_overlay", &bg_layout, &module, "vs_overlay", &vb, hdr("fs_overlay", blend), MSAA, wire3d_depth.clone()); let highlight_pipeline = pipeline(device, "tc_highlight", &layout, &module, "vs_wire_highlight", &vb, hdr("fs_wire_highlight", blend), MSAA, wire3d_depth); let bg_pipeline = pipeline(device, "tc_bg", &bg_layout, &module, "vs_bg", &[], hdr("fs_bg", None), MSAA, always()); @@ -1013,6 +1021,7 @@ impl Renderer { uv_pipeline, wire_pipeline, wire3d_pipeline, + overlay_pipeline, highlight_pipeline, bg_pipeline, blit_pipeline, @@ -1472,6 +1481,8 @@ impl Renderer { behind: None, blit_buf, blit_bg, + overlay: None, + overlay_vertices: 0, ready: false, } } @@ -1735,6 +1746,7 @@ impl Renderer { let Some(v) = self.targets(device, frame.view_id, frame.size, bloom, fx_on, refraction) else { return }; queue.write_buffer(&v.globals, 0, bytemuck::bytes_of(&raw)); queue.write_buffer(&v.post_buf, 0, bytemuck::bytes_of(&post)); + upload_overlay(device, queue, v, &frame.overlay, (!data).then_some(s.exposure_ev)); v.ready = true; v.history = Some((frame.clone(), rev)); v.samples = sample; @@ -1947,6 +1959,15 @@ impl Renderer { pass.draw_indexed(range, 0, 0..instances); } } + + // Overlay quads last, so the mesh's depth hides what is behind it + if uv_ts.is_none() + && let Some(overlay) = v.overlay.as_ref().filter(|_| v.overlay_vertices > 0) + { + pass.set_pipeline(&self.overlay_pipeline); + pass.set_vertex_buffer(0, overlay.slice(..)); + pass.draw(0..v.overlay_vertices, 0..1); + } } /// Draw view `id` into the current pass at `rect` (target pixels: x, y, w, h). @@ -2004,6 +2025,38 @@ fn drawable_ranges<'a>( }) } +/// A quad's two triangles, as corner indices +const QUAD_TRIANGLES: [usize; 6] = [0, 1, 2, 0, 2, 3]; + +/// Write `quads` into the view's overlay buffer, colors divided by the exposure only (undoing ACES makes saturated colors overshoot) +fn upload_overlay(device: &wgpu::Device, queue: &wgpu::Queue, view: &mut ViewTargets, quads: &[OverlayQuad], exposure_ev: Option) { + let vertices: Vec = quads + .iter() + .flat_map(|quad| { + let [r, g, b] = exposure_ev.map_or(quad.color, |exposure_ev| crate::set_highlight::scene_color_showing(quad.color, exposure_ev, false)); + let vertex = |corner: Vec3| Vertex { pos: corner.to_array(), nrm: [0.0; 3], tan: [r, g, b, quad.opacity], uv: [0.0; 2] }; + QUAD_TRIANGLES.map(|corner| vertex(quad.corners[corner])) + }) + .collect(); + view.overlay_vertices = u32::try_from(vertices.len()).unwrap_or(0); + if vertices.is_empty() { + return; + } + + let bytes: &[u8] = bytemuck::cast_slice(&vertices); + if view.overlay.as_ref().is_none_or(|buffer| buffer.size() < bytes.len() as u64) { + view.overlay = Some(device.create_buffer(&wgpu::BufferDescriptor { + label: Some("tc_overlay"), + size: bytes.len() as u64, + usage: wgpu::BufferUsages::VERTEX | wgpu::BufferUsages::COPY_DST, + mapped_at_creation: false, + })); + } + if let Some(buffer) = &view.overlay { + queue.write_buffer(buffer, 0, bytes); + } +} + /// Globals `highlight`: the highlight's color and opacity, all zero without one. Data views skip exposure and tone mapping, so they take the color as it is fn highlight_globals(shade: &Shade, data: bool) -> [f32; 4] { let Some(highlight) = shade.highlight else { return [0.0; 4] }; diff --git a/crates/render/src/set_highlight.rs b/crates/render/src/set_highlight.rs index 878968c1..cc29879e 100644 --- a/crates/render/src/set_highlight.rs +++ b/crates/render/src/set_highlight.rs @@ -17,17 +17,22 @@ pub struct SetHighlight { impl SetHighlight { /// The scene color the lines are drawn with so that exposure `exposure_ev` and the tone curve (ACES when `aces`) show them in [`Self::color`] pub fn scene_color(&self, exposure_ev: f32, aces: bool) -> [f32; 3] { - let exposure = 2f32.powf(exposure_ev).max(f32::MIN_POSITIVE); - - self.color.map(|screen| { - let screen = screen.max(0.0); - let exposed = if aces { inverse_aces(screen.min(MAX_ACES_SCREEN_VALUE)) } else { screen }; - - exposed / exposure - }) + scene_color_showing(self.color, exposure_ev, aces) } } +/// The scene color that exposure `exposure_ev` and the tone curve (ACES when `aces`) show as `screen` (linear RGB) +pub(crate) fn scene_color_showing(screen: [f32; 3], exposure_ev: f32, aces: bool) -> [f32; 3] { + let exposure = 2f32.powf(exposure_ev).max(f32::MIN_POSITIVE); + + screen.map(|screen| { + let screen = screen.max(0.0); + let exposed = if aces { inverse_aces(screen.min(MAX_ACES_SCREEN_VALUE)) } else { screen }; + + exposed / exposure + }) +} + /// The input of post.wgsl's `aces` that gives `screen`: the positive root of its rational curve solved for the input fn inverse_aces(screen: f32) -> f32 { let (a, b, c) = (2.43 * screen - 2.51, 0.59 * screen - 0.03, 0.14 * screen); diff --git a/crates/render/src/shaders/mesh.wgsl b/crates/render/src/shaders/mesh.wgsl index 863d6eae..23c4bd64 100644 --- a/crates/render/src/shaders/mesh.wgsl +++ b/crates/render/src/shaders/mesh.wgsl @@ -682,6 +682,26 @@ fn fs_wire3d(i: VOut) -> @location(0) vec4 { return vec4(0.35, 0.35, 0.35, 0.45); } +// How far overlay quads move toward the eye, as a fraction of their distance (as the wireframe does) +const OVERLAY_TOWARD_EYE: f32 = 0.002; + +// See-through overlay quads (the symmetry plane and the lines on the mesh): the color comes in the tangent slot, nudged toward the eye like the wireframe so lines on the surface win the depth test +@vertex +fn vs_overlay(v: VIn) -> VOut { + var o: VOut; + o.wpos = v.pos; + o.nrm = v.nrm; + o.tan = v.tan; + o.uv = v.uv; + o.clip = g.view_proj * vec4(v.pos + (g.eye.xyz - v.pos) * OVERLAY_TOWARD_EYE, 1.0); + return o; +} + +@fragment +fn fs_overlay(i: VOut) -> @location(0) vec4 { + return i.tan; +} + // The highlighted set's edges: four copies of each line, shifted to the corners of the extra width, make it wider than one pixel @vertex fn vs_wire_highlight(v: VIn, @builtin(instance_index) copy: u32) -> VOut { diff --git a/crates/render/tests/headless.rs b/crates/render/tests/headless.rs index 864c70c3..2fd17b52 100644 --- a/crates/render/tests/headless.rs +++ b/crates/render/tests/headless.rs @@ -54,7 +54,8 @@ fn setup() -> Option<(Headless, Frame)> { let mut cam = OrbitCamera { yaw: 0.6, pitch: 0.25, ..OrbitCamera::default() }; let (lo, hi) = mesh.bounds(); cam.frame(lo, hi); - let frame = Frame { view_id: 1, size: [480, 360], kind: ViewKind::Scene, camera: cam, shade: Shade::default(), visible: vec![true, true] }; + let frame = + Frame { view_id: 1, size: [480, 360], kind: ViewKind::Scene, camera: cam, shade: Shade::default(), visible: vec![true, true], overlay: Vec::new() }; Some((h, frame)) } From d60c954cdd2257b5cedfd3de93007943fb822f06 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sun, 8 Nov 2026 01:39:59 +0000 Subject: [PATCH 28/64] Symmetry: toolbar toggle and settings popup, plane, axis and manipulator in the 3D view - The toolbar's X/Y buttons become a Symmetry toggle and a settings button with a popup: type, axis, axis position, radial count and angle span with a preview, and display options; the symmetry rows leave brush Properties - The 3D view draws where the plane cuts the mesh, where the radial axis meets it, copies of the brush cursor where they land on the surface, and an axis position manipulator that moves the plane or axis - Translations for the new strings --- crates/ui-egui/src/dock.rs | 19 +- crates/ui-egui/src/i18n/ar.rs | 26 +- crates/ui-egui/src/i18n/de.rs | 26 +- crates/ui-egui/src/i18n/es.rs | 26 +- crates/ui-egui/src/i18n/fr.rs | 26 +- crates/ui-egui/src/i18n/it.rs | 26 +- crates/ui-egui/src/i18n/ja.rs | 26 +- crates/ui-egui/src/i18n/ko.rs | 26 +- crates/ui-egui/src/i18n/pt_br.rs | 26 +- crates/ui-egui/src/i18n/zh_hans.rs | 26 +- crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/state.rs | 4 + crates/ui-egui/src/symmetry/mod.rs | 114 +++++++ crates/ui-egui/src/symmetry/ribbons.rs | 35 ++ crates/ui-egui/src/symmetry/settings_popup.rs | 140 ++++++++ .../ui-egui/src/symmetry/symmetry_display.rs | 41 +++ crates/ui-egui/src/symmetry/symmetry_drag.rs | 12 + .../src/symmetry/symmetry_intersection.rs | 50 +++ .../src/symmetry/symmetry_manipulator.rs | 192 +++++++++++ .../symmetry/symmetry_manipulator_arrow.rs | 18 ++ crates/ui-egui/src/symmetry/view_overlay.rs | 305 ++++++++++++++++++ crates/ui-egui/src/toolbar.rs | 9 +- crates/ui-egui/src/viewport.rs | 28 +- crates/ui-egui/src/widgets.rs | 34 +- crates/ui-egui/tests/symmetry.rs | 140 ++++++++ 25 files changed, 1270 insertions(+), 106 deletions(-) create mode 100644 crates/ui-egui/src/symmetry/mod.rs create mode 100644 crates/ui-egui/src/symmetry/ribbons.rs create mode 100644 crates/ui-egui/src/symmetry/settings_popup.rs create mode 100644 crates/ui-egui/src/symmetry/symmetry_display.rs create mode 100644 crates/ui-egui/src/symmetry/symmetry_drag.rs create mode 100644 crates/ui-egui/src/symmetry/symmetry_intersection.rs create mode 100644 crates/ui-egui/src/symmetry/symmetry_manipulator.rs create mode 100644 crates/ui-egui/src/symmetry/symmetry_manipulator_arrow.rs create mode 100644 crates/ui-egui/src/symmetry/view_overlay.rs create mode 100644 crates/ui-egui/tests/symmetry.rs diff --git a/crates/ui-egui/src/dock.rs b/crates/ui-egui/src/dock.rs index 976a3035..abb0cf8d 100644 --- a/crates/ui-egui/src/dock.rs +++ b/crates/ui-egui/src/dock.rs @@ -1221,25 +1221,8 @@ fn brush_section(app: &mut TextureCraftApp, ui: &mut Ui) { } slider(ui, tr("Gravity"), &mut pt.gravity, 0.0..=2.0, 2); }); - section(ui, "sec_lazy", tr("Lazy mouse and symmetry"), false, |ui| { + section(ui, "sec_lazy", tr("Lazy mouse"), false, |ui| { slider(ui, tr("Lazy mouse distance"), &mut b.lazy, 0.0..=200.0, 0); - ui.horizontal(|ui| { - ui.checkbox(&mut b.symmetry.x, tr("Mirror X")); - ui.checkbox(&mut b.symmetry.y, tr("Mirror Y")); - ui.checkbox(&mut b.symmetry.z, tr("Mirror Z")); - }); - let mut copies = f32::from(b.symmetry.radial); - if slider(ui, tr("Radial copies"), &mut copies, 0.0..=32.0, 0).changed() { - b.symmetry.radial = copies as u8; - } - ui.add_enabled_ui(b.symmetry.radial > 1, |ui| { - ui.horizontal(|ui| { - ui.label(tr("Radial axis")); - for (k, name) in ["X", "Y", "Z"].into_iter().enumerate() { - ui.selectable_value(&mut b.symmetry.axis, k as u8, name); - } - }); - }); }); *b = b.sanitized(); } diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 21c87eb2..b4e2f7d6 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -432,7 +432,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Layer memory: {mb} MB", "ذاكرة الطبقات: {mb} ميغابايت"), ("Layers", "الطبقات"), ("Lazy mouse", "الفأرة الكسولة (Lazy mouse)"), - ("Lazy mouse and symmetry", "الفأرة الكسولة والتناظر"), ("Lazy mouse distance", "مسافة الفأرة الكسولة"), ("Leather grain", "حبيبات جلدية"), ("Lens size: how quickly things blur away from the focus distance", "حجم العدسة: سرعة تمويه العناصر البعيدة عن مسافة التركيز"), @@ -478,9 +477,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Midtones", "درجات الإضاءة المتوسطة"), ("Minimum", "الحد الأدنى"), ("Minimum size (%)", "الحد الأدنى للحجم (%)"), - ("Mirror X", "مرآة X"), - ("Mirror Y", "مرآة Y"), - ("Mirror Z", "مرآة Z"), ("Missing (bake to create)", "مفقود (اخبز للإنشاء)"), ("Mixed AO", "انسداد محيطي مختلط"), ("Mode", "النمط"), @@ -607,8 +603,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Quarter", "ربع"), ("Quick mask", "قناع سريع"), ("Quit", "إنهاء"), - ("Radial axis", "المحور الدائري"), - ("Radial copies", "نُسخ دائرية"), ("Radius (texels at 2K)", "نصف القطر (تكسل بدقة 2K)"), ("RENDERING", "التصيير"), ("Range", "النطاق"), @@ -743,8 +737,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Subsampling 8x8", "استعيان فرعي 8×8"), ("Subsurface scattering", "تشتت تحت السطح (SSS)"), ("Subtract", "طرح"), - ("Symmetry (X)", "تناظر (X)"), - ("Symmetry (Y)", "تناظر (Y)"), ("Tangent | Wrap", "مماس | التفاف"), ("Temporal anti-aliasing (refines the 3D view while it is still)", "تنعيم حواف زمني (يحسّن العرض ثلاثي الأبعاد أثناء ثباته)"), ("Texture Sets", "مجموعات الخامات"), @@ -1035,4 +1027,22 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "إزالة تجاوز الدقة"), ("Texture set resolution", "دقة مجموعة الخامات"), ("UV tile {tile} resolution", "دقة بلاطة UV {tile}"), + ("Angle span", "مدى الزاوية"), + ("Axis position", "موضع المحور"), + ("Count", "العدد"), + ("Display", "العرض"), + ("Hide while painting", "إخفاء أثناء الرسم"), + ("Manipulator size", "حجم أداة التحريك"), + ("Mirror symmetry", "تناظر مرآوي"), + ("Radial settings", "إعدادات التناظر الدائري"), + ("Radial symmetry", "تناظر دائري"), + ("Show axis", "إظهار المحور"), + ("Show axis position manipulator", "إظهار أداة تحريك موضع المحور"), + ("Show cursor", "إظهار المؤشر"), + ("Show intersection", "إظهار التقاطع"), + ("Show plane", "إظهار المستوى"), + ("Symmetry", "التناظر"), + ("Symmetry color display", "لون عرض التناظر"), + ("Symmetry settings", "إعدادات التناظر"), + ("Type", "النوع"), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index ea536d5e..d2c8b0cc 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -459,7 +459,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Layer memory: {mb} MB", "Ebenenspeicher: {mb} MB"), ("Layers", "Ebenen"), ("Lazy mouse", "Lazy Mouse"), - ("Lazy mouse and symmetry", "Lazy Mouse und Symmetrie"), ("Lazy mouse distance", "Lazy-Mouse-Distanz"), ("Leather grain", "Ledernarbung"), ("Lens size: how quickly things blur away from the focus distance", "Linsengröße: wie schnell Objekte außerhalb der Fokusdistanz unscharf werden"), @@ -505,9 +504,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Midtones", "Mitteltöne"), ("Minimum", "Minimum"), ("Minimum size (%)", "Mindestgröße (%)"), - ("Mirror X", "Spiegeln X"), - ("Mirror Y", "Spiegeln Y"), - ("Mirror Z", "Spiegeln Z"), ("Missing (bake to create)", "Fehlt (zum Erstellen backen)"), ("Mixed AO", "Gemischte AO"), ("Mode", "Modus"), @@ -646,8 +642,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Quarter", "Viertel"), ("Quick mask", "Schnellmaske"), ("Quit", "Beenden"), - ("Radial axis", "Radiale Achse"), - ("Radial copies", "Radiale Kopien"), ("Radius (texels at 2K)", "Radius (Texel bei 2K)"), ("RENDERING", "RENDERING"), ("Range", "Bereich"), @@ -782,8 +776,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Subsampling 8x8", "Subsampling 8x8"), ("Subsurface scattering", "Subsurface Scattering"), ("Subtract", "Subtrahieren"), - ("Symmetry (X)", "Symmetrie (X)"), - ("Symmetry (Y)", "Symmetrie (Y)"), ("Tangent | Wrap", "Tangente | Umhüllen"), ("Temporal anti-aliasing (refines the 3D view while it is still)", "Temporale Kantenglättung (verfeinert die 3D-Ansicht im Stillstand)"), ("Texture Sets", "Textursets"), @@ -1078,4 +1070,22 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Auflösungsüberschreibung entfernen"), ("Texture set resolution", "Auflösung des Textursets"), ("UV tile {tile} resolution", "Auflösung der UV-Kachel {tile}"), + ("Angle span", "Winkelbereich"), + ("Axis position", "Achsenposition"), + ("Count", "Anzahl"), + ("Display", "Anzeige"), + ("Hide while painting", "Beim Malen ausblenden"), + ("Manipulator size", "Manipulatorgröße"), + ("Mirror symmetry", "Spiegelsymmetrie"), + ("Radial settings", "Radial-Einstellungen"), + ("Radial symmetry", "Radialsymmetrie"), + ("Show axis", "Achse anzeigen"), + ("Show axis position manipulator", "Manipulator für die Achsenposition anzeigen"), + ("Show cursor", "Cursor anzeigen"), + ("Show intersection", "Schnittlinie anzeigen"), + ("Show plane", "Ebene anzeigen"), + ("Symmetry", "Symmetrie"), + ("Symmetry color display", "Anzeigefarbe der Symmetrie"), + ("Symmetry settings", "Symmetrie-Einstellungen"), + ("Type", "Typ"), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index de7c76e2..c14d21f0 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -450,7 +450,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Layer memory: {mb} MB", "Memoria de capas: {mb} MB"), ("Layers", "Capas"), ("Lazy mouse", "Ratón perezoso"), - ("Lazy mouse and symmetry", "Ratón perezoso y simetría"), ("Lazy mouse distance", "Distancia del ratón perezoso"), ("Leather grain", "Grano de cuero"), ("Lens size: how quickly things blur away from the focus distance", "Tamaño de la lente: lo rápido que se desenfoca todo fuera de la distancia de enfoque"), @@ -496,9 +495,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Midtones", "Medios tonos"), ("Minimum", "Mínimo"), ("Minimum size (%)", "Tamaño mínimo (%)"), - ("Mirror X", "Reflejar X"), - ("Mirror Y", "Reflejar Y"), - ("Mirror Z", "Reflejar Z"), ("Missing (bake to create)", "Falta (hornear para crear)"), ("Mixed AO", "AO mixta"), ("Mode", "Modo"), @@ -634,8 +630,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Quarter", "Cuarto"), ("Quick mask", "Máscara rápida"), ("Quit", "Salir"), - ("Radial axis", "Eje radial"), - ("Radial copies", "Copias radiales"), ("Radius (texels at 2K)", "Radio (téxeles a 2K)"), ("RENDERING", "RENDERIZADO"), ("Range", "Rango"), @@ -770,8 +764,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Subsampling 8x8", "Submuestreo 8x8"), ("Subsurface scattering", "Dispersión subsuperficial"), ("Subtract", "Restar"), - ("Symmetry (X)", "Simetría (X)"), - ("Symmetry (Y)", "Simetría (Y)"), ("Tangent | Wrap", "Tangente | Envolver"), ("Temporal anti-aliasing (refines the 3D view while it is still)", "Antialiasing temporal (refina la vista 3D mientras está quieta)"), ("Texture Sets", "Conjuntos de texturas"), @@ -1063,4 +1055,22 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Quitar resolución personalizada"), ("Texture set resolution", "Resolución del conjunto de texturas"), ("UV tile {tile} resolution", "Resolución del mosaico UV {tile}"), + ("Angle span", "Amplitud del ángulo"), + ("Axis position", "Posición del eje"), + ("Count", "Cantidad"), + ("Display", "Visualización"), + ("Hide while painting", "Ocultar al pintar"), + ("Manipulator size", "Tamaño del manipulador"), + ("Mirror symmetry", "Simetría de espejo"), + ("Radial settings", "Ajustes radiales"), + ("Radial symmetry", "Simetría radial"), + ("Show axis", "Mostrar eje"), + ("Show axis position manipulator", "Mostrar manipulador de posición del eje"), + ("Show cursor", "Mostrar cursor"), + ("Show intersection", "Mostrar intersección"), + ("Show plane", "Mostrar plano"), + ("Symmetry", "Simetría"), + ("Symmetry color display", "Color de visualización de simetría"), + ("Symmetry settings", "Ajustes de simetría"), + ("Type", "Tipo"), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index fc4b8b11..ca23f191 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -462,7 +462,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Layer memory: {mb} MB", "Mémoire des calques : {mb} Mo"), ("Layers", "Calques"), ("Lazy mouse", "Stabilisateur"), - ("Lazy mouse and symmetry", "Stabilisateur et symétrie"), ("Lazy mouse distance", "Distance du stabilisateur"), ("Leather grain", "Grain de cuir"), ( @@ -511,9 +510,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Midtones", "Tons moyens"), ("Minimum", "Minimum"), ("Minimum size (%)", "Taille minimale (%)"), - ("Mirror X", "Miroir X"), - ("Mirror Y", "Miroir Y"), - ("Mirror Z", "Miroir Z"), ("Missing (bake to create)", "Manquante (précalculer pour la créer)"), ("Mixed AO", "AO mixte"), ("Mode", "Mode"), @@ -649,8 +645,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Quarter", "Quart"), ("Quick mask", "Masque rapide"), ("Quit", "Quitter"), - ("Radial axis", "Axe radial"), - ("Radial copies", "Copies radiales"), ("Radius (texels at 2K)", "Rayon (texels en 2K)"), ("RENDERING", "RENDU"), ("Range", "Plage"), @@ -788,8 +782,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Subsampling 8x8", "Sous-échantillonnage 8x8"), ("Subsurface scattering", "Diffusion sous-surfacique"), ("Subtract", "Soustraction"), - ("Symmetry (X)", "Symétrie (X)"), - ("Symmetry (Y)", "Symétrie (Y)"), ("Tangent | Wrap", "Tangente | Enveloppe"), ("Temporal anti-aliasing (refines the 3D view while it is still)", "Anticrénelage temporel (affine la vue 3D tant qu'elle est immobile)"), ("Texture Sets", "Ensembles de textures"), @@ -1087,4 +1079,22 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Supprimer la résolution personnalisée"), ("Texture set resolution", "Résolution de l'ensemble de textures"), ("UV tile {tile} resolution", "Résolution de la tuile UV {tile}"), + ("Angle span", "Amplitude d'angle"), + ("Axis position", "Position de l'axe"), + ("Count", "Nombre"), + ("Display", "Affichage"), + ("Hide while painting", "Masquer pendant la peinture"), + ("Manipulator size", "Taille du manipulateur"), + ("Mirror symmetry", "Symétrie miroir"), + ("Radial settings", "Paramètres radiaux"), + ("Radial symmetry", "Symétrie radiale"), + ("Show axis", "Afficher l'axe"), + ("Show axis position manipulator", "Afficher le manipulateur de position de l'axe"), + ("Show cursor", "Afficher le curseur"), + ("Show intersection", "Afficher l'intersection"), + ("Show plane", "Afficher le plan"), + ("Symmetry", "Symétrie"), + ("Symmetry color display", "Couleur d'affichage de la symétrie"), + ("Symmetry settings", "Paramètres de symétrie"), + ("Type", "Type"), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 67648219..4bf2f0ec 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -453,7 +453,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Layer memory: {mb} MB", "Memoria livelli: {mb} MB"), ("Layers", "Livelli"), ("Lazy mouse", "Lazy mouse"), - ("Lazy mouse and symmetry", "Lazy mouse e simmetria"), ("Lazy mouse distance", "Distanza lazy mouse"), ("Leather grain", "Grana pelle"), ( @@ -502,9 +501,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Midtones", "Mezzitoni"), ("Minimum", "Minimo"), ("Minimum size (%)", "Dimensione minima (%)"), - ("Mirror X", "Specchia X"), - ("Mirror Y", "Specchia Y"), - ("Mirror Z", "Specchia Z"), ("Missing (bake to create)", "Mancante (esegui il bake per crearla)"), ("Mixed AO", "AO miscelata"), ("Mode", "Modalità"), @@ -643,8 +639,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Quarter", "Un quarto"), ("Quick mask", "Maschera rapida"), ("Quit", "Esci"), - ("Radial axis", "Asse radiale"), - ("Radial copies", "Copie radiali"), ("Radius (texels at 2K)", "Raggio (texel a 2K)"), ("RENDERING", "RENDERING"), ("Range", "Intervallo"), @@ -779,8 +773,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Subsampling 8x8", "Sottocampionamento 8x8"), ("Subsurface scattering", "Subsurface scattering"), ("Subtract", "Sottrai"), - ("Symmetry (X)", "Simmetria (X)"), - ("Symmetry (Y)", "Simmetria (Y)"), ("Tangent | Wrap", "Tangente | Avvolgi"), ("Temporal anti-aliasing (refines the 3D view while it is still)", "Anti-aliasing temporale (affina la vista 3D quando è ferma)"), ("Texture Sets", "Set di texture"), @@ -1072,4 +1064,22 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Rimuovi risoluzione personalizzata"), ("Texture set resolution", "Risoluzione del set di texture"), ("UV tile {tile} resolution", "Risoluzione del tile UV {tile}"), + ("Angle span", "Ampiezza angolo"), + ("Axis position", "Posizione asse"), + ("Count", "Numero"), + ("Display", "Visualizzazione"), + ("Hide while painting", "Nascondi durante la pittura"), + ("Manipulator size", "Dimensione manipolatore"), + ("Mirror symmetry", "Simmetria speculare"), + ("Radial settings", "Impostazioni radiali"), + ("Radial symmetry", "Simmetria radiale"), + ("Show axis", "Mostra asse"), + ("Show axis position manipulator", "Mostra manipolatore posizione asse"), + ("Show cursor", "Mostra cursore"), + ("Show intersection", "Mostra intersezione"), + ("Show plane", "Mostra piano"), + ("Symmetry", "Simmetria"), + ("Symmetry color display", "Colore di visualizzazione simmetria"), + ("Symmetry settings", "Impostazioni simmetria"), + ("Type", "Tipo"), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index dfbe8a65..bd11ccad 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -444,7 +444,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Layer memory: {mb} MB", "レイヤーメモリ: {mb} MB"), ("Layers", "レイヤー"), ("Lazy mouse", "レイジーマウス"), - ("Lazy mouse and symmetry", "レイジーマウスと対称"), ("Lazy mouse distance", "レイジーマウスの距離"), ("Leather grain", "革のシボ"), ("Lens size: how quickly things blur away from the focus distance", "レンズサイズ: フォーカス距離から離れるにつれてぼける速さ"), @@ -490,9 +489,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Midtones", "中間調"), ("Minimum", "最小"), ("Minimum size (%)", "最小サイズ (%)"), - ("Mirror X", "ミラー X"), - ("Mirror Y", "ミラー Y"), - ("Mirror Z", "ミラー Z"), ("Missing (bake to create)", "なし (ベイクで作成)"), ("Mixed AO", "ミックスAO"), ("Mode", "モード"), @@ -625,8 +621,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Quarter", "1/4"), ("Quick mask", "クイックマスク"), ("Quit", "終了"), - ("Radial axis", "放射軸"), - ("Radial copies", "放射状コピー"), ("Radius (texels at 2K)", "半径 (2K時のテクセル)"), ("RENDERING", "レンダリング"), ("Range", "範囲"), @@ -761,8 +755,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Subsampling 8x8", "サブサンプリング 8x8"), ("Subsurface scattering", "サブサーフェススキャタリング"), ("Subtract", "減算"), - ("Symmetry (X)", "対称 (X)"), - ("Symmetry (Y)", "対称 (Y)"), ("Tangent | Wrap", "タンジェント | ラップ"), ("Temporal anti-aliasing (refines the 3D view while it is still)", "テンポラルアンチエイリアス (静止中に3Dビューを精細化)"), ("Texture Sets", "テクスチャセット"), @@ -1057,4 +1049,22 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "解像度の上書きを解除"), ("Texture set resolution", "テクスチャセットの解像度"), ("UV tile {tile} resolution", "UVタイル {tile} の解像度"), + ("Angle span", "角度範囲"), + ("Axis position", "軸の位置"), + ("Count", "数"), + ("Display", "表示"), + ("Hide while painting", "ペイント中は隠す"), + ("Manipulator size", "マニピュレーターのサイズ"), + ("Mirror symmetry", "ミラー対称"), + ("Radial settings", "放射の設定"), + ("Radial symmetry", "放射対称"), + ("Show axis", "軸を表示"), + ("Show axis position manipulator", "軸位置マニピュレーターを表示"), + ("Show cursor", "カーソルを表示"), + ("Show intersection", "交差部を表示"), + ("Show plane", "平面を表示"), + ("Symmetry", "対称"), + ("Symmetry color display", "対称の表示色"), + ("Symmetry settings", "対称の設定"), + ("Type", "種類"), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index f81cfe6d..3e2dfab6 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -438,7 +438,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Layer memory: {mb} MB", "레이어 메모리: {mb} MB"), ("Layers", "레이어"), ("Lazy mouse", "레이지 마우스"), - ("Lazy mouse and symmetry", "레이지 마우스 및 대칭"), ("Lazy mouse distance", "레이지 마우스 거리"), ("Leather grain", "가죽 결"), ("Lens size: how quickly things blur away from the focus distance", "렌즈 크기: 초점 거리에서 멀어질수록 얼마나 빠르게 흐려지는지 결정합니다"), @@ -484,9 +483,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Midtones", "중간 영역"), ("Minimum", "최소"), ("Minimum size (%)", "최소 크기 (%)"), - ("Mirror X", "미러 X"), - ("Mirror Y", "미러 Y"), - ("Mirror Z", "미러 Z"), ("Missing (bake to create)", "없음 (베이크하여 생성)"), ("Mixed AO", "혼합 AO"), ("Mode", "모드"), @@ -616,8 +612,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Quarter", "1/4"), ("Quick mask", "퀵 마스크"), ("Quit", "종료"), - ("Radial axis", "방사형 축"), - ("Radial copies", "방사형 복사본"), ("Radius (texels at 2K)", "반경 (2K 기준 텍셀)"), ("RENDERING", "렌더링"), ("Range", "범위"), @@ -752,8 +746,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Subsampling 8x8", "서브샘플링 8x8"), ("Subsurface scattering", "서브서피스 스캐터링"), ("Subtract", "빼기"), - ("Symmetry (X)", "대칭 (X)"), - ("Symmetry (Y)", "대칭 (Y)"), ("Tangent | Wrap", "탄젠트 | 랩"), ("Temporal anti-aliasing (refines the 3D view while it is still)", "시간적 안티앨리어싱 (3D 뷰가 정지해 있을 때 품질을 높임)"), ("Texture Sets", "텍스처 세트"), @@ -1045,4 +1037,22 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "해상도 재정의 제거"), ("Texture set resolution", "텍스처 세트 해상도"), ("UV tile {tile} resolution", "UV 타일 {tile} 해상도"), + ("Angle span", "각도 범위"), + ("Axis position", "축 위치"), + ("Count", "개수"), + ("Display", "표시"), + ("Hide while painting", "페인팅 중 숨기기"), + ("Manipulator size", "조작기 크기"), + ("Mirror symmetry", "미러 대칭"), + ("Radial settings", "방사형 설정"), + ("Radial symmetry", "방사형 대칭"), + ("Show axis", "축 표시"), + ("Show axis position manipulator", "축 위치 조작기 표시"), + ("Show cursor", "커서 표시"), + ("Show intersection", "교차선 표시"), + ("Show plane", "평면 표시"), + ("Symmetry", "대칭"), + ("Symmetry color display", "대칭 표시 색상"), + ("Symmetry settings", "대칭 설정"), + ("Type", "유형"), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 7bd3d231..a3b3781b 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -447,7 +447,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Layer memory: {mb} MB", "Memória das camadas: {mb} MB"), ("Layers", "Camadas"), ("Lazy mouse", "Lazy mouse"), - ("Lazy mouse and symmetry", "Lazy mouse e simetria"), ("Lazy mouse distance", "Distância do lazy mouse"), ("Leather grain", "Grão de couro"), ("Lens size: how quickly things blur away from the focus distance", "Tamanho da lente: quão rápido os objetos desfocam fora da distância de foco"), @@ -493,9 +492,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Midtones", "Tons médios"), ("Minimum", "Mínimo"), ("Minimum size (%)", "Tamanho mínimo (%)"), - ("Mirror X", "Espelhar X"), - ("Mirror Y", "Espelhar Y"), - ("Mirror Z", "Espelhar Z"), ("Missing (bake to create)", "Ausente (faça o bake para criar)"), ("Mixed AO", "AO combinada"), ("Mode", "Modo"), @@ -631,8 +627,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Quarter", "Um quarto"), ("Quick mask", "Máscara rápida"), ("Quit", "Sair"), - ("Radial axis", "Eixo radial"), - ("Radial copies", "Cópias radiais"), ("Radius (texels at 2K)", "Raio (texels em 2K)"), ("RENDERING", "RENDERIZAÇÃO"), ("Range", "Intervalo"), @@ -767,8 +761,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Subsampling 8x8", "Subamostragem 8x8"), ("Subsurface scattering", "Dispersão subsuperficial"), ("Subtract", "Subtração"), - ("Symmetry (X)", "Simetria (X)"), - ("Symmetry (Y)", "Simetria (Y)"), ("Tangent | Wrap", "Tangente | Envolver"), ("Temporal anti-aliasing (refines the 3D view while it is still)", "Antisserrilhamento temporal (refina a vista 3D enquanto está parada)"), ("Texture Sets", "Conjuntos de texturas"), @@ -1060,4 +1052,22 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "Remover resolução personalizada"), ("Texture set resolution", "Resolução do conjunto de texturas"), ("UV tile {tile} resolution", "Resolução do tile UV {tile}"), + ("Angle span", "Amplitude do ângulo"), + ("Axis position", "Posição do eixo"), + ("Count", "Quantidade"), + ("Display", "Exibição"), + ("Hide while painting", "Ocultar ao pintar"), + ("Manipulator size", "Tamanho do manipulador"), + ("Mirror symmetry", "Simetria espelhada"), + ("Radial settings", "Configurações radiais"), + ("Radial symmetry", "Simetria radial"), + ("Show axis", "Mostrar eixo"), + ("Show axis position manipulator", "Mostrar manipulador da posição do eixo"), + ("Show cursor", "Mostrar cursor"), + ("Show intersection", "Mostrar interseção"), + ("Show plane", "Mostrar plano"), + ("Symmetry", "Simetria"), + ("Symmetry color display", "Cor de exibição da simetria"), + ("Symmetry settings", "Configurações de simetria"), + ("Type", "Tipo"), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 7d393f75..49b989c4 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -405,7 +405,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Layer memory: {mb} MB", "图层内存:{mb} MB"), ("Layers", "图层"), ("Lazy mouse", "平滑跟随"), - ("Lazy mouse and symmetry", "平滑跟随与对称"), ("Lazy mouse distance", "平滑跟随距离"), ("Leather grain", "皮革纹理"), ("Lens size: how quickly things blur away from the focus distance", "镜头大小:远离对焦距离时物体变模糊的速度"), @@ -451,9 +450,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Midtones", "中间调"), ("Minimum", "最小值"), ("Minimum size (%)", "最小尺寸(%)"), - ("Mirror X", "镜像 X"), - ("Mirror Y", "镜像 Y"), - ("Mirror Z", "镜像 Z"), ("Missing (bake to create)", "缺失(烘焙以创建)"), ("Mixed AO", "混合 AO"), ("Mode", "模式"), @@ -577,8 +573,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Quarter", "1/4"), ("Quick mask", "快速遮罩"), ("Quit", "退出"), - ("Radial axis", "径向轴"), - ("Radial copies", "径向副本"), ("Radius (texels at 2K)", "半径(2K 下的纹素数)"), ("RENDERING", "渲染"), ("Range", "范围"), @@ -713,8 +707,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Subsampling 8x8", "8x8 子采样"), ("Subsurface scattering", "次表面散射"), ("Subtract", "减去"), - ("Symmetry (X)", "对称(X)"), - ("Symmetry (Y)", "对称(Y)"), ("Tangent | Wrap", "切线 | 包裹"), ("Temporal anti-aliasing (refines the 3D view while it is still)", "时间抗锯齿(在 3D 视图静止时逐步细化)"), ("Texture Sets", "纹理集"), @@ -1003,4 +995,22 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove resolution override", "移除分辨率覆盖"), ("Texture set resolution", "纹理集分辨率"), ("UV tile {tile} resolution", "UV 图块 {tile} 的分辨率"), + ("Angle span", "角度范围"), + ("Axis position", "轴位置"), + ("Count", "数量"), + ("Display", "显示"), + ("Hide while painting", "绘制时隐藏"), + ("Manipulator size", "操纵器大小"), + ("Mirror symmetry", "镜像对称"), + ("Radial settings", "径向设置"), + ("Radial symmetry", "径向对称"), + ("Show axis", "显示轴"), + ("Show axis position manipulator", "显示轴位置操纵器"), + ("Show cursor", "显示光标"), + ("Show intersection", "显示交线"), + ("Show plane", "显示平面"), + ("Symmetry", "对称"), + ("Symmetry color display", "对称显示颜色"), + ("Symmetry settings", "对称设置"), + ("Type", "类型"), ]; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5b5045e6..4e649b1e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -29,6 +29,7 @@ pub mod render_mode; pub mod shelf; pub mod shelf_preview; pub mod state; +pub mod symmetry; pub mod theme; pub mod thumbs; pub mod titlebar; diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 0a9f6033..adf5637a 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -296,6 +296,9 @@ pub struct UiState { /// The brush that paints the skew correction map in the 2D view of bake mode. #[serde(default)] pub bake_paint_brush: crate::bake_mode::BakePaintBrush, + /// How the 3D view shows symmetry + #[serde(default)] + pub symmetry: crate::symmetry::SymmetryDisplay, } impl UiState { @@ -365,6 +368,7 @@ impl Default for UiState { recent: Vec::new(), keymap: Keymap::new(), bake_paint_brush: crate::bake_mode::BakePaintBrush::default(), + symmetry: crate::symmetry::SymmetryDisplay::default(), } } } diff --git a/crates/ui-egui/src/symmetry/mod.rs b/crates/ui-egui/src/symmetry/mod.rs new file mode 100644 index 00000000..e9f95716 --- /dev/null +++ b/crates/ui-egui/src/symmetry/mod.rs @@ -0,0 +1,114 @@ +//! Symmetry: the toolbar toggle and settings popup, and what the 3D view draws for it + +mod ribbons; +mod settings_popup; +mod symmetry_display; +mod symmetry_drag; +mod symmetry_intersection; +mod symmetry_manipulator; +mod symmetry_manipulator_arrow; +mod view_overlay; + +use egui::Ui; +use egui_phosphor::regular as ic; +use texturecraft_engine::Tool; +use texturecraft_engine::paint::Symmetry; + +pub use symmetry_display::SymmetryDisplay; +pub(crate) use view_overlay::{manipulator_hovered, manipulator_input, overlay, scene_overlay}; + +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::widgets::{icon_badge_dropdown_button, icon_button}; + +/// Radial copies a brush gets when it switches to radial symmetry +const DEFAULT_RADIAL_COUNT: u8 = 6; + +/// Whether `tool` paints symmetry copies +pub(crate) fn applies_to(tool: Tool) -> bool { + matches!(tool, Tool::Paint | Tool::Eraser | Tool::Projection | Tool::Clone | Tool::Path) +} + +/// Whether the 3D view shows symmetry now +pub(crate) fn shown(app: &TextureCraftApp) -> bool { + app.ui.mode == crate::state::Mode::Painting && applies_to(app.session.tool.tool) && app.session.tool.brush.symmetry.any() +} + +/// The axis the popup shows: the radial axis, or the first mirror axis +fn current_axis(symmetry: &Symmetry) -> usize { + if symmetry.radial > 1 { + return symmetry.axis_index(); + } + [symmetry.x, symmetry.y, symmetry.z].iter().position(|on| *on).unwrap_or(symmetry.axis_index()) +} + +/// The world axes the plane (mirror) or the axis (radial) can move along +pub(crate) fn movable_axes(symmetry: &Symmetry) -> [bool; 3] { + // The popup's type, also while the toggle is off + if symmetry.radial > 1 { + let axis = symmetry.axis_index(); + return [0, 1, 2].map(|other| other != axis); + } + [symmetry.x, symmetry.y, symmetry.z] +} + +/// Mirror on one axis, or radial copies around it +fn set_mode(symmetry: &mut Symmetry, radial: bool, axis: usize) { + symmetry.axis = axis as u8; + if radial { + (symmetry.x, symmetry.y, symmetry.z) = (false, false, false); + if symmetry.radial <= 1 { + symmetry.radial = DEFAULT_RADIAL_COUNT; + } + } else { + (symmetry.x, symmetry.y, symmetry.z) = (axis == 0, axis == 1, axis == 2); + symmetry.radial = 0; + } +} + +/// The toolbar's Symmetry toggle: turning it on with nothing set mirrors on X +fn toggle(symmetry: &mut Symmetry) { + if symmetry.any() { + symmetry.enabled = false; + return; + } + + symmetry.enabled = true; + if !symmetry.x && !symmetry.y && !symmetry.z && symmetry.radial <= 1 { + set_mode(symmetry, false, 0); + } +} + +/// The Symmetry toggle and the settings button with its popup +pub(crate) fn toolbar_controls(app: &mut TextureCraftApp, ui: &mut Ui) { + let button_size = ui.spacing().interact_size.y; + if icon_button(ui, ic::FLIP_HORIZONTAL, tr("Symmetry"), app.session.tool.brush.symmetry.any(), button_size).clicked() { + toggle(&mut app.session.tool.brush.symmetry); + } + + // No tooltip on the settings button; the label still names it for screen readers + let popup_id = ui.make_persistent_id("symmetry_settings"); + let mut open = ui.data(|data| data.get_temp::(popup_id)).unwrap_or(false); + let response = icon_badge_dropdown_button(ui, ic::FLIP_HORIZONTAL, ic::GEAR, tr("Symmetry settings"), open, button_size); + if response.clicked() { + open = !open; + } + + // Open state kept here, not in egui's popup memory: that holds one popup, so the Type dropdown or the color picker inside would close this one + let shown = egui::Popup::from_response(&response) + .id(popup_id) + .open_bool(&mut open) + .close_behavior(egui::PopupCloseBehavior::IgnoreClicks) + .show(|ui| settings_popup::show(app, ui)); + + // A click outside the popup and the dropdowns it opens (foreground layers too) closes it + if let Some(shown) = shown + && !response.clicked() + && ui.input(|input| input.pointer.any_click()) + && let Some(at) = ui.input(|input| input.pointer.interact_pos()) + && ui.ctx().layer_id_at(at).is_none_or(|layer| layer != shown.response.layer_id && layer.order != egui::Order::Foreground) + { + open = false; + } + ui.data_mut(|data| data.insert_temp(popup_id, open)); +} diff --git a/crates/ui-egui/src/symmetry/ribbons.rs b/crates/ui-egui/src/symmetry/ribbons.rs new file mode 100644 index 00000000..24b49c51 --- /dev/null +++ b/crates/ui-egui/src/symmetry/ribbons.rs @@ -0,0 +1,35 @@ +//! Lines drawn into the 3D view as thin quads + +use egui::Rect; +use texturecraft_engine::geom::glam::{Mat4, Vec3}; +use texturecraft_render::OverlayQuad; + +use crate::TextureCraftApp; + +/// Height of the view in normalized device coordinates (−1 to 1) +const NDC_HEIGHT: f32 = 2.0; + +/// Lines drawn as thin quads turned to face the camera, a steady width on screen +pub(crate) struct Ribbons { + eye: Vec3, + view_proj: Mat4, + /// World units per screen point at clip-space w = 1 + world_per_point: f32, +} + +impl Ribbons { + pub(crate) fn new(app: &TextureCraftApp, rect: Rect) -> Self { + let camera = &app.session.camera; + let view_proj = camera.view_proj(rect.width() / rect.height().max(1.0)); + let ndc_per_unit = view_proj.row(1).truncate().length(); + Ribbons { eye: camera.eye(), view_proj, world_per_point: NDC_HEIGHT / (rect.height() * ndc_per_unit).max(f32::EPSILON) } + } + + /// The line from `from` to `to`, `width` points wide + pub(crate) fn quad(&self, from: Vec3, to: Vec3, width: f32, color: [f32; 3], opacity: f32) -> OverlayQuad { + let middle = (from + to) * 0.5; + let clip_w = (self.view_proj * middle.extend(1.0)).w.max(0.0); + let side = (to - from).cross(self.eye - middle).normalize_or_zero() * (clip_w * self.world_per_point * width * 0.5); + OverlayQuad { corners: [from - side, to - side, to + side, from + side], color, opacity } + } +} diff --git a/crates/ui-egui/src/symmetry/settings_popup.rs b/crates/ui-egui/src/symmetry/settings_popup.rs new file mode 100644 index 00000000..a30ec120 --- /dev/null +++ b/crates/ui-egui/src/symmetry/settings_popup.rs @@ -0,0 +1,140 @@ +//! The symmetry settings popup: type, axis, axis position, radial settings and display + +use egui::{Align, Color32, Layout, Stroke, Ui, vec2}; +use texturecraft_engine::paint::{FULL_TURN_DEGREES, MAX_RADIAL_COPIES, Symmetry}; + +use super::{current_axis, movable_axes, set_mode}; +use crate::TextureCraftApp; +use crate::i18n::tr; +use crate::widgets::{color_swatch, section, slider}; + +/// The popup's width (points) +const POPUP_WIDTH: f32 = 340.0; + +/// Width of the label column of the Type and Axis rows +const LABEL_WIDTH: f32 = 64.0; + +const AXIS_NAMES: [&str; 3] = ["X", "Y", "Z"]; + +/// Space between the Type and Axis rows and the first section +const SECTIONS_GAP: f32 = 4.0; + +/// The color square's width (points) and the Manipulator size slider's range +const COLOR_SWATCH_WIDTH: f32 = 48.0; +const MANIPULATOR_SIZES: std::ops::RangeInclusive = 0.1..=1.0; + +/// Side of the radial copies preview beside the Count and Angle span sliders +const PREVIEW_SIZE: f32 = 96.0; + +/// The popup's content, editing the brush's symmetry and the display settings in place +pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui) { + ui.set_width(POPUP_WIDTH); + let (lo, hi) = app.session.mesh.bounds(); + let half_extent = (hi - lo) * 0.5; + let display = &mut app.ui.symmetry; + let symmetry = &mut app.session.tool.brush.symmetry; + let radial = symmetry.radial > 1; + let axis = current_axis(symmetry); + + labelled_row(ui, tr("Type"), |ui| { + let type_name = if radial { tr("Radial symmetry") } else { tr("Mirror symmetry") }; + egui::ComboBox::from_id_salt("symmetry_type").width(ui.available_width()).selected_text(type_name).show_ui(ui, |ui| { + if ui.selectable_label(!radial, tr("Mirror symmetry")).clicked() { + set_mode(symmetry, false, axis); + } + if ui.selectable_label(radial, tr("Radial symmetry")).clicked() { + set_mode(symmetry, true, axis); + } + }); + }); + labelled_row(ui, tr("Axis"), |ui| { + let cell = vec2(ui.available_width() / AXIS_NAMES.len() as f32, ui.spacing().interact_size.y); + for (choice, name) in AXIS_NAMES.into_iter().enumerate() { + ui.allocate_ui_with_layout(cell, Layout::left_to_right(Align::Center), |ui| { + if ui.radio(axis == choice, name).clicked() { + set_mode(symmetry, radial, choice); + } + }); + } + }); + ui.add_space(SECTIONS_GAP); + + let movable = movable_axes(symmetry); + section(ui, "symmetry_axis_position", tr("Axis position"), true, |ui| { + for (along, name) in AXIS_NAMES.into_iter().enumerate() { + ui.add_enabled_ui(movable[along], |ui| slider(ui, name, &mut symmetry.offset[along], -half_extent[along]..=half_extent[along], 2)); + } + }); + + if radial { + section(ui, "symmetry_radial", tr("Radial settings"), true, |ui| { + ui.horizontal_top(|ui| { + let sliders_width = ui.available_width() - PREVIEW_SIZE - ui.spacing().item_spacing.x; + ui.allocate_ui_with_layout(vec2(sliders_width, PREVIEW_SIZE), Layout::top_down(Align::Min), |ui| { + let mut count = f32::from(symmetry.radial); + if slider(ui, tr("Count"), &mut count, 2.0..=f32::from(MAX_RADIAL_COPIES), 0).changed() { + symmetry.radial = count.round() as u8; + } + slider(ui, tr("Angle span"), &mut symmetry.angle_span, 0.0..=FULL_TURN_DEGREES, 0); + }); + copies_preview(ui, symmetry, super::view_overlay::color(display.color, u8::MAX)); + }); + }); + } + + section(ui, "symmetry_display", tr("Display"), true, |ui| { + ui.horizontal(|ui| { + ui.label(tr("Symmetry color display")); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| color_swatch(ui, "symmetry_color", &mut display.color, COLOR_SWATCH_WIDTH)); + }); + if radial { + ui.checkbox(&mut display.show_axis, tr("Show axis")); + } else { + ui.checkbox(&mut display.show_plane, tr("Show plane")); + } + ui.checkbox(&mut display.show_intersection, tr("Show intersection")); + ui.checkbox(&mut display.show_cursor, tr("Show cursor")); + ui.indent("symmetry_hide_while_painting", |ui| { + ui.add_enabled(display.show_cursor, egui::Checkbox::new(&mut display.hide_while_painting, tr("Hide while painting"))); + }); + ui.checkbox(&mut display.show_manipulator, tr("Show axis position manipulator")); + ui.add_enabled_ui(display.show_manipulator, |ui| slider(ui, tr("Manipulator size"), &mut display.manipulator_size, MANIPULATOR_SIZES, 1)); + }); +} + +/// A row with `label` in a fixed-width column and the control filling the rest +fn labelled_row(ui: &mut Ui, label: &str, control: impl FnOnce(&mut Ui)) { + ui.horizontal(|ui| { + let height = ui.spacing().interact_size.y; + ui.allocate_ui_with_layout(vec2(LABEL_WIDTH, height), Layout::left_to_right(Align::Center), |ui| { + ui.set_min_width(LABEL_WIDTH); + ui.label(label); + }); + control(ui); + }); +} + +/// Where the radial copies go, on the view's backdrop: the stroke in white on the right, its copies in `copy_color` +fn copies_preview(ui: &mut Ui, symmetry: &Symmetry, copy_color: Color32) { + const RING_FRACTION: f32 = 0.32; + const DOT_RADIUS: f32 = 3.0; + const CROSS_HALF: f32 = 4.0; + const CORNER_RADIUS: f32 = 2.0; + + let tokens = crate::theme::Tokens::get(ui.ctx()); + let (rect, _) = ui.allocate_exact_size(vec2(PREVIEW_SIZE, PREVIEW_SIZE), egui::Sense::hover()); + let painter = ui.painter_at(rect); + painter.rect_filled(rect, CORNER_RADIUS, tokens.viewport); + + let center = rect.center(); + let ring = PREVIEW_SIZE * RING_FRACTION; + let cross = Stroke::new(1.0, tokens.viewport_text); + painter.line_segment([center - vec2(CROSS_HALF, 0.0), center + vec2(CROSS_HALF, 0.0)], cross); + painter.line_segment([center - vec2(0.0, CROSS_HALF), center + vec2(0.0, CROSS_HALF)], cross); + for copy in 0..symmetry.radial { + // Screen y points down: positive angles turn counter-clockwise + let angle = symmetry.radial_angle(copy); + let at = center + vec2(angle.cos(), -angle.sin()) * ring; + painter.circle_filled(at, DOT_RADIUS, if copy == 0 { Color32::WHITE } else { copy_color }); + } +} diff --git a/crates/ui-egui/src/symmetry/symmetry_display.rs b/crates/ui-egui/src/symmetry/symmetry_display.rs new file mode 100644 index 00000000..5ef64405 --- /dev/null +++ b/crates/ui-egui/src/symmetry/symmetry_display.rs @@ -0,0 +1,41 @@ +//! How the 3D view shows symmetry: the settings popup's Display section + +use serde::{Deserialize, Serialize}; + +/// The manipulator size the popup starts at; the manipulator's measurements are given at this size +pub(crate) const DEFAULT_MANIPULATOR_SIZE: f32 = 0.4; + +/// Display settings for the symmetry plane, axis, intersection, cursors and manipulator +#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)] +#[serde(default)] +pub struct SymmetryDisplay { + /// Linear RGB of everything drawn for symmetry + pub color: [f32; 3], + /// Mirror: a see-through plane between the two sides + pub show_plane: bool, + /// Radial: a see-through line along the axis + pub show_axis: bool, + /// Where the plane cuts the mesh (a line) or the axis meets it (a point) + pub show_intersection: bool, + /// A brush cursor at every copy of the cursor + pub show_cursor: bool, + pub hide_while_painting: bool, + pub show_manipulator: bool, + /// Manipulator scale; [`DEFAULT_MANIPULATOR_SIZE`] draws it at its base size + pub manipulator_size: f32, +} + +impl Default for SymmetryDisplay { + fn default() -> Self { + SymmetryDisplay { + color: [1.0, 0.0, 0.0], + show_plane: false, + show_axis: false, + show_intersection: true, + show_cursor: true, + hide_while_painting: true, + show_manipulator: false, + manipulator_size: DEFAULT_MANIPULATOR_SIZE, + } + } +} diff --git a/crates/ui-egui/src/symmetry/symmetry_drag.rs b/crates/ui-egui/src/symmetry/symmetry_drag.rs new file mode 100644 index 00000000..5c5b39f5 --- /dev/null +++ b/crates/ui-egui/src/symmetry/symmetry_drag.rs @@ -0,0 +1,12 @@ +//! A symmetry manipulator drag in progress + +use egui::Pos2; + +/// Kept in egui's memory between the frames of one drag +#[derive(Clone, Copy, Debug)] +pub(crate) struct SymmetryDrag { + /// The world axes the grabbed handle moves along + pub(crate) axes: [bool; 3], + pub(crate) from: Pos2, + pub(crate) start_offset: [f32; 3], +} diff --git a/crates/ui-egui/src/symmetry/symmetry_intersection.rs b/crates/ui-egui/src/symmetry/symmetry_intersection.rs new file mode 100644 index 00000000..2099d304 --- /dev/null +++ b/crates/ui-egui/src/symmetry/symmetry_intersection.rs @@ -0,0 +1,50 @@ +//! Where a mirror plane cuts the mesh, kept between frames + +use std::sync::Arc; + +use texturecraft_engine::geom::Mesh; +use texturecraft_engine::geom::glam::Vec3; + +/// The segments where the plane `p[axis] = position` crosses the mesh's triangles +#[derive(Clone, Debug)] +pub(crate) struct SymmetryIntersection { + mesh_id: u64, + axis: usize, + position: f32, + pub(crate) segments: Arc>, +} + +impl SymmetryIntersection { + /// Every triangle's crossing with the plane (mesh `mesh_id`, the plane `p[axis] = position`) + pub(crate) fn compute(mesh: &Mesh, mesh_id: u64, axis: usize, position: f32) -> Self { + let mut segments = Vec::new(); + for triangle in 0..mesh.triangle_count() { + let Some([first, second, third]) = mesh.tri(triangle) else { continue }; + let (Some(&first), Some(&second), Some(&third)) = (mesh.positions.get(first), mesh.positions.get(second), mesh.positions.get(third)) else { + continue; + }; + + let corners = [first, second, third]; + + // Each edge whose ends lie on opposite sides crosses the plane once + let side = |corner: usize| corners[corner][axis] - position; + let mut crossings = [Vec3::ZERO; 2]; + let mut count = 0; + for (start, end) in [(0, 1), (1, 2), (2, 0)] { + if (side(start) < 0.0) != (side(end) < 0.0) && count < crossings.len() { + crossings[count] = corners[start].lerp(corners[end], side(start) / (side(start) - side(end))); + count += 1; + } + } + if count == crossings.len() { + segments.push(crossings); + } + } + SymmetryIntersection { mesh_id, axis, position, segments: Arc::new(segments) } + } + + /// Whether this is the cut of mesh `mesh_id` by the plane `p[axis] = position` + pub(crate) fn is_for(&self, mesh_id: u64, axis: usize, position: f32) -> bool { + self.mesh_id == mesh_id && self.axis == axis && self.position == position + } +} diff --git a/crates/ui-egui/src/symmetry/symmetry_manipulator.rs b/crates/ui-egui/src/symmetry/symmetry_manipulator.rs new file mode 100644 index 00000000..9fa14e02 --- /dev/null +++ b/crates/ui-egui/src/symmetry/symmetry_manipulator.rs @@ -0,0 +1,192 @@ +//! The axis position manipulator: arrows at the symmetry origin that move it + +use egui::{Pos2, Rect, Vec2}; +use texturecraft_engine::geom::glam::Vec3; + +use super::symmetry_display::DEFAULT_MANIPULATOR_SIZE; +use super::symmetry_manipulator_arrow::SymmetryManipulatorArrow; +use crate::TextureCraftApp; + +/// Arrow length at the default manipulator size, as a fraction of the view height +const ARROW_LENGTH: f32 = 0.1; + +/// Gap between the center and where the shafts start (points at the default size) +const SHAFT_GAP: f32 = 5.0; + +/// Cone length and base radius (points at the default size, at the origin's depth) +pub(crate) const CONE_LENGTH: f32 = 15.0; +pub(crate) const CONE_RADIUS: f32 = 5.0; + +/// Radial: the square handle spans this part of the arrows, clear of the shafts +const SQUARE_FROM: f32 = 0.16; +const SQUARE_TO: f32 = 0.46; + +/// How far (fraction of the mesh diagonal, at least a minimum) the screen scale is measured along each axis +const PROBE_FRACTION: f32 = 0.01; +const MIN_PROBE: f32 = 1e-4; + +/// Shortest on-screen axis (points per world unit) the manipulator offers a handle for +const MIN_SCREEN_SCALE: f32 = 1e-3; + +/// Grab radius around an arrow and around the center (points, at least this at any size) +const GRAB_RADIUS: f32 = 7.0; + +/// The manipulator as the 3D view shows it this frame +#[derive(Clone, Debug)] +pub(crate) struct SymmetryManipulator { + pub(crate) center: Pos2, + pub(crate) arrows: Vec, + /// Radial: a square between the two arrows that moves the axis along both + pub(crate) square: Option<[Pos2; 4]>, + /// World units per screen point at the origin + pub(crate) world_per_point: f32, + /// The manipulator size relative to the default: every measurement scales with it + pub(crate) scale: f32, + /// Screen points per world unit along X, Y and Z at the origin + screen_per_unit: [Vec2; 3], +} + +impl SymmetryManipulator { + /// Handles along the axes the plane or axis can move on, or None when the manipulator is hidden + pub(crate) fn of(app: &TextureCraftApp, rect: Rect) -> Option { + let symmetry = app.session.tool.brush.symmetry; + if !app.ui.symmetry.show_manipulator || !super::shown(app) { + return None; + } + + let project = |point: Vec3| crate::viewport::project(app, rect, point); + let (lo, hi) = app.session.mesh.bounds(); + let origin = symmetry.origin((lo + hi) * 0.5); + let center = project(origin)?; + let step = ((hi - lo).length() * PROBE_FRACTION).max(MIN_PROBE); + let screen_per_unit = [Vec3::X, Vec3::Y, Vec3::Z].map(|axis| project(origin + axis * step).map_or(Vec2::ZERO, |point| (point - center) / step)); + + // Sized in points at the origin's depth, so the arrows keep their size on screen but still turn in 3D + let right = app.session.camera.forward().cross(Vec3::Y).try_normalize().unwrap_or(Vec3::X); + let points_per_unit = project(origin + right * step).map_or(0.0, |point| (point - center).length() / step); + if points_per_unit <= MIN_SCREEN_SCALE { + return None; + } + let world_per_point = 1.0 / points_per_unit; + let scale = app.ui.symmetry.manipulator_size / DEFAULT_MANIPULATOR_SIZE; + let length = rect.height() * ARROW_LENGTH * scale * world_per_point; + + let movable = super::movable_axes(&symmetry); + let signs: &[f32] = if symmetry.radial_mode() { &[1.0] } else { &[1.0, -1.0] }; + let arrows: Vec = (0..3) + .filter(|axis| movable[*axis] && screen_per_unit[*axis].length() > MIN_SCREEN_SCALE) + .flat_map(|axis| signs.iter().map(move |sign| (axis, [Vec3::X, Vec3::Y, Vec3::Z][axis] * *sign))) + .filter_map(|(axis, direction)| { + let tip_world = origin + direction * length; + let base_world = origin + direction * (length - CONE_LENGTH * scale * world_per_point); + let start = project(origin + direction * SHAFT_GAP * scale * world_per_point)?; + Some(SymmetryManipulatorArrow { axis, direction, start, base: project(base_world)?, tip: project(tip_world)?, base_world, tip_world }) + }) + .collect(); + + let square = match movable_pair(&movable) { + Some((first, second)) if symmetry.radial_mode() => { + let corner = |along_first: f32, along_second: f32| { + let mut point = origin; + (point[first], point[second]) = (origin[first] + along_first * length, origin[second] + along_second * length); + project(point) + }; + let (from, to) = (SQUARE_FROM, SQUARE_TO); + match [corner(from, from), corner(to, from), corner(to, to), corner(from, to)] { + [Some(near), Some(along_first), Some(far), Some(along_second)] => Some([near, along_first, far, along_second]), + _ => None, + } + } + _ => None, + }; + Some(SymmetryManipulator { center, arrows, square, world_per_point, scale, screen_per_unit }) + } + + /// The axes the handle under `point` moves along: the center and the square move along all movable axes (two at most) + pub(crate) fn grab(&self, point: Pos2) -> Option<[bool; 3]> { + let mut all = [false; 3]; + self.arrows.iter().for_each(|arrow| all[arrow.axis] = true); + let grab_radius = GRAB_RADIUS * self.scale.max(1.0); + // The center moves along all movable axes, which a screen drag can only do for two of them + let center_grabs = all.iter().filter(|axis| **axis).count() <= 2 && point.distance(self.center) <= grab_radius; + if center_grabs || self.square.is_some_and(|square| inside(&square, point)) { + return Some(all); + } + + let arrow = self.arrows.iter().find(|arrow| distance_to_segment(point, arrow.start, arrow.tip) <= grab_radius)?; + let mut axes = [false; 3]; + axes[arrow.axis] = true; + Some(axes) + } + + /// The world offset change that follows a pointer move of `moved` along `axes` + pub(crate) fn world_delta(&self, axes: [bool; 3], moved: Vec2) -> Vec3 { + let picked: Vec = (0..3).filter(|axis| axes[*axis]).collect(); + let mut delta = Vec3::ZERO; + match picked.as_slice() { + [axis] => { + let along = self.screen_per_unit[*axis]; + delta[*axis] = moved.dot(along) / along.length_sq().max(MIN_SCREEN_SCALE); + } + [first, second] => { + // Solve moved = a * first_axis + b * second_axis on screen + let (u, v) = (self.screen_per_unit[*first], self.screen_per_unit[*second]); + let determinant = u.x * v.y - u.y * v.x; + if determinant.abs() > MIN_SCREEN_SCALE { + delta[*first] = (moved.x * v.y - moved.y * v.x) / determinant; + delta[*second] = (u.x * moved.y - u.y * moved.x) / determinant; + } + } + _ => {} + } + delta + } +} + +/// The two movable axes, when there are two +fn movable_pair(movable: &[bool; 3]) -> Option<(usize, usize)> { + let picked: Vec = (0..3).filter(|axis| movable[*axis]).collect(); + match picked.as_slice() { + [first, second] => Some((*first, *second)), + _ => None, + } +} + +fn distance_to_segment(point: Pos2, from: Pos2, to: Pos2) -> f32 { + let along = to - from; + let t = ((point - from).dot(along) / along.length_sq().max(f32::EPSILON)).clamp(0.0, 1.0); + point.distance(from + along * t) +} + +/// Whether `point` is inside the convex quad `corners` +fn inside(corners: &[Pos2; 4], point: Pos2) -> bool { + let side = |i: usize| { + let (a, b) = (corners[i], corners[(i + 1) % 4]); + (b - a).x * (point - a).y - (b - a).y * (point - a).x + }; + let sides = [side(0), side(1), side(2), side(3)]; + sides.iter().all(|s| *s >= 0.0) || sides.iter().all(|s| *s <= 0.0) +} + +#[cfg(test)] +mod tests { + use egui::pos2; + + use super::*; + + #[test] + fn a_two_axis_drag_splits_the_move_between_both_axes() { + let manipulator = SymmetryManipulator { + center: pos2(0.0, 0.0), + arrows: Vec::new(), + square: None, + world_per_point: 1.0, + scale: 1.0, + screen_per_unit: [Vec2::new(10.0, 0.0), Vec2::new(0.0, -10.0), Vec2::ZERO], + }; + + let delta = manipulator.world_delta([true, true, false], Vec2::new(20.0, -30.0)); + + assert!((delta - Vec3::new(2.0, 3.0, 0.0)).length() < 1e-5, "{delta}"); + } +} diff --git a/crates/ui-egui/src/symmetry/symmetry_manipulator_arrow.rs b/crates/ui-egui/src/symmetry/symmetry_manipulator_arrow.rs new file mode 100644 index 00000000..29d5144e --- /dev/null +++ b/crates/ui-egui/src/symmetry/symmetry_manipulator_arrow.rs @@ -0,0 +1,18 @@ +//! One arrow of the symmetry manipulator + +use egui::Pos2; +use texturecraft_engine::geom::glam::Vec3; + +/// An arrow along one world axis, in 3D (so it foreshortens) and where it lands on screen +#[derive(Clone, Copy, Debug)] +pub(crate) struct SymmetryManipulatorArrow { + pub(crate) axis: usize, + /// The world axis, pointing toward the tip + pub(crate) direction: Vec3, + /// Where the shaft starts, just off the center, and where it meets the cone + pub(crate) start: Pos2, + pub(crate) base: Pos2, + pub(crate) tip: Pos2, + pub(crate) base_world: Vec3, + pub(crate) tip_world: Vec3, +} diff --git a/crates/ui-egui/src/symmetry/view_overlay.rs b/crates/ui-egui/src/symmetry/view_overlay.rs new file mode 100644 index 00000000..a4fe7d8c --- /dev/null +++ b/crates/ui-egui/src/symmetry/view_overlay.rs @@ -0,0 +1,305 @@ +//! What the 3D view draws for symmetry: the plane or axis, where they meet the mesh, the cursor copies and the manipulator + +use egui::{Color32, PointerButton, Pos2, Rect, Response, Stroke, Ui}; +use texturecraft_engine::geom::glam::Vec3; +use texturecraft_render::OverlayQuad; + +use super::ribbons::Ribbons; +use super::shown; +use super::symmetry_drag::SymmetryDrag; +use super::symmetry_intersection::SymmetryIntersection; +use super::symmetry_manipulator::SymmetryManipulator; +use super::symmetry_manipulator_arrow::SymmetryManipulatorArrow; +use crate::TextureCraftApp; + +/// The plane reaches this far past the mesh, as a fraction of its size +const PLANE_MARGIN: f32 = 0.05; +const PLANE_OPACITY: f32 = 0.18; + +/// The radial axis line's width (points) and opacity +const AXIS_WIDTH: f32 = 1.5; +const AXIS_OPACITY: f32 = 0.85; + +/// The intersection line's opacity +const LINE_OPACITY: f32 = 0.9; + +/// A point counts as visible when nothing is in front of it by more than this fraction of the mesh diagonal +const VISIBILITY_TOLERANCE: f32 = 2e-3; + +/// Width of the cut line and radius of the radial axis points (points) +const INTERSECTION_WIDTH: f32 = 1.5; +const INTERSECTION_POINT_RADIUS: f32 = 3.0; + +/// Manipulator arrows along X, Y and Z (the view-corner axis colors, a little softer) +const AXIS_COLORS: [Color32; 3] = [Color32::from_rgb(0xd8, 0x60, 0x4f), Color32::from_rgb(0x6c, 0xbc, 0x5a), Color32::from_rgb(0x5a, 0x8c, 0xe0)]; + +/// Arrow shaft width, its dark halo and the halo's extra width (points at the default size) +const SHAFT_WIDTH: f32 = 2.2; +const SHAFT_HALO: Color32 = Color32::from_black_alpha(128); +const SHAFT_HALO_EXTRA_WIDTH: f32 = 3.0; + +/// Faces around a cone +const CONE_SEGMENTS: usize = 20; + +/// Cone faces facing the camera more than this (cosine) are tinted toward white, the others toward black +const CONE_LIT_FROM: f32 = 0.55; + +/// How strongly the cone faces' tint follows their facing, toward white and toward black +const CONE_LIGHTEN: f32 = 0.9; +const CONE_DARKEN: f32 = 0.8; + +/// The center: a small disc in the arrows' material, its rim shaded and its middle lit like the cones +const CENTER_RADIUS: f32 = 4.0; +const CENTER_LIT_RADIUS: f32 = 0.6; +const CENTER_SHADE: f32 = 0.3; +const CENTER_LIGHT: f32 = 0.25; + +/// The radial square at rest and the opacity of its accent fill when active +const SQUARE_EDGE_WIDTH: f32 = 1.3; +const SQUARE_FILL: Color32 = Color32::from_rgba_premultiplied(40, 40, 40, 40); +const SQUARE_EDGE: Color32 = Color32::from_rgba_premultiplied(190, 190, 190, 190); +const SQUARE_ACTIVE_OPACITY: f32 = 0.45; + +/// `linear` RGB as a screen color with `alpha` +pub(super) fn color(linear: [f32; 3], alpha: u8) -> Color32 { + let [r, g, b] = linear.map(|channel| (texturecraft_engine::texel::linear_to_srgb(channel.clamp(0.0, 1.0)) * 255.0 + 0.5) as u8); + Color32::from_rgba_unmultiplied(r, g, b, alpha) +} + +/// The planes, the axis and where the planes cut the mesh, drawn by the renderer: the mesh hides them pixel by pixel where it is in front +pub(crate) fn scene_overlay(app: &TextureCraftApp, ui: &Ui, rect: Rect) -> Vec { + if !shown(app) { + return Vec::new(); + } + + let symmetry = app.session.tool.brush.symmetry; + let display = app.ui.symmetry; + let (lo, hi) = app.session.mesh.bounds(); + let origin = symmetry.origin((lo + hi) * 0.5); + let ribbon = Ribbons::new(app, rect); + let mut quads = Vec::new(); + + for (axis, on) in [symmetry.x, symmetry.y, symmetry.z].into_iter().enumerate() { + if !on { + continue; + } + + if display.show_plane { + let margin = (hi - lo) * PLANE_MARGIN; + let (lo, hi) = (lo - margin, hi + margin); + let (u, v) = ((axis + 1) % 3, (axis + 2) % 3); + let corner = |at_u: f32, at_v: f32| { + let mut point = origin; + (point[u], point[v]) = (at_u, at_v); + point + }; + let corners = [corner(lo[u], lo[v]), corner(hi[u], lo[v]), corner(hi[u], hi[v]), corner(lo[u], hi[v])]; + quads.push(OverlayQuad { corners, color: display.color, opacity: PLANE_OPACITY }); + } + if display.show_intersection { + let segments = intersection(app, ui, axis, origin[axis]); + quads.extend(segments.iter().map(|[from, to]| ribbon.quad(*from, *to, INTERSECTION_WIDTH, display.color, LINE_OPACITY))); + } + } + + if display.show_axis && symmetry.radial_mode() { + let direction = symmetry.radial_axis(); + let reach = (hi - lo).length() * 0.5; + quads.push(ribbon.quad(origin - direction * reach, origin + direction * reach, AXIS_WIDTH, display.color, AXIS_OPACITY)); + } + + quads +} + +/// Whether `point` is on the mesh's surface where the camera sees it: in the air (a copy that missed the mesh) or hidden behind the mesh, it is not +fn on_visible_surface(app: &TextureCraftApp, rect: Rect, point: Vec3) -> bool { + let camera = &app.session.camera; + let aspect = rect.width() / rect.height().max(1.0); + let Some(ndc) = camera.project(point, aspect) else { return false }; + + let ray = camera.ray(ndc.truncate(), aspect); + let (lo, hi) = app.session.mesh.bounds(); + let tolerance = (hi - lo).length() * VISIBILITY_TOLERANCE; + let distance = (point - ray.origin).dot(ray.dir); + app.session.bvh.closest(ray.origin, ray.dir, f32::MAX).is_some_and(|hit| (hit.t - distance).abs() <= tolerance) +} + +/// Over the 3D view: where the planes or axis meet the mesh, copies of the brush `cursor` (position, normal) and the manipulator +pub(crate) fn overlay(app: &TextureCraftApp, ui: &Ui, rect: Rect, cursor: Option<(Vec3, Vec3)>) { + if !shown(app) { + return; + } + + let symmetry = app.session.tool.brush.symmetry; + let display = app.ui.symmetry; + let (lo, hi) = app.session.mesh.bounds(); + let origin = symmetry.origin((lo + hi) * 0.5); + let painter = ui.painter_at(rect); + let line = Stroke::new(INTERSECTION_WIDTH, color(display.color, u8::MAX)); + let project = |point: Vec3| crate::viewport::project(app, rect, point); + + // The planes' lines are drawn in the scene (see scene_overlay); where the radial axis enters the mesh, from either end, is drawn here + if display.show_intersection && symmetry.radial_mode() { + let axis = symmetry.radial_axis(); + let reach = (hi - lo).length(); + for (start, direction) in [(origin - axis * reach, axis), (origin + axis * reach, -axis)] { + if let Some(hit) = app.session.bvh.closest(start, direction, reach * 2.0) + && let point = start + direction * hit.t + && on_visible_surface(app, rect, point) + && let Some(at) = project(point) + { + painter.circle_filled(at, INTERSECTION_POINT_RADIUS, line.color); + } + } + } + + let painting = app.session.stroke_active(); + if display.show_cursor + && !(display.hide_while_painting && painting) + && let Some((position, normal)) = cursor + { + for map in symmetry.transforms().iter().skip(1) { + let copy = origin + *map * (position - origin); + if on_visible_surface(app, rect, copy) { + crate::viewport::brush_cursor(app, ui, rect, copy, (*map * normal).normalize_or_zero()); + } + } + } + + if let Some(manipulator) = SymmetryManipulator::of(app, rect) { + draw_manipulator(app, ui, rect, &painter, &manipulator); + } +} + +/// Where the mirror plane `p[axis] = position` cuts the mesh, recomputed only when it moves +fn intersection(app: &TextureCraftApp, ui: &Ui, axis: usize, position: f32) -> std::sync::Arc> { + let id = egui::Id::unique("symmetry_intersection").with(axis); + let mesh_id = app.session.mesh_id; + let cached = ui.ctx().data(|data| data.get_temp::(id)).filter(|cached| cached.is_for(mesh_id, axis, position)); + let current = cached.unwrap_or_else(|| { + let computed = SymmetryIntersection::compute(&app.session.mesh, mesh_id, axis, position); + ui.ctx().data_mut(|data| data.insert_temp(id, computed.clone())); + computed + }); + current.segments +} + +/// The manipulator: the radial square, the arrows with their cones and the center; copper where hovered or dragged +fn draw_manipulator(app: &TextureCraftApp, ui: &Ui, rect: Rect, painter: &egui::Painter, manipulator: &SymmetryManipulator) { + let accent = crate::theme::Tokens::get(ui.ctx()).viewport_accent; + let hovered = ui.ctx().pointer_hover_pos().and_then(|pointer| manipulator.grab(pointer)); + let dragging = ui.ctx().data(|data| data.get_temp::(drag_id())).map(|drag| drag.axes); + let highlighted = dragging.or(hovered).unwrap_or_default(); + let all_highlighted = manipulator.arrows.iter().all(|arrow| highlighted[arrow.axis]); + let tint = |axis: usize| if highlighted[axis] { accent } else { AXIS_COLORS[axis] }; + + if let Some(square) = manipulator.square { + let fill = if all_highlighted { accent.gamma_multiply(SQUARE_ACTIVE_OPACITY) } else { SQUARE_FILL }; + let edge = if all_highlighted { accent } else { SQUARE_EDGE }; + painter.add(egui::Shape::convex_polygon(square.to_vec(), fill, Stroke::new(SQUARE_EDGE_WIDTH * manipulator.scale, edge))); + } + + for arrow in &manipulator.arrows { + let color = tint(arrow.axis); + painter.line_segment([arrow.start, arrow.base], Stroke::new((SHAFT_WIDTH + SHAFT_HALO_EXTRA_WIDTH) * manipulator.scale, SHAFT_HALO)); + painter.line_segment([arrow.start, arrow.base], Stroke::new(SHAFT_WIDTH * manipulator.scale, color)); + cone(app, rect, painter, arrow, manipulator.world_per_point * super::symmetry_manipulator::CONE_RADIUS * manipulator.scale, color); + } + + let center_color = if all_highlighted { accent } else { manipulator.arrows.first().map_or(AXIS_COLORS[0], |arrow| AXIS_COLORS[arrow.axis]) }; + painter.circle_filled(manipulator.center, CENTER_RADIUS * manipulator.scale, center_color.lerp_to_gamma(Color32::BLACK, CENTER_SHADE)); + painter.circle_filled(manipulator.center, CENTER_RADIUS * CENTER_LIT_RADIUS * manipulator.scale, center_color.lerp_to_gamma(Color32::WHITE, CENTER_LIGHT)); +} + +/// A flat-shaded 3D cone over `arrow`'s head: faces facing the camera lighter, back to front +fn cone(app: &TextureCraftApp, rect: Rect, painter: &egui::Painter, arrow: &SymmetryManipulatorArrow, radius: f32, color: Color32) { + let camera = &app.session.camera; + let (eye, forward) = (camera.eye(), camera.forward()); + let side = arrow.direction.any_orthonormal_vector(); + let up = arrow.direction.cross(side); + let rim: Vec = (0..CONE_SEGMENTS) + .map(|segment| { + let angle = segment as f32 / CONE_SEGMENTS as f32 * std::f32::consts::TAU; + arrow.base_world + (side * angle.cos() + up * angle.sin()) * radius + }) + .collect(); + + // Each face: its corners, its depth and how much it faces the camera + let mut faces: Vec<(Vec, f32, f32)> = (0..CONE_SEGMENTS) + .map(|segment| { + let (rim_start, rim_end) = (rim[segment], rim[(segment + 1) % CONE_SEGMENTS]); + let middle = (rim_start + rim_end + arrow.tip_world) / 3.0; + let normal = (rim_end - rim_start).cross(arrow.tip_world - rim_start).normalize_or_zero(); + (vec![arrow.tip_world, rim_start, rim_end], (middle - eye).dot(forward), normal.dot((eye - middle).normalize_or_zero())) + }) + .collect(); + faces.push((rim.clone(), (arrow.base_world - eye).dot(forward), (-arrow.direction).dot((eye - arrow.base_world).normalize_or_zero()))); + faces.sort_by(|(_, nearer, _), (_, farther, _)| farther.total_cmp(nearer)); + + // One plain triangle mesh: anti-aliased polygons smear thin edge-on faces into long hairlines + let mut mesh = egui::Mesh::default(); + for (corners, _, facing) in faces { + let Some(points) = corners.iter().map(|corner| crate::viewport::project(app, rect, *corner)).collect::>>() else { + continue; + }; + + let facing = facing.max(0.0); + let fill = if facing > CONE_LIT_FROM { + color.lerp_to_gamma(Color32::WHITE, (facing - CONE_LIT_FROM) * CONE_LIGHTEN) + } else { + color.lerp_to_gamma(Color32::BLACK, (CONE_LIT_FROM - facing) * CONE_DARKEN) + }; + let first = mesh.vertices.len() as u32; + points.iter().for_each(|point| mesh.colored_vertex(*point, fill)); + for corner in 1..points.len().saturating_sub(1) as u32 { + mesh.add_triangle(first, first + corner, first + corner + 1); + } + } + painter.add(egui::Shape::mesh(mesh)); +} + +fn drag_id() -> egui::Id { + egui::Id::unique("symmetry_manipulator_drag") +} + +/// Whether the pointer is on a manipulator handle or dragging one (the brush cursor hides then) +pub(crate) fn manipulator_hovered(app: &TextureCraftApp, ui: &Ui, rect: Rect) -> bool { + let dragging = ui.ctx().data(|data| data.get_temp::(drag_id())).is_some(); + let hovered = + ui.ctx().pointer_hover_pos().is_some_and(|pointer| SymmetryManipulator::of(app, rect).is_some_and(|manipulator| manipulator.grab(pointer).is_some())); + dragging || hovered +} + +/// Drags on the manipulator move the symmetry origin. Returns whether a drag owns the pointer +pub(crate) fn manipulator_input(app: &mut TextureCraftApp, ui: &Ui, response: &Response, rect: Rect) -> bool { + let ctx = ui.ctx(); + let manipulator = SymmetryManipulator::of(app, rect); + let mut drag = ctx.data(|data| data.get_temp::(drag_id())); + if response.drag_started_by(PointerButton::Primary) + && let (Some(manipulator), Some(from)) = (&manipulator, ctx.input(|input| input.pointer.press_origin())) + && let Some(axes) = manipulator.grab(from) + { + drag = Some(SymmetryDrag { axes, from, start_offset: app.session.tool.brush.symmetry.offset }); + } + + let dragging = response.dragged_by(PointerButton::Primary) || response.drag_started_by(PointerButton::Primary); + let (Some(manipulator), Some(drag)) = (manipulator, drag.filter(|_| dragging)) else { + ctx.data_mut(|data| data.remove::(drag_id())); + if let (Some(manipulator), Some(hover)) = (SymmetryManipulator::of(app, rect), response.hover_pos()) + && manipulator.grab(hover).is_some() + { + ctx.set_cursor_icon(egui::CursorIcon::Move); + } + return false; + }; + + if let Some(pointer) = response.interact_pointer_pos() { + let (lo, hi) = app.session.mesh.bounds(); + let half_extent = (hi - lo) * 0.5; + let moved = Vec3::from(drag.start_offset) + manipulator.world_delta(drag.axes, pointer - drag.from); + app.session.tool.brush.symmetry.offset = moved.clamp(-half_extent, half_extent).to_array(); + } + ctx.data_mut(|data| data.insert_temp(drag_id(), drag)); + ctx.set_cursor_icon(egui::CursorIcon::Grabbing); + true +} diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index eee357f7..e4da67c6 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -253,15 +253,12 @@ fn tool_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui, tokens: &Tokens) } ui.separator(); - if icon_button(ui, ic::FLIP_HORIZONTAL, tr("Symmetry (X)"), brush.symmetry.x, button_size).clicked() { - brush.symmetry.x = !brush.symmetry.x; - } - if icon_button(ui, ic::FLIP_VERTICAL, tr("Symmetry (Y)"), brush.symmetry.y, button_size).clicked() { - brush.symmetry.y = !brush.symmetry.y; - } if icon_button(ui, ic::CLOUD_RAIN, tr("Particle brush: particles slide down the surface"), brush.particles.enabled, button_size).clicked() { brush.particles.enabled = !brush.particles.enabled; } + if crate::symmetry::applies_to(tool) { + crate::symmetry::toolbar_controls(app, ui); + } if tool == Tool::Smudge { ui.separator(); diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index f20210d4..0b5ab6c9 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -560,6 +560,15 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin // The selected decal's frame and handles: drag to move, scale or turn it let decal_drag = !alt && !s_held && !v_held && !focus_pick && !popup && placing.is_none() && touch.is_none() && decal_input(app, ui, &response, rect); + let symmetry_drag = !alt + && !s_held + && !v_held + && !focus_pick + && !popup + && placing.is_none() + && touch.is_none() + && !decal_drag + && crate::symmetry::manipulator_input(app, ui, &response, rect); // Painting let painting = app.ui.mode == crate::state::Mode::Painting @@ -571,7 +580,8 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && !focus_pick && placing.is_none() && touch.is_none() - && !decal_drag; + && !decal_drag + && !symmetry_drag; let path_tool = app.session.tool.tool == Tool::Path; let viewport = app.session.viewport; let show = |app: &TextureCraftApp, point: Vec3| project(app, rect, point); @@ -619,6 +629,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin camera: app.session.camera, shade: Shade { highlight: drop_highlight(app, ui, &response), ..shade(app) }, visible: app.session.doc.project.texture_sets.iter().map(|texture_set| texture_set.visible).collect(), + overlay: crate::symmetry::scene_overlay(app, ui, rect), }; add_callback(app, ui, rect, frame, sync); @@ -626,15 +637,18 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin crate::shelf::drop_target(app, ui, &response, crate::shelf::DropZone::View3d); // Brush cursor; while a Ctrl+drag changes the brush it stays where the drag began + let mut symmetry_cursor = None; if app.ui.mode == crate::state::Mode::Painting && !navigating && response.hovered() && brush_tool(app.session.tool.tool) + && !crate::symmetry::manipulator_hovered(app, ui, rect) && let Some(hover_pos) = if adjusting { ui.input(|input| input.pointer.press_origin()) } else { response.hover_pos() } && let Some(hit) = app.session.pick(local(hover_pos), app.session.viewport) { ui.ctx().set_cursor_icon(egui::CursorIcon::None); brush_cursor(app, ui, rect, hit.pos, hit.nrm); + symmetry_cursor = Some((hit.pos, hit.nrm)); if app.session.tool.tool == Tool::Clone && let Some(source) = app.session.clone_source_point(Some(hit.uv)) { @@ -653,6 +667,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin if app.ui.mode == crate::state::Mode::Painting && path_tool { path_overlay(app, ui, rect, &response, false, show); } + crate::symmetry::overlay(app, ui, rect, symmetry_cursor); stencil_overlay(app, ui, rect); decal_overlay(app, ui, rect); brush_readout(app, ui, &response, adjusting); @@ -891,10 +906,10 @@ fn stencil_overlay(app: &mut TextureCraftApp, ui: &Ui, rect: Rect) { painter.add(egui::Shape::dashed_line(&outline, Stroke::new(1.0, Color32::from_white_alpha(120)), 5.0, 4.0)); } -/// A world point on screen in the 3D view `rect` (None behind the camera). -fn project(app: &TextureCraftApp, rect: Rect, p: Vec3) -> Option { - let n = app.session.camera.project(p, rect.width() / rect.height().max(1.0))?; - Some(pos2(rect.left() + (n.x * 0.5 + 0.5) * rect.width(), rect.top() + (0.5 - n.y * 0.5) * rect.height())) +/// A world point on screen in the 3D view `rect` (None behind the camera) +pub(crate) fn project(app: &TextureCraftApp, rect: Rect, point: Vec3) -> Option { + let ndc = app.session.camera.project(point, rect.width() / rect.height().max(1.0))?; + Some(pos2(rect.left() + (ndc.x * 0.5 + 0.5) * rect.width(), rect.top() + (0.5 - ndc.y * 0.5) * rect.height())) } /// Control point grab radius (points). @@ -1087,7 +1102,7 @@ fn adjust_brush(brush: &mut texturecraft_engine::paint::BrushSettings, right: bo } } -fn brush_cursor(app: &TextureCraftApp, ui: &Ui, rect: Rect, pos: Vec3, nrm: Vec3) { +pub(crate) fn brush_cursor(app: &TextureCraftApp, ui: &Ui, rect: Rect, pos: Vec3, nrm: Vec3) { let (lo, hi) = app.session.mesh.bounds(); let r = app.session.tool.brush.size * (hi - lo).length(); let t = nrm.any_orthonormal_vector(); @@ -1252,6 +1267,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin camera: app.session.camera, shade: shade(app), visible: app.session.doc.project.texture_sets.iter().map(|texture_set| texture_set.visible).collect(), + overlay: Vec::new(), }; add_callback(app, ui, rect, frame, sync); crate::shelf::drop_target(app, ui, &response, crate::shelf::DropZone::View2d); diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 79aa7eab..f2090e47 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -185,6 +185,10 @@ const ICON_SCALE: f32 = 0.62; /// Extra width an `icon_dropdown_button` gives its caret, as a fraction of the button height const CARET_STRIP_SCALE: f32 = 0.34; +/// Caret glyph size, and how far its center sits from the right edge, as fractions of the button height +const CARET_SCALE: f32 = 0.34; +const CARET_INSET_SCALE: f32 = 0.25; + /// An `icon_button` with no tooltip, whose `label` still names it for screen readers pub fn icon_button_without_tooltip(ui: &mut Ui, icon: &str, label: &str, selected: bool, size: f32) -> Response { let style = icon_button_style(&Tokens::get(ui.ctx())); @@ -200,10 +204,6 @@ pub fn icon_dropdown_button_width(size: f32) -> f32 { /// An `icon_button_without_tooltip` with a dropdown caret after the icon, drawn in the icon's color pub fn icon_dropdown_button(ui: &mut Ui, icon: &str, label: &str, selected: bool, size: f32) -> Response { - // Caret glyph size, and how far its center sits from the right edge, as fractions of the height - const CARET_SCALE: f32 = 0.34; - const CARET_INSET_SCALE: f32 = 0.25; - let style = icon_button_style(&Tokens::get(ui.ctx())); IconButton::new(label, vec2(icon_dropdown_button_width(size), size), &style).selected(selected).show(ui, |ui, rect, color| { let icon_center = rect.left_center() + vec2(size / 2.0, 0.0); @@ -213,6 +213,32 @@ pub fn icon_dropdown_button(ui: &mut Ui, icon: &str, label: &str, selected: bool }) } +/// An `icon_dropdown_button` whose icon carries a small `badge` glyph at its lower right (e.g. a gear for a feature's settings) +pub fn icon_badge_dropdown_button(ui: &mut Ui, icon: &str, badge: &str, label: &str, selected: bool, size: f32) -> Response { + // Badge glyph size and inset, as fractions of the height + const BADGE_SCALE: f32 = 0.5; + const BADGE_INSET_SCALE: f32 = 0.24; + // The icon shrinks a little and moves up and left, making room for the badge + const ICON_WITH_BADGE_SCALE: f32 = 0.78; + const ICON_SHIFT_SCALE: f32 = 0.09; + + let style = icon_button_style(&Tokens::get(ui.ctx())); + IconButton::new(label, vec2(icon_dropdown_button_width(size), size), &style).selected(selected).show(ui, |ui, rect, color| { + let icon_center = rect.left_center() + vec2(size / 2.0, 0.0); + let badge_center = rect.left_top() + vec2(size - size * BADGE_INSET_SCALE, size - size * BADGE_INSET_SCALE); + let caret_center = rect.right_center() - vec2(size * CARET_INSET_SCALE, 0.0); + ui.painter().text( + icon_center - vec2(size, size) * ICON_SHIFT_SCALE, + egui::Align2::CENTER_CENTER, + icon, + egui::FontId::proportional(size * ICON_SCALE * ICON_WITH_BADGE_SCALE), + color, + ); + ui.painter().text(badge_center, egui::Align2::CENTER_CENTER, badge, egui::FontId::proportional(size * BADGE_SCALE), color); + ui.painter().text(caret_center, egui::Align2::CENTER_CENTER, egui_phosphor::regular::CARET_DOWN, egui::FontId::proportional(size * CARET_SCALE), color); + }) +} + /// Transparent at rest, a hover well, and the active-tool well when pressed or selected fn icon_button_style(tokens: &Tokens) -> IconButtonStyle { let well = |fill, icon| ButtonVisuals { fill, stroke: Stroke::NONE, icon }; diff --git a/crates/ui-egui/tests/symmetry.rs b/crates/ui-egui/tests/symmetry.rs new file mode 100644 index 00000000..70996abc --- /dev/null +++ b/crates/ui-egui/tests/symmetry.rs @@ -0,0 +1,140 @@ +//! Symmetry: the toolbar toggle, the settings popup and the 3D view's manipulator + +use egui::{Event, Modifiers, PointerButton, Pos2}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::{Value, json}; +use texturecraft_engine::Tool; +use texturecraft_engine::geom::glam::Vec3; +use texturecraft_ui_egui::TextureCraftApp; + +/// The settings popup's width and its color square's (points) +const POPUP_WIDTH: f32 = 340.0; +const COLOR_SWATCH_WIDTH: f32 = 48.0; + +/// How far along Y (world units) the test measures the arrow's direction on screen +const AXIS_PROBE: f32 = 0.05; + +/// Points from the manipulator's center to grab the arrow (inside its length at the default size) and how far to drag it +const ON_THE_SHAFT: f32 = 40.0; +const DRAG_DISTANCE: f32 = 60.0; + +/// A point inside the 3D view near its lower left corner, clear of the mesh and the popup (points from the corner) +const VIEW_CORNER_INSET: f32 = 40.0; + +fn app_harness() -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(1024, 256).unwrap(); + let mut harness = + Harness::builder().with_size(egui::vec2(1600.0, 960.0)).with_pixels_per_point(1.0).wgpu().build_eframe(|cc| TextureCraftApp::new(cc, session)); + harness.state_mut().session.tool.tool = Tool::Paint; + harness.run_steps(4); + harness +} + +/// Hold a primary-button drag from `from` to `to` without releasing it +fn hold_drag(harness: &mut Harness<'_, TextureCraftApp>, from: Pos2, to: Pos2) { + harness.hover_at(from); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(2); + + for step in 1..=4 { + harness.hover_at(from + (to - from) * (step as f32 / 4.0)); + harness.run_steps(1); + } +} + +fn click_at(harness: &mut Harness<'_, TextureCraftApp>, at: Pos2) { + harness.hover_at(at); + harness.run_steps(1); + harness.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(1); + release(harness, at); +} + +fn release(harness: &mut Harness<'_, TextureCraftApp>, at: Pos2) { + harness.event(Event::PointerButton { pos: at, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(2); +} + +/// The brush settings as agents read them +fn brush(harness: &mut Harness<'_, TextureCraftApp>) -> Value { + texturecraft_engine::execute(&mut harness.state_mut().session, "tool.brush", &json!({})).unwrap() +} + +/// Where world `point` is in the 3D view +fn on_screen(harness: &Harness<'_, TextureCraftApp>, point: Vec3) -> Pos2 { + let rect = harness.state().viewport_rect; + let ndc = harness.state().session.camera.project(point, rect.width() / rect.height()).unwrap(); + egui::pos2(rect.left() + (ndc.x * 0.5 + 0.5) * rect.width(), rect.top() + (0.5 - ndc.y * 0.5) * rect.height()) +} + +#[test] +fn the_toolbar_popup_and_manipulator_change_the_brush_symmetry() { + let mut harness = app_harness(); + + harness.get_by_label("Symmetry").click(); + harness.run_steps(2); + assert_eq!(brush(&mut harness)["symmetry"], json!([true, false, false]), "the toggle mirrors on X"); + + harness.get_by_label("Symmetry settings").click(); + harness.run_steps(2); + harness.get_by_role_and_label(egui::accesskit::Role::RadioButton, "Y").click(); + harness.run_steps(2); + assert_eq!(brush(&mut harness)["symmetry"], json!([false, true, false]), "one axis at a time"); + + harness.get_by_label("Symmetry settings").click(); + harness.state_mut().ui.symmetry.show_manipulator = true; + harness.run_steps(2); + + // Drag the arrow along Y, starting on its shaft + let (lo, hi) = harness.state().session.mesh.bounds(); + let origin = (lo + hi) * 0.5; + let center = on_screen(&harness, origin); + let along = (on_screen(&harness, origin + Vec3::Y * AXIS_PROBE) - center).normalized(); + let from = center + along * ON_THE_SHAFT; + let to = from + along * DRAG_DISTANCE; + hold_drag(&mut harness, from, to); + release(&mut harness, to); + + let offset = brush(&mut harness)["symmetryOffset"].clone(); + assert!(offset[1].as_f64().unwrap() > 0.05, "the plane moved up: {offset}"); + assert_eq!((offset[0].as_f64(), offset[2].as_f64()), (Some(0.0), Some(0.0)), "only along Y: {offset}"); + + harness.get_by_label("Symmetry").click(); + harness.run_steps(2); + let settings = brush(&mut harness); + assert_eq!(settings["symmetryOn"], json!(false), "the toggle turns it off"); + assert_eq!(settings["symmetry"], json!([false, true, false]), "and keeps the settings"); +} + +#[test] +fn the_type_dropdown_and_color_picker_open_inside_the_settings_popup() { + let mut harness = app_harness(); + harness.get_by_label("Symmetry").click(); + harness.run_steps(2); + harness.get_by_label("Symmetry settings").click(); + harness.run_steps(2); + + // The Type dropdown shows its choice as its value + harness.get_by_value("Mirror symmetry").click(); + harness.run_steps(2); + harness.get_by_label("Radial symmetry").click(); + harness.run_steps(2); + assert_eq!(brush(&mut harness)["radialSymmetry"], json!({"copies": 6, "axis": "x"}), "radial around the axis mirror X used"); + assert!(harness.query_by_label("Angle span").is_some(), "the popup stays open after the dropdown"); + + // The color square sits at the right end of its row, the popup's width from the Type label + let row = harness.get_by_label("Symmetry color display").rect(); + let left = harness.get_by_label("Type").rect().left(); + click_at(&mut harness, egui::pos2(left + POPUP_WIDTH - COLOR_SWATCH_WIDTH / 2.0, row.center().y)); + harness.run_steps(2); + assert!(harness.query_by_label("Copy RGB values").is_some(), "the color picker opened"); + assert!(harness.query_by_label("Show cursor").is_some(), "the popup stays open with the color picker"); + + // A click on the view closes it + let view_corner = harness.state().viewport_rect.left_bottom() + egui::vec2(VIEW_CORNER_INSET, -VIEW_CORNER_INSET); + click_at(&mut harness, view_corner); + harness.run_steps(2); + assert!(harness.query_by_label("Show cursor").is_none(), "a click elsewhere closes the popup"); +} From 4003e3172d3e05f5f3ea7817db936b8b9f1542e4 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sun, 8 Nov 2026 04:51:39 +0000 Subject: [PATCH 29/64] Path tool: live preview while placing points, edit points in the views - The brush stroke paints while points are placed and dragged (3D and 2D); applying is one undo step, Esc removes the unfinished path - Click the curve to insert a point, select a point and remove it with Backspace or the Remove point button; undo steps through point changes - The selected layer's other paths are drawn (lit under the pointer) and a click opens one for editing; 3D lines follow where their paint lands - A path repaint recomposites only the tiles it changed, not the whole set - Pen pointer for the tool; new paths start open; Apply/Cancel removed - Switching texture sets applies a path being placed first Closes #333 --- crates/engine/src/layer_cmds.rs | 7 + crates/engine/src/lib.rs | 1 + crates/engine/src/path_draft.rs | 13 + crates/engine/src/path_tool.rs | 357 ++++++++++++++++++++++---- crates/engine/src/session.rs | 75 +++++- crates/engine/src/set_cmds.rs | 6 + crates/engine/tests/path_tool.rs | 168 ++++++++++++- crates/paint/src/lib.rs | 2 +- crates/paint/src/path.rs | 36 +-- crates/ui-egui/src/i18n/ar.rs | 9 +- crates/ui-egui/src/i18n/de.rs | 8 +- crates/ui-egui/src/i18n/es.rs | 9 +- crates/ui-egui/src/i18n/fr.rs | 9 +- crates/ui-egui/src/i18n/it.rs | 8 +- crates/ui-egui/src/i18n/ja.rs | 9 +- crates/ui-egui/src/i18n/ko.rs | 9 +- crates/ui-egui/src/i18n/pt_br.rs | 9 +- crates/ui-egui/src/i18n/zh_hans.rs | 9 +- crates/ui-egui/src/lib.rs | 9 +- crates/ui-egui/src/menus.rs | 3 +- crates/ui-egui/src/path_hit.rs | 17 ++ crates/ui-egui/src/toolbar.rs | 30 +-- crates/ui-egui/src/viewport.rs | 364 ++++++++++++++++++++++----- crates/ui-egui/tests/path_in_view.rs | 144 +++++++++++ 24 files changed, 1117 insertions(+), 194 deletions(-) create mode 100644 crates/engine/src/path_draft.rs create mode 100644 crates/ui-egui/src/path_hit.rs create mode 100644 crates/ui-egui/tests/path_in_view.rs diff --git a/crates/engine/src/layer_cmds.rs b/crates/engine/src/layer_cmds.rs index 747d7da1..36cd090c 100644 --- a/crates/engine/src/layer_cmds.rs +++ b/crates/engine/src/layer_cmds.rs @@ -168,6 +168,12 @@ fn group(s: &mut Session, p: &Value) -> Result { fn select(s: &mut Session, p: &Value) -> Result { let id = layer_param(s, "layer.select", p)?; let (ts, _, _) = s.doc.project.locate(id).ok_or_else(|| bad("layer.select", "layer not in a stack"))?; + + // Paths paint into the active set + if ts != s.ts() { + s.finish_path()?; + } + s.active_set = ts; s.selected.insert(ts, id); s.target = match p.get("target") { @@ -184,6 +190,7 @@ fn select(s: &mut Session, p: &Value) -> Result { }, None => StackTarget::Content, }; + s.revision = s.revision.wrapping_add(1); Ok(json!({ "layer": id.0, "textureSet": ts })) } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 2f5887a6..bfc3bf9e 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -30,6 +30,7 @@ pub mod materials; pub mod materialx_cmds; pub mod meshmap_cmds; pub mod painting; +mod path_draft; pub mod path_tool; // Mesh reimport reads files: native only. #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/engine/src/path_draft.rs b/crates/engine/src/path_draft.rs new file mode 100644 index 00000000..6322a7dc --- /dev/null +++ b/crates/engine/src/path_draft.rs @@ -0,0 +1,13 @@ +//! A new Path tool path previewed in the document before it is applied + +use serde_json::Value; + +use crate::Document; + +/// A new path previewed in the document before it is applied +pub(crate) struct PathDraft { + /// The document before the preview + pub(crate) base: Document, + /// What painting the preview last reported (the commit's report when nothing changed since) + pub(crate) painted: Value, +} diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index 150a103e..d5b232b1 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -7,45 +7,59 @@ //! (`path.edit`, live while the points, brush or material change) or removed (`path.remove`). use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; +use texturecraft_compose::{PaintTarget, PixelStore}; use texturecraft_core::{Channel, Effect, EffectKind, LayerId, Mask, MaskBackground, PathShape}; use texturecraft_geom::glam::{Vec2, Vec3}; use texturecraft_geom::{OrbitCamera, surface_at}; -use texturecraft_paint::{BrushSettings, Lasso, fill_coverage, spline}; +use texturecraft_paint::{BrushSettings, Lasso, PickCtx, fill_coverage, pick, spline, spline_segments}; +use texturecraft_texel::TileImage; use crate::commands::{CommandSpec, always, bad, boolp, has_layer, u64p}; +use crate::path_draft::PathDraft; use crate::session::{StackTarget, Tool}; use crate::tool_cmds::{points_param, set_tool, viewport_of}; -use crate::{EngineError, Result, Session, cmd}; +use crate::{Document, EngineError, Result, Session, cmd}; /// Control points kept at most. pub const MAX_PATH_POINTS: usize = 4096; +/// The undo step that adds a new path +pub(crate) const NEW_PATH_LABEL: &str = "Path"; /// Curve sampling step in viewport pixels (3D view) and texture units (2D view). const STEP_PX: f32 = 2.0; const STEP_UV: f32 = 0.001; +/// A stored path's viewport is clamped to this range (pixels per side) before painting from it +const MIN_PAINT_VIEWPORT_PX: f32 = 16.0; +const MAX_PAINT_VIEWPORT_PX: f32 = 16384.0; +/// Sampling step of a 3D path's curve on the mesh for the views, in its paint viewport pixels +const SURFACE_STEP_PX: f32 = 4.0; const MIN_PROJECTIVE_W: f32 = 1e-6; // Allow ray hits to differ slightly from transformed texel positions const RAY_HIT_RELATIVE_TOLERANCE: f32 = 0.001; -/// The curve being edited with the Path tool. +/// The curve being edited with the Path tool #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] pub struct PathState { - /// Control points: surface positions (3D view) or texture coordinates with z = 0 (2D view). + /// Control points: surface positions (3D view) or texture coordinates with z = 0 (2D view) pub points: Vec, - /// The points are texture coordinates (placed in the 2D view). + /// The points are texture coordinates (placed in the 2D view) pub uv: bool, - /// The curve loops back to its first point. + /// The curve loops back to its first point pub closed: bool, - /// A closed path fills its interior instead of stroking the curve. + /// A closed path fills its interior instead of stroking the curve pub fill: bool, - /// The stored path being edited: (path sublayer, index). Changes repaint it live. + /// The stored path being edited: (path sublayer, index). Changes repaint it live #[serde(default)] pub editing: Option<(LayerId, usize)>, - /// This edit has already repainted: later changes join its undo step, not an earlier edit's. + /// This edit has already repainted: later changes join its undo step, not an earlier edit's #[serde(default)] pub edited: bool, + /// The selected control point (drawn in the accent color; Backspace or Remove point removes it) + #[serde(default)] + pub selected: Option, } impl PathState { @@ -59,6 +73,42 @@ impl PathState { self.points.push(p); } } + + /// Insert a control point before point `at` (on the segment ending there) and select it; None when it can't + pub fn insert(&mut self, at: usize, p: Vec3) -> Option { + if at > self.points.len() || self.points.len() >= MAX_PATH_POINTS { + return None; + } + + self.points.insert(at, p); + self.selected = Some(at); + self.selected + } + + /// The same curve (points, open or closed, filled, view) as `other` + fn same_curve(&self, other: &PathState) -> bool { + (&self.points, self.closed, self.fill, self.uv) == (&other.points, other.closed, other.fill, other.uv) + } + + /// Empty the tool for the next path: no points, open, nothing selected or edited + pub fn clear(&mut self) { + self.points.clear(); + self.closed = false; + self.selected = None; + self.editing = None; + self.edited = false; + } + + /// Remove the selected control point, or the last one when none is selected + pub fn remove_selected(&mut self) { + let at = self.selected.take().filter(|i| *i < self.points.len()).or(self.points.len().checked_sub(1)); + if let Some(i) = at { + self.points.remove(i); + } + if self.closed && self.points.len() < 3 { + self.closed = false; + } + } } /// A path sublayer's pixels after painting its first paths (`below`), with the mesh and @@ -121,20 +171,21 @@ fn path(s: &mut Session, p: &Value) -> Result { if s.tool.tool != Tool::Path { set_tool(s, Tool::Path)?; } - let vp = viewport_of(s, p); + let viewport = viewport_of(s, p); if boolp(p, "clear") == Some(true) { - s.tool.path.points.clear(); - s.tool.path.editing = None; + s.cancel_path(); } + let placed = match (points_param(CMD, p, "points")?, points_param(CMD, p, "uvPoints")?) { - (Some(pts), _) => Some(( - pts.iter() + (Some(pixels), _) => Some(( + pixels + .iter() .enumerate() - .map(|(i, q)| s.pick(*q, vp).map(|h| h.pos).ok_or_else(|| bad(CMD, format!("point {i} misses the mesh")))) + .map(|(i, pixel)| s.pick(*pixel, viewport).map(|hit| hit.pos).ok_or_else(|| bad(CMD, format!("point {i} misses the mesh")))) .collect::>>()?, false, )), - (None, Some(pts)) => Some((pts.iter().map(|q| q.clamp(Vec2::ZERO, Vec2::ONE).extend(0.0)).collect(), true)), + (None, Some(uvs)) => Some((uvs.iter().map(|uv| uv.clamp(Vec2::ZERO, Vec2::ONE).extend(0.0)).collect(), true)), (None, None) => None, }; if let Some((points, uv)) = placed { @@ -151,19 +202,21 @@ fn path(s: &mut Session, p: &Value) -> Result { s.tool.path.fill = v; } s.revision = s.revision.wrapping_add(1); + let committed = if boolp(p, "commit") == Some(true) { - let r = s.commit_path(vp)?; + let report = s.commit_path(viewport)?; s.update(); - r + report } else { if s.path_live()? { s.update(); } Value::Null }; - let st = &s.tool.path; - let editing = st.editing.map(|(e, i)| json!({ "effect": e.0, "index": i })); - Ok(json!({ "points": st.points.len(), "uv": st.uv, "closed": st.closed, "fill": st.fill, "editing": editing, "committed": committed })) + + let path = &s.tool.path; + let editing = path.editing.map(|(e, i)| json!({ "effect": e.0, "index": i })); + Ok(json!({ "points": path.points.len(), "uv": path.uv, "closed": path.closed, "fill": path.fill, "editing": editing, "committed": committed })) } /// The `effect` and `index` params naming a stored path, with the path. @@ -181,12 +234,15 @@ fn edit_path(s: &mut Session, p: &Value) -> Result { const CMD: &str = "path.edit"; let (eid, index, shape) = path_ref(s, CMD, p)?; let paint = read_paint(&shape)?; + + s.finish_path()?; set_tool(s, Tool::Path)?; s.tool.brush = paint.brush; s.tool.values = paint.values; s.tool.enabled = paint.enabled; s.tool.mask_value = paint.mask_value; s.tool.path = PathState { editing: Some((eid, index)), ..state_of(&shape) }; + s.path_steps = Default::default(); s.target = StackTarget::Effect(eid); Ok(json!({ "effect": eid.0, "index": index, "points": s.tool.path.points.len() })) } @@ -216,10 +272,46 @@ fn read_paint(shape: &PathShape) -> Result { Ok(paint) } -/// The Path tool state showing a stored path (finite points only, at most [`MAX_PATH_POINTS`]). +/// The Path tool state showing a stored path (finite points only, at most [`MAX_PATH_POINTS`]) fn state_of(shape: &PathShape) -> PathState { let points = shape.points.iter().filter(|p| p.iter().all(|v| v.is_finite())).take(MAX_PATH_POINTS).map(|p| Vec3::from_array(*p)).collect(); - PathState { points, uv: shape.uv, closed: shape.closed, fill: shape.fill, editing: None, edited: false } + PathState { points, uv: shape.uv, closed: shape.closed, fill: shape.fill, ..PathState::default() } +} + +/// Tiles (x, y) where sublayer `eid`'s pixels differ between `before` and `after` (copy-on-write: an unchanged tile is the same allocation) +fn changed_tiles(before: &PixelStore, after: &PixelStore, eid: LayerId) -> BTreeSet<(u32, u32)> { + let (before_images, after_images) = (sublayer_images(before, eid), sublayer_images(after, eid)); + let channels: BTreeSet> = before_images.keys().chain(after_images.keys()).copied().collect(); + + let mut tiles = BTreeSet::new(); + for channel in channels { + let (before_image, after_image) = (before_images.get(&channel), after_images.get(&channel)); + let Some(image) = before_image.or(after_image) else { continue }; + for ty in 0..image.tiles_y() { + for tx in 0..image.tiles_x() { + let same = match (before_image.and_then(|i| i.tile_handle(tx, ty)), after_image.and_then(|i| i.tile_handle(tx, ty))) { + (None, None) => true, + (Some(before_tile), Some(after_tile)) => Arc::ptr_eq(before_tile, after_tile), + _ => false, + }; + if !same { + tiles.insert((tx, ty)); + } + } + } + } + tiles +} + +/// Sublayer `eid`'s images by channel (None: its mask image) +fn sublayer_images(pixels: &PixelStore, eid: LayerId) -> BTreeMap, &TileImage> { + let layers = pixels.layers.iter().filter(|((id, _), _)| *id == eid).map(|((_, channel), image)| (Some(*channel), image)); + layers.chain(pixels.masks.get(&eid).map(|mask| (None, mask))).collect() +} + +/// The camera and viewport a stored path paints through (the views draw its curve the same way) +fn paint_view(shape: &PathShape, paint: &PathPaint) -> (OrbitCamera, Vec2) { + (paint.camera, Vec2::from_array(shape.viewport).max(Vec2::splat(MIN_PAINT_VIEWPORT_PX)).min(Vec2::splat(MAX_PAINT_VIEWPORT_PX))) } /// NDC (y up) to viewport pixels (origin top-left). @@ -239,6 +331,11 @@ impl Session { path.points.iter().map(|p| self.camera.project(*p, aspect).map(|n| to_pixels(n.truncate(), viewport))).collect() } + /// The stored paths of path sublayer `eid` as Path tool states, for the views to draw + pub fn stored_path_states(&self, eid: LayerId) -> Vec { + self.paths(eid).unwrap_or_default().iter().map(state_of).collect() + } + /// The stored paths of path sublayer `eid` (None if it isn't one). pub fn paths(&self, eid: LayerId) -> Option<&[PathShape]> { match self.doc.project.effect(eid) { @@ -261,12 +358,32 @@ impl Session { } } - /// Store the Path tool's curve (a new path in the selected path sublayer, or in a new one; - /// or the path being edited) and repaint the sublayer, as one undo step. Clears the tool. + /// Store the Path tool's curve (new, or the path being edited) and repaint its sublayer as one undo step, then clear the tool pub fn commit_path(&mut self, viewport: Vec2) -> Result { let shape = self.path_shape(self.camera, viewport); + if let Some(draft) = self.path_draft.take() { + match self.tool.path.editing { + // The preview is what applying paints: keep its pixels + Some((eid, index)) if self.paths(eid).and_then(|v| v.get(index)) == Some(&shape) => { + self.push_step(NEW_PATH_LABEL, draft.base, false); + self.target = StackTarget::Effect(eid); + self.tool.path.clear(); + let mut out = draft.painted; + out["effect"] = json!(eid.0); + out["index"] = json!(index); + return Ok(out); + } + // Otherwise it paints again from the document before the preview + _ => { + let preview = std::mem::replace(&mut self.doc, draft.base); + self.changed_without_history(&preview); + self.tool.path.editing = None; + } + } + } + let editing = self.tool.path.editing; - let label = editing.map_or("Path".to_string(), |(_, i)| format!("Edit path {}", i + 1)); + let label = editing.map_or(NEW_PATH_LABEL.to_string(), |(_, i)| format!("Edit path {}", i + 1)); let out = self.edit_merging(&label, editing.is_some() && self.tool.path.edited, |s| { let (eid, index) = match editing { Some(at) => at, @@ -274,29 +391,34 @@ impl Session { }; s.put_path(eid, index, shape) })?; + if let Some(eid) = out.get("effect").and_then(Value::as_u64) { self.target = StackTarget::Effect(LayerId(eid)); } - self.tool.path.points.clear(); - self.tool.path.editing = None; + self.tool.path.clear(); Ok(out) } - /// While a stored path is edited, repaint its sublayer when the tool's points, brush or - /// material changed (orbiting or resizing the view alone doesn't), merged into one undo - /// step. Cheap when nothing changed; the UI calls it every frame. Returns whether it - /// repainted. + /// Repaint the edited path (one merged undo step) or a new path's preview (no step) when its points, brush or material changed; called every frame pub fn path_live(&mut self) -> Result { - let Some((eid, index)) = self.tool.path.editing else { return Ok(false) }; - let Some(stored) = self.paths(eid).and_then(|v| v.get(index)).cloned() else { - self.stop_path_edit(); - return Ok(false); + let stored = match self.tool.path.editing { + Some((eid, index)) => match self.paths(eid).and_then(|v| v.get(index)).cloned() { + Some(shape) => Some((eid, index, shape)), + None => { + self.stop_path_edit(); + return Ok(false); + } + }, + None => None, }; + let path = &self.tool.path; if self.tool.tool != Tool::Path || self.stroke.is_some() || path.points.is_empty() || (path.closed && path.fill && path.points.len() < 3) { return Ok(false); } - // Typed comparison: the stored settings went through JSON (f64), maybe a save and load. + let Some((eid, index, stored)) = stored else { return self.start_path_draft() }; + + // Typed comparison: the stored settings went through JSON (f64), maybe a save and load let unchanged = read_paint(&stored).is_ok_and(|p| { let now = self.path_shape(p.camera, Vec2::from_array(stored.viewport)); (&now.points, now.uv, now.closed, now.fill) == (&stored.points, stored.uv, stored.closed, stored.fill) && read_paint(&now).is_ok_and(|n| n == p) @@ -304,19 +426,111 @@ impl Session { if unchanged { return Ok(false); } + let shape = self.path_shape(self.camera, self.viewport); - self.edit_merging(&format!("Edit path {}", index + 1), self.tool.path.edited, |s| s.put_path(eid, index, shape))?; - self.tool.path.edited = true; + let (painted, before) = self.repaint_path(eid, index, shape)?; + match &mut self.path_draft { + Some(draft) => draft.painted = painted, + None => { + // The path's own repaint keeps its point changes undoable, unlike other steps + let steps = std::mem::take(&mut self.path_steps); + self.push_step(&format!("Edit path {}", index + 1), before, self.tool.path.edited); + self.path_steps = steps; + self.tool.path.edited = true; + } + } Ok(true) } - /// Stop editing a stored path (its changes are already applied) and clear the tool. - pub fn stop_path_edit(&mut self) { - if self.tool.path.editing.take().is_some() { - self.tool.path.points.clear(); + /// Paint a new path's first preview where [`Session::commit_path`] would add it, keeping the document before it for apply and cancel + fn start_path_draft(&mut self) -> Result { + let base = self.doc.clone(); + let shape = self.path_shape(self.camera, self.viewport); + let placed = self.path_effect().and_then(|eid| { + let index = self.paths(eid).map_or(0, <[_]>::len); + self.put_path(eid, index, shape).map(|painted| ((eid, index), painted)) + }); + match placed { + Ok((at, painted)) => { + // Placing a path is a new action: what was undone before can't be redone over it + self.redo.clear(); + self.tool.path.editing = Some(at); + self.changed_without_history(&base); + self.path_draft = Some(PathDraft { base, painted }); + Ok(true) + } + Err(e) => { + self.doc = base; + Err(e) + } } } + /// Remember the curve before a point change from a view, so undo steps back through those changes while the path is edited + pub fn path_checkpoint(&mut self) { + if !self.path_steps.0.last().is_some_and(|s| s.same_curve(&self.tool.path)) { + self.path_steps.0.push(self.tool.path.clone()); + self.path_steps.1.clear(); + } + } + + /// Whether [`Session::step_path`] would undo (`back`) or redo a point change + pub(crate) fn path_step_pending(&self, back: bool) -> bool { + let steps = if back { &self.path_steps.0 } else { &self.path_steps.1 }; + self.tool.tool == Tool::Path && steps.iter().any(|s| !s.same_curve(&self.tool.path)) + } + + /// Undo (`back`) or redo the edited path's last point change, false when there is none; with no points left the path is gone + pub(crate) fn step_path(&mut self, back: bool) -> bool { + if self.tool.tool != Tool::Path { + return false; + } + + let (from, to) = if back { (&mut self.path_steps.0, &mut self.path_steps.1) } else { (&mut self.path_steps.1, &mut self.path_steps.0) }; + // A checkpoint taken by a press that changed nothing isn't a step + while from.last().is_some_and(|s| s.same_curve(&self.tool.path)) { + from.pop(); + } + let Some(state) = from.pop() else { return false }; + + let path = &mut self.tool.path; + let now = std::mem::replace(path, PathState { editing: path.editing, edited: path.edited, ..state }); + to.push(now); + + if self.tool.path.points.is_empty() { + self.stop_path_edit(); + } + true + } + + /// Apply a new path being placed (as Enter would) and end the edit of a stored one, e.g. before the active texture set changes + pub fn finish_path(&mut self) -> Result<()> { + if self.path_draft.is_some() { + let viewport = self.viewport; + self.commit_path(viewport)?; + } + self.stop_path_edit(); + Ok(()) + } + + /// Cancel the Path tool's path: a new one's preview is removed, a stored one keeps its applied changes + pub fn cancel_path(&mut self) { + self.stop_path_edit(); + self.tool.path.clear(); + } + + /// Stop editing a stored path (its changes are already applied) and clear the tool; a new path's preview is removed + pub fn stop_path_edit(&mut self) { + if let Some(draft) = self.path_draft.take() { + let preview = std::mem::replace(&mut self.doc, draft.base); + self.changed_without_history(&preview); + } + if self.tool.path.editing.is_some() { + self.tool.path.clear(); + } + self.path_steps = Default::default(); + } + /// The selected path sublayer, or a new one on the selected layer's content or mask /// (whichever is selected). fn path_effect(&mut self) -> Result { @@ -346,6 +560,32 @@ impl Session { Ok(eid) } + /// [`Session::put_path`] recompositing only the tiles it changed, with no undo step: returns the paint report and the document before + fn repaint_path(&mut self, eid: LayerId, index: usize, shape: PathShape) -> Result<(Value, Document)> { + let before = self.doc.clone(); + let painted = match self.put_path(eid, index, shape) { + Ok(v) => v, + Err(e) => { + self.doc = before; + return Err(e); + } + }; + + // Paths paint into the active set; a sublayer in another set recomposites in full + let project = &self.doc.project; + let set = project.effect(eid).and_then(|(owner, _)| project.locate(owner)).map(|(ts, _, _)| ts); + if set == Some(self.ts()) { + // Content or mask, the sublayer's owner decides which sets redraw + let tiles = changed_tiles(&before.pixels, &self.doc.pixels, eid); + self.mark_painted(self.ts(), Some(PaintTarget::Layer(eid)), tiles); + } else { + self.invalidate_changed(&before); + } + self.revision = self.revision.wrapping_add(1); + self.modified = true; + Ok((painted, before)) + } + /// Replace path `index` of sublayer `eid` (append when out of range) and repaint the /// sublayer. Returns what painting that path reported, with the sublayer and index. fn put_path(&mut self, eid: LayerId, index: usize, shape: PathShape) -> Result { @@ -421,13 +661,40 @@ impl Session { fn paint_shape(&mut self, shape: &PathShape) -> Result { let paint = read_paint(shape)?; + let (camera, viewport) = paint_view(shape, &paint); self.tool.brush = paint.brush; self.tool.values = paint.values; self.tool.enabled = paint.enabled; self.tool.mask_value = paint.mask_value; - self.camera = paint.camera; + self.camera = camera; self.tool.path = state_of(shape); - self.paint_path(Vec2::from_array(shape.viewport).max(Vec2::splat(16.0)).min(Vec2::splat(16384.0))) + self.paint_path(viewport) + } + + /// Where a 3D path's curve lands on the mesh painted through `camera`, per segment as [`spline_segments`] (None off the mesh) + pub fn path_surface(&self, points: &[Vec3], closed: bool, camera: OrbitCamera, viewport: Vec2) -> Vec>> { + let aspect = viewport.x.max(1.0) / viewport.y.max(1.0); + let Some(screen) = points.iter().map(|p| camera.project(*p, aspect).map(|n| to_pixels(n.truncate(), viewport))).collect::>>() else { + return Vec::new(); + }; + + let ctx = PickCtx { mesh: &self.mesh, bvh: &self.bvh, camera: &camera, viewport }; + spline_segments(&screen, closed, SURFACE_STEP_PX) + .into_iter() + .zip(&screen) + .map(|(samples, first)| std::iter::once(*first).chain(samples).map(|q| pick(&ctx, q).map(|hit| hit.pos)).collect()) + .collect() + } + + /// [`Session::path_surface`] of a stored 3D path through the camera and viewport it paints with + pub fn stored_path_surface(&self, eid: LayerId, index: usize) -> Option>>> { + let shape = self.paths(eid)?.get(index)?; + if shape.uv { + return None; + } + let (camera, viewport) = paint_view(shape, &read_paint(shape).ok()?); + let path = state_of(shape); + Some(self.path_surface(&path.points, path.closed, camera, viewport)) } /// Paint the Path tool's curve with the current brush (or fill it when closed and filled) diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 36263560..d4b61a9d 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -347,6 +347,10 @@ pub struct Session { pub(crate) painting_paths: bool, /// Pixels of the paths below the one being edited, so live edits skip repainting them. pub(crate) path_cache: Option, + /// A new path's live preview: the path becomes an undo step only when it is applied + pub(crate) path_draft: Option, + /// Point changes of the path being edited: (earlier states for undo, undone states for redo) + pub(crate) path_steps: (Vec, Vec), pub path: Option, pub modified: bool, /// Bumps on every document change. @@ -363,8 +367,7 @@ pub struct Session { } impl Session { - /// A session for `project` on `mesh` (texture sets must reference mesh materials). The - /// UVs of UV-tiled sets are mapped into their tile atlas (see [`Session::source_mesh`]). + /// A session for `project` on `mesh` (its sets must reference mesh materials), with UV-tiled sets' UVs mapped into their atlas ([`Session::source_mesh`]) pub fn new(doc: Document, mesh: Mesh, mesh_source: Option<(String, Vec)>) -> Result { mesh.validate().map_err(|e| EngineError::Other(e.to_string()))?; let source = Arc::new(mesh); @@ -400,6 +403,8 @@ impl Session { quick_mask: Default::default(), painting_paths: false, path_cache: None, + path_draft: None, + path_steps: Default::default(), path: None, modified: false, revision: 1, @@ -513,24 +518,45 @@ impl Session { self.record(label, before, false); } - /// A change from `before` to the current document: a new undo step `label`, or with - /// `merge` part of the previous one when it has the same label. + /// A change from `before`: a new undo step `label`, or with `merge` part of the previous one when it has the same label fn record(&mut self, label: &str, before: Document, merge: bool) { + self.invalidate_changed(&before); + self.push_step(label, before, merge); + } + + /// [`Session::record`] for a change whose tiles the caller already marked for recompositing + pub(crate) fn push_step(&mut self, label: &str, before: Document, merge: bool) { + // Another change during a new path's preview makes the path its own step first + if !self.painting_paths + && let Some(draft) = self.path_draft.take() + { + self.undo.push((crate::path_tool::NEW_PATH_LABEL.to_string(), draft.base)); + } + + // Point changes of an edited path undo only until another step lands + if !self.painting_paths { + self.path_steps = Default::default(); + } self.modified = true; self.revision = self.revision.wrapping_add(1); - self.invalidate_changed(&before); if !(merge && self.undo.last().is_some_and(|(l, _)| l == label)) { self.undo.push((label.to_string(), before)); - if self.undo.len() > MAX_HISTORY { - self.undo.remove(0); - } } + let over = self.undo.len().saturating_sub(MAX_HISTORY); + self.undo.drain(..over); self.redo.clear(); } + /// A change from `other` to the current document that is not an undo step (a path preview) + pub(crate) fn changed_without_history(&mut self, other: &Document) { + self.modified = true; + self.revision = self.revision.wrapping_add(1); + self.invalidate_changed(other); + } + /// Mark dirty every texture set whose composite differs between `other` and the current /// document (after an edit, undo or redo). - fn invalidate_changed(&mut self, other: &Document) { + pub(crate) fn invalidate_changed(&mut self, other: &Document) { self.follow_uv_layouts(&other.project); self.sync_caches(); let resources = |d: &Document| d.resources.iter().map(|(n, b)| (n.clone(), Arc::as_ptr(b))).collect::>(); @@ -605,15 +631,21 @@ impl Session { } pub fn can_undo(&self) -> bool { - !self.undo.is_empty() + !self.undo.is_empty() || self.path_draft.is_some() || self.path_step_pending(true) } pub fn can_redo(&self) -> bool { - !self.redo.is_empty() + !self.redo.is_empty() || self.path_step_pending(false) } pub fn undo_label(&self) -> Option<&str> { + if self.path_draft.is_some() || self.path_step_pending(true) { + return Some(crate::path_tool::NEW_PATH_LABEL); + } self.undo.last().map(|(l, _)| l.as_str()) } pub fn redo_label(&self) -> Option<&str> { + if self.path_step_pending(false) { + return Some(crate::path_tool::NEW_PATH_LABEL); + } self.redo.last().map(|(l, _)| l.as_str()) } /// The undone steps, the next one to redo first. @@ -626,7 +658,19 @@ impl Session { pub fn undo(&mut self) -> Result { self.cancel_stroke(); - // An edited path would otherwise repaint over the restored document. + + // While a path is edited, undo steps back through its point changes first + if self.step_path(true) { + return Ok(crate::path_tool::NEW_PATH_LABEL.to_string()); + } + + // A path being placed isn't a step yet: undo removes it + if self.path_draft.is_some() { + self.stop_path_edit(); + return Ok(crate::path_tool::NEW_PATH_LABEL.to_string()); + } + + // An edited path would otherwise repaint over the restored document self.stop_path_edit(); let (label, doc) = self.undo.pop().ok_or_else(|| EngineError::Other("nothing to undo".into()))?; let now = std::mem::replace(&mut self.doc, doc); @@ -638,7 +682,12 @@ impl Session { pub fn redo(&mut self) -> Result { self.cancel_stroke(); - // An edited path would otherwise repaint over the restored document. + + if self.step_path(false) { + return Ok(crate::path_tool::NEW_PATH_LABEL.to_string()); + } + + // An edited path would otherwise repaint over the restored document self.stop_path_edit(); let (label, doc) = self.redo.pop().ok_or_else(|| EngineError::Other("nothing to redo".into()))?; let now = std::mem::replace(&mut self.doc, doc); diff --git a/crates/engine/src/set_cmds.rs b/crates/engine/src/set_cmds.rs index 1d9cc7f0..e9a77b96 100644 --- a/crates/engine/src/set_cmds.rs +++ b/crates/engine/src/set_cmds.rs @@ -77,6 +77,12 @@ pub(crate) fn ts_param(s: &Session, p: &Value, cmd: &str) -> Result { fn select(s: &mut Session, p: &Value) -> Result { let ts = u64p(p, "ts").map(|t| t as usize).filter(|t| *t < s.set_count()).ok_or_else(|| bad("textureSet.select", "valid `ts` index required"))?; s.cancel_stroke(); + + // Paths paint into the active set + if ts != s.ts() { + s.finish_path()?; + } + s.active_set = ts; s.target = StackTarget::Content; s.revision = s.revision.wrapping_add(1); diff --git a/crates/engine/tests/path_tool.rs b/crates/engine/tests/path_tool.rs index b053e979..429f506b 100644 --- a/crates/engine/tests/path_tool.rs +++ b/crates/engine/tests/path_tool.rs @@ -37,7 +37,7 @@ fn path_stroke_paints_along_the_curve() { let r = execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]]})).unwrap(); assert_eq!(r["points"], 3); assert_eq!(s.tool.tool, texturecraft_engine::Tool::Path); - assert!(!red_at(&s, 200.0, 180.0), "nothing painted before commit"); + assert!(red_at(&s, 200.0, 180.0), "the path is previewed before it is applied"); let r = execute(&mut s, "tool.path", &json!({"commit": true})).unwrap(); assert!(r["committed"]["stamps"].as_u64().unwrap() > 10, "{r}"); assert_eq!(r["points"], 0, "commit clears the path"); @@ -46,11 +46,11 @@ fn path_stroke_paints_along_the_curve() { } assert!(!red_at(&s, 200.0, 240.0), "below the curve"); assert!(!red_at(&s, 200.0, 130.0), "above the curve"); - // One undo step. + // One undo step execute(&mut s, "edit.undo", &Value::Null).unwrap(); s.update(); assert!(!red_at(&s, 200.0, 180.0)); - // Errors: no points, points off the mesh. + // Errors: no points, points off the mesh assert!(execute(&mut s, "tool.path", &json!({"commit": true})).is_err()); assert!(execute(&mut s, "tool.path", &json!({"points": [[2, 2]]})).is_err()); } @@ -278,3 +278,165 @@ fn each_path_and_each_edit_of_one_is_its_own_undo_step() { s.update(); assert!(red_at(&s, 200.0, 230.0), "undo brings back the first edit"); } + +/// The pixels of every path sublayer of the selected layer, comparable +fn path_pixels(s: &Session) -> Vec { + let ids: Vec = path_sublayers(s).into_iter().map(|(id, _)| id).collect(); + let mut v: Vec = s.doc.pixels.layers.iter().filter(|((id, _), _)| ids.contains(&id.0)).map(|(k, img)| format!("{k:?}{img:?}")).collect(); + v.sort(); + v +} + +#[test] +fn placing_points_previews_the_path_with_no_undo_step_until_it_is_applied() { + let points = json!([[140, 210], [200, 180], [260, 210]]); + let mut direct = session(primitives::sphere(1.0, 48, 24)); + execute(&mut direct, "tool.path", &json!({"points": points, "commit": true})).unwrap(); + + let mut s = session(primitives::sphere(1.0, 48, 24)); + let start = s.history_labels(); + execute(&mut s, "tool.path", &json!({"points": [[140, 280], [260, 280]]})).unwrap(); + assert!(red_at(&s, 200.0, 280.0)); + execute(&mut s, "tool.path", &json!({"points": points})).unwrap(); + assert!(red_at(&s, 200.0, 180.0) && !red_at(&s, 200.0, 280.0), "the preview follows the points"); + assert_eq!(s.history_labels(), start, "no undo step while placing"); + execute(&mut s, "tool.path", &json!({"commit": true})).unwrap(); + assert_eq!(s.history_labels().len(), start.len() + 1, "applying is one undo step"); + assert_eq!(s.undo_label(), Some("Path")); + assert_eq!(path_pixels(&s), path_pixels(&direct), "the same pixels as applying without a preview"); + + // Cancelling removes the preview + execute(&mut s, "tool.path", &json!({"points": [[140, 260], [200, 250], [260, 260]]})).unwrap(); + assert!(red_at(&s, 200.0, 250.0)); + execute(&mut s, "tool.path", &json!({"clear": true})).unwrap(); + s.update(); + assert!(!red_at(&s, 200.0, 250.0) && red_at(&s, 200.0, 180.0)); + assert_eq!(s.history_labels().len(), start.len() + 1); +} + +#[test] +fn undo_while_placing_removes_the_preview_only() { + let mut s = session(primitives::sphere(1.0, 48, 24)); + execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "commit": true})).unwrap(); + let steps = s.history_labels().len(); + execute(&mut s, "tool.path", &json!({"points": [[140, 260], [200, 250], [260, 260]]})).unwrap(); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + s.update(); + assert!(!red_at(&s, 200.0, 250.0), "the preview is gone"); + assert!(red_at(&s, 200.0, 180.0), "the applied path stays"); + assert_eq!(s.history_labels().len(), steps); + assert!(s.tool.path.points.is_empty() && s.tool.path.editing.is_none()); +} + +#[test] +fn another_change_while_placing_makes_the_path_its_own_step_first() { + let mut s = session(primitives::sphere(1.0, 48, 24)); + let steps = s.history_labels().len(); + execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]]})).unwrap(); + execute(&mut s, "layer.add.paint", &Value::Null).unwrap(); + let labels = s.history_labels(); + assert_eq!(labels.len(), steps + 2); + assert_eq!(labels.get(steps).map(String::as_str), Some("Path")); + // Undoing the other change keeps the path; undoing again removes it + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + s.update(); + assert!(red_at(&s, 200.0, 180.0)); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + s.update(); + assert!(!red_at(&s, 200.0, 180.0)); +} + +#[test] +fn editing_another_path_while_placing_applies_the_new_one() { + let mut s = session(primitives::sphere(1.0, 48, 24)); + let r = execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "commit": true})).unwrap(); + let eid = r["committed"]["effect"].as_u64().unwrap(); + execute(&mut s, "tool.path", &json!({"points": [[140, 260], [200, 250], [260, 260]]})).unwrap(); + execute(&mut s, "path.edit", &json!({"effect": eid, "index": 0})).unwrap(); + assert_eq!(path_sublayers(&s), vec![(eid, 2)], "the new path was applied"); + assert_eq!(s.undo_label(), Some("Path")); + assert_eq!(s.tool.path.editing, Some((texturecraft_engine::core::LayerId(eid), 0))); +} + +#[test] +fn the_next_path_starts_open_after_a_closed_one() { + let mut s = session(primitives::sphere(1.0, 48, 24)); + execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "closed": true, "commit": true})).unwrap(); + assert!(!s.tool.path.closed, "applying a closed path leaves the tool open for the next one"); + execute(&mut s, "tool.path", &json!({"points": [[140, 260], [200, 250], [260, 260]], "closed": true})).unwrap(); + execute(&mut s, "tool.path", &json!({"clear": true})).unwrap(); + assert!(!s.tool.path.closed, "cancelling does too"); +} + +/// A short path's repaint marks under 1/N of a 1024-texel set's 256 tiles +const SHORT_PATH_TILE_SHARE_DIVISOR: usize = 4; + +/// Move the middle point of the Path tool's curve down to viewport row `y` and repaint, returning the (dirty, all) tile counts +fn move_middle_point(s: &mut Session, y: f32) -> (usize, usize) { + s.tool.path.points[1] = s.pick(Vec2::new(200.0, y), s.viewport).unwrap().pos; + assert!(s.path_live().unwrap()); + (s.caches[0].dirty.len(), s.caches[0].covered_tiles.len()) +} + +#[test] +fn moving_a_point_recomposites_only_the_paths_tiles() { + // 1024 texels: 256 tiles, so a short path covers few of them + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:test", None, 1024).unwrap(); + s.viewport = Vec2::new(400.0, 400.0); + (s.camera.yaw, s.camera.pitch) = (0.0, 0.0); + execute(&mut s, "tool.brush", &json!({"size": 6})).unwrap(); + execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]]})).unwrap(); + s.update(); + + let (dirty, all) = move_middle_point(&mut s, 190.0); + assert!(dirty > 0 && dirty * SHORT_PATH_TILE_SHARE_DIVISOR < all, "a new path: {dirty} of {all} tiles to recomposite"); + s.update(); + + let r = execute(&mut s, "tool.path", &json!({"commit": true})).unwrap(); + execute(&mut s, "path.edit", &json!({"effect": r["committed"]["effect"], "index": 0})).unwrap(); + s.update(); + // Another row than the applied one, so the edit changes the path + let (dirty, all) = move_middle_point(&mut s, 200.0); + assert!(dirty > 0 && dirty * SHORT_PATH_TILE_SHARE_DIVISOR < all, "an applied path being edited: {dirty} of {all} tiles to recomposite"); +} + +#[test] +fn another_change_ends_the_point_undo_of_an_edited_path() { + let mut s = session(primitives::sphere(1.0, 48, 24)); + let r = execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "commit": true})).unwrap(); + let eid = texturecraft_engine::core::LayerId(r["committed"]["effect"].as_u64().unwrap()); + execute(&mut s, "path.edit", &json!({"effect": eid.0, "index": 0})).unwrap(); + s.path_checkpoint(); + s.tool.path.points[1] = s.pick(Vec2::new(200.0, 230.0), s.viewport).unwrap().pos; + assert!(s.path_live().unwrap()); + let moved: Vec<[f32; 3]> = s.tool.path.points.iter().map(|p| p.to_array()).collect(); + let layers = s.doc.project.layers.len(); + + execute(&mut s, "layer.add.paint", &Value::Null).unwrap(); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert_eq!(s.doc.project.layers.len(), layers, "undo removes the new layer"); + assert_eq!(s.paths(eid).unwrap()[0].points, moved, "the path keeps its moved point"); +} + +#[test] +fn placing_a_path_ends_redo() { + let mut s = session(primitives::sphere(1.0, 48, 24)); + execute(&mut s, "tool.path", &json!({"points": [[140, 210], [200, 180], [260, 210]], "commit": true})).unwrap(); + execute(&mut s, "edit.undo", &Value::Null).unwrap(); + assert!(s.can_redo()); + execute(&mut s, "tool.path", &json!({"points": [[140, 260], [200, 250], [260, 260]]})).unwrap(); + assert!(!s.can_redo(), "redo would throw the path being placed away"); +} + +#[test] +fn switching_texture_sets_applies_the_path_being_placed() { + let mut s = texturecraft_engine::sample_session(256, 64).unwrap(); + execute(&mut s, "layer.add.paint", &Value::Null).unwrap(); + let steps = s.history_labels().len(); + execute(&mut s, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.5, 0.45], [0.8, 0.5]]})).unwrap(); + + execute(&mut s, "textureSet.select", &json!({"ts": 1})).unwrap(); + assert_eq!(s.history_labels().len(), steps + 1); + assert_eq!(s.undo_label(), Some("Path")); + assert!(s.tool.path.points.is_empty() && s.tool.path.editing.is_none(), "the path no longer paints into the other set"); +} diff --git a/crates/paint/src/lib.rs b/crates/paint/src/lib.rs index c34415ed..aad8fbda 100644 --- a/crates/paint/src/lib.rs +++ b/crates/paint/src/lib.rs @@ -25,7 +25,7 @@ pub mod visibility; pub use brush::{Alignment, BrushAlpha, BrushSettings, Particles, Shape, Symmetry, image_alpha}; pub use commit::{CommitSource, Staging, TexelFn, commit_coverage, commit_layer, commit_mask}; -pub use path::{Lasso, spline}; +pub use path::{Lasso, spline, spline_segments}; pub use pickup::{Pickup, PickupMode}; pub use raster::{RasterCtx, StrokeCanvas, UvStamp, fill_coverage, fill_triangles, rasterize, rasterize_uv}; pub use stroke::{PickCtx, Stamp, Stroke, SurfaceHit, pick}; diff --git a/crates/paint/src/path.rs b/crates/paint/src/path.rs index fe483ee0..0075e411 100644 --- a/crates/paint/src/path.rs +++ b/crates/paint/src/path.rs @@ -6,12 +6,18 @@ use texturecraft_geom::glam::Vec2; /// Most samples per curve segment. const MAX_SEGMENT_SAMPLES: f32 = 1024.0; -/// A Catmull-Rom spline through `points`, sampled about every `step` units. Closed curves wrap -/// back to the first point; the result starts at the first point. +/// A Catmull-Rom spline through `points`, sampled about every `step` units, starting on the first point (closed curves end there too) pub fn spline(points: &[Vec2], closed: bool, step: f32) -> Vec { + let mut out: Vec = points.first().copied().into_iter().collect(); + out.extend(spline_segments(points, closed, step).into_iter().flatten()); + out +} + +/// [`spline`]'s samples per segment: segment `s` holds those after point `s`, up to and including the next point +pub fn spline_segments(points: &[Vec2], closed: bool, step: f32) -> Vec> { let n = points.len(); if n < 2 { - return points.to_vec(); + return Vec::new(); } let at = |i: isize| { let i = if closed { i.rem_euclid(n as isize) } else { i.clamp(0, n as isize - 1) }; @@ -19,17 +25,19 @@ pub fn spline(points: &[Vec2], closed: bool, step: f32) -> Vec { }; let step = if step.is_finite() && step > 1e-6 { step } else { 1.0 }; let segments = if closed { n } else { n - 1 } as isize; - let mut out = vec![at(0)]; - for s in 0..segments { - let (p0, p1, p2, p3) = (at(s - 1), at(s), at(s + 1), at(s + 2)); - let k = ((p2 - p1).length() / step).ceil().clamp(1.0, MAX_SEGMENT_SAMPLES) as usize; - for j in 1..=k { - let t = j as f32 / k as f32; - let (t2, t3) = (t * t, t * t * t); - out.push(0.5 * (2.0 * p1 + (p2 - p0) * t + (2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * t2 + (3.0 * p1 - p0 - 3.0 * p2 + p3) * t3)); - } - } - out + (0..segments) + .map(|s| { + let (p0, p1, p2, p3) = (at(s - 1), at(s), at(s + 1), at(s + 2)); + let k = ((p2 - p1).length() / step).ceil().clamp(1.0, MAX_SEGMENT_SAMPLES) as usize; + (1..=k) + .map(|j| { + let t = j as f32 / k as f32; + let (t2, t3) = (t * t, t * t * t); + 0.5 * (2.0 * p1 + (p2 - p0) * t + (2.0 * p0 - 5.0 * p1 + 4.0 * p2 - p3) * t2 + (3.0 * p1 - p0 - 3.0 * p2 + p3) * t3) + }) + .collect() + }) + .collect() } /// A closed polygon's coverage: 1 inside, 0 outside, a one-unit ramp across the edge. diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 21c87eb2..d3fd9f4b 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -74,7 +74,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Anisotropy level", "مستوى تباين الخواص"), ("Antialiasing", "تنعيم الحواف"), ("Aperture", "فتحة العدسة"), - ("Apply", "تطبيق"), ("ArtCraft website...", "موقع ArtCraft الإلكتروني..."), ("Assets", "الأصول"), ("Automatic (from the mesh UVs)", "تلقائي (من إحداثيات UV للمجسم)"), @@ -561,7 +560,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", "ارسم على المجسم لتعديل هذا القناع. استخدم قيمة القناع في لسان تبويب المادة للتدرج الرمادي.", ), - ("Paint the path with the brush (Enter)", "رسم المسار بالفرشاة (Enter)"), ("Paint with the current tool", "الرسم بالأداة الحالية"), ( "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", @@ -580,7 +578,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Paste layer(s)", "لصق الطبقة (الطبقات)"), ("Path", "مسار"), ("Path trace on the processor instead of the graphics card (slower)", "تتبع المسار على المعالج بدلاً من بطاقة الرسوميات (أبطأ)"), - ("Path: click adds a point, drag moves it, Enter applies, Esc cancels", "المسار: النقر يضيف نقطة، والسحب يحركها، وEnter يطبق، وEsc يلغي"), + ( + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "المسار: النقر يضيف نقطة، والنقر على المنحنى يُدرج نقطة، والسحب يحركها، وEnter يطبق، وEsc يلغي", + ), ("Pattern scale", "مقياس النمط"), ("Perlin noise", "ضوضاء بيرلن (Perlin)"), ("Pick focus in the viewport", "اختر نقطة التركيز في منفذ العرض"), @@ -627,8 +628,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer", "إزالة الطبقة"), ("Remove layer(s)", "إزالة الطبقة (الطبقات)"), ("Remove mask", "إزالة القناع"), + ("Remove point", "إزالة النقطة"), ("Remove resource", "إزالة المورد"), - ("Remove the path (Esc)", "إزالة المسار (Esc)"), ("Remove the shortcut", "إزالة الاختصار"), ("Remove this output", "إزالة هذا المخرج"), ("Remove unused resources...", "إزالة الموارد غير المستخدمة..."), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index ea536d5e..ff19c0c0 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -77,7 +77,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Anisotropy level", "Anisotropiestärke"), ("Antialiasing", "Kantenglättung"), ("Aperture", "Blende"), - ("Apply", "Anwenden"), ("ArtCraft website...", "ArtCraft-Website..."), ("Assets", "Assets"), ("Automatic (from the mesh UVs)", "Automatisch (aus den UVs des Meshs)"), @@ -594,7 +593,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", "Auf das Mesh malen, um diese Maske zu bearbeiten. Für Grau den Maskenwert im Tab Material verwenden.", ), - ("Paint the path with the brush (Enter)", "Pfad mit dem Pinsel malen (Eingabe)"), ("Paint with the current tool", "Mit dem aktuellen Werkzeug malen"), ( "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", @@ -617,8 +615,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Path", "Pfad"), ("Path trace on the processor instead of the graphics card (slower)", "Path Tracing auf dem Prozessor statt auf der Grafikkarte (langsamer)"), ( - "Path: click adds a point, drag moves it, Enter applies, Esc cancels", - "Pfad: Klicken fügt einen Punkt hinzu, Ziehen verschiebt ihn, Eingabe wendet an, Esc bricht ab", + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "Pfad: Klicken fügt einen Punkt hinzu, Klicken auf die Kurve fügt einen ein, Ziehen verschiebt ihn, Eingabe wendet an, Esc bricht ab", ), ("Pattern scale", "Musterskalierung"), ("Perlin noise", "Perlin-Rauschen"), @@ -666,8 +664,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer", "Ebene entfernen"), ("Remove layer(s)", "Ebene(n) entfernen"), ("Remove mask", "Maske entfernen"), + ("Remove point", "Punkt entfernen"), ("Remove resource", "Ressource entfernen"), - ("Remove the path (Esc)", "Pfad entfernen (Esc)"), ("Remove the shortcut", "Tastenkürzel entfernen"), ("Remove this output", "Diese Ausgabe entfernen"), ("Remove unused resources...", "Unbenutzte Ressourcen entfernen..."), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index de7c76e2..d38471eb 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -74,7 +74,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Anisotropy level", "Nivel de anisotropía"), ("Antialiasing", "Antialiasing"), ("Aperture", "Apertura"), - ("Apply", "Aplicar"), ("ArtCraft website...", "Sitio web de ArtCraft..."), ("Assets", "Recursos"), ("Automatic (from the mesh UVs)", "Automático (según las UV de la malla)"), @@ -585,7 +584,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", "Pinta sobre la malla para editar esta máscara. Usa el valor de máscara de la pestaña Material para el gris.", ), - ("Paint the path with the brush (Enter)", "Pintar el trazado con el pincel (Intro)"), ("Paint with the current tool", "Pintar con la herramienta actual"), ( "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", @@ -607,7 +605,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Paste layer(s)", "Pegar capa(s)"), ("Path", "Trazado"), ("Path trace on the processor instead of the graphics card (slower)", "Trazar trayectorias en el procesador en lugar de la tarjeta gráfica (más lento)"), - ("Path: click adds a point, drag moves it, Enter applies, Esc cancels", "Trazado: clic añade un punto, arrastrar lo mueve, Intro aplica, Esc cancela"), + ( + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "Trazado: clic añade un punto, clic en la curva inserta uno, arrastrar lo mueve, Intro aplica, Esc cancela", + ), ("Pattern scale", "Escala del patrón"), ("Perlin noise", "Ruido Perlin"), ("Pick focus in the viewport", "Elegir el enfoque en la ventana gráfica"), @@ -654,8 +655,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer", "Eliminar capa"), ("Remove layer(s)", "Eliminar capa(s)"), ("Remove mask", "Quitar máscara"), + ("Remove point", "Quitar punto"), ("Remove resource", "Quitar recurso"), - ("Remove the path (Esc)", "Quitar el trazado (Esc)"), ("Remove the shortcut", "Quitar el atajo"), ("Remove this output", "Quitar esta salida"), ("Remove unused resources...", "Quitar recursos no usados..."), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index fc4b8b11..fcebf4b9 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -80,7 +80,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Anisotropy level", "Niveau d'anisotropie"), ("Antialiasing", "Anticrénelage"), ("Aperture", "Ouverture"), - ("Apply", "Appliquer"), ("ArtCraft website...", "Site web d'ArtCraft..."), ("Assets", "Ressources"), ("Automatic (from the mesh UVs)", "Automatique (d'après les UV du maillage)"), @@ -600,7 +599,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", "Peignez sur le maillage pour modifier ce masque. Utilisez la valeur de masque de l'onglet Matériau pour le gris.", ), - ("Paint the path with the brush (Enter)", "Peindre le tracé avec le pinceau (Enter)"), ("Paint with the current tool", "Peindre avec l'outil actuel"), ( "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", @@ -622,7 +620,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Paste layer(s)", "Coller le(s) calque(s)"), ("Path", "Tracé"), ("Path trace on the processor instead of the graphics card (slower)", "Tracé de chemins sur le processeur au lieu de la carte graphique (plus lent)"), - ("Path: click adds a point, drag moves it, Enter applies, Esc cancels", "Tracé : cliquer ajoute un point, glisser le déplace, Enter applique, Esc annule"), + ( + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "Tracé : cliquer ajoute un point, cliquer sur la courbe en insère un, glisser le déplace, Enter applique, Esc annule", + ), ("Pattern scale", "Échelle du motif"), ("Perlin noise", "Bruit de Perlin"), ("Pick focus in the viewport", "Choisir la mise au point dans la fenêtre d'affichage"), @@ -669,8 +670,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer", "Supprimer le calque"), ("Remove layer(s)", "Supprimer le(s) calque(s)"), ("Remove mask", "Supprimer le masque"), + ("Remove point", "Retirer le point"), ("Remove resource", "Supprimer la ressource"), - ("Remove the path (Esc)", "Supprimer le tracé (Esc)"), ("Remove the shortcut", "Supprimer le raccourci"), ("Remove this output", "Supprimer cette sortie"), ("Remove unused resources...", "Supprimer les ressources inutilisées..."), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 67648219..a22e34ae 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -77,7 +77,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Anisotropy level", "Livello anisotropia"), ("Antialiasing", "Antialiasing"), ("Aperture", "Apertura"), - ("Apply", "Applica"), ("ArtCraft website...", "Sito web di ArtCraft..."), ("Assets", "Risorse"), ("Automatic (from the mesh UVs)", "Automatico (dagli UV della mesh)"), @@ -591,7 +590,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", "Dipingi sulla mesh per modificare questa maschera. Usa il valore maschera della scheda Materiale per il grigio.", ), - ("Paint the path with the brush (Enter)", "Dipingi il tracciato con il pennello (Invio)"), ("Paint with the current tool", "Dipingi con lo strumento corrente"), ( "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", @@ -614,8 +612,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Path", "Tracciato"), ("Path trace on the processor instead of the graphics card (slower)", "Esegui il path tracing sul processore anziché sulla scheda grafica (più lento)"), ( - "Path: click adds a point, drag moves it, Enter applies, Esc cancels", - "Tracciato: clic aggiunge un punto, trascina lo sposta, Invio applica, Esc annulla", + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "Tracciato: clic aggiunge un punto, clic sulla curva ne inserisce uno, trascina lo sposta, Invio applica, Esc annulla", ), ("Pattern scale", "Scala motivo"), ("Perlin noise", "Rumore Perlin"), @@ -663,8 +661,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer", "Rimuovi livello"), ("Remove layer(s)", "Rimuovi livello/i"), ("Remove mask", "Rimuovi maschera"), + ("Remove point", "Rimuovi punto"), ("Remove resource", "Rimuovi risorsa"), - ("Remove the path (Esc)", "Rimuovi il tracciato (Esc)"), ("Remove the shortcut", "Rimuovi la scorciatoia"), ("Remove this output", "Rimuovi questo output"), ("Remove unused resources...", "Rimuovi risorse inutilizzate..."), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index dfbe8a65..b44388e3 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -80,7 +80,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Anisotropy level", "異方性レベル"), ("Antialiasing", "アンチエイリアス"), ("Aperture", "絞り"), - ("Apply", "適用"), ("ArtCraft website...", "ArtCraft ウェブサイト..."), ("Assets", "アセット"), ("Automatic (from the mesh UVs)", "自動 (メッシュのUVから)"), @@ -579,7 +578,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", "メッシュにペイントしてこのマスクを編集します。グレーには「マテリアル」タブのマスク値を使用します。", ), - ("Paint the path with the brush (Enter)", "ブラシでパスをペイント (Enter)"), ("Paint with the current tool", "現在のツールでペイント"), ( "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", @@ -598,7 +596,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Paste layer(s)", "レイヤーを貼り付け"), ("Path", "パス"), ("Path trace on the processor instead of the graphics card (slower)", "グラフィックカードではなくプロセッサーでパストレース (低速)"), - ("Path: click adds a point, drag moves it, Enter applies, Esc cancels", "パス: クリックでポイントを追加、ドラッグで移動、Enterで適用、Escでキャンセル"), + ( + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "パス: クリックでポイントを追加、カーブをクリックで挿入、ドラッグで移動、Enterで適用、Escでキャンセル", + ), ("Pattern scale", "パターンのスケール"), ("Perlin noise", "パーリンノイズ"), ("Pick focus in the viewport", "ビューポートでフォーカスを指定"), @@ -645,8 +646,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer", "レイヤーを削除"), ("Remove layer(s)", "レイヤーを削除"), ("Remove mask", "マスクを削除"), + ("Remove point", "ポイントを削除"), ("Remove resource", "リソースを削除"), - ("Remove the path (Esc)", "パスを削除 (Esc)"), ("Remove the shortcut", "ショートカットを削除"), ("Remove this output", "この出力を削除"), ("Remove unused resources...", "未使用のリソースを削除..."), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index f81cfe6d..34293f2b 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -77,7 +77,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Anisotropy level", "이방성 레벨"), ("Antialiasing", "안티앨리어싱"), ("Aperture", "조리개"), - ("Apply", "적용"), ("ArtCraft website...", "ArtCraft 웹사이트..."), ("Assets", "에셋"), ("Automatic (from the mesh UVs)", "자동 (메시 UV 기준)"), @@ -570,7 +569,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", "메시에 칠하여 이 마스크를 편집합니다. 회색은 머티리얼 탭의 마스크 값을 사용하세요.", ), - ("Paint the path with the brush (Enter)", "브러시로 패스를 칠합니다 (Enter)"), ("Paint with the current tool", "현재 도구로 페인팅"), ( "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", @@ -589,7 +587,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Paste layer(s)", "레이어 붙여넣기"), ("Path", "패스"), ("Path trace on the processor instead of the graphics card (slower)", "그래픽 카드 대신 프로세서에서 패스 트레이싱합니다 (더 느림)"), - ("Path: click adds a point, drag moves it, Enter applies, Esc cancels", "패스: 클릭으로 점 추가, 드래그로 이동, Enter로 적용, Esc로 취소"), + ( + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "패스: 클릭으로 점 추가, 곡선 클릭으로 점 삽입, 드래그로 이동, Enter로 적용, Esc로 취소", + ), ("Pattern scale", "패턴 스케일"), ("Perlin noise", "펄린 노이즈"), ("Pick focus in the viewport", "뷰포트에서 초점 선택"), @@ -636,8 +637,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer", "레이어 제거"), ("Remove layer(s)", "레이어 제거"), ("Remove mask", "마스크 제거"), + ("Remove point", "점 제거"), ("Remove resource", "리소스 제거"), - ("Remove the path (Esc)", "패스를 제거합니다 (Esc)"), ("Remove the shortcut", "단축키를 제거합니다"), ("Remove this output", "이 출력을 제거합니다"), ("Remove unused resources...", "사용하지 않는 리소스 제거..."), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 7bd3d231..317410ce 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -77,7 +77,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Anisotropy level", "Nível de anisotropia"), ("Antialiasing", "Antisserrilhamento"), ("Aperture", "Abertura"), - ("Apply", "Aplicar"), ("ArtCraft website...", "Site da ArtCraft..."), ("Assets", "Recursos"), ("Automatic (from the mesh UVs)", "Automático (das UVs da malha)"), @@ -582,7 +581,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", "Pinte na malha para editar esta máscara. Use o valor de máscara da aba Material para cinza.", ), - ("Paint the path with the brush (Enter)", "Pintar o caminho com o pincel (Enter)"), ("Paint with the current tool", "Pintar com a ferramenta atual"), ( "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", @@ -604,7 +602,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Paste layer(s)", "Colar camada(s)"), ("Path", "Caminho"), ("Path trace on the processor instead of the graphics card (slower)", "Fazer path tracing no processador em vez da placa de vídeo (mais lento)"), - ("Path: click adds a point, drag moves it, Enter applies, Esc cancels", "Caminho: clicar adiciona um ponto, arrastar o move, Enter aplica, Esc cancela"), + ( + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "Caminho: clicar adiciona um ponto, clicar na curva insere um, arrastar o move, Enter aplica, Esc cancela", + ), ("Pattern scale", "Escala do padrão"), ("Perlin noise", "Ruído Perlin"), ("Pick focus in the viewport", "Escolher o foco na viewport"), @@ -651,8 +652,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer", "Remover camada"), ("Remove layer(s)", "Remover camada(s)"), ("Remove mask", "Remover máscara"), + ("Remove point", "Remover ponto"), ("Remove resource", "Remover recurso"), - ("Remove the path (Esc)", "Remover o caminho (Esc)"), ("Remove the shortcut", "Remover o atalho"), ("Remove this output", "Remover esta saída"), ("Remove unused resources...", "Remover recursos não usados..."), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 7d393f75..0fea6a3a 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -68,7 +68,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Anisotropy level", "各向异性强度"), ("Antialiasing", "抗锯齿"), ("Aperture", "光圈"), - ("Apply", "应用"), ("ArtCraft website...", "ArtCraft 网站..."), ("Assets", "资产"), ("Automatic (from the mesh UVs)", "自动(基于网格 UV)"), @@ -531,7 +530,6 @@ pub const TABLE: &[(&str, &str)] = &[ ("Paint chips", "掉漆"), ("Paint on the mesh to edit the layer content.", "在网格上绘画以编辑图层内容。"), ("Paint on the mesh to edit this mask. Use the Material tab's mask value for gray.", "在网格上绘画以编辑此遮罩。灰度请使用“材质”选项卡中的遮罩值。"), - ("Paint the path with the brush (Enter)", "用笔刷绘制路径(Enter)"), ("Paint with the current tool", "使用当前工具绘画"), ( "Painted layer pixels {pixels} MB, composited channels {composites} MB, compositing cache {cache} MB", @@ -550,7 +548,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Paste layer(s)", "粘贴图层"), ("Path", "路径"), ("Path trace on the processor instead of the graphics card (slower)", "在处理器而非显卡上进行路径追踪(较慢)"), - ("Path: click adds a point, drag moves it, Enter applies, Esc cancels", "路径:单击添加点,拖动移动点,Enter 应用,Esc 取消"), + ( + "Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels", + "路径:单击添加点,单击曲线插入点,拖动移动点,Enter 应用,Esc 取消", + ), ("Pattern scale", "图案缩放"), ("Perlin noise", "柏林噪波"), ("Pick focus in the viewport", "在视口中拾取焦点"), @@ -597,8 +598,8 @@ pub const TABLE: &[(&str, &str)] = &[ ("Remove layer", "移除图层"), ("Remove layer(s)", "移除图层"), ("Remove mask", "移除遮罩"), + ("Remove point", "移除点"), ("Remove resource", "移除资源"), - ("Remove the path (Esc)", "移除路径(Esc)"), ("Remove the shortcut", "移除快捷键"), ("Remove this output", "移除此输出"), ("Remove unused resources...", "移除未使用的资源..."), diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5b5045e6..91194620 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -20,6 +20,7 @@ mod mask_preview_image; mod mask_shape; pub mod menus; pub mod parity; +mod path_hit; mod preview_image; mod preview_request; mod preview_worker; @@ -508,7 +509,7 @@ impl eframe::App for TextureCraftApp { self.poll_bake(ctx); self.poll_resize(ctx); self.poll_link_cooks(ctx); - // The library shelf rescans when the window comes back (MaterialCraft may have sent a material). + // The library shelf rescans when the window comes back (MaterialCraft may have sent a material) let focused = ctx.input(|i| i.viewport().focused).unwrap_or(true); if focused && !self.focused { self.library = None; @@ -528,9 +529,9 @@ impl eframe::App for TextureCraftApp { } self.fonts.update(ctx, i18n::current().code, self.ui.windows.settings); menus::shortcuts(self, ctx); - // A stored path being edited repaints its sublayer as its points, brush or material change. + // The Path tool's curve repaints (a preview while placed) as its points, brush or material change if let Err(e) = self.session.path_live() { - self.session.stop_path_edit(); + self.session.cancel_path(); self.toast(e.to_string(), true); } profile::drive(self, ctx); @@ -553,7 +554,7 @@ impl eframe::App for TextureCraftApp { } let hide = self.ui.hide_ui; let tk = theme::Tokens::get(&ctx); - // The dock keeps the cards' gutter from the bars and rails around it. + // The dock keeps the cards' gutter from the bars and rails around it let frame = if hide { egui::Frame::NONE.fill(tk.viewport) } else { egui::Frame::NONE.fill(tk.chrome).inner_margin(theme::GUTTER) }; egui::CentralPanel::default().frame(frame).show(ui, |ui| if hide { viewport::central(self, ui) } else { docking::show(self, ui) }); windows::show(self, &ctx); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index b74aa300..dff70ca7 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -341,8 +341,7 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { app.properties_popup = None; } else if app.ui.mode == Mode::Painting && input.consume_key(Modifiers::NONE, Key::Escape) { app.session.cancel_stroke(); - app.session.tool.path.points.clear(); - app.session.tool.path.editing = None; + app.session.cancel_path(); } }); diff --git a/crates/ui-egui/src/path_hit.rs b/crates/ui-egui/src/path_hit.rs new file mode 100644 index 00000000..6b62f0f0 --- /dev/null +++ b/crates/ui-egui/src/path_hit.rs @@ -0,0 +1,17 @@ +//! What a pointer position in a view is over, for the Path tool + +use egui::Pos2; +use texturecraft_engine::core::LayerId; + +/// What a pointer position in a view is over, for the Path tool +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum PathHit { + /// A control point of the path being edited + Point(usize), + /// The edited path's curve: the segment starting at this point, and the nearest screen position on it + Curve(usize, Pos2), + /// Another stored path of the selected layer: (path sublayer, index) + Stored(LayerId, usize), + /// Nothing of a path + Miss, +} diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index eee357f7..9cc550ae 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -320,25 +320,21 @@ fn mode_buttons(app: &mut TextureCraftApp, ui: &mut egui::Ui) { /// Path tool options and actions (top bar and properties) pub fn path_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui) { let button_size = ui.spacing().interact_size.y; - let path = &mut app.session.tool.path; - if icon_button(ui, ic::POLYGON, tr("Closed path"), path.closed, button_size).clicked() { - path.closed = !path.closed; + let path = &app.session.tool.path; + let (closed, fill) = (path.closed, path.fill); + let selected = path.selected.is_some_and(|i| i < path.points.len()); + if icon_button(ui, ic::POLYGON, tr("Closed path"), closed, button_size).clicked() { + app.session.path_checkpoint(); + app.session.tool.path.closed = !closed; } - let fill_tip = if path.closed { tr("Fill the closed path (lasso)") } else { tr("Fill the path (close it first)") }; - if icon_button(ui, ic::PAINT_BUCKET, fill_tip, path.fill, button_size).clicked() { - path.fill = !path.fill; + let fill_tip = if closed { tr("Fill the closed path (lasso)") } else { tr("Fill the path (close it first)") }; + if icon_button(ui, ic::PAINT_BUCKET, fill_tip, fill, button_size).clicked() { + app.session.path_checkpoint(); + app.session.tool.path.fill = !fill; } - - let has_points = !path.points.is_empty(); - if ui - .add_enabled(has_points, egui::Button::new(format!("{} {}", ic::CHECK, tr("Apply")))) - .on_hover_text(tr("Paint the path with the brush (Enter)")) - .clicked() - { - app.run("tool.path", json!({"commit": true})); - } - if ui.add_enabled(has_points, egui::Button::new(format!("{} {}", ic::X, tr("Cancel")))).on_hover_text(tr("Remove the path (Esc)")).clicked() { - app.run("tool.path", json!({"clear": true})); + if ui.add_enabled_ui(selected, |ui| icon_button(ui, ic::BACKSPACE, tr("Remove point"), false, button_size)).inner.clicked() { + app.session.path_checkpoint(); + app.session.tool.path.remove_selected(); } } diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index f20210d4..ff8c2ae8 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -1,7 +1,7 @@ //! The 3D viewport and the 2D UV view: navigation, painting input, brush cursor and the GPU //! callbacks that render them. -use std::sync::Mutex; +use std::sync::{Arc, Mutex}; use egui::emath::GuiRounding as _; use egui::{Color32, PointerButton, Pos2, Rect, Sense, Stroke, Ui, pos2, vec2}; @@ -15,6 +15,7 @@ use texturecraft_render::{Frame, SetHighlight, Shade, ViewKind}; use crate::TextureCraftApp; use crate::gpu::ViewCallback; use crate::i18n::{tr, trf}; +use crate::path_hit::PathHit; use crate::state::ViewLayout; use crate::theme::Tokens; use crate::toolbar::{MAX_BRUSH_SIZE, MIN_BRUSH_SIZE}; @@ -576,7 +577,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin let viewport = app.session.viewport; let show = |app: &TextureCraftApp, point: Vec3| project(app, rect, point); if painting && path_tool { - path_input(app, ui, &response, false, |app, pointer| app.session.pick(local(pointer), viewport).map(|hit| hit.pos), show); + path_input(app, ui, &response, (rect, false), |app, pointer| app.session.pick(local(pointer), viewport).map(|hit| hit.pos), show); } else if painting { let pressure = pen_pressure(ui); if response.drag_started_by(PointerButton::Primary) || response.clicked_by(PointerButton::Primary) { @@ -630,6 +631,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && !navigating && response.hovered() && brush_tool(app.session.tool.tool) + && (app.session.tool.tool != Tool::Path || adjusting) && let Some(hover_pos) = if adjusting { ui.input(|input| input.pointer.press_origin()) } else { response.hover_pos() } && let Some(hit) = app.session.pick(local(hover_pos), app.session.viewport) { @@ -646,7 +648,7 @@ fn view_3d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin && !path_tool && let Some(from) = app.last_paint_point { - rubber_band(ui, rect, pos2(rect.left() + from.x, rect.top() + from.y), hover_pos); + rubber_band(ui, rect, &[pos2(rect.left() + from.x, rect.top() + from.y), hover_pos]); } } @@ -897,11 +899,42 @@ fn project(app: &TextureCraftApp, rect: Rect, p: Vec3) -> Option { Some(pos2(rect.left() + (n.x * 0.5 + 0.5) * rect.width(), rect.top() + (0.5 - n.y * 0.5) * rect.height())) } -/// Control point grab radius (points). +/// Control point and curve grab radius (points) const HANDLE_GRAB: f32 = 8.0; +/// Opacity of the selected layer's other stored paths +const PATH_STORED_OPACITY: f32 = 0.55; +/// Opacity of a curve where the mesh hides it +const PATH_HIDDEN_OPACITY: f32 = 0.5; +/// A control point counts as hidden when the surface under it is this much closer (relative) +const PATH_HIDDEN_DEPTH: f32 = 0.01; +/// The Path tool's pointer glyph size (points) +const PATH_CURSOR_SIZE: f32 = 18.0; +/// A path's line and the dark outline under it (points) +const PATH_LINE_WIDTH: f32 = 1.4; +const PATH_OUTLINE_WIDTH: f32 = 3.0; +/// Where the view hint sits from the view's bottom left corner, and its text size (points) +const PATH_HINT_OFFSET: egui::Vec2 = vec2(56.0, -12.0); +const PATH_HINT_FONT_SIZE: f32 = 12.0; +/// The pen pointer's drop shadow, and the space before its insert plus (points) +const PATH_CURSOR_SHADOW_OFFSET: egui::Vec2 = vec2(1.0, 1.0); +const PATH_CURSOR_PLUS_GAP: f32 = 1.0; +/// Dash and gap lengths of a line still to be painted (points) +const RUBBER_BAND_DASH: f32 = 6.0; +const RUBBER_BAND_GAP: f32 = 4.0; +/// The insert plus beside the pen pointer, relative to the pen's size +const PATH_CURSOR_PLUS_SCALE: f32 = 0.6; +/// Space kept right of the view hint, and its narrowest wrap width (points) +const PATH_HINT_MARGIN: f32 = 8.0; +const PATH_HINT_MIN_WIDTH: f32 = 80.0; +/// How much a control point marker grows under the pointer, and when selected (points) +const PATH_POINT_HOVER_GROWTH: f32 = 1.5; +const PATH_POINT_SELECTED_GROWTH: f32 = 0.5; +/// Control point marker radius (points) +const PATH_POINT_RADIUS: f32 = 3.0; +/// Curve sampling step on screen (points) +const PATH_SCREEN_STEP: f32 = 3.0; -/// Path tool keys: Enter applies the path, Backspace removes its last point (Esc, handled with -/// the global shortcuts, cancels it). +/// Path tool keys: Enter applies the path, Backspace removes the selected (or last) point; Esc is a global shortcut fn path_keys(app: &mut TextureCraftApp, ui: &Ui) { if app.ui.mode != crate::state::Mode::Painting || app.session.tool.tool != Tool::Path @@ -915,19 +948,123 @@ fn path_keys(app: &mut TextureCraftApp, ui: &Ui) { app.run("tool.path", json!({"commit": true})); } if back { - app.session.tool.path.points.pop(); + app.session.path_checkpoint(); + app.session.tool.path.remove_selected(); } } -/// Path tool input in a view (`uv`: the 2D view). Pressing on a control point drags it, -/// elsewhere adds a point (and drags it); clicking the first point of an open path closes it. -/// `place` maps a pointer position to a path point (None off the surface), `show` a path point -/// to the screen. +/// The selected layer's stored paths except the edited one: (path sublayer, index, path) +fn other_paths(app: &TextureCraftApp) -> Vec<(texturecraft_engine::core::LayerId, usize, texturecraft_engine::PathState)> { + let s = &app.session; + let Some(layer) = s.selected_layer().and_then(|id| s.doc.project.layer(id).ok()) else { return Vec::new() }; + let effects = layer.content_effects.iter().chain(layer.mask.iter().flat_map(|m| m.effects.iter())); + effects + .flat_map(|e| s.stored_path_states(e.id).into_iter().enumerate().map(move |(i, path)| (e.id, i, path))) + .filter(|(e, i, _)| s.tool.path.editing != Some((*e, *i))) + .collect() +} + +/// The screen curve through `points` per segment, each starting on its first point +fn screen_segments(points: &[Pos2], closed: bool) -> Vec> { + let pts: Vec = points.iter().map(|p| Vec2::new(p.x, p.y)).collect(); + texturecraft_engine::paint::spline_segments(&pts, closed, PATH_SCREEN_STEP) + .into_iter() + .zip(points) + .map(|(samples, first)| std::iter::once(*first).chain(samples.into_iter().map(|v| pos2(v.x, v.y))).collect()) + .collect() +} + +/// A path's curve in a view per segment: screen position and whether the mesh leaves it visible (None off the mesh or screen) +type ScreenCurve = Vec>>; + +/// A 3D path's curve on the mesh, per segment ([`texturecraft_engine::Session::path_surface`]) +type SurfaceCurve = Arc>>>; + +/// The nearest segment of `curve` within grab distance of `at`, with the nearest position on it +fn segment_near(curve: &ScreenCurve, at: Pos2) -> Option<(usize, Pos2)> { + let nearest = |segment: &Vec>| { + segment.windows(2).filter_map(|w| Some(closest_on_line(w[0]?.0, w[1]?.0, at))).min_by(|a, b| a.distance(at).total_cmp(&b.distance(at))) + }; + curve + .iter() + .enumerate() + .filter_map(|(i, segment)| nearest(segment).map(|p| (i, p))) + .filter(|(_, p)| p.distance(at) < HANDLE_GRAB) + .min_by(|a, b| a.1.distance(at).total_cmp(&b.1.distance(at))) +} + +/// `path`'s curve in a view; a 3D curve lies where its paint lands, and without `depth_test` (hit tests) every sample counts as visible +fn curve_on_screen( + app: &TextureCraftApp, + ui: &Ui, + (rect, uv, depth_test): (Rect, bool, bool), + path: &texturecraft_engine::PathState, + stored: Option<(texturecraft_engine::core::LayerId, usize)>, + show: &impl Fn(&TextureCraftApp, Vec3) -> Option, +) -> ScreenCurve { + if uv { + let Some(points) = path.points.iter().map(|p| show(app, *p)).collect::>>() else { return Vec::new() }; + return screen_segments(&points, path.closed).into_iter().map(|segment| segment.into_iter().map(|at| Some((at, true))).collect()).collect(); + } + let s = &app.session; + let surface = stored + .and_then(|(eid, index)| stored_surface(app, ui, eid, index)) + .unwrap_or_else(|| Arc::new(s.path_surface(&path.points, path.closed, s.camera, s.viewport))); + surface + .iter() + .map(|segment| segment.iter().map(|p| p.and_then(|p| show(app, p).map(|at| (at, !depth_test || path_point_visible(app, rect, p, at))))).collect()) + .collect() +} + +/// [`texturecraft_engine::Session::stored_path_surface`], kept until the path or the mesh changes +fn stored_surface(app: &TextureCraftApp, ui: &Ui, eid: texturecraft_engine::core::LayerId, index: usize) -> Option { + let key = (app.session.mesh_id, app.session.paths(eid)?.get(index)?.clone()); + let id = egui::Id::unique(("path_surface", eid.0, index)); + if let Some((cached, surface)) = ui.data(|d| d.get_temp::<((u64, texturecraft_engine::core::PathShape), SurfaceCurve)>(id)) + && cached == key + { + return Some(surface); + } + let surface = Arc::new(app.session.stored_path_surface(eid, index)?); + ui.data_mut(|d| d.insert_temp(id, (key, surface.clone()))); + Some(surface) +} + +/// The point of the segment `a`–`b` nearest to `p` +fn closest_on_line(a: Pos2, b: Pos2, p: Pos2) -> Pos2 { + let ab = b - a; + let t = if ab.length_sq() > 0.0 { ((p - a).dot(ab) / ab.length_sq()).clamp(0.0, 1.0) } else { 0.0 }; + a + ab * t +} + +/// What `at` is over in a view (`uv`: the 2D view); `show` maps a path point to the screen +fn path_hit(app: &TextureCraftApp, ui: &Ui, (rect, uv): (Rect, bool), at: Pos2, show: &impl Fn(&TextureCraftApp, Vec3) -> Option) -> PathHit { + let path = &app.session.tool.path; + if path.uv == uv { + if let Some(i) = path.points.iter().position(|p| show(app, *p).is_some_and(|s| s.distance(at) < HANDLE_GRAB)) { + return PathHit::Point(i); + } + if let Some((i, on)) = segment_near(&curve_on_screen(app, ui, (rect, uv, false), path, path.editing, show), at) { + return PathHit::Curve(i, on); + } + } + for (eid, i, other) in other_paths(app) { + if other.uv == uv + && (other.points.iter().any(|p| show(app, *p).is_some_and(|s| s.distance(at) < HANDLE_GRAB)) + || segment_near(&curve_on_screen(app, ui, (rect, uv, false), &other, Some((eid, i)), show), at).is_some()) + { + return PathHit::Stored(eid, i); + } + } + PathHit::Miss +} + +/// Path tool presses in a view: select and drag a point, insert on the curve, open another path, close on the first point, or add a point fn path_input( app: &mut TextureCraftApp, ui: &Ui, resp: &egui::Response, - uv: bool, + (rect, uv): (Rect, bool), place: impl Fn(&TextureCraftApp, Pos2) -> Option, show: impl Fn(&TextureCraftApp, Vec3) -> Option, ) { @@ -937,24 +1074,48 @@ fn path_input( && let Some(at) = ui.input(|i| i.pointer.press_origin()).or(resp.interact_pointer_pos()) { let path = &app.session.tool.path; - let near = if path.uv == uv { path.points.iter().position(|p| show(app, *p).is_some_and(|s| s.distance(at) < HANDLE_GRAB)) } else { None }; - match near { - Some(0) if clicked && !path.closed && path.points.len() >= 3 => app.session.tool.path.closed = true, - Some(i) => ui.data_mut(|d| { - d.insert_temp(drag_id, i); - }), - None => match place(app, at) { + let (closed, len) = (path.closed, path.points.len()); + let hit = path_hit(app, ui, (rect, uv), at, &show); + if !matches!(hit, PathHit::Stored(..)) { + app.session.path_checkpoint(); + } + + let grab = match hit { + PathHit::Point(0) if clicked && !closed && len >= 3 => { + app.session.tool.path.closed = true; + None + } + PathHit::Point(i) => { + app.session.tool.path.selected = Some(i); + Some(i) + } + PathHit::Stored(eid, index) => { + app.run("path.edit", json!({"effect": eid.0, "index": index})); + None + } + hit => match place(app, if let PathHit::Curve(_, on) = hit { on } else { at }) { Some(p) => { - app.session.tool.path.push(p, uv); - let last = app.session.tool.path.points.len().saturating_sub(1); - ui.data_mut(|d| { - d.insert_temp(drag_id, last); - }); + let path = &mut app.session.tool.path; + match hit { + PathHit::Curve(i, _) => path.insert(i + 1, p), + _ => { + path.push(p, uv); + path.selected = path.points.len().checked_sub(1); + path.selected + } + } + } + None => { + app.toast(tr("Place path points on the mesh"), false); + None } - None => app.toast(tr("Place path points on the mesh"), false), }, + }; + if let Some(i) = grab { + ui.data_mut(|d| d.insert_temp(drag_id, i)); } } + if resp.dragged_by(PointerButton::Primary) && let Some(i) = ui.data(|d| d.get_temp::(drag_id)) && let Some(p) = resp.interact_pointer_pos().and_then(|pos| place(app, pos)) @@ -962,45 +1123,134 @@ fn path_input( { *q = p; } + if !resp.is_pointer_button_down_on() { ui.data_mut(|d| d.remove::(drag_id)); } } -/// The path being edited: its curve, control points (the first one in the accent color) and, -/// while open, a dashed preview of the next segment. -fn path_overlay(app: &TextureCraftApp, ui: &Ui, rect: Rect, resp: &egui::Response, uv: bool, show: impl Fn(&TextureCraftApp, Vec3) -> Option) { - let tk = Tokens::get(ui.ctx()); - let p = ui.painter_at(rect); - let path = &app.session.tool.path; - let hint = tr("Path: click adds a point, drag moves it, Enter applies, Esc cancels"); - p.text(rect.left_bottom() + vec2(56.0, -12.0), egui::Align2::LEFT_BOTTOM, hint, egui::FontId::proportional(12.0), tk.viewport_text); - if path.uv != uv { - return; - } - let handles: Vec = path.points.iter().filter_map(|q| show(app, *q)).collect(); - let pts: Vec = handles.iter().map(|h| Vec2::new(h.x, h.y)).collect(); - let curve: Vec = texturecraft_engine::paint::spline(&pts, path.closed, 3.0).into_iter().map(|v| pos2(v.x, v.y)).collect(); - let color = if path.closed && path.fill { tk.viewport_accent } else { Color32::from_white_alpha(230) }; - p.add(egui::Shape::line(curve.clone(), Stroke::new(3.0, Color32::from_black_alpha(140)))); - p.add(egui::Shape::line(curve, Stroke::new(1.4, color))); - let hover = resp.hover_pos(); - if !path.closed - && let (Some(last), Some(to)) = (handles.last(), hover) - { - rubber_band(ui, rect, *last, to); - } - for (i, h) in handles.iter().enumerate() { - let r = if hover.is_some_and(|m| m.distance(*h) < HANDLE_GRAB) { 5.5 } else { 4.0 }; - p.circle(*h, r, if i == 0 { tk.viewport_accent } else { Color32::WHITE }, Stroke::new(1.5, Color32::from_black_alpha(180))); +/// Is path point `p` (on screen at `at`) in front of the mesh in the 3D view `rect`? +fn path_point_visible(app: &TextureCraftApp, rect: Rect, p: Vec3, at: Pos2) -> bool { + let eye = app.session.camera.eye(); + let local = Vec2::new(at.x - rect.left(), at.y - rect.top()); + app.session.pick(local, app.session.viewport).is_none_or(|hit| hit.pos.distance(eye) >= p.distance(eye) * (1.0 - PATH_HIDDEN_DEPTH)) +} + +/// Draw `curve` in `color` over a dark outline, as a faint line where the mesh hides it +fn draw_path_curve(painter: &egui::Painter, curve: &ScreenCurve, color: Color32) { + let draw = |run: &mut Vec, shown: bool| { + if run.len() > 1 { + // Hidden parts are a ghost line: no outline, half strength + if shown { + painter.add(egui::Shape::line(run.clone(), Stroke::new(PATH_OUTLINE_WIDTH, Color32::from_black_alpha(140)))); + } + painter.add(egui::Shape::line( + std::mem::take(run), + Stroke::new(PATH_LINE_WIDTH, if shown { color } else { color.gamma_multiply(PATH_HIDDEN_OPACITY) }), + )); + } + run.clear(); + }; + for segment in curve { + // Runs of samples the view shows (or hides) alike, joined at the sample where that changes + let (mut run, mut shown) = (Vec::new(), true); + for sample in segment { + match *sample { + Some((at, visible)) => { + if visible != shown && !run.is_empty() { + run.push(at); + draw(&mut run, shown); + } + shown = visible; + run.push(at); + } + None => draw(&mut run, shown), + } + } + draw(&mut run, shown); } } -/// Dashed preview of a straight segment. -fn rubber_band(ui: &Ui, rect: Rect, from: Pos2, to: Pos2) { - let p = ui.painter_at(rect); - p.add(egui::Shape::dashed_line(&[from, to], Stroke::new(2.5, Color32::from_black_alpha(120)), 6.0, 4.0)); - p.add(egui::Shape::dashed_line(&[from, to], Stroke::new(1.0, Color32::from_white_alpha(200)), 6.0, 4.0)); +/// The layer's other paths (lit under the pointer), then the edited path with its points, the next segment's preview and the pen cursor +fn path_overlay(app: &TextureCraftApp, ui: &Ui, rect: Rect, resp: &egui::Response, uv: bool, show: impl Fn(&TextureCraftApp, Vec3) -> Option) { + let tk = Tokens::get(ui.ctx()); + let painter = ui.painter_at(rect); + let hint = tr("Path: click adds a point, click the curve inserts one, drag moves it, Enter applies, Esc cancels"); + // Wrapped to the view: the hint is longer than a narrow split view + let at = rect.left_bottom() + PATH_HINT_OFFSET; + let wrap = (rect.right() - at.x - PATH_HINT_MARGIN).max(PATH_HINT_MIN_WIDTH); + let hint = painter.layout(hint.to_string(), egui::FontId::proportional(PATH_HINT_FONT_SIZE), tk.viewport_text, wrap); + painter.galley(at - vec2(0.0, hint.size().y), hint, tk.viewport_text); + + let hover = resp.hover_pos(); + let hit = hover.map(|at| (at, path_hit(app, ui, (rect, uv), at, &show))); + for (eid, i, other) in other_paths(app).iter().filter(|(_, _, other)| other.uv == uv) { + let curve = curve_on_screen(app, ui, (rect, uv, true), other, Some((*eid, *i)), &show); + // The path a click opens lights up + let opened = matches!(hit, Some((_, PathHit::Stored(e, n))) if (e, n) == (*eid, *i)); + draw_path_curve(&painter, &curve, if opened { Color32::WHITE } else { Color32::WHITE.gamma_multiply(PATH_STORED_OPACITY) }); + } + + let path = &app.session.tool.path; + if path.uv == uv { + draw_path_curve(&painter, &curve_on_screen(app, ui, (rect, uv, true), path, path.editing, &show), tk.viewport_accent); + let handles: Vec = path.points.iter().filter_map(|q| show(app, *q)).collect(); + if !path.closed + && !handles.is_empty() + && let Some((to, PathHit::Miss)) = hit + { + let mut next = handles.clone(); + next.push(to); + if let Some(segment) = screen_segments(&next, false).last() { + rubber_band(ui, rect, segment); + } + } + + for (i, handle) in handles.iter().enumerate() { + // Small markers: the curve is what the user is shaping + let hovered = hover.is_some_and(|m| m.distance(*handle) < HANDLE_GRAB); + let radius = if hovered { PATH_POINT_RADIUS + PATH_POINT_HOVER_GROWTH } else { PATH_POINT_RADIUS }; + if path.selected == Some(i) { + painter.circle(*handle, radius + PATH_POINT_SELECTED_GROWTH, tk.viewport_accent, Stroke::new(1.0, Color32::from_black_alpha(160))); + } else { + painter.circle(*handle, radius, Color32::from_black_alpha(110), Stroke::new(1.0, Color32::from_white_alpha(if hovered { 230 } else { 150 }))); + } + } + } + + if let Some((at, hit)) = hit + && !ui.input(|i| i.modifiers.command) + { + if let PathHit::Curve(_, on) = hit { + // Where the click inserts its point + painter.circle(on, PATH_POINT_RADIUS, Color32::from_black_alpha(60), Stroke::new(1.0, Color32::from_white_alpha(110))); + } + path_cursor(ui, &painter, at, matches!(hit, PathHit::Curve(..))); + } +} + +/// The Path tool's pointer: a pen with its nib at `at`, and a plus when a click inserts a point +fn path_cursor(ui: &Ui, painter: &egui::Painter, at: Pos2, insert: bool) { + ui.ctx().set_cursor_icon(egui::CursorIcon::None); + let glyph = |icon: &str, size: f32, color: Color32| painter.layout_no_wrap(icon.to_string(), egui::FontId::proportional(size), color); + for (offset, color) in [(PATH_CURSOR_SHADOW_OFFSET, Color32::from_black_alpha(200)), (egui::Vec2::ZERO, Color32::WHITE)] { + // The pen's nib is the bottom left corner of the drawn glyph + let pen = glyph(egui_phosphor::regular::PEN_NIB, PATH_CURSOR_SIZE, color); + let origin = at + offset - pen.mesh_bounds.left_bottom().to_vec2(); + let right = origin + pen.mesh_bounds.right_bottom().to_vec2(); + painter.galley(origin, pen, color); + if insert { + let plus = glyph(egui_phosphor::regular::PLUS, PATH_CURSOR_SIZE * PATH_CURSOR_PLUS_SCALE, color); + painter.galley(right + vec2(PATH_CURSOR_PLUS_GAP, 0.0) - plus.mesh_bounds.left_top().to_vec2(), plus, color); + } + } +} + +/// Dashed preview of a line still to be painted +fn rubber_band(ui: &Ui, rect: Rect, line: &[Pos2]) { + let painter = ui.painter_at(rect); + painter.add(egui::Shape::dashed_line(line, Stroke::new(2.5, Color32::from_black_alpha(120)), RUBBER_BAND_DASH, RUBBER_BAND_GAP)); + painter.add(egui::Shape::dashed_line(line, Stroke::new(1.0, Color32::from_white_alpha(200)), RUBBER_BAND_DASH, RUBBER_BAND_GAP)); } /// V held with the Clone tool in painting mode: clicks set the clone source. @@ -1214,7 +1464,7 @@ fn view_2d(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect, sync: &mut Pendin // Painting in UV space let painting = app.ui.mode == crate::state::Mode::Painting && app.properties_popup.is_none() && !alt && !adjusting && !v_held; if painting && path_tool { - path_input(app, ui, &response, true, |_, pointer| Some(to_uv(pointer).extend(0.0)), show); + path_input(app, ui, &response, (rect, true), |_, pointer| Some(to_uv(pointer).extend(0.0)), show); } else if painting { let pressure = pen_pressure(ui); if response.drag_started_by(PointerButton::Primary) || response.clicked_by(PointerButton::Primary) { diff --git a/crates/ui-egui/tests/path_in_view.rs b/crates/ui-egui/tests/path_in_view.rs new file mode 100644 index 00000000..d044ff4d --- /dev/null +++ b/crates/ui-egui/tests/path_in_view.rs @@ -0,0 +1,144 @@ +//! The Path tool in the 2D view: placing previews the path, and points are edited where they are drawn + +use egui::{Event, Key, Modifiers, PointerButton, Pos2, pos2}; +use egui_kittest::Harness; +use serde_json::json; +use texturecraft_engine::core::LayerId; +use texturecraft_engine::execute; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::state::ViewLayout; + +type AppHarness<'a> = Harness<'a, TextureCraftApp>; + +// Three points left to right across the middle of the 2D view's texture +const A: Pos2 = pos2(600.0, 500.0); +const B: Pos2 = pos2(700.0, 500.0); +const C: Pos2 = pos2(800.0, 500.0); + +fn harness() -> AppHarness<'static> { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + execute(&mut session, "layer.add.paint", &serde_json::Value::Null).unwrap(); + execute(&mut session, "tool.select", &json!({"tool": "path"})).unwrap(); + // Tall enough that the 2D view's texture square takes A, B and C + let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1500.0)).build_eframe(|cc| TextureCraftApp::new(cc, session)); + h.state_mut().ui.layout = ViewLayout::Only2D; + h.run_steps(4); + h +} + +fn pointer(h: &mut AppHarness<'_>, pos: Pos2, pressed: Option) { + let events = &mut h.input_mut().events; + events.push(Event::PointerMoved(pos)); + if let Some(pressed) = pressed { + events.push(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); + } + h.step(); +} + +fn click(h: &mut AppHarness<'_>, at: Pos2) { + pointer(h, at, Some(true)); + pointer(h, at, Some(false)); + h.run_steps(2); +} + +fn drag(h: &mut AppHarness<'_>, from: Pos2, to: Pos2) { + pointer(h, from, Some(true)); + for k in 1..=6 { + pointer(h, from + (to - from) * (k as f32 / 6.0), None); + } + pointer(h, to, Some(false)); + h.run_steps(2); +} + +fn key(h: &mut AppHarness<'_>, key: Key) { + h.input_mut().events.push(Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }); + h.run_steps(2); +} + +/// The path sublayers of the selected layer: (id, stored paths) +fn path_sublayers(h: &AppHarness<'_>) -> Vec<(LayerId, usize)> { + let s = &h.state().session; + let layer = s.doc.project.layer(s.selected_layer().unwrap()).unwrap(); + layer.content_effects.iter().filter_map(|e| s.paths(e.id).map(|p| (e.id, p.len()))).collect() +} + +/// Channel images painted in path sublayer `eid` +fn painted_channels(h: &AppHarness<'_>, eid: LayerId) -> usize { + h.state().session.doc.pixels.layers.iter().filter(|((id, _), _)| *id == eid).count() +} + +#[test] +fn placing_points_previews_the_path_and_enter_applies_it_as_one_step() { + let mut h = harness(); + let steps = h.state().session.history_labels().len(); + for at in [A, B, C] { + click(&mut h, at); + } + assert_eq!(h.state().session.tool.path.points.len(), 3); + let [(eid, 1)] = path_sublayers(&h)[..] else { panic!("the preview is a path in a path sublayer: {:?}", path_sublayers(&h)) }; + assert!(painted_channels(&h, eid) > 0, "the preview painted"); + assert_eq!(h.state().session.history_labels().len(), steps, "no undo step while placing"); + key(&mut h, Key::Enter); + assert_eq!(h.state().session.history_labels().len(), steps + 1); + assert_eq!(h.state().session.undo_label(), Some("Path")); + assert!(h.state().session.tool.path.points.is_empty()); + assert_eq!(path_sublayers(&h), vec![(eid, 1)]); +} + +#[test] +fn clicking_an_applied_path_edits_it_and_dragging_a_point_changes_it() { + let mut h = harness(); + for at in [A, B, C] { + click(&mut h, at); + } + key(&mut h, Key::Enter); + let [(eid, 1)] = path_sublayers(&h)[..] else { panic!("one path") }; + let stored = |h: &AppHarness<'_>| h.state().session.paths(eid).unwrap()[0].points.clone(); + let before = stored(&h); + let steps = h.state().session.history_labels().len(); + + // A click on the path's curve opens it for editing without repainting it + click(&mut h, A.lerp(B, 0.5)); + assert_eq!(h.state().session.tool.path.editing, Some((eid, 0))); + assert_eq!(h.state().session.history_labels().len(), steps, "opening a path repaints nothing"); + + drag(&mut h, B, B + egui::vec2(0.0, 60.0)); + let after = stored(&h); + assert_eq!(after.len(), 3); + assert_eq!((after[0], after[2]), (before[0], before[2])); + assert!(after[1][1] > before[1][1], "the dragged point moved down: {:?} -> {:?}", before[1], after[1]); + assert_eq!(h.state().session.history_labels().len(), steps + 1, "the edit is one step"); +} + +#[test] +fn clicking_the_curve_inserts_a_point_and_backspace_removes_the_selected_one() { + let mut h = harness(); + for at in [A, B, C] { + click(&mut h, at); + } + let path = |h: &AppHarness<'_>| h.state().session.tool.path.clone(); + let before = path(&h).points; + click(&mut h, B.lerp(C, 0.5)); + let after = path(&h); + assert_eq!(after.points.len(), 4, "inserted, not appended"); + assert_eq!(after.selected, Some(2)); + assert_eq!((after.points[1], after.points[3]), (before[1], before[2])); + assert!(after.points[2].x > before[1].x && after.points[2].x < before[2].x); + + // B, not A: clicking the first point closes the path + click(&mut h, B); + assert_eq!(path(&h).selected, Some(1)); + key(&mut h, Key::Backspace); + assert_eq!(path(&h).points, vec![after.points[0], after.points[2], after.points[3]]); + + // Undo brings the point back and keeps the path; again, the inserted point goes + let undo = |h: &mut AppHarness<'_>| { + h.input_mut().events.push(Event::Key { key: Key::Z, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::COMMAND }); + h.run_steps(2); + }; + undo(&mut h); + assert_eq!(path(&h).points, after.points); + undo(&mut h); + assert_eq!(path(&h).points, before); + assert!(!path_sublayers(&h).is_empty(), "the path is still there"); +} From a3d9b719c5910c7460316af78e70c5d59e4107a8 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sun, 8 Nov 2026 05:03:59 +0000 Subject: [PATCH 30/64] Open the rail's panels in a popup beside their icon, one at a time A click on a rail icon (Texture Set Settings, Display, Shader Settings, History) opened the panel as a separate floating window near the middle of the main window, and the Log had no icon. The rail now has a Log icon, and each of these panels opens in a popup beside its icon, level with it, in the menus' frame with an accent outline. The popup covers the panels between the viewport and the rail and reaches a little into the viewport. Settings panels fit their contents up to a height; History and Log take one height. Opening another closes it, and so do its icon, its close button, a press outside it and Escape. Dragging its title docks or floats the panel like a tab. A panel in the dock, docked or floating, has no rail icon until it is closed there. Window > Views opens these panels the same way. --- crates/ui-egui/src/docking.rs | 93 ++++++++------ crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/menus.rs | 16 ++- crates/ui-egui/src/rail_popup.rs | 205 +++++++++++++++++++++++++++++++ crates/ui-egui/src/state.rs | 4 + crates/ui-egui/src/toolbar.rs | 43 +++++-- crates/ui-egui/tests/it/main.rs | 1 + crates/ui-egui/tests/it/rail.rs | 197 +++++++++++++++++++++++++++++ 8 files changed, 504 insertions(+), 56 deletions(-) create mode 100644 crates/ui-egui/src/rail_popup.rs create mode 100644 crates/ui-egui/tests/it/rail.rs diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 789ddc51..906b03ce 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -133,9 +133,7 @@ fn split(axis: SplitAxis, size: SplitSize, first: Node, second: Node Workspace { use Panel::*; let column = split( @@ -147,20 +145,13 @@ pub fn default_workspace() -> Workspace { let root = split(SplitAxis::Horizontal, SplitSize::Ratio(0.115), tabs(&[Assets]), split(SplitAxis::Horizontal, SplitSize::Ratio(0.78), tabs(&[Viewport]), column)); let mut workspace = Workspace::new(Layout { root: Some(root), floating: Vec::new() }); + for panel in Panel::ALL { if let Some(rect) = panel.float_rect() { - let location = Location { - floating: Some(rect), - anchor: None, - placement: Placement::Tab { before: None }, - size: None, - stack: None, - sibling: Vec::new(), - group: None, - }; - workspace.hidden.push((panel, location)); + workspace.hidden.push((panel, floating_location(rect))); } } + for panel in [MeshMapSettings, CommonSettings, MeshMapBakers] { workspace.hidden.push(( panel, @@ -175,9 +166,15 @@ pub fn default_workspace() -> Workspace { }, )); } + workspace } +/// Where a closed panel reopens as its own floating window at `rect` (`[x, y, width, height]`) +fn floating_location(rect: [f32; 4]) -> Location { + Location { floating: Some(rect), anchor: None, placement: Placement::Tab { before: None }, size: None, stack: None, sibling: Vec::new(), group: None } +} + /// craft-ui's checks plus the viewport's: a saved or hand-edited file cannot hide, float, group /// or collapse it. pub fn validate(workspace: &Workspace) -> Result<(), String> { @@ -344,6 +341,13 @@ impl Dock { } } + /// Open the closed `panel` as a floating window at `rect` (`[x, y, width, height]`) + pub(crate) fn float_at(&mut self, panel: Panel, rect: [f32; 4]) { + self.workspace.hidden.retain(|(hidden_panel, _)| *hidden_panel != panel); + self.workspace.hidden.push((panel, floating_location(rect))); + self.focus(panel); + } + /// One change from the dock area's gestures. A change that is rejected leaves the layout as /// it was. fn apply(&mut self, action: Action) { @@ -388,7 +392,7 @@ fn style(ui: &Ui, t: &Tokens) -> DockStyle { s } -/// Draw the dock (viewport and panels) into `ui`. +/// Draw the dock (viewport and panels) into `ui` pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) { for panel in Panel::ALL { if !panel.available_in(app.ui.mode) && app.ui.dock.is_open(panel) { @@ -404,57 +408,68 @@ pub fn show(app: &mut TextureCraftApp, ui: &mut Ui) { if let Some(panel) = app.ui.dock.raise.take() { area = area.raise_panel(panel); } - let output = area.show_content(ui, &layout, &style, &mut Panels { app, tk: tokens }); + let output = area.show_content(ui, &layout, &style, &mut Panels { app, tokens }); + crate::rail_popup::hand_drag_to_dock(&context, area_id()); + // After the dock, which records the viewport the popup reaches into, and before a changed layout returns early + crate::rail_popup::show(app, &context); + #[cfg(not(target_arch = "wasm32"))] crate::menus::forwarded_shortcuts(app, &context, output.forwarded_events, output.forwarded_modifiers.unwrap_or_default()); if let Some(error) = &output.error { log::warn!("docking: {error}"); } + // A layout changed by a panel takes priority over gestures from the old layout if app.ui.dock.workspace.layout != layout { craft_ui::docking::cancel_drag::(&context, area_id()); return; } + for action in output.actions { app.ui.dock.apply(action); } } -/// The panels' contents, names and limits for the dock area. +/// The panels' contents, names and limits for the dock area struct Panels<'a> { app: &'a mut TextureCraftApp, - tk: Tokens, + tokens: Tokens, +} + +/// Room between a panel's edges and its contents +const PANEL_BODY_MARGIN: Margin = Margin::symmetric(8, 4); + +/// The body of every panel except the viewport, in the dock or on the rail +pub(crate) fn panel_body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) { + egui::Frame::new().inner_margin(PANEL_BODY_MARGIN).show(ui, |ui| match panel { + Panel::MeshMapSettings => crate::bake_mode::mesh_map_settings_panel(app, ui), + Panel::Assets => crate::shelf::body(app, ui), + Panel::CommonSettings => crate::bake_mode::common_settings_panel(app, ui), + Panel::MeshMapBakers => crate::bake_mode::mesh_map_bakers_panel(app, ui), + Panel::TextureSetList if app.ui.mode == crate::state::Mode::Baking => crate::bake_mode::texture_sets(app, ui), + Panel::TextureSetList => crate::dock::texture_set_list(app, ui), + Panel::Layers => crate::dock::layers(app, ui), + Panel::TextureSetSettings => crate::dock::texture_set_settings(app, ui), + Panel::Properties => crate::dock::properties(app, ui), + // Display and Shader Settings scroll here, as tall as their contents; History and Log scroll their own lists + Panel::Display => egui::ScrollArea::vertical().id_salt("dock-display").auto_shrink([false, true]).show(ui, |ui| crate::windows::display(app, ui)).inner, + Panel::Shader => egui::ScrollArea::vertical().id_salt("dock-shader").auto_shrink([false, true]).show(ui, |ui| crate::windows::shader(app, ui)).inner, + Panel::History => crate::windows::history(app, ui), + Panel::Log => crate::windows::log(app, ui), + Panel::Viewport => {} + }); } impl DockContent for Panels<'_> { fn body(&mut self, ui: &mut Ui, panel: &Panel) { let app = &mut *self.app; if *panel == Panel::Viewport { - ui.painter().rect_filled(ui.max_rect(), 0.0, self.tk.viewport); + crate::rail_popup::remember_viewport(ui.ctx(), ui.max_rect()); + ui.painter().rect_filled(ui.max_rect(), 0.0, self.tokens.viewport); crate::viewport::central(app, ui); return; } - egui::Frame::new().inner_margin(Margin::symmetric(8, 4)).show(ui, |ui| match panel { - Panel::MeshMapSettings => crate::bake_mode::mesh_map_settings_panel(app, ui), - Panel::Assets => crate::shelf::body(app, ui), - Panel::CommonSettings => crate::bake_mode::common_settings_panel(app, ui), - Panel::MeshMapBakers => crate::bake_mode::mesh_map_bakers_panel(app, ui), - Panel::TextureSetList if app.ui.mode == crate::state::Mode::Baking => crate::bake_mode::texture_sets(app, ui), - Panel::TextureSetList => crate::dock::texture_set_list(app, ui), - Panel::Layers => crate::dock::layers(app, ui), - Panel::TextureSetSettings => crate::dock::texture_set_settings(app, ui), - Panel::Properties => crate::dock::properties(app, ui), - // The other panels scroll their own lists. - Panel::Display => { - egui::ScrollArea::vertical().id_salt("dock-display").auto_shrink([false, false]).show(ui, |ui| crate::windows::display(app, ui)).inner - } - Panel::Shader => { - egui::ScrollArea::vertical().id_salt("dock-shader").auto_shrink([false, false]).show(ui, |ui| crate::windows::shader(app, ui)).inner - } - Panel::History => crate::windows::history(app, ui), - Panel::Log => crate::windows::log(app, ui), - Panel::Viewport => {} - }); + panel_body(app, ui, *panel); } fn logical_label(&self, panel: &Panel) -> String { diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 9d117e06..4a56260e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -27,6 +27,7 @@ mod preview_request; mod preview_worker; pub mod profile; pub mod properties_popup; +mod rail_popup; pub mod render_mode; mod resource_picker; mod resource_picker_item; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 3f645eeb..e0e32352 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -129,7 +129,7 @@ pub fn implemented(id: &str) -> bool { is_ui(id) || texturecraft_engine::find(id).is_some() } -/// Invoke a menu item (menus, shortcuts, palette, control channel `ui.menu.invoke`). +/// Invoke a menu item (menus, shortcuts, palette, control channel `ui.menu.invoke`) pub fn invoke(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) { if !enabled(app, id) { return; @@ -140,15 +140,21 @@ pub fn invoke(app: &mut TextureCraftApp, ctx: &egui::Context, id: &str) { { return; } + if let Some(panel) = crate::docking::view_panel(id) { - app.ui.dock.toggle(panel); + if crate::rail_popup::is_rail_panel(panel) { + crate::rail_popup::toggle(app, panel); + } else { + app.ui.dock.toggle(panel); + } return; } + match id { "ui.newProject" => app.ui.windows.new_project = true, "ui.export" => app.ui.windows.export = true, "ui.quit" => ctx.send_viewport_cmd(egui::ViewportCommand::Close), - "ui.projectConfig" => app.ui.dock.focus(crate::docking::Panel::Display), + "ui.projectConfig" => crate::rail_popup::open(app, crate::docking::Panel::Display), "ui.settings" => app.ui.windows.settings = true, "ui.mode.bake" => app.ui.mode = Mode::Baking, "ui.mode.paint" => app.ui.mode = Mode::Painting, @@ -320,7 +326,7 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { return; } - // Escape closes an open popup first, before the Properties popup or the stroke + // Escape closes an open popup first, then the Properties popup, the rail's popup or the stroke let popup_open = egui::Popup::is_any_open(ctx); let active_shortcuts = crate::keymap::active(&app.ui.keymap); @@ -343,6 +349,8 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { if !popup_open && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.properties_popup = None; + } else if !popup_open && app.ui.rail_panel.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + app.ui.rail_panel = None; } else if app.ui.mode == Mode::Painting && !popup_open && input.consume_key(Modifiers::NONE, Key::Escape) { app.session.cancel_stroke(); app.session.tool.path.points.clear(); diff --git a/crates/ui-egui/src/rail_popup.rs b/crates/ui-egui/src/rail_popup.rs new file mode 100644 index 00000000..9340f6eb --- /dev/null +++ b/crates/ui-egui/src/rail_popup.rs @@ -0,0 +1,205 @@ +//! The rail's panels open in a popup beside their rail icon, one at a time; dragging its title docks or floats the panel + +use egui::{Id, Pos2, Rect, RichText, Sense, Ui}; +use egui_phosphor::regular as ic; + +use crate::TextureCraftApp; +use crate::docking::Panel; +use crate::i18n::tr; +use crate::state::Mode; +use crate::theme::Tokens; +use crate::widgets::icon_button; + +/// The rail's panels, top to bottom, with their icons and Window ▸ Views ids +pub(crate) const RAIL_PANELS: [(Panel, &str, &str); 5] = [ + (Panel::TextureSetSettings, ic::STACK, "ui.view.textureSetSettings"), + (Panel::Display, ic::MONITOR, "ui.view.display"), + (Panel::Shader, ic::SLIDERS_HORIZONTAL, "ui.view.shader"), + (Panel::History, ic::CLOCK_COUNTER_CLOCKWISE, "ui.view.history"), + (Panel::Log, ic::FILE_TEXT, "ui.view.log"), +]; + +/// The popup reaches this far into the viewport, so it covers the panels between the viewport and the rail +const VIEWPORT_OVERHANG: f32 = 48.0; + +/// Narrowest the popup gets, when the viewport is not left of the rail's column +const POPUP_MIN_WIDTH: f32 = 320.0; + +/// Settings panels' popups fit their contents up to this height, then scroll +const SETTINGS_MAX_HEIGHT: f32 = 640.0; + +/// History and Log fill their popup, so it has one height +const LIST_HEIGHT: f32 = 400.0; + +/// Gap between the popup and the rail +const RAIL_GAP: f32 = 4.0; + +/// Size of the close button in the popup's title row +const TITLE_BUTTON_SIZE: f32 = 22.0; + +/// The popup's area, whose rect egui remembers between frames +fn area_id() -> Id { + Id::unique("rail_popup") +} + +/// Where the rail drew its strip on this frame +fn strip_id() -> Id { + Id::unique("rail_popup_strip") +} + +/// Where the rail drew each panel's icon on this frame +fn icons_id() -> Id { + Id::unique("rail_popup_icons") +} + +/// The panel whose popup title a drag left, and the title's rect, until the dock takes the drag over +fn pending_drag_id() -> Id { + Id::unique("rail_popup_pending_drag") +} + +/// Where the dock drew the viewport on this frame +fn viewport_id() -> Id { + Id::unique("rail_popup_viewport") +} + +/// Whether `panel` opens from the rail rather than in the dock +pub(crate) fn is_rail_panel(panel: Panel) -> bool { + RAIL_PANELS.iter().any(|(rail_panel, _, _)| *rail_panel == panel) +} + +/// Record the rail's strip before its icons, so the popup can line up with them +pub(crate) fn begin_rail(ctx: &egui::Context, strip: Rect) { + ctx.data_mut(|data| { + data.insert_temp(strip_id(), strip); + data.insert_temp(icons_id(), Vec::<(Panel, Rect)>::new()); + }); +} + +/// Record where the rail drew `panel`'s icon +pub(crate) fn remember_icon(ctx: &egui::Context, panel: Panel, icon: Rect) { + ctx.data_mut(|data| data.get_temp_mut_or_default::>(icons_id()).push((panel, icon))); +} + +/// Record where the dock drew the viewport, whose right edge the popup reaches past +pub(crate) fn remember_viewport(ctx: &egui::Context, viewport: Rect) { + ctx.data_mut(|data| data.insert_temp(viewport_id(), viewport)); +} + +/// A rail icon or its Window ▸ Views item: open `panel` in the popup in place of the one there, or close it +pub(crate) fn toggle(app: &mut TextureCraftApp, panel: Panel) { + // Bake mode has no rail, and a panel in the dock (which then has no rail icon) is toggled there + if app.ui.mode == Mode::Baking || app.ui.dock.is_open(panel) { + app.ui.dock.toggle(panel); + return; + } + + app.ui.rail_panel = if app.ui.rail_panel == Some(panel) { None } else { Some(panel) }; +} + +/// Open `panel` from the rail: in its popup, or where it is in the dock (bake mode has no rail) +pub(crate) fn open(app: &mut TextureCraftApp, panel: Panel) { + if app.ui.mode == Mode::Baking || app.ui.dock.is_open(panel) { + app.ui.dock.focus(panel); + } else { + app.ui.rail_panel = Some(panel); + } +} + +/// Hand a drag that left the popup's title to the dock, once the dock has drawn the panel it floated +pub(crate) fn hand_drag_to_dock(ctx: &egui::Context, dock_area: Id) { + let Some((panel, title)) = ctx.data(|data| data.get_temp::<(Panel, Rect)>(pending_drag_id())) else { return }; + + ctx.data_mut(|data| data.remove::<(Panel, Rect)>(pending_drag_id())); + if ctx.input(|input| input.pointer.primary_down()) { + craft_ui::docking::begin_drag(ctx, dock_area, panel, title); + } +} + +/// Draw the open popup beside its icon; a press outside it closes it, as for a menu (Escape does too, in `menus.rs`) +pub(crate) fn show(app: &mut TextureCraftApp, ctx: &egui::Context) { + let Some(panel) = app.ui.rail_panel else { return }; + if app.ui.mode == Mode::Baking || app.ui.dock.is_open(panel) { + app.ui.rail_panel = None; + return; + } + + let strip = ctx.data(|data| data.get_temp::(strip_id())).unwrap_or(Rect::NOTHING); + let icons = ctx.data(|data| data.get_temp::>(icons_id())).unwrap_or_default(); + let Some(icon) = icons.iter().find(|(icon_panel, _)| *icon_panel == panel).map(|(_, rect)| *rect) else { + app.ui.rail_panel = None; + return; + }; + + let shown = ctx.memory(|memory| memory.area_rect(area_id())); + if closed_by_input(ctx, shown, strip) { + app.ui.rail_panel = None; + return; + } + + let tokens = Tokens::get(ctx); + let frame = egui::Frame::popup(&ctx.global_style()).fill(tokens.panel).stroke(egui::Stroke::new(1.0, tokens.accent)); + let (top_right, width) = placement(ctx, strip, icon); + let mut closed = false; + let mut dragged_from = None; + egui::Area::new(area_id()).order(egui::Order::Foreground).pivot(egui::Align2::RIGHT_TOP).fixed_pos(top_right).show(ctx, |ui| { + frame.show(ui, |ui| { + ui.set_width(width - frame.total_margin().sum().x); + (closed, dragged_from) = title_row(ui, &tokens, panel); + ui.separator(); + body(app, ui, panel); + }); + }); + + if closed { + app.ui.rail_panel = None; + } else if let Some(title) = dragged_from { + app.ui.rail_panel = None; + let rect = shown.unwrap_or(title); + app.ui.dock.float_at(panel, [rect.left(), rect.top(), rect.width(), rect.height()]); + ctx.data_mut(|data| data.insert_temp(pending_drag_id(), (panel, title))); + } +} + +/// The popup's top right corner, beside the rail and level with its icon, and its width (egui keeps the area on screen) +fn placement(ctx: &egui::Context, strip: Rect, icon: Rect) -> (Pos2, f32) { + let right = strip.left() - RAIL_GAP; + let viewport = ctx.data(|data| data.get_temp::(viewport_id())); + let width = viewport.map_or(POPUP_MIN_WIDTH, |viewport| right - (viewport.right() - VIEWPORT_OVERHANG)).max(POPUP_MIN_WIDTH); + (Pos2::new(right, icon.top()), width) +} + +/// A press outside the popup and the rail, unless in one of the popup's own dropdowns +fn closed_by_input(ctx: &egui::Context, shown: Option, strip: Rect) -> bool { + let pressed_at = ctx.input(|input| input.pointer.press_origin().filter(|_| input.pointer.any_pressed())); + // A press on the rail is left to its icons, which switch or close the popup themselves + let outside = pressed_at.is_some_and(|at| !strip.contains(at) && shown.is_some_and(|rect| !rect.contains(at))); + outside && !egui::Popup::is_any_open(ctx) +} + +/// The panel's contents: History and Log at one height, the settings panels as tall as their contents up to a limit +fn body(app: &mut TextureCraftApp, ui: &mut Ui, panel: Panel) { + // A child Ui, so the height limits start below the title row instead of moving the cursor back up to it + ui.scope(|ui| { + if matches!(panel, Panel::History | Panel::Log) { + ui.set_height(LIST_HEIGHT); + } else { + // The area's remembered size would otherwise cap the height + ui.set_max_height(SETTINGS_MAX_HEIGHT); + } + crate::docking::panel_body(app, ui, panel); + }); +} + +/// The panel's name, which drags like a tab, and a close button: whether it was clicked, and where a drag started +fn title_row(ui: &mut Ui, tokens: &Tokens, panel: Panel) -> (bool, Option) { + let row = ui.horizontal(|ui| { + ui.label(RichText::new(tr(panel.name())).strong().color(tokens.text_strong)); + ui.add_space((ui.available_width() - TITLE_BUTTON_SIZE).max(0.0)); + icon_button(ui, ic::X, tr("Close"), false, TITLE_BUTTON_SIZE) + }); + + let (row, close) = (row.response.rect, row.inner); + let title = Rect::from_min_max(row.min, egui::pos2(close.rect.left(), row.bottom())); + let drag = ui.interact(title, ui.scope_id().with("rail_popup_title"), Sense::drag()).on_hover_cursor(egui::CursorIcon::Grab); + (close.clicked(), drag.drag_started().then_some(title)) +} diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 0a9f6033..585f88c1 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -249,6 +249,9 @@ pub struct UiState { /// The docked, tabbed and floating panels around the viewport. #[serde(default)] pub dock: Dock, + /// The panel open against the icon rail, if any; not saved, so the app starts with the rail closed + #[serde(skip)] + pub rail_panel: Option, #[serde(default = "Dock::for_baking")] pub(crate) inactive_mode_dock: Dock, #[serde(default)] @@ -342,6 +345,7 @@ impl Default for UiState { layout: ViewLayout::Split, split_ratio: default_split_ratio(), dock: Dock::default(), + rail_panel: None, inactive_mode_dock: Dock::for_baking(), dock_is_baking: false, bake_layout_version: BAKE_LAYOUT_VERSION, diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index 889d2de7..3780dc0f 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -386,22 +386,39 @@ pub fn tool_shelf(app: &mut TextureCraftApp, ui: &mut egui::Ui) { }); } +/// Width of the icon rail beside the dock +const RAIL_WIDTH: f32 = 38.0; + +/// Size of the rail's icons +const RAIL_ICON_SIZE: f32 = 26.0; + +/// Gap between the rail's icons +const RAIL_ICON_GAP: f32 = 4.0; + +/// Padding inside the rail's card around its icons, as the tool shelf's +const RAIL_CARD_PADDING: egui::Margin = egui::Margin::symmetric(3, 6); + +/// The icon rail: Export, then the rail panels that are not in the dock, each opening its popup pub fn rail(app: &mut TextureCraftApp, ui: &mut egui::Ui) { - let tk = Tokens::get(ui.ctx()); - egui::Panel::right("rail").resizable(false).exact_size(38.0).show_separator_line(false).frame(egui::Frame::NONE).show(ui, |ui| { - card(ui, &tk, egui::Margin { left: 0, right: GUTTER, top: GUTTER, bottom: GUTTER }, egui::Margin::symmetric(3, 6), |ui| { - ui.spacing_mut().item_spacing.y = 4.0; - if icon_button(ui, ic::EXPORT, &tip(&app.ui.keymap, tr("Export textures"), "ui.export"), app.ui.windows.export, 26.0).clicked() { + let tokens = Tokens::get(ui.ctx()); + egui::Panel::right("rail").resizable(false).exact_size(RAIL_WIDTH).show_separator_line(false).frame(egui::Frame::NONE).show(ui, |ui| { + card(ui, &tokens, egui::Margin { left: 0, right: GUTTER, top: GUTTER, bottom: GUTTER }, RAIL_CARD_PADDING, |ui| { + ui.spacing_mut().item_spacing.y = RAIL_ICON_GAP; + crate::rail_popup::begin_rail(ui.ctx(), ui.max_rect()); + if icon_button(ui, ic::EXPORT, &tip(&app.ui.keymap, tr("Export textures"), "ui.export"), app.ui.windows.export, RAIL_ICON_SIZE).clicked() { app.ui.windows.export = !app.ui.windows.export; } - for (panel, icon, id) in [ - (Panel::TextureSetSettings, ic::STACK, "ui.view.textureSetSettings"), - (Panel::Display, ic::MONITOR, "ui.view.display"), - (Panel::Shader, ic::SLIDERS_HORIZONTAL, "ui.view.shader"), - (Panel::History, ic::CLOCK_COUNTER_CLOCKWISE, "ui.view.history"), - ] { - if icon_button(ui, icon, &tip(&app.ui.keymap, tr(panel.name()), id), app.ui.dock.is_visible(panel), 26.0).clicked() { - app.ui.dock.toggle(panel); + + // A panel in the dock, docked or floating, leaves the rail until it is closed there + for (panel, icon, id) in crate::rail_popup::RAIL_PANELS { + if app.ui.dock.is_open(panel) { + continue; + } + + let response = icon_button(ui, icon, &tip(&app.ui.keymap, tr(panel.name()), id), app.ui.rail_panel == Some(panel), RAIL_ICON_SIZE); + crate::rail_popup::remember_icon(ui.ctx(), panel, response.rect); + if response.clicked() { + crate::rail_popup::toggle(app, panel); } } }); diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index e39551bf..aa709ee4 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -18,6 +18,7 @@ mod path_list; mod pen_pressure; mod polygon_fill; mod properties_popup; +mod rail; mod shelf_drop; mod shelf_hover_preview; mod shift_lines_2d; diff --git a/crates/ui-egui/tests/it/rail.rs b/crates/ui-egui/tests/it/rail.rs new file mode 100644 index 00000000..64c3a975 --- /dev/null +++ b/crates/ui-egui/tests/it/rail.rs @@ -0,0 +1,197 @@ +//! The rail opens its panels in a popup beside their icons, one at a time; dragging the popup's title docks or floats the panel + +use egui::{Event, Modifiers, PointerButton, Pos2, Role}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use texturecraft_ui_egui::TextureCraftApp; +use texturecraft_ui_egui::docking::Panel; + +const WINDOW_SIZE: egui::Vec2 = egui::vec2(1600.0, 960.0); + +/// The rail is the last 38 points of the window; the popup's own buttons sit left of it +const RAIL_LEFT_EDGE: f32 = WINDOW_SIZE.x - 38.0; + +// Small texture and bake sizes keep the sample session fast; the rail doesn't depend on them +const TEXTURE_RESOLUTION: u32 = 256; +const BAKE_RESOLUTION: u32 = 64; + +/// Frames for the first layout and fonts to settle +const STARTUP_FRAMES: usize = 4; + +/// Where a drag out of the popup ends: in the viewport, clear of every panel +const INTO_THE_VIEWPORT: egui::Vec2 = egui::vec2(-500.0, 100.0); + +/// Moves a drag takes, so the dock sees it pass its threshold and move +const DRAG_STEPS: usize = 6; + +/// Frames between a drag's events: the press must land before the moves, and each move be seen +const FRAMES_PER_DRAG_EVENT: usize = 2; + +/// Frames for a click to reach the rail, the popup and the dock +const SETTLE_FRAMES: usize = 3; + +// A setting only Shader Settings shows, and one only Display Settings shows +const SHADER_SETTING: &str = "Index of refraction"; +const DISPLAY_SETTING: &str = "Environment opacity"; + +fn app() -> Harness<'static, TextureCraftApp> { + app_of_size(WINDOW_SIZE) +} + +fn app_of_size(size: egui::Vec2) -> Harness<'static, TextureCraftApp> { + let session = texturecraft_engine::sample_session(TEXTURE_RESOLUTION, BAKE_RESOLUTION).unwrap(); + let mut harness = Harness::builder().with_size(size).build_eframe(|cc| TextureCraftApp::new(cc, session)); + // The labels below are English; a first run would speak the system's language + harness.state_mut().ui.prefs.language = "en".into(); + harness.run_steps(STARTUP_FRAMES); + harness +} + +/// The rail icon of the panel named `name`, if the rail shows one +fn rail_icon<'h>(harness: &'h Harness<'_, TextureCraftApp>, name: &str) -> Option> { + // A rail icon's label is its tooltip, which adds the shortcut when the panel has one + let is_panel = |label: &str| label == name || label.starts_with(&format!("{name} (")); + harness + .get_all_by_role(Role::Button) + .find(|button| button.rect().min.x >= RAIL_LEFT_EDGE && button.accesskit_node().label().is_some_and(|label| is_panel(&label))) +} + +fn click_rail(harness: &mut Harness<'_, TextureCraftApp>, name: &str) { + rail_icon(harness, name).expect("the panel's icon on the rail").click(); + harness.run_steps(SETTLE_FRAMES); +} + +/// Drag with the primary button from `from` to `to` in a few moves +fn drag(harness: &mut Harness<'_, TextureCraftApp>, from: Pos2, to: Pos2) { + harness.hover_at(from); + harness.run_steps(FRAMES_PER_DRAG_EVENT); + harness.event(Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + harness.run_steps(FRAMES_PER_DRAG_EVENT); + for step in 1..=DRAG_STEPS { + harness.hover_at(from + (to - from) * (step as f32 / DRAG_STEPS as f32)); + harness.run_steps(FRAMES_PER_DRAG_EVENT); + } + harness.event(Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + harness.run_steps(SETTLE_FRAMES); +} + +/// The popup's title: the panel's name left of the rail +fn popup_title(harness: &Harness<'_, TextureCraftApp>, name: &str) -> egui::Rect { + harness.get_all_by_label(name).map(|node| node.rect()).find(|rect| rect.max.x < RAIL_LEFT_EDGE).expect("the popup's title") +} + +#[test] +fn the_rail_shows_one_panel_at_a_time() { + let mut harness = app(); + + click_rail(&mut harness, "Shader Settings"); + assert_eq!(harness.state().ui.rail_panel, Some(Panel::Shader)); + assert!(harness.query_by_label(SHADER_SETTING).is_some()); + + click_rail(&mut harness, "Display Settings"); + assert_eq!(harness.state().ui.rail_panel, Some(Panel::Display)); + assert!(harness.query_by_label(SHADER_SETTING).is_none(), "opening Display Settings closed Shader Settings"); + assert!(harness.query_by_label(DISPLAY_SETTING).is_some()); + assert!(!harness.state().ui.dock.is_open(Panel::Shader), "the rail's panels are not dock windows"); + + click_rail(&mut harness, "Display Settings"); + assert_eq!(harness.state().ui.rail_panel, None, "its own icon closes it"); +} + +#[test] +fn the_popup_lines_up_with_its_icon() { + let mut harness = app(); + + click_rail(&mut harness, "History"); + let icon = rail_icon(&harness, "History").expect("the History icon").rect(); + let title = popup_title(&harness, "History"); + assert!(title.top() >= icon.top() && title.top() <= icon.bottom(), "the title {title:?} is not level with the icon {icon:?}"); +} + +#[test] +fn the_close_button_a_press_outside_and_escape_close_it() { + let mut harness = app(); + + click_rail(&mut harness, "Display Settings"); + harness.get_by_role_and_label(Role::Button, "Close").click(); + harness.run_steps(SETTLE_FRAMES); + assert_eq!(harness.state().ui.rail_panel, None, "Close"); + + click_rail(&mut harness, "Log"); + harness.get_by_label("Assets").click(); + harness.run_steps(SETTLE_FRAMES); + assert_eq!(harness.state().ui.rail_panel, None, "a press outside"); + + click_rail(&mut harness, "Log"); + harness.key_press(egui::Key::Escape); + harness.run_steps(SETTLE_FRAMES); + assert_eq!(harness.state().ui.rail_panel, None, "Escape"); +} + +#[test] +fn dragging_the_title_out_floats_the_panel_and_frees_the_rail() { + let mut harness = app(); + + click_rail(&mut harness, "History"); + let title = popup_title(&harness, "History").center(); + drag(&mut harness, title, title + INTO_THE_VIEWPORT); + assert_eq!(harness.state().ui.rail_panel, None); + assert!(harness.state().ui.dock.is_visible(Panel::History), "History floats on its own"); + assert!(rail_icon(&harness, "History").is_none(), "a panel in the dock has no rail icon"); + + click_rail(&mut harness, "Shader Settings"); + assert_eq!(harness.state().ui.rail_panel, Some(Panel::Shader)); + assert!(harness.state().ui.dock.is_visible(Panel::History), "History stays open beside the rail's panel"); +} + +#[test] +fn dragging_the_title_onto_a_tab_strip_docks_the_panel_there() { + let mut harness = app(); + + click_rail(&mut harness, "Log"); + let title = popup_title(&harness, "Log").center(); + let properties_tab = harness.get_by_label("Properties - Paint").rect().center(); + drag(&mut harness, title, properties_tab); + + let layout = &harness.state().ui.dock.workspace().layout; + assert!(layout.contains(&Panel::Log) && !layout.floating.iter().any(|window| window.contains(&Panel::Log)), "the Log is docked"); +} + +#[test] +fn a_panel_closed_in_the_dock_returns_to_the_rail() { + let mut harness = app(); + assert!(rail_icon(&harness, "Texture Set Settings").is_none(), "Texture Set Settings starts in the dock, beside Layers"); + + harness.state_mut().ui.dock.close(Panel::TextureSetSettings); + harness.run_steps(SETTLE_FRAMES); + click_rail(&mut harness, "Texture Set Settings"); + assert_eq!(harness.state().ui.rail_panel, Some(Panel::TextureSetSettings)); +} + +#[test] +fn window_views_open_the_rail_panels_popup() { + let mut harness = app(); + + let ctx = harness.ctx.clone(); + texturecraft_ui_egui::menus::invoke(harness.state_mut(), &ctx, "ui.view.shader"); + harness.run_steps(SETTLE_FRAMES); + assert_eq!(harness.state().ui.rail_panel, Some(Panel::Shader)); + assert!(!harness.state().ui.dock.is_open(Panel::Shader)); + + // Project configuration opens Display Settings, in its popup too + texturecraft_ui_egui::menus::invoke(harness.state_mut(), &ctx, "ui.projectConfig"); + harness.run_steps(SETTLE_FRAMES); + assert_eq!(harness.state().ui.rail_panel, Some(Panel::Display)); +} + +#[test] +fn a_popup_that_would_run_past_the_bottom_moves_up() { + // Too short for Display Settings below its icon + const SHORT_WINDOW: egui::Vec2 = egui::vec2(1600.0, 600.0); + let mut harness = app_of_size(SHORT_WINDOW); + + click_rail(&mut harness, "Display Settings"); + let icon = rail_icon(&harness, "Display Settings").expect("the Display Settings icon").rect(); + let title = popup_title(&harness, "Display Settings"); + assert!(title.top() < icon.top(), "the popup at {title:?} did not move up from the icon at {icon:?}"); +} From e7e43047f3d017dacf381ed50851c2b08b0c8e81 Mon Sep 17 00:00:00 2001 From: Rebornim Date: Sun, 8 Nov 2026 21:40:19 +0000 Subject: [PATCH 31/64] Rail tests: check the popup on screen, not the rail_panel field --- crates/ui-egui/tests/it/rail.rs | 50 ++++++++++++++++++++++++--------- 1 file changed, 37 insertions(+), 13 deletions(-) diff --git a/crates/ui-egui/tests/it/rail.rs b/crates/ui-egui/tests/it/rail.rs index 64c3a975..3a5586c3 100644 --- a/crates/ui-egui/tests/it/rail.rs +++ b/crates/ui-egui/tests/it/rail.rs @@ -75,9 +75,33 @@ fn drag(harness: &mut Harness<'_, TextureCraftApp>, from: Pos2, to: Pos2) { harness.run_steps(SETTLE_FRAMES); } -/// The popup's title: the panel's name left of the rail +/// The popup's Close button, left of the rail (the window's own Close sits above the rail) +fn popup_close_button(harness: &Harness<'_, TextureCraftApp>) -> Option { + harness + .get_all_by_role(Role::Button) + .find(|button| button.rect().max.x < RAIL_LEFT_EDGE && button.accesskit_node().label().as_deref() == Some("Close")) + .map(|button| button.rect()) +} + +/// The title of the popup open on the panel named `name`: that name, level with the popup's Close button +fn open_popup_title(harness: &Harness<'_, TextureCraftApp>, name: &str) -> Option { + let close = popup_close_button(harness)?; + harness + .get_all_by_label(name) + .map(|node| node.rect()) + .find(|title| title.right() < close.left() && (close.top()..=close.bottom()).contains(&title.center().y)) +} + fn popup_title(harness: &Harness<'_, TextureCraftApp>, name: &str) -> egui::Rect { - harness.get_all_by_label(name).map(|node| node.rect()).find(|rect| rect.max.x < RAIL_LEFT_EDGE).expect("the popup's title") + open_popup_title(harness, name).expect("the popup's title") +} + +fn popup_shows(harness: &Harness<'_, TextureCraftApp>, name: &str) -> bool { + open_popup_title(harness, name).is_some() +} + +fn popup_closed(harness: &Harness<'_, TextureCraftApp>) -> bool { + popup_close_button(harness).is_none() } #[test] @@ -85,17 +109,17 @@ fn the_rail_shows_one_panel_at_a_time() { let mut harness = app(); click_rail(&mut harness, "Shader Settings"); - assert_eq!(harness.state().ui.rail_panel, Some(Panel::Shader)); + assert!(popup_shows(&harness, "Shader Settings")); assert!(harness.query_by_label(SHADER_SETTING).is_some()); click_rail(&mut harness, "Display Settings"); - assert_eq!(harness.state().ui.rail_panel, Some(Panel::Display)); + assert!(popup_shows(&harness, "Display Settings")); assert!(harness.query_by_label(SHADER_SETTING).is_none(), "opening Display Settings closed Shader Settings"); assert!(harness.query_by_label(DISPLAY_SETTING).is_some()); assert!(!harness.state().ui.dock.is_open(Panel::Shader), "the rail's panels are not dock windows"); click_rail(&mut harness, "Display Settings"); - assert_eq!(harness.state().ui.rail_panel, None, "its own icon closes it"); + assert!(popup_closed(&harness), "its own icon closes it"); } #[test] @@ -115,17 +139,17 @@ fn the_close_button_a_press_outside_and_escape_close_it() { click_rail(&mut harness, "Display Settings"); harness.get_by_role_and_label(Role::Button, "Close").click(); harness.run_steps(SETTLE_FRAMES); - assert_eq!(harness.state().ui.rail_panel, None, "Close"); + assert!(popup_closed(&harness), "Close"); click_rail(&mut harness, "Log"); harness.get_by_label("Assets").click(); harness.run_steps(SETTLE_FRAMES); - assert_eq!(harness.state().ui.rail_panel, None, "a press outside"); + assert!(popup_closed(&harness), "a press outside"); click_rail(&mut harness, "Log"); harness.key_press(egui::Key::Escape); harness.run_steps(SETTLE_FRAMES); - assert_eq!(harness.state().ui.rail_panel, None, "Escape"); + assert!(popup_closed(&harness), "Escape"); } #[test] @@ -135,12 +159,12 @@ fn dragging_the_title_out_floats_the_panel_and_frees_the_rail() { click_rail(&mut harness, "History"); let title = popup_title(&harness, "History").center(); drag(&mut harness, title, title + INTO_THE_VIEWPORT); - assert_eq!(harness.state().ui.rail_panel, None); + assert!(popup_closed(&harness)); assert!(harness.state().ui.dock.is_visible(Panel::History), "History floats on its own"); assert!(rail_icon(&harness, "History").is_none(), "a panel in the dock has no rail icon"); click_rail(&mut harness, "Shader Settings"); - assert_eq!(harness.state().ui.rail_panel, Some(Panel::Shader)); + assert!(popup_shows(&harness, "Shader Settings")); assert!(harness.state().ui.dock.is_visible(Panel::History), "History stays open beside the rail's panel"); } @@ -165,7 +189,7 @@ fn a_panel_closed_in_the_dock_returns_to_the_rail() { harness.state_mut().ui.dock.close(Panel::TextureSetSettings); harness.run_steps(SETTLE_FRAMES); click_rail(&mut harness, "Texture Set Settings"); - assert_eq!(harness.state().ui.rail_panel, Some(Panel::TextureSetSettings)); + assert!(popup_shows(&harness, "Texture Set Settings")); } #[test] @@ -175,13 +199,13 @@ fn window_views_open_the_rail_panels_popup() { let ctx = harness.ctx.clone(); texturecraft_ui_egui::menus::invoke(harness.state_mut(), &ctx, "ui.view.shader"); harness.run_steps(SETTLE_FRAMES); - assert_eq!(harness.state().ui.rail_panel, Some(Panel::Shader)); + assert!(popup_shows(&harness, "Shader Settings")); assert!(!harness.state().ui.dock.is_open(Panel::Shader)); // Project configuration opens Display Settings, in its popup too texturecraft_ui_egui::menus::invoke(harness.state_mut(), &ctx, "ui.projectConfig"); harness.run_steps(SETTLE_FRAMES); - assert_eq!(harness.state().ui.rail_panel, Some(Panel::Display)); + assert!(popup_shows(&harness, "Display Settings")); } #[test] From f5e41e759f63f68993eafa855f1fd585de9ec289 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Mon, 9 Nov 2026 10:09:43 -0500 Subject: [PATCH 32/64] docs: add SonarCloud badge to README (#371) --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 80f807b6..69cd720c 100644 --- a/README.md +++ b/README.md @@ -32,6 +32,7 @@ MCP server for agents License: MIT OR Apache-2.0
+ Scanned by SonarCloud Reviewed by CodeRabbit

From 1a795584f12d113f70675c34c424dfab5c1d4037 Mon Sep 17 00:00:00 2001 From: vangel76 Date: Tue, 10 Nov 2026 00:06:01 +0100 Subject: [PATCH 33/64] perf(formats): cores kept for the UI and a RAM share for project saves are settings The worker cap of 8 and the fixed 3 GiB in-flight budget are gone. Prefs gets 'cores kept for the UI' (default 1, 0 or more) and 'max RAM while saving' (default 50% of the free RAM). Co-Authored-By: Claude Sonnet 5.5 --- Cargo.lock | 74 +++++++++++++++++++--- Cargo.toml | 2 + crates/formats/Cargo.toml | 3 + crates/formats/src/lib.rs | 2 +- crates/formats/src/project_file/entries.rs | 63 +++++++++++++++--- crates/formats/src/project_file/mod.rs | 2 + crates/formats/src/project_file/tests.rs | 38 +++++++++++ crates/ui-egui/src/i18n/ar.rs | 6 ++ crates/ui-egui/src/i18n/de.rs | 6 ++ crates/ui-egui/src/i18n/es.rs | 6 ++ crates/ui-egui/src/i18n/fr.rs | 6 ++ crates/ui-egui/src/i18n/it.rs | 6 ++ crates/ui-egui/src/i18n/ja.rs | 6 ++ crates/ui-egui/src/i18n/ko.rs | 6 ++ crates/ui-egui/src/i18n/pt_br.rs | 6 ++ crates/ui-egui/src/i18n/zh_hans.rs | 6 ++ crates/ui-egui/src/lib.rs | 5 +- crates/ui-egui/src/state.rs | 7 ++ crates/ui-egui/src/windows.rs | 7 ++ 19 files changed, 237 insertions(+), 20 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7a9453c3..8f34fc52 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -563,7 +563,7 @@ dependencies = [ "maybe-owned", "rustix 1.1.5", "rustix-linux-procfs", - "windows-sys 0.60.2", + "windows-sys 0.61.2", "winx", ] @@ -1171,7 +1171,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -2417,6 +2417,15 @@ dependencies = [ "memchr", ] +[[package]] +name = "ntapi" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3b335231dfd352ffb0f8017f3b6027a4917f7df785ea2143d8af2adc66980ae" +dependencies = [ + "winapi", +] + [[package]] name = "num-complex" version = "0.4.6" @@ -2629,6 +2638,16 @@ dependencies = [ "objc2-core-foundation", ] +[[package]] +name = "objc2-io-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33fafba39597d6dc1fb709123dfa8289d39406734be322956a69f0931c73bb15" +dependencies = [ + "libc", + "objc2-core-foundation", +] + [[package]] name = "objc2-io-surface" version = "0.3.2" @@ -2812,7 +2831,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" dependencies = [ "libc", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -3414,7 +3433,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.12.1", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -3713,7 +3732,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" dependencies = [ "libc", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -3788,6 +3807,20 @@ dependencies = [ "web-sys", ] +[[package]] +name = "sysinfo" +version = "0.40.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e8a3edbe0394ce115f3917a00349dd242be09eb5a091ed509eaf67b55cfb8a8" +dependencies = [ + "libc", + "memchr", + "ntapi", + "objc2-core-foundation", + "objc2-io-kit", + "windows", +] + [[package]] name = "tempfile" version = "3.27.0" @@ -3795,10 +3828,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" dependencies = [ "fastrand", - "getrandom 0.3.4", + "getrandom 0.4.3", "once_cell", "rustix 1.1.5", - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] [[package]] @@ -3929,6 +3962,7 @@ dependencies = [ "rayon", "serde", "serde_json", + "sysinfo", "texturecraft-compose", "texturecraft-core", "texturecraft-geom", @@ -4274,7 +4308,7 @@ checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" dependencies = [ "memoffset", "tempfile", - "windows-sys 0.60.2", + "windows-sys 0.61.2", ] [[package]] @@ -4787,15 +4821,37 @@ dependencies = [ "web-sys", ] +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + [[package]] name = "winapi-util" version = "0.1.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" dependencies = [ - "windows-sys 0.52.0", + "windows-sys 0.61.2", ] +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + [[package]] name = "windows" version = "0.62.2" diff --git a/Cargo.toml b/Cargo.toml index 02b5a6dc..a63fdcc7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -32,6 +32,8 @@ serde_json = "1" glam = { version = "0.30", features = ["serde", "bytemuck"] } bytemuck = { version = "1", features = ["derive"] } rayon = "1" +# Free RAM, to size how much a project save holds in flight. +sysinfo = { version = "0.40", default-features = false, features = ["system"] } # Text alphas: shaping and glyph outlines, the versions egui's text layout already builds. harfrust = "0.12" skrifa = { version = "0.44", default-features = false, features = ["std"] } diff --git a/crates/formats/Cargo.toml b/crates/formats/Cargo.toml index cb0fa8c5..7b458a53 100644 --- a/crates/formats/Cargo.toml +++ b/crates/formats/Cargo.toml @@ -27,3 +27,6 @@ serde_json = { workspace = true } thiserror = { workspace = true } rayon = { workspace = true } base64 = { workspace = true } + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +sysinfo = { workspace = true } diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index d504072a..15df21f4 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -54,7 +54,7 @@ pub use export::write_files; #[cfg(not(target_arch = "wasm32"))] pub use mesh_import::{import_mesh, read_mesh_file}; #[cfg(not(target_arch = "wasm32"))] -pub use project_file::{load_project, save_project}; +pub use project_file::{DEFAULT_RAM_PERCENT, DEFAULT_RESERVED_CORES, load_project, save_project, set_save_resources}; #[derive(Debug, thiserror::Error)] pub enum FormatError { diff --git a/crates/formats/src/project_file/entries.rs b/crates/formats/src/project_file/entries.rs index 9e4c6d03..8bdd8906 100644 --- a/crates/formats/src/project_file/entries.rs +++ b/crates/formats/src/project_file/entries.rs @@ -8,8 +8,8 @@ //! therefore the same as in a serial save. //! //! Memory stays bounded: a worker only starts an entry while the entries started but not yet written -//! have an estimated compressed size under [`IN_FLIGHT_BUDGET`] (a single entry larger than that runs -//! alone), and entry bodies stream into the compressor instead of building a raw copy first. +//! have an estimated compressed size under the RAM share the user allows (a single entry larger than +//! that runs alone), and entry bodies stream into the compressor instead of building a raw copy first. use std::io::{Seek, Write}; @@ -31,22 +31,67 @@ pub(super) struct Entry<'a> { pub body: Body<'a>, } -/// Compressed bytes (estimated) that may be held in memory at once while entries are in flight. +/// How much of the machine a save may use. Native targets only; the browser saves on one thread. #[cfg(not(target_arch = "wasm32"))] -const IN_FLIGHT_BUDGET: u64 = 3 << 30; -/// More workers than this do not help: a project has a handful of large entries. +mod limits { + use std::sync::atomic::{AtomicU8, AtomicUsize, Ordering}; + + /// Cores a save leaves to the UI (an autosave runs while the user keeps painting). + static RESERVED_CORES: AtomicUsize = AtomicUsize::new(DEFAULT_RESERVED_CORES); + /// Share of the available RAM, in percent, that entries in flight may hold. + static RAM_PERCENT: AtomicU8 = AtomicU8::new(DEFAULT_RAM_PERCENT); + + pub const DEFAULT_RESERVED_CORES: usize = 1; + pub const DEFAULT_RAM_PERCENT: u8 = 50; + + pub fn set(reserved_cores: usize, ram_percent: u8) { + RESERVED_CORES.store(reserved_cores, Ordering::Relaxed); + RAM_PERCENT.store(ram_percent.clamp(1, 100), Ordering::Relaxed); + } + + pub fn get() -> (usize, u8) { + (RESERVED_CORES.load(Ordering::Relaxed), RAM_PERCENT.load(Ordering::Relaxed)) + } + + /// RAM the system can give out now, in bytes (the total when the system does not say it; 8 GiB + /// when the system tells nothing). + pub fn available_ram() -> u64 { + let Ok(mut sys) = sysinfo::System::new() else { return 8 << 30 }; + sys.refresh_memory(); + match sys.available_memory() { + 0 => sys.total_memory(), + n => n, + } + } +} + #[cfg(not(target_arch = "wasm32"))] -const MAX_WORKERS: usize = 8; +pub use limits::{DEFAULT_RAM_PERCENT, DEFAULT_RESERVED_CORES}; + +/// Set what saves may use: cores left to the UI (any number; at least one worker always runs) and +/// the percentage (1 to 100) of the available RAM that entries in flight may hold. +#[cfg(not(target_arch = "wasm32"))] +pub fn set_save_resources(reserved_cores: usize, ram_percent: u8) { + limits::set(reserved_cores, ram_percent); +} + +/// Worker threads and in-flight byte budget for a save of `entries` entries. +#[cfg(not(target_arch = "wasm32"))] +pub(super) fn plan(cpus: usize, reserved_cores: usize, entries: usize, available_ram: u64, ram_percent: u8) -> (usize, u64) { + let workers = cpus.saturating_sub(reserved_cores).max(1).min(entries); + let budget = u64::try_from(u128::from(available_ram) * u128::from(ram_percent.clamp(1, 100)) / 100).unwrap_or(u64::MAX); + (workers, budget) +} /// Write `entries` in order: in parallel where threads exist, else one after the other. pub(super) fn write_entries(zip: &mut ZipWriter, entries: Vec>) -> Result<()> { #[cfg(not(target_arch = "wasm32"))] { - // Leave one core to the UI: an autosave runs while the user keeps painting. let cpus = std::thread::available_parallelism().map_or(1, usize::from); - let workers = cpus.saturating_sub(1).clamp(1, MAX_WORKERS).min(entries.len()); + let (reserved, percent) = limits::get(); + let (workers, budget) = plan(cpus, reserved, entries.len(), limits::available_ram(), percent); if workers > 1 { - return parallel::write(zip, entries, workers, IN_FLIGHT_BUDGET); + return parallel::write(zip, entries, workers, budget); } } write_serial(zip, entries) diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index 7a8a39fa..3d8d35f7 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -32,6 +32,8 @@ use self::entries::Entry; use crate::{FormatError, MAX_IMAGE_SIZE, Result, malformed}; mod entries; +#[cfg(not(target_arch = "wasm32"))] +pub use entries::{DEFAULT_RAM_PERCENT, DEFAULT_RESERVED_CORES, set_save_resources}; const KIND: &str = "project file"; const MAGIC: &[u8; 4] = b"TCTX"; diff --git a/crates/formats/src/project_file/tests.rs b/crates/formats/src/project_file/tests.rs index e5952be9..cc2bd385 100644 --- a/crates/formats/src/project_file/tests.rs +++ b/crates/formats/src/project_file/tests.rs @@ -258,6 +258,44 @@ fn parallel_bytes(pf: &ProjectFile, workers: usize, budget: u64) -> Vec { zip.finish().unwrap().into_inner() } +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn save_plan_follows_the_reserved_cores_and_the_ram_share() { + // No cap of 8 workers any more, only the entry count and the cores. + assert_eq!(entries::plan(64, 1, 100, 1000, 50), (63, 500)); + assert_eq!(entries::plan(64, 1, 20, 1000, 50).0, 20); + // 0 reserved uses every core; more reserved than cores still leaves one worker. + assert_eq!(entries::plan(16, 0, 100, 1000, 100), (16, 1000)); + assert_eq!(entries::plan(4, 9, 100, 1000, 100).0, 1); + assert_eq!(entries::plan(1, 0, 100, 1000, 100).0, 1); + // The share is of the RAM given, clamped to 1..=100 percent, and never overflows. + assert_eq!(entries::plan(2, 1, 5, 1000, 0).1, 10); + assert_eq!(entries::plan(2, 1, 5, 1000, 250).1, 1000); + assert_eq!(entries::plan(2, 1, 5, u64::MAX, 100).1, u64::MAX); + assert_eq!(entries::plan(2, 1, 5, u64::MAX, 50).1, u64::MAX / 2); +} + +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn parallel_save_with_any_reserved_cores_and_ram_share_matches_serial() { + let pf = big_sample(); + let want = payloads(&serial_bytes(&pf)); + let n = want.len(); + // (cpus, reserved cores, available RAM, percent): none reserved, all reserved, a tiny and a huge share. + for (cpus, reserved, ram, percent) in [(8, 0, 1u64 << 40, 100u8), (8, 1, 1 << 40, 50), (8, 99, 1 << 40, 50), (16, 0, 1000, 1), (6, 1, u64::MAX, 100)] { + let (workers, budget) = entries::plan(cpus, reserved, n, ram, percent); + let got = parallel_bytes(&pf, workers, budget); + assert!(payloads(&got) == want, "{cpus} cpus, {reserved} reserved, {ram} bytes at {percent}%"); + assert_same(&pf, &load_project_bytes(&got).unwrap()); + } + // The setting is read by the public save; extreme values still save the same entries. + for (reserved, percent) in [(0, 100), (1000, 1), (1, 50)] { + set_save_resources(reserved, percent); + assert!(payloads(&save_project_bytes(&pf).unwrap()) == want, "{reserved} reserved, {percent}%"); + } + set_save_resources(DEFAULT_RESERVED_CORES, DEFAULT_RAM_PERCENT); +} + #[test] #[cfg(not(target_arch = "wasm32"))] fn parallel_save_writes_the_same_entries_as_serial() { diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 6ef517e9..ff6d2d92 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1041,4 +1041,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "الحد الأقصى للقيمة"), ("Value Bounds Min", "الحد الأدنى للقيمة"), ("Vertex Color", "لون الرأس"), + ("Cores kept for the UI", "أنوية محجوزة للواجهة"), + ("Max RAM while saving", "أقصى ذاكرة عند الحفظ"), + ( + "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", + "يستخدم الحفظ الأنوية الأخرى وحدًا أقصى بهذه النسبة من الذاكرة الحرة. يعمل نواة واحدة على الأقل دائمًا.", + ), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index caaabb14..0ae53a8e 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1090,4 +1090,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "Maximaler Grenzwert"), ("Value Bounds Min", "Minimaler Grenzwert"), ("Vertex Color", "Scheitelpunktfarbe"), + ("Cores kept for the UI", "Für die Oberfläche reservierte Kerne"), + ("Max RAM while saving", "Max. RAM beim Speichern"), + ( + "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", + "Das Speichern nutzt die übrigen Kerne und höchstens diesen Anteil des freien RAMs. Mindestens ein Kern arbeitet immer.", + ), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 6c8ccccb..23cb6675 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1075,4 +1075,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "Límite máximo"), ("Value Bounds Min", "Límite mínimo"), ("Vertex Color", "Color de vértice"), + ("Cores kept for the UI", "Núcleos reservados para la interfaz"), + ("Max RAM while saving", "RAM máx. al guardar"), + ( + "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", + "Guardar usa los demás núcleos y como máximo esta parte de la RAM libre. Siempre trabaja al menos un núcleo.", + ), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index f10bba8d..bd822836 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1099,4 +1099,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "Borne maximale"), ("Value Bounds Min", "Borne minimale"), ("Vertex Color", "Couleur des sommets"), + ("Cores kept for the UI", "Cœurs réservés à l'interface"), + ("Max RAM while saving", "RAM max. à l'enregistrement"), + ( + "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", + "L'enregistrement utilise les autres cœurs et au plus cette part de la RAM libre. Au moins un cœur travaille toujours.", + ), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 1c19d597..319c78cd 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1084,4 +1084,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "Limite massimo"), ("Value Bounds Min", "Limite minimo"), ("Vertex Color", "Colore dei vertici"), + ("Cores kept for the UI", "Core riservati all'interfaccia"), + ("Max RAM while saving", "RAM max durante il salvataggio"), + ( + "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", + "Il salvataggio usa gli altri core e al massimo questa quota della RAM libera. Almeno un core lavora sempre.", + ), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 068603b5..43785df8 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1069,4 +1069,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "値の上限"), ("Value Bounds Min", "値の下限"), ("Vertex Color", "頂点カラー"), + ("Cores kept for the UI", "UI用に確保するコア数"), + ("Max RAM while saving", "保存時のRAM上限"), + ( + "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", + "保存は残りのコアと、空きRAMのこの割合までを使います。少なくとも1コアは常に動作します。", + ), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 137d6177..617838b0 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1054,4 +1054,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "값 상한"), ("Value Bounds Min", "값 하한"), ("Vertex Color", "정점 색상"), + ("Cores kept for the UI", "UI용으로 남겨 둘 코어"), + ("Max RAM while saving", "저장 시 최대 RAM"), + ( + "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", + "저장은 나머지 코어와 여유 RAM의 이 비율까지만 사용합니다. 최소 한 개의 코어는 항상 작동합니다.", + ), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 99627b25..4e35f4f9 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1072,4 +1072,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "Limite máximo"), ("Value Bounds Min", "Limite mínimo"), ("Vertex Color", "Cor do vértice"), + ("Cores kept for the UI", "Núcleos reservados para a interface"), + ("Max RAM while saving", "RAM máx. ao salvar"), + ( + "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", + "Salvar usa os outros núcleos e no máximo esta parte da RAM livre. Pelo menos um núcleo sempre trabalha.", + ), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index 18623ce3..5677d139 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1000,4 +1000,10 @@ pub const TABLE: &[(&str, &str)] = &[ ("Value Bounds Max", "值上限"), ("Value Bounds Min", "值下限"), ("Vertex Color", "顶点颜色"), + ("Cores kept for the UI", "为界面保留的核心数"), + ("Max RAM while saving", "保存时的最大内存"), + ( + "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", + "保存使用其余核心,并最多占用这一比例的可用内存。至少始终有一个核心工作。", + ), ]; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 8bfc66c9..fd5c2351 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -462,7 +462,10 @@ impl eframe::App for TextureCraftApp { ctx.set_zoom_factor(scale); } #[cfg(not(target_arch = "wasm32"))] - self.autosave(now); + { + texturecraft_engine::formats::set_save_resources(self.ui.prefs.reserved_cores as usize, self.ui.prefs.save_ram_percent); + self.autosave(now); + } i18n::set_language(&self.ui.prefs.language); #[cfg(target_arch = "wasm32")] { diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index 89c12bb0..45117787 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -118,6 +118,11 @@ pub struct Prefs { /// Where autosaves, smart materials, presets, templates and layouts go (desktop; read at /// startup). Empty or relative: `Documents/TextureCraft`. pub data_folder: String, + /// Cores a project save leaves to the UI; it compresses on the others (desktop). Any number: + /// at least one worker always runs. + pub reserved_cores: u32, + /// Percent of the free RAM a project save may hold at once (desktop; 1 to 100). + pub save_ram_percent: u8, } impl Default for Prefs { @@ -132,6 +137,8 @@ impl Default for Prefs { system_title_bar: false, start_window: true, data_folder: String::new(), + reserved_cores: 1, + save_ram_percent: 50, } } } diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index c8bd72c5..7708e21f 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -572,7 +572,14 @@ fn settings(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.label(tr("Autosave every")); ui.add(egui::DragValue::new(&mut p.autosave_minutes).range(0..=120).suffix(format!(" {}", tr("min")))); ui.end_row(); + ui.label(tr("Cores kept for the UI")); + ui.add(egui::DragValue::new(&mut p.reserved_cores).range(0..=1024)); + ui.end_row(); + ui.label(tr("Max RAM while saving")); + ui.add(egui::DragValue::new(&mut p.save_ram_percent).range(1..=100).suffix(" %")); + ui.end_row(); }); + ui.label(RichText::new(tr("Saving uses the other cores and at most this share of the free RAM. At least one core always works.")).small().color(tk.text_dim)); ui.label( RichText::new(trf("0 turns autosave off. Copies go to {folder}", &[("folder", &crate::user_dir("autosave").display())])) .small() From 832a7f9e89662745c2945c487d36790feac33845 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Tue, 10 Nov 2026 01:34:02 -0500 Subject: [PATCH 34/64] Fix live bake preview review findings --- crates/engine/src/bake/bake_task.rs | 39 ++----- crates/engine/src/bake/mesh_map_command.rs | 1 + crates/engine/src/bake/mod.rs | 6 +- crates/engine/src/bake/streamed_bake.rs | 14 +++ crates/engine/src/bake/streamed_map.rs | 17 +++ crates/engine/src/bake_preview.rs | 67 ++++------- crates/engine/src/bake_preview/preview_set.rs | 10 ++ .../engine/src/bake_preview/preview_show.rs | 30 +++++ crates/engine/src/bake_preview/stage.rs | 11 ++ crates/engine/src/polygon_fill.rs | 5 + crates/engine/tests/bake_preview.rs | 104 +++++++++++++++++- crates/ui-egui/src/bake_job.rs | 8 ++ crates/ui-egui/src/bake_mode/mod.rs | 5 + crates/ui-egui/src/control.rs | 2 + crates/ui-egui/src/lib.rs | 56 +++++----- crates/ui-egui/src/running_bake.rs | 15 +++ crates/ui-egui/src/viewport.rs | 29 ++++- crates/ui-egui/tests/bake_preview.rs | 66 +++++++++++ docs/control-protocol.md | 4 +- 19 files changed, 381 insertions(+), 108 deletions(-) create mode 100644 crates/engine/src/bake/streamed_bake.rs create mode 100644 crates/engine/src/bake/streamed_map.rs create mode 100644 crates/engine/src/bake_preview/preview_set.rs create mode 100644 crates/engine/src/bake_preview/preview_show.rs create mode 100644 crates/engine/src/bake_preview/stage.rs create mode 100644 crates/ui-egui/src/bake_job.rs create mode 100644 crates/ui-egui/src/running_bake.rs diff --git a/crates/engine/src/bake/bake_task.rs b/crates/engine/src/bake/bake_task.rs index 2614890d..1148f998 100644 --- a/crates/engine/src/bake/bake_task.rs +++ b/crates/engine/src/bake/bake_task.rs @@ -1,4 +1,4 @@ -use super::MergedHigh; +use super::{MergedHigh, StreamedBake, StreamedMap}; use crate::{EngineError, Result}; use std::sync::Arc; use texturecraft_bake::{BakeOutput, BakePaintMap, BakeRequest, HighPoly, Progress, bake_tiles, tracing::Tracer}; @@ -28,30 +28,6 @@ pub struct BakeTask { pub tracer: Option>, } -/// One finished map of a streamed bake (see [`BakeTask::run_streaming`]). -#[derive(Clone, Debug)] -pub struct StreamedMap { - pub map: BakedMap, - /// Position among the maps this bake makes, from 0, and how many there are. - pub index: usize, - pub total: usize, - /// Width and height in texels. - pub resolution: u32, - pub height: u32, - /// Row-major, `map.components()` floats per texel, padded. - pub data: Arc>, -} - -/// The result of a streamed bake: the finished maps stay shared (`Arc`) with whoever was shown them, -/// so the preview and the document hold one buffer per map, never two -#[derive(Clone, Debug)] -pub struct StreamedBake { - pub resolution: u32, - pub height: u32, - pub maps: std::collections::BTreeMap>>, - pub tracer: String, -} - impl BakeTask { /// The maps this task makes, in the order [`BakeTask::run_streaming`] finishes them pub fn maps(&self) -> Vec { @@ -69,22 +45,28 @@ impl BakeTask { let maps = self.maps(); let total = maps.len(); let mut combined: Option = None; + for (index, map) in maps.into_iter().enumerate() { let mut settings = self.settings.clone(); settings.maps.select([map]); let mut output = self.run_with(&settings, progress)?; let Some(data) = output.maps.remove(&map) else { continue }; + let data = Arc::new(data); on_map(StreamedMap { map, index, total, resolution: output.resolution, height: output.height, data: data.clone() }); match &mut combined { - Some(all) => { - all.maps.insert(map, data); + Some(combined) => { + combined.maps.insert(map, data); } None => { - combined = Some(StreamedBake { resolution: output.resolution, height: output.height, maps: [(map, data)].into(), tracer: output.tracer }); + // A resized partial bake also returns unchecked maps that must survive application + let mut retained: std::collections::BTreeMap<_, _> = output.maps.into_iter().map(|(map, pixels)| (map, Arc::new(pixels))).collect(); + retained.insert(map, data); + combined = Some(StreamedBake { resolution: output.resolution, height: output.height, maps: retained, tracer: output.tracer }); } } } + match combined { Some(output) => Ok(output), None => { @@ -118,6 +100,7 @@ impl BakeTask { cage_paint: self.cage_paint.as_deref(), tiles: self.tiles, }; + let mut output = bake_tiles(&request, progress, &self.excluded_tiles, self.tracer.as_deref()) .map_err(|error| EngineError::Other(format!("bake failed: {error}")))?; super::preserve_tiles::restore(&mut output, &self.previous_maps, &self.excluded_tiles, self.tiles)?; diff --git a/crates/engine/src/bake/mesh_map_command.rs b/crates/engine/src/bake/mesh_map_command.rs index 50d923ec..14248cc3 100644 --- a/crates/engine/src/bake/mesh_map_command.rs +++ b/crates/engine/src/bake/mesh_map_command.rs @@ -226,6 +226,7 @@ impl Session { if entry.resolution != resolution || entry.maps.keys().any(|map| entry.height(*map) != height) { entry.maps.clear(); } + entry.resolution = resolution; entry.maps.extend(maps); self.doc.project.texture_set_mut(texture_set)?.baked = entry.maps.keys().copied().collect(); diff --git a/crates/engine/src/bake/mod.rs b/crates/engine/src/bake/mod.rs index 093cfcf5..f06ab265 100644 --- a/crates/engine/src/bake/mod.rs +++ b/crates/engine/src/bake/mod.rs @@ -11,16 +11,20 @@ mod mesh_map_command; mod model_patch; mod paint_command; mod preserve_tiles; +mod streamed_bake; +mod streamed_map; mod tile_command; pub use bake_cage_inputs::BakeCageInputs; pub use bake_mesh::BakeMesh; pub use bake_meshes::BakeMeshes; -pub use bake_task::{BakeTask, StreamedBake, StreamedMap}; +pub use bake_task::BakeTask; pub use high_poly_missed::high_poly_missed; pub use merged_high::MergedHigh; pub use mesh_map_command::{install_gpu_tracer, meshes_json, settings_params}; pub use model_patch::settings_patch; +pub use streamed_bake::StreamedBake; +pub use streamed_map::StreamedMap; pub use texturecraft_bake::*; use crate::CommandSpec; diff --git a/crates/engine/src/bake/streamed_bake.rs b/crates/engine/src/bake/streamed_bake.rs new file mode 100644 index 00000000..55aecbca --- /dev/null +++ b/crates/engine/src/bake/streamed_bake.rs @@ -0,0 +1,14 @@ +use std::collections::BTreeMap; +use std::sync::Arc; + +use texturecraft_core::BakedMap; + +/// The result of a streamed bake: the finished maps stay shared (`Arc`) with whoever was shown them, +/// so the preview and the document hold one buffer per map, never two +#[derive(Clone, Debug)] +pub struct StreamedBake { + pub resolution: u32, + pub height: u32, + pub maps: BTreeMap>>, + pub tracer: String, +} diff --git a/crates/engine/src/bake/streamed_map.rs b/crates/engine/src/bake/streamed_map.rs new file mode 100644 index 00000000..33781099 --- /dev/null +++ b/crates/engine/src/bake/streamed_map.rs @@ -0,0 +1,17 @@ +use std::sync::Arc; + +use texturecraft_core::BakedMap; + +/// One finished map of a streamed bake (see [`crate::BakeTask::run_streaming`]). +#[derive(Clone, Debug)] +pub struct StreamedMap { + pub map: BakedMap, + /// Position among the maps this bake makes, from 0, and how many there are. + pub index: usize, + pub total: usize, + /// Width and height in texels. + pub resolution: u32, + pub height: u32, + /// Row-major, `map.components()` floats per texel, padded. + pub data: Arc>, +} diff --git a/crates/engine/src/bake_preview.rs b/crates/engine/src/bake_preview.rs index 801cf817..c19e9802 100644 --- a/crates/engine/src/bake_preview.rs +++ b/crates/engine/src/bake_preview.rs @@ -6,6 +6,14 @@ //! shows one map at a time, raw on the model; maps and texture sets not baked yet show their //! neutral value. +mod preview_set; +mod preview_show; +mod stage; + +pub use preview_set::PreviewSet; +pub use preview_show::PreviewShow; +pub use stage::Stage; + use std::collections::BTreeMap; use serde_json::{Value, json}; @@ -32,53 +40,6 @@ pub fn specs() -> Vec { )] } -/// What the 3D view shows while a bake runs. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub enum PreviewShow { - /// The newest finished map (the first one, still neutral, before any is done). - Follow, - /// One map, pinned: neutral until it is baked. - Pin(BakedMap), - /// The lit material. - Material, -} - -impl PreviewShow { - pub fn id(self) -> String { - match self { - PreviewShow::Follow => "follow".into(), - PreviewShow::Pin(map) => format!("map:{}", map.id()), - PreviewShow::Material => "material".into(), - } - } - - pub fn parse(text: &str) -> Option { - match text { - "follow" => Some(PreviewShow::Follow), - "material" => Some(PreviewShow::Material), - _ => text.strip_prefix("map:").and_then(BakedMap::parse).map(PreviewShow::Pin), - } - } -} - -/// The maps of one texture set streamed so far. -#[derive(Clone, Debug, Default)] -pub struct PreviewSet { - pub baked: BakedMaps, - /// The maps this set's bake makes, in the order they arrive. - pub order: Vec, -} - -/// The map a bake is working on. -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub struct Stage { - pub texture_set: usize, - pub map: BakedMap, - /// 1-based position among the set's maps, and how many there are. - pub position: usize, - pub total: usize, -} - #[derive(Clone, Debug)] pub struct BakePreview { /// The view mode to put back when the preview ends. @@ -124,6 +85,7 @@ impl Session { pub fn bake_preview_begin(&mut self, sets: Vec<(usize, Vec)>) { let restore = self.bake_preview.as_ref().map_or(self.view, |preview| preview.restore); let sets = sets.into_iter().map(|(texture_set, order)| (texture_set, PreviewSet { baked: BakedMaps::default(), order })).collect(); + self.bake_preview = Some(BakePreview { restore, show: PreviewShow::Follow, sets, current: None, newest: None }); self.bake_preview_refresh(); } @@ -133,17 +95,21 @@ impl Session { if let Some(preview) = &mut self.bake_preview { preview.current = Some(texture_set); } + self.bake_preview_refresh(); } /// Install one finished map of set `texture_set`. Returns false when no preview shows. pub fn bake_preview_map(&mut self, texture_set: usize, streamed: StreamedMap) -> bool { let Some(preview) = &mut self.bake_preview else { return false }; + let set = preview.sets.entry(texture_set).or_default(); + // A new bake of the set starts from nothing (the baker never repeats a map) if streamed.index == 0 { set.baked = BakedMaps::default(); } + set.baked.resolution = streamed.resolution; set.baked.maps.insert(streamed.map, streamed.data); preview.newest = Some(streamed.map); @@ -154,6 +120,7 @@ impl Session { /// Choose what the view shows (Follow, a pinned map or the material). pub fn bake_preview_show(&mut self, show: PreviewShow) -> Result<()> { let Some(preview) = &mut self.bake_preview else { return Err(bad("bake.preview", "no bake is running")) }; + preview.show = show; self.bake_preview_refresh(); Ok(()) @@ -163,6 +130,7 @@ impl Session { /// the material and is what comes back when the bake ends. pub(crate) fn bake_preview_user_view(&mut self, view: ViewMode) { let Some(preview) = &mut self.bake_preview else { return }; + match view { ViewMode::MeshMap(map) => preview.show = PreviewShow::Pin(map), other => { @@ -170,6 +138,7 @@ impl Session { preview.restore = other; } } + self.bake_preview_refresh(); if !matches!(view, ViewMode::MeshMap(_)) { self.view = view; @@ -201,6 +170,7 @@ impl Session { fn bake_preview_refresh(&mut self) { let Some(preview) = &self.bake_preview else { return }; + self.view = match preview.shown() { Some(map) => ViewMode::MeshMap(map), None => ViewMode::Material, @@ -212,6 +182,7 @@ impl Session { /// The preview as JSON, for `bake.preview`, `session.inspect` and `ui.inspect`. pub fn preview_json(session: &Session) -> Value { let Some(preview) = &session.bake_preview else { return json!({ "active": false }) }; + let stage = preview.stage().map(|stage| json!({ "set": stage.texture_set, "map": stage.map.id(), "n": stage.position, "total": stage.total })); let sets: Vec = preview .sets @@ -224,6 +195,7 @@ pub fn preview_json(session: &Session) -> Value { }) }) .collect(); + json!({ "active": true, "show": preview.show.id(), @@ -240,5 +212,6 @@ fn preview(session: &mut Session, params: &Value) -> Result { let show = PreviewShow::parse(show).ok_or_else(|| bad("bake.preview", format!("unknown `show` {show:?}: follow, material or map:")))?; session.bake_preview_show(show)?; } + Ok(preview_json(session)) } diff --git a/crates/engine/src/bake_preview/preview_set.rs b/crates/engine/src/bake_preview/preview_set.rs new file mode 100644 index 00000000..e1eabef8 --- /dev/null +++ b/crates/engine/src/bake_preview/preview_set.rs @@ -0,0 +1,10 @@ +use texturecraft_compose::BakedMaps; +use texturecraft_core::BakedMap; + +/// The maps of one texture set streamed so far. +#[derive(Clone, Debug, Default)] +pub struct PreviewSet { + pub baked: BakedMaps, + /// The maps this set's bake makes, in the order they arrive. + pub order: Vec, +} diff --git a/crates/engine/src/bake_preview/preview_show.rs b/crates/engine/src/bake_preview/preview_show.rs new file mode 100644 index 00000000..28a13614 --- /dev/null +++ b/crates/engine/src/bake_preview/preview_show.rs @@ -0,0 +1,30 @@ +use texturecraft_core::BakedMap; + +/// What the 3D view shows while a bake runs. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum PreviewShow { + /// The newest finished map (the first one, still neutral, before any is done). + Follow, + /// One map, pinned: neutral until it is baked. + Pin(BakedMap), + /// The lit material. + Material, +} + +impl PreviewShow { + pub fn id(self) -> String { + match self { + PreviewShow::Follow => "follow".into(), + PreviewShow::Pin(map) => format!("map:{}", map.id()), + PreviewShow::Material => "material".into(), + } + } + + pub fn parse(text: &str) -> Option { + match text { + "follow" => Some(PreviewShow::Follow), + "material" => Some(PreviewShow::Material), + _ => text.strip_prefix("map:").and_then(BakedMap::parse).map(PreviewShow::Pin), + } + } +} diff --git a/crates/engine/src/bake_preview/stage.rs b/crates/engine/src/bake_preview/stage.rs new file mode 100644 index 00000000..d1513ae2 --- /dev/null +++ b/crates/engine/src/bake_preview/stage.rs @@ -0,0 +1,11 @@ +use texturecraft_core::BakedMap; + +/// The map a bake is working on. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Stage { + pub texture_set: usize, + pub map: BakedMap, + /// 1-based position among the set's maps, and how many there are. + pub position: usize, + pub total: usize, +} diff --git a/crates/engine/src/polygon_fill.rs b/crates/engine/src/polygon_fill.rs index 0372a9eb..af93f71c 100644 --- a/crates/engine/src/polygon_fill.rs +++ b/crates/engine/src/polygon_fill.rs @@ -45,6 +45,8 @@ impl Session { /// Fill what the box between viewport pixels `corner` and `opposite` selects (one undo step) pub fn polygon_fill_box(&mut self, corner: Vec2, opposite: Vec2, viewport: Vec2) -> Result { + self.refuse_while_baking()?; + // A scripted box stands alone: it finishes any drag under way, and ends even when it fails self.end_polygon_fill_box(); let shown = self.drag_polygon_fill_box(corner, opposite, viewport); @@ -54,6 +56,8 @@ impl Session { /// Fill what the box between texture coordinates `corner` and `opposite` selects (the 2D view, one undo step) pub fn polygon_fill_box_uv(&mut self, corner: Vec2, opposite: Vec2) -> Result { + self.refuse_while_baking()?; + self.end_polygon_fill_box(); let shown = self.drag_polygon_fill_box_uv(corner, opposite); let filled = self.end_polygon_fill_box(); @@ -85,6 +89,7 @@ impl Session { /// Show the fill of a box from `corner` to `opposite` in the 3D view of size `viewport`, or in the 2D view when None fn drag_polygon_fill(&mut self, corner: Vec2, opposite: Vec2, viewport: Option) -> Result { + self.refuse_while_baking()?; if !corner.is_finite() || !opposite.is_finite() { return Err(EngineError::Other("the box corners must be finite".into())); } diff --git a/crates/engine/tests/bake_preview.rs b/crates/engine/tests/bake_preview.rs index 1a53611b..bc72339d 100644 --- a/crates/engine/tests/bake_preview.rs +++ b/crates/engine/tests/bake_preview.rs @@ -19,6 +19,7 @@ fn session() -> Session { texture_set.bake.maps.ao.parameters.rays.rays = 8; texture_set.bake.maps.select(MAPS); } + session } @@ -38,7 +39,9 @@ fn streamed_maps_are_the_pixels_of_one_bake() { let task = task(&session); let whole = task.run(&Progress::new()).unwrap(); let mut streamed = Vec::new(); + let combined = task.run_streaming(&Progress::new(), &mut |map| streamed.push(map)).unwrap(); + assert_eq!(streamed.iter().map(|map| map.map).collect::>(), order(&session)); assert_eq!(streamed.iter().map(|map| (map.index, map.total)).collect::>(), (0..MAPS.len()).map(|index| (index, MAPS.len())).collect::>()); assert_eq!((combined.resolution, combined.height), (whole.resolution, whole.height)); @@ -58,8 +61,10 @@ fn the_view_follows_each_map_and_the_previous_mode_comes_back() { let before = session.view; let baked_before = session.doc.baked.get(&0).cloned(); let maps = order(&session); + session.bake_preview_begin(vec![(0, maps.clone())]); session.bake_preview_set_current(0); + // Nothing is baked yet: the first map shows, neutral assert_eq!(session.view, ViewMode::MeshMap(maps[0])); assert!(session.bake_preview_baked(0).is_some_and(|baked| baked.maps.is_empty())); @@ -74,6 +79,7 @@ fn the_view_follows_each_map_and_the_previous_mode_comes_back() { stages.push(session.bake_preview.as_ref().and_then(|preview| preview.stage()).map(|stage| (stage.position, stage.total))); }) .unwrap(); + assert_eq!(shown, maps.iter().map(|map| ViewMode::MeshMap(*map)).collect::>(), "the view follows the newest map"); assert_eq!(stages, [Some((2, 4)), Some((3, 4)), Some((4, 4)), None], "the stage names the next map"); assert_eq!(session.doc.baked.get(&0).cloned(), baked_before, "the document is untouched until the bake is applied"); @@ -82,6 +88,7 @@ fn the_view_follows_each_map_and_the_previous_mode_comes_back() { session.apply_streamed_bake(0, output).unwrap(); assert_ne!(session.undo_label().map(str::to_owned), undo_before, "applying the bake is one undo step"); session.bake_preview_end(); + assert_eq!(session.view, before, "the previous view mode is restored"); assert!(!session.bake_preview_active()); assert!(maps.iter().all(|map| session.doc.baked[&0].maps.contains_key(map))); @@ -91,10 +98,12 @@ fn the_view_follows_each_map_and_the_previous_mode_comes_back() { fn pinning_material_and_follow() { let mut session = session(); let maps = order(&session); + session.bake_preview_begin(vec![(0, maps.clone())]); session.bake_preview_set_current(0); let task = task(&session); let mut count = 0; + task.run_streaming(&Progress::new(), &mut |map| { session.bake_preview_map(0, map); count += 1; @@ -114,12 +123,14 @@ fn pinning_material_and_follow() { } }) .unwrap(); + // A mesh map picked in the viewport pins it; another mode is what comes back at the end execute(&mut session, "viewport.view", &json!({ "mode": "map:height" })).unwrap(); assert_eq!(session.bake_preview.as_ref().map(|preview| preview.show), Some(PreviewShow::Pin(BakedMap::Height))); execute(&mut session, "viewport.view", &json!({ "mode": "uvChecker" })).unwrap(); assert_eq!(session.view, ViewMode::UvChecker); session.bake_preview_end(); + assert_eq!(session.view, ViewMode::UvChecker); } @@ -128,11 +139,14 @@ fn unbaked_sets_show_neutral_and_the_control_command_reports() { let mut session = session(); assert_eq!(execute(&mut session, "bake.preview", &Value::Null).unwrap()["active"], false); assert!(execute(&mut session, "bake.preview", &json!({ "show": "material" })).is_err(), "nothing to show when no bake runs"); + session.bake_preview_begin(vec![(0, order(&session)), (1, order(&session))]); session.bake_preview_set_current(0); + assert!(session.bake_preview_baked(1).is_some_and(|baked| baked.maps.is_empty()), "a queued set has nothing yet"); assert!(session.bake_preview_baked(7).is_none(), "a set outside the bake shows its document maps"); let reply = execute(&mut session, "bake.preview", &json!({ "show": "map:ambientOcclusion" })).unwrap(); + assert_eq!( (reply["active"].clone(), reply["show"].clone(), reply["shown"].clone()), (json!(true), json!("map:ambientOcclusion"), json!("ambientOcclusion")) @@ -145,7 +159,9 @@ fn unbaked_sets_show_neutral_and_the_control_command_reports() { fn painting_is_refused_while_a_bake_shows() { let mut session = session(); session.bake_preview_begin(vec![(0, order(&session))]); + let error = session.begin_stroke(Vec2::new(10.0, 10.0), Vec2::new(100.0, 100.0), 1.0).unwrap_err().to_string(); + assert_eq!(error, texturecraft_engine::bake_preview::PAINTING_PAUSED); assert!(session.begin_stroke_uv(Vec2::new(0.5, 0.5), 1.0).is_err()); assert!(session.polygon_fill(Vec2::new(10.0, 10.0), Vec2::new(100.0, 100.0)).is_err()); @@ -164,21 +180,26 @@ fn cancelling_mid_bake_leaves_the_document_and_the_shown_maps_whole() { session.bake_preview_set_current(0); let progress = Progress::new(); let task = task(&session); + let result = task.run_streaming(&progress, &mut |map| { if map.index == 1 { progress.cancel(); } session.bake_preview_map(0, map); }); + assert!(result.is_err(), "a cancelled bake fails"); + // The two maps that landed are whole and equal to a full bake's; the others are still neutral let shown = session.bake_preview_baked(0).unwrap(); assert_eq!(shown.maps.len(), 2); for (map, data) in &shown.maps { assert!(**data == full.maps[map], "{map:?}"); } + // What the app does on cancel: end the preview; the document keeps what it had session.bake_preview_end(); + assert_eq!(session.doc.baked.get(&0).cloned(), before); assert!(session.bake_preview_baked(0).is_none()); } @@ -187,22 +208,26 @@ fn cancelling_mid_bake_leaves_the_document_and_the_shown_maps_whole() { fn the_preview_and_the_applied_document_share_each_map_buffer() { let mut session = session(); let maps = order(&session); + session.bake_preview_begin(vec![(0, maps)]); session.bake_preview_set_current(0); let mut handed_over = Vec::new(); + let output = task(&session) .run_streaming(&Progress::new(), &mut |map| { handed_over.push((map.map, map.data.clone())); session.bake_preview_map(0, map); }) .unwrap(); - // The returned maps are the handed-over buffers, not copies of them + + // Sharing the streamed buffers keeps preview memory independent of document ownership for (map, data) in &handed_over { assert!(std::sync::Arc::ptr_eq(data, &output.maps[map]), "{map:?} was copied on the way out of the bake"); let shown = &session.bake_preview_baked(0).unwrap().maps[map]; assert!(std::sync::Arc::ptr_eq(data, shown), "{map:?} is held twice by the preview"); } - // Applying keeps sharing them: the document holds the buffers the preview shows + + // Applying the result must preserve sharing with the preview session.apply_streamed_bake(0, output).unwrap(); for (map, data) in &handed_over { assert!(std::sync::Arc::ptr_eq(data, &session.doc.baked[&0].maps[map]), "{map:?} was copied into the document"); @@ -215,6 +240,7 @@ fn cancelling_keeps_a_set_that_was_already_applied_as_one_undo_step() { let mut session = session(); let before = session.doc.baked.get(&0).cloned(); let maps = order(&session); + // A multi-set bake applies each set when it finishes; a later cancel does not undo it session.bake_preview_begin(vec![(0, maps)]); session.bake_preview_set_current(0); @@ -225,7 +251,81 @@ fn cancelling_keeps_a_set_that_was_already_applied_as_one_undo_step() { .unwrap(); session.apply_streamed_bake(0, output).unwrap(); session.bake_preview_end(); + assert!(MAPS.iter().all(|map| session.doc.baked[&0].maps.contains_key(map)), "the finished set stays baked after the cancel"); session.undo().unwrap(); assert_eq!(session.doc.baked.get(&0).cloned(), before, "applying the set was one undo step"); } + +#[test] +fn a_resized_partial_streamed_bake_keeps_unchecked_maps() { + use std::sync::Arc; + use texturecraft_engine::compose::BakedMaps; + use texturecraft_engine::geom::primitives; + + let mut session = Session::new_project("Partial bake", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap(); + session.doc.baked.insert( + 0, + BakedMaps { + resolution: 64, + maps: [ + (BakedMap::AmbientOcclusion, Arc::new(vec![0.25; 64 * 32])), + (BakedMap::Normal, Arc::new(vec![0.4; 64 * 32 * 3])), + (BakedMap::Height, Arc::new(vec![0.75; 64 * 32])), + ] + .into(), + }, + ); + execute(&mut session, "bake.settings", &json!({"resolution": 64, "maps": ["ambientOcclusion", "height"], "rays": 2})).unwrap(); + execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": false})).unwrap(); + let before = session.doc.baked.clone(); + let task = task(&session); + let whole = task.run(&Progress::new()).unwrap(); + let mut streamed = Vec::new(); + + let output = task.run_streaming(&Progress::new(), &mut |map| streamed.push(map)).unwrap(); + + assert_eq!((output.resolution, output.height), (128, 64)); + assert_eq!(output.maps.keys().collect::>(), whole.maps.keys().collect::>()); + for (map, pixels) in &whole.maps { + assert_eq!(*output.maps[map], *pixels, "{map:?} must match a whole bake, including retained pixels"); + } + assert_eq!(streamed.iter().map(|map| map.map).collect::>(), [BakedMap::AmbientOcclusion, BakedMap::Height]); + for map in &streamed { + assert!(Arc::ptr_eq(&map.data, &output.maps[&map.map])); + } + + session.apply_streamed_bake(0, output).unwrap(); + + for (map, pixels) in &whole.maps { + assert_eq!(*session.doc.baked[&0].maps[map], *pixels); + } + session.undo().unwrap(); + assert_eq!(session.doc.baked, before); +} + +#[test] +fn box_fills_are_refused_while_a_bake_shows() { + let mut session = session(); + execute(&mut session, "layer.add.paint", &Value::Null).unwrap(); + execute(&mut session, "tool.polygonFill", &Value::Null).unwrap(); + session.bake_preview_begin(vec![(0, order(&session))]); + let before = texturecraft_engine::inspect::session(&session); + let viewport = Vec2::new(100.0, 100.0); + + for result in [ + session.drag_polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE), + session.drag_polygon_fill_box(Vec2::ZERO, viewport, viewport), + session.polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE), + session.polygon_fill_box(Vec2::ZERO, viewport, viewport), + execute(&mut session, "tool.click", &json!({"uv0": [0, 0], "uv1": [1, 1]})).map(|_| 0), + execute(&mut session, "tool.click", &json!({"x0": 0, "y0": 0, "x1": 100, "y1": 100})).map(|_| 0), + ] { + assert_eq!(result.unwrap_err().to_string(), texturecraft_engine::bake_preview::PAINTING_PAUSED); + } + + assert_eq!(session.end_polygon_fill_box(), 0); + assert_eq!(texturecraft_engine::inspect::session(&session), before); + session.bake_preview_end(); + assert!(session.polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap() > 0); +} diff --git a/crates/ui-egui/src/bake_job.rs b/crates/ui-egui/src/bake_job.rs new file mode 100644 index 00000000..f585d326 --- /dev/null +++ b/crates/ui-egui/src/bake_job.rs @@ -0,0 +1,8 @@ +use crate::RunningBake; + +/// A background bake of one or more texture sets. +pub struct BakeJob { + pub queue: Vec, + pub current: Option, + pub total: usize, +} diff --git a/crates/ui-egui/src/bake_mode/mod.rs b/crates/ui-egui/src/bake_mode/mod.rs index 1fc245e9..9013be73 100644 --- a/crates/ui-egui/src/bake_mode/mod.rs +++ b/crates/ui-egui/src/bake_mode/mod.rs @@ -187,8 +187,11 @@ fn edit_settings( /// What the 3D view shows while a bake runs: the newest finished map, one finished map or the material fn preview_control(app: &mut TextureCraftApp, ui: &mut Ui) { use texturecraft_engine::PreviewShow; + let Some(preview) = app.session.bake_preview.as_ref() else { return }; + let show = preview.show; + // Finished maps of the set baking now can be pinned; the others are still neutral let rows: Vec<(BakedMap, bool)> = preview.current_set().map(|set| set.order.iter().map(|&map| (map, set.baked.maps.contains_key(&map))).collect()).unwrap_or_default(); @@ -197,6 +200,7 @@ fn preview_control(app: &mut TextureCraftApp, ui: &mut Ui) { PreviewShow::Material => tr("Material").to_owned(), PreviewShow::Pin(map) => trf("Mesh map: {map}", &[("map", &tr(crate::i18n::baked_map_label(map)))]), }; + let mut choice = None; egui::ComboBox::from_id_salt("bake_preview_show") .selected_text(text) @@ -218,6 +222,7 @@ fn preview_control(app: &mut TextureCraftApp, ui: &mut Ui) { .on_hover_text(tr( "What the 3D view shows while the bake runs: the newest finished map, one finished map, or the material. Maps not baked yet show a neutral value.", )); + if let Some(show) = choice { app.run("bake.preview", json!({ "show": show.id() })); } diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index fa73e485..0260d65c 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -137,9 +137,11 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, p: & if app.bake.is_some() { return err("a bake is already running"); } + if sets.is_empty() { return err("no texture set to bake: tick one in Bake mode or pass `ts`"); } + app.ui.mode = crate::state::Mode::Baking; app.start_bake(sets); ok(texturecraft_engine::bake_preview::preview_json(&app.session)) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 3b30f9fb..69ae5a47 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -7,6 +7,7 @@ #![forbid(unsafe_code)] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +mod bake_job; pub mod bake_mode; mod bake_scene; mod color_selection_editor; @@ -36,6 +37,7 @@ pub mod properties_popup; pub mod render_mode; mod resource_picker; mod resource_picker_item; +mod running_bake; pub mod shelf; pub mod shelf_preview; mod soft_box; @@ -61,7 +63,9 @@ use serde_json::Value; use texturecraft_engine::Session; use texturecraft_engine::bake::Progress; +pub use bake_job::BakeJob; pub use control::ControlRequest; +pub use running_bake::RunningBake; pub use state::UiState; /// The app as the updater knows it: its releases, and the icon and color of its update prompt. @@ -78,25 +82,6 @@ pub struct ResizeJob { pub rx: std::sync::mpsc::Receiver>, } -/// The texture set baking on a worker thread: its progress, its result and the maps it finishes -/// on the way (the 3D view shows one per UI poll). -pub struct RunningBake { - pub set_index: usize, - pub progress: Arc, - pub receiver: std::sync::mpsc::Receiver>, - pub maps: std::sync::mpsc::Receiver, - /// Maps finished so far, and how many the set makes. - pub maps_done: Arc, - pub maps_total: usize, -} - -/// A background bake of one or more texture sets. -pub struct BakeJob { - pub queue: Vec, - pub current: Option, - pub total: usize, -} - /// A MaterialCraft material re-cooking on a worker thread (one per layer at a time). pub struct LinkCook { pub layer: texturecraft_engine::core::LayerId, @@ -316,8 +301,8 @@ impl TextureCraftApp { if self.bake.is_some() || sets.is_empty() { return; } + let total = sets.len(); - // The 3D view shows the maps landing on the model while they bake let orders = sets .iter() .map(|&set_index| { @@ -326,6 +311,7 @@ impl TextureCraftApp { (set_index, maps) }) .collect(); + self.session.bake_preview_begin(orders); self.bake = Some(BakeJob { queue: sets, current: None, total }); } @@ -384,6 +370,7 @@ impl TextureCraftApp { if self.session.bake_preview_active() && self.ui.mode != state::Mode::Baking { self.session.bake_preview_end(); } + let Some(job) = self.bake.as_mut() else { // A preview whose bake is gone must not keep the view self.session.bake_preview_end(); @@ -393,12 +380,18 @@ impl TextureCraftApp { ctx.request_repaint_after(std::time::Duration::from_millis(50)); if let Some(running) = &job.current { let set_index = running.set_index; - // One streamed map per poll, so each lands on the model in its own frame. The worker - // sends every map before its result, so the last map shows before the bake is applied - if let Ok(map) = running.maps.try_recv() { - self.session.bake_preview_map(set_index, map); - return; + + // Show one map per poll so each reaches its own frame + // An empty channel can gain a map before the result arrives: wait for the sender to close + match running.maps.try_recv() { + Ok(map) => { + self.session.bake_preview_map(set_index, map); + return; + } + Err(std::sync::mpsc::TryRecvError::Empty) => return, + Err(std::sync::mpsc::TryRecvError::Disconnected) => {} } + match running.receiver.try_recv() { Ok(Ok(output)) => { job.current = None; @@ -419,6 +412,7 @@ impl TextureCraftApp { } } } + let Some(job) = self.bake.as_mut() else { return }; if job.queue.is_empty() { @@ -427,6 +421,7 @@ impl TextureCraftApp { self.toast(i18n::tr("Mesh maps baked"), false); return; } + let set_index = job.queue.remove(0); self.session.bake_preview_set_current(set_index); match self.session.bake_task(set_index) { @@ -443,6 +438,7 @@ impl TextureCraftApp { let _ = sender.send(map); }) }); + if let Some(job) = self.bake.as_mut() { job.current = Some(RunningBake { set_index, progress, receiver, maps, maps_done, maps_total }); } @@ -458,6 +454,7 @@ impl TextureCraftApp { if let Some(running) = job.current { running.progress.cancel.store(true, Ordering::Relaxed); } + // The streamed maps were only shown: the document keeps the maps it had self.session.bake_preview_end(); } @@ -496,7 +493,7 @@ impl TextureCraftApp { } } - /// Bake progress 0..1 across all queued sets. + /// The map being baked and its position among the queued maps and texture sets. pub fn bake_status(&self) -> Option { let job = self.bake.as_ref()?; let stage = self.session.bake_preview.as_ref()?.stage()?; @@ -509,19 +506,22 @@ impl TextureCraftApp { &[("map", &map), ("n", &n), ("total", &total), ("set", &set.max(1)), ("sets", &job.total)], )); } + Some(i18n::trf("Baking {map} ({n}/{total})", &[("map", &map), ("n", &n), ("total", &total)])) } + /// Bake progress 0..1 across all queued sets. pub fn bake_progress(&self) -> Option { let job = self.bake.as_ref()?; let done = job.total - job.queue.len() - usize::from(job.current.is_some()); + // Each map is a bake of its own: its progress runs from 0 to 1 within the set's share - let cur = job + let current = job .current .as_ref() .map(|running| (running.maps_done.load(Ordering::Relaxed) as f32 + running.progress.fraction()) / running.maps_total.max(1) as f32) .unwrap_or(0.0); - Some(((done as f32 + cur) / job.total.max(1) as f32).clamp(0.0, 1.0)) + Some(((done as f32 + current) / job.total.max(1) as f32).clamp(0.0, 1.0)) } } diff --git a/crates/ui-egui/src/running_bake.rs b/crates/ui-egui/src/running_bake.rs new file mode 100644 index 00000000..512af28a --- /dev/null +++ b/crates/ui-egui/src/running_bake.rs @@ -0,0 +1,15 @@ +use std::sync::Arc; + +use texturecraft_engine::bake::Progress; + +/// The texture set baking on a worker thread: its progress, its result and the maps it finishes +/// on the way (the 3D view shows one per UI poll). +pub struct RunningBake { + pub set_index: usize, + pub progress: Arc, + pub receiver: std::sync::mpsc::Receiver>, + pub maps: std::sync::mpsc::Receiver, + /// Maps finished so far, and how many the set makes. + pub maps_done: Arc, + pub maps_total: usize, +} diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index ad137bb5..f3087537 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -741,7 +741,12 @@ const QUICK_MASK_NOTICE_COLOR: Color32 = Color32::from_rgb(0xe8, 0x6a, 0x6a); /// What bake mode's 3D view draws besides the low poly (nothing in the other modes) fn bake_visualization(app: &TextureCraftApp) -> Option { - (app.ui.mode == crate::state::Mode::Baking).then(|| app.ui.bake_visualization.visualization(app.session.ts())).flatten() + // Setup meshes can cover the low-poly map preview; keep the switches for when setup resumes + if app.ui.mode != crate::state::Mode::Baking || app.session.bake_preview_active() { + return None; + } + + app.ui.bake_visualization.visualization(app.session.ts()) } /// What a drag on the selected decal's frame does. @@ -1579,6 +1584,28 @@ fn bake_paint_overlay(app: &TextureCraftApp, ui: &Ui, painter: &egui::Painter, t mod tests { use super::*; + #[test] + fn live_bake_preview_hides_setup_overlays_and_restores_their_preferences() { + let session = texturecraft_engine::sample_session(256, 64).unwrap(); + let mut harness = egui_kittest::Harness::builder().build_eframe(|context| TextureCraftApp::new(context, session)); + let app = harness.state_mut(); + app.ui.mode = crate::state::Mode::Baking; + let before = bake_visualization(app).unwrap(); + assert!(before.high_poly && before.cage); + + app.start_bake(vec![0]); + + assert!(bake_visualization(app).is_none(), "setup overlays must not obscure the finished map"); + for show in [texturecraft_engine::PreviewShow::Pin(BakedMap::Normal), texturecraft_engine::PreviewShow::Material] { + app.session.bake_preview_show(show).unwrap(); + assert!(bake_visualization(app).is_none()); + } + + app.cancel_bake(); + + assert_eq!(bake_visualization(app), Some(before)); + } + const VIEW: Rect = Rect::from_min_max(pos2(0.0, 0.0), pos2(100.0, 100.0)); const DASH_PERIOD: f32 = RUBBER_BAND_DASH + RUBBER_BAND_GAP; diff --git a/crates/ui-egui/tests/bake_preview.rs b/crates/ui-egui/tests/bake_preview.rs index a24b2352..08152589 100644 --- a/crates/ui-egui/tests/bake_preview.rs +++ b/crates/ui-egui/tests/bake_preview.rs @@ -17,6 +17,7 @@ fn harness() -> Harness<'static, TextureCraftApp> { texture_set.bake.maps.ao.parameters.rays.rays = 8; texture_set.bake.maps.select(MAPS); } + session.view = ViewMode::UvChecker; let mut harness = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_eframe(|context| TextureCraftApp::new(context, session)); harness.state_mut().ui.mode = Mode::Baking; @@ -35,18 +36,22 @@ fn run_to_the_end(harness: &mut Harness<'static, TextureCraftApp>) -> Vec = Vec::new(); for view in seen { @@ -66,13 +71,16 @@ fn the_view_shows_each_map_as_it_lands_and_the_previous_mode_comes_back() { fn cancelling_restores_the_view_and_leaves_the_document_alone() { let mut harness = harness(); let before = harness.state().session.doc.baked.get(&0).cloned(); + harness.state_mut().start_bake(vec![0]); harness.run_steps(2); + assert!(harness.state().session.bake_preview_active()); let (at, viewport) = (texturecraft_engine::geom::glam::Vec2::new(5.0, 5.0), texturecraft_engine::geom::glam::Vec2::new(100.0, 100.0)); assert!(harness.state_mut().session.begin_stroke(at, viewport, 1.0).is_err(), "painting is paused"); harness.state_mut().cancel_bake(); harness.run_steps(2); + assert_eq!(harness.state().session.view, ViewMode::UvChecker); assert!(!harness.state().session.bake_preview_active() && harness.state().bake.is_none()); assert_eq!(harness.state().session.doc.baked.get(&0).cloned(), before); @@ -81,13 +89,16 @@ fn cancelling_restores_the_view_and_leaves_the_document_alone() { #[test] fn leaving_bake_mode_closes_the_preview_but_the_bake_goes_on() { let mut harness = harness(); + harness.state_mut().start_bake(vec![0]); harness.run_steps(2); harness.state_mut().ui.mode = Mode::Painting; harness.run_steps(2); + assert_eq!(harness.state().session.view, ViewMode::UvChecker); assert!(!harness.state().session.bake_preview_active()); run_to_the_end(&mut harness); + assert!(harness.state().session.doc.baked[&0].maps.contains_key(&BakedMap::Height), "the bake finished and was applied"); assert_eq!(harness.state().session.view, ViewMode::UvChecker); } @@ -96,3 +107,58 @@ fn leaving_bake_mode_closes_the_preview_but_the_bake_goes_on() { fn the_painting_message_is_a_translated_key() { assert_eq!(texturecraft_ui_egui::PAINTING_PAUSED, texturecraft_engine::bake_preview::PAINTING_PAUSED); } + +#[test] +fn a_ready_result_waits_for_the_map_stream_to_close() { + use std::sync::{Arc, atomic::AtomicUsize, mpsc}; + use texturecraft_engine::bake::Progress; + use texturecraft_ui_egui::{BakeJob, RunningBake}; + + let mut harness = harness(); + let before = harness.state().session.doc.baked.clone(); + let mut task = harness.state().session.bake_task(0).unwrap(); + task.tracer = None; + let mut finished_maps = Vec::new(); + let output = task.run_streaming(&Progress::new(), &mut |map| finished_maps.push(map)).unwrap(); + let (map_sender, maps) = mpsc::channel(); + let (result_sender, receiver) = mpsc::channel(); + result_sender.send(Ok(output)).unwrap(); + let app = harness.state_mut(); + app.start_bake(vec![0]); + app.bake = Some(BakeJob { + queue: Vec::new(), + total: 1, + current: Some(RunningBake { + set_index: 0, + progress: Arc::new(Progress::new()), + receiver, + maps, + maps_done: Arc::new(AtomicUsize::new(MAPS.len())), + maps_total: MAPS.len(), + }), + }); + + // A ready result cannot make an earlier empty map read conclusive + harness.run_steps(1); + + assert!(harness.state().bake.is_some(), "an open map stream can still deliver a map"); + assert_eq!(harness.state().session.doc.baked, before); + for map in finished_maps { + map_sender.send(map).unwrap(); + } + drop(map_sender); + + // Each queued map must reach a frame before the result ends the preview + for map in MAPS { + harness.run_steps(1); + + assert_eq!(harness.state().session.view, ViewMode::MeshMap(map)); + assert!(harness.state().session.bake_preview_baked(0).unwrap().maps.contains_key(&map)); + assert_eq!(harness.state().session.doc.baked, before); + } + harness.run_steps(1); + + assert!(harness.state().bake.is_none()); + assert_eq!(harness.state().session.view, ViewMode::UvChecker); + assert!(MAPS.iter().all(|map| harness.state().session.doc.baked[&0].maps.contains_key(map))); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index cf39aa38..c02a7617 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -143,7 +143,9 @@ The streamed maps are held by the session, not the document: nothing enters the until a texture set's bake is applied (one undo step); a cancelled bake leaves the set it was baking as it was, while sets that finished before the cancel stay applied. When the bake ends, is cancelled or Bake mode is left, the view mode that was in use comes back. -**Painting is paused while a bake is shown**: strokes fail with "Painting is paused while a bake +Bake setup overlays are hidden during the preview so they cannot cover the maps; their visibility +settings take effect again when the preview ends. +**Painting is paused while a bake is shown**: strokes and polygon fills fail with "Painting is paused while a bake is shown. Cancel the bake or wait for it to finish." `bake.preview` `{show?: "follow" \| "material" \| "map:"}` reads and sets what the view shows From 7e2b3c7e6ac9c795b4b3369ce471a44f3895978b Mon Sep 17 00:00:00 2001 From: chasse20 Date: Tue, 10 Nov 2026 01:58:43 -0500 Subject: [PATCH 35/64] Move bake preview setup into the engine --- crates/engine/src/bake_preview.rs | 26 ++++++++++++++++---- crates/engine/tests/bake_preview.rs | 36 ++++++++++++++++++++++++++++ crates/ui-egui/src/lib.rs | 25 ++++++++++--------- crates/ui-egui/tests/bake_preview.rs | 20 ++++++++++++++++ 4 files changed, 89 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/bake_preview.rs b/crates/engine/src/bake_preview.rs index c19e9802..63163722 100644 --- a/crates/engine/src/bake_preview.rs +++ b/crates/engine/src/bake_preview.rs @@ -1,10 +1,9 @@ //! Live bake preview: while the app bakes, the 3D view shows each mesh map on the model as soon //! as it is finished ([`crate::BakeTask::run_streaming`]). The streamed maps live here, not in //! the document: nothing enters the undo history until a texture set's bake is applied -//! ([`Session::apply_bake`]), and a cancelled bake leaves the set it was baking as it was (a set finished before the cancel -//! stays applied: each set is its own undo step). The preview -//! shows one map at a time, raw on the model; maps and texture sets not baked yet show their -//! neutral value. +//! ([`Session::apply_streamed_bake`]). Cancellation leaves the current set unchanged; sets already +//! applied keep their results and undo steps. The preview shows one map at a time, raw on the +//! model; maps and texture sets not baked yet show their neutral value. mod preview_set; mod preview_show; @@ -79,6 +78,22 @@ impl BakePreview { } impl Session { + /// Start a preview from each selected texture set's enabled maps, in the same order as + /// [`crate::BakeTask::maps`]. Invalid indices return the project's texture-set error before + /// changing the preview or view mode. This reads settings without preparing bake geometry. + pub fn bake_preview_begin_for(&mut self, sets: &[usize]) -> Result<()> { + let orders = sets + .iter() + .map(|&texture_set| { + let set = self.doc.project.texture_set(texture_set)?; + Ok((texture_set, set.bake.maps.enabled().collect())) + }) + .collect::>>()?; + + self.bake_preview_begin(orders); + Ok(()) + } + /// Start showing a bake of `sets` (each with the maps it makes, in order): the 3D view /// follows the newest map and every set shows neutral values until its maps arrive. The /// view mode in use comes back with [`Session::bake_preview_end`]. @@ -145,7 +160,8 @@ impl Session { } } - /// The bake is over, cancelled or no longer shown: put the previous view mode back. + /// Drop the displayed maps and restore the previous view mode. This does not stop a + /// worker or undo any applied results; the UI also uses it when leaving Bake mode. pub fn bake_preview_end(&mut self) { if let Some(preview) = self.bake_preview.take() { self.view = preview.restore; diff --git a/crates/engine/tests/bake_preview.rs b/crates/engine/tests/bake_preview.rs index bc72339d..cb452b92 100644 --- a/crates/engine/tests/bake_preview.rs +++ b/crates/engine/tests/bake_preview.rs @@ -329,3 +329,39 @@ fn box_fills_are_refused_while_a_bake_shows() { session.bake_preview_end(); assert!(session.polygon_fill_box_uv(Vec2::ZERO, Vec2::ONE).unwrap() > 0); } + +#[test] +fn preview_order_matches_each_sets_bake_task() { + let mut session = session(); + session.doc.project.texture_sets[1].bake.maps.select([BakedMap::WorldNormal, BakedMap::Height]); + let expected: Vec<_> = [0, 1].into_iter().map(|texture_set| session.bake_task(texture_set).unwrap().maps()).collect(); + + session.bake_preview_begin_for(&[0, 1]).unwrap(); + + let preview = session.bake_preview.as_ref().unwrap(); + for (texture_set, maps) in expected.iter().enumerate() { + assert_eq!(&preview.sets[&texture_set].order, maps); + assert!(preview.sets[&texture_set].baked.maps.is_empty()); + } + assert_eq!(session.view, ViewMode::MeshMap(expected[0][0])); +} + +#[test] +fn invalid_preview_sets_preserve_the_existing_preview_and_view() { + let mut session = session(); + session.bake_preview_begin_for(&[0]).unwrap(); + session.bake_preview_set_current(0); + session.bake_preview_show(PreviewShow::Material).unwrap(); + let before = texturecraft_engine::bake_preview::preview_json(&session); + let view = session.view; + let revision = session.revision; + let invalid_set = session.set_count(); + let expected_error = session.doc.project.texture_set(invalid_set).unwrap_err().to_string(); + + let error = session.bake_preview_begin_for(&[1, invalid_set]).unwrap_err(); + + assert!(error.to_string().contains(&expected_error)); + assert_eq!(texturecraft_engine::bake_preview::preview_json(&session), before); + assert_eq!(session.view, view); + assert_eq!(session.revision, revision); +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 69ae5a47..78a3de2b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -296,23 +296,19 @@ impl TextureCraftApp { self.toasts.push(Toast { text: text.into(), error: true, until: f64::INFINITY }); } - /// Start baking texture sets in the background (one after another). + /// Start baking texture sets in the background, one after another. Invalid set indices + /// show an error without starting a preview or queuing any work. pub fn start_bake(&mut self, sets: Vec) { if self.bake.is_some() || sets.is_empty() { return; } - let total = sets.len(); - let orders = sets - .iter() - .map(|&set_index| { - let maps = - self.session.doc.project.texture_sets.get(set_index).map(|texture_set| texture_set.bake.maps.enabled().collect()).unwrap_or_default(); - (set_index, maps) - }) - .collect(); + if let Err(error) = self.session.bake_preview_begin_for(&sets) { + self.toast(error.to_string(), true); + return; + } - self.session.bake_preview_begin(orders); + let total = sets.len(); self.bake = Some(BakeJob { queue: sets, current: None, total }); } @@ -365,6 +361,8 @@ impl TextureCraftApp { } } + /// Show at most one streamed map per frame, then apply the set as one undo step after + /// its map channel closes. Closing the preview alone does not stop the background bake. fn poll_bake(&mut self, ctx: &egui::Context) { // Leaving Bake mode puts the view mode back; the bake goes on if self.session.bake_preview_active() && self.ui.mode != state::Mode::Baking { @@ -447,7 +445,8 @@ impl TextureCraftApp { } } - /// Cancel the active bake and discard queued sets + /// Cancel the active worker, discard queued sets and restore the view. The current set's + /// preview maps are discarded; previously applied sets keep their results and undo steps. pub fn cancel_bake(&mut self) { let Some(job) = self.bake.take() else { return }; @@ -455,7 +454,7 @@ impl TextureCraftApp { running.progress.cancel.store(true, Ordering::Relaxed); } - // The streamed maps were only shown: the document keeps the maps it had + // Only the current set is uncommitted; completed sets remain applied self.session.bake_preview_end(); } diff --git a/crates/ui-egui/tests/bake_preview.rs b/crates/ui-egui/tests/bake_preview.rs index 08152589..6860bdc4 100644 --- a/crates/ui-egui/tests/bake_preview.rs +++ b/crates/ui-egui/tests/bake_preview.rs @@ -162,3 +162,23 @@ fn a_ready_result_waits_for_the_map_stream_to_close() { assert_eq!(harness.state().session.view, ViewMode::UvChecker); assert!(MAPS.iter().all(|map| harness.state().session.doc.baked[&0].maps.contains_key(map))); } + +#[test] +fn an_invalid_set_does_not_start_a_partial_bake_or_change_the_view() { + let mut harness = harness(); + let app = harness.state_mut(); + let invalid_set = app.session.set_count(); + let expected_error = app.session.doc.project.texture_set(invalid_set).unwrap_err().to_string(); + let view = app.session.view; + let revision = app.session.revision; + let history_steps = app.session.history_labels().len(); + + app.start_bake(vec![0, invalid_set]); + + assert!(app.bake.is_none(), "validate every set before queuing any work"); + assert!(!app.session.bake_preview_active()); + assert_eq!(app.session.view, view); + assert_eq!(app.session.revision, revision); + assert_eq!(app.session.history_labels().len(), history_steps); + assert!(app.toasts.iter().any(|toast| toast.error && toast.text.contains(&expected_error))); +} From 3496930a87db6a0bbb88466b24d7bd9a2d8ca550 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Tue, 10 Nov 2026 02:29:37 -0500 Subject: [PATCH 36/64] Cancel active strokes when bake preview starts --- crates/engine/src/bake_preview.rs | 5 ++- crates/engine/tests/bake_preview.rs | 61 +++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/bake_preview.rs b/crates/engine/src/bake_preview.rs index 63163722..878fb276 100644 --- a/crates/engine/src/bake_preview.rs +++ b/crates/engine/src/bake_preview.rs @@ -96,8 +96,11 @@ impl Session { /// Start showing a bake of `sets` (each with the maps it makes, in order): the 3D view /// follows the newest map and every set shows neutral values until its maps arrive. The - /// view mode in use comes back with [`Session::bake_preview_end`]. + /// view mode in use comes back with [`Session::bake_preview_end`]. An active stroke is + /// discarded so a later pointer release cannot commit paint during the preview. pub fn bake_preview_begin(&mut self, sets: Vec<(usize, Vec)>) { + self.cancel_stroke(); + let restore = self.bake_preview.as_ref().map_or(self.view, |preview| preview.restore); let sets = sets.into_iter().map(|(texture_set, order)| (texture_set, PreviewSet { baked: BakedMaps::default(), order })).collect(); diff --git a/crates/engine/tests/bake_preview.rs b/crates/engine/tests/bake_preview.rs index cb452b92..e8eb477b 100644 --- a/crates/engine/tests/bake_preview.rs +++ b/crates/engine/tests/bake_preview.rs @@ -365,3 +365,64 @@ fn invalid_preview_sets_preserve_the_existing_preview_and_view() { assert_eq!(session.view, view); assert_eq!(session.revision, revision); } + +#[test] +fn starting_a_bake_preview_discards_an_active_stroke() { + for (from_settings, paint_mask) in [(false, false), (true, false), (false, true), (true, true)] { + let mut session = session(); + execute(&mut session, "layer.add.paint", &Value::Null).unwrap(); + if paint_mask { + session.target = texturecraft_engine::StackTarget::Mask; + } + + let before = session.doc.clone(); + let history = session.history_labels(); + let view = session.view; + session.begin_stroke_uv(Vec2::splat(0.5), 1.0).unwrap(); + assert!(session.stroke_tiles() > 0, "the stroke must contain paint before the preview starts"); + + if from_settings { + session.bake_preview_begin_for(&[0]).unwrap(); + } else { + session.bake_preview_begin(vec![(0, order(&session))]); + } + let stroke_survived = session.stroke_active(); + session.continue_stroke_uv(Vec2::splat(0.6), 1.0); + session.end_stroke().unwrap(); + + assert_eq!(session.history_labels(), history, "releasing the pointer during a preview must not commit paint"); + assert!(!stroke_survived, "activation must cancel the stroke immediately"); + assert_eq!(session.doc.project, before.project); + assert_eq!(session.doc.pixels.layers, before.pixels.layers); + assert_eq!(session.doc.pixels.masks, before.pixels.masks); + assert!(session.bake_preview_active()); + session.bake_preview_end(); + + assert_eq!(session.view, view); + session.begin_stroke_uv(Vec2::splat(0.5), 1.0).unwrap(); + session.end_stroke().unwrap(); + assert_eq!(session.history_labels().len(), history.len() + 1, "painting resumes after the preview ends"); + } +} + +#[test] +fn a_rejected_bake_preview_preserves_the_active_stroke() { + let mut session = session(); + execute(&mut session, "layer.add.paint", &Value::Null).unwrap(); + let history_steps = session.history_labels().len(); + let view = session.view; + session.begin_stroke_uv(Vec2::splat(0.5), 1.0).unwrap(); + let painted_tiles = session.stroke_tiles(); + assert!(painted_tiles > 0); + + let result = session.bake_preview_begin_for(&[0, session.set_count()]); + + assert!(result.is_err()); + assert!(!session.bake_preview_active()); + assert!(session.stroke_active()); + assert_eq!(session.stroke_tiles(), painted_tiles); + assert_eq!(session.view, view); + session.end_stroke().unwrap(); + + assert_eq!(session.history_labels().len(), history_steps + 1, "a rejected preview must not discard painting"); +} From 6cdc7789cbedd3f4379d32391b5fecfe1c3f69d3 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Tue, 10 Nov 2026 02:41:08 -0500 Subject: [PATCH 37/64] End ID color picking before bake preview --- crates/ui-egui/src/lib.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 78a3de2b..b71b6557 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -303,6 +303,9 @@ impl TextureCraftApp { return; } + // Restore the picker's view before the preview starts following baked maps + id_color_pick::IdColorPick::end(self); + if let Err(error) = self.session.bake_preview_begin_for(&sets) { self.toast(error.to_string(), true); return; From 3fc540e5704f067f87228fd735728b445dd71b36 Mon Sep 17 00:00:00 2001 From: FredApps Date: Tue, 10 Nov 2026 09:31:14 +0100 Subject: [PATCH 38/64] Test retained-map allocations in streamed partial bakes --- crates/engine/src/bake/bake_task.rs | 101 +++++++++++++++++++++++ crates/engine/src/bake/preserve_tiles.rs | 14 ++++ 2 files changed, 115 insertions(+) diff --git a/crates/engine/src/bake/bake_task.rs b/crates/engine/src/bake/bake_task.rs index 1148f998..3c865253 100644 --- a/crates/engine/src/bake/bake_task.rs +++ b/crates/engine/src/bake/bake_task.rs @@ -107,3 +107,104 @@ impl BakeTask { Ok(output) } } + +#[cfg(test)] +mod tests { + use super::*; + use crate::{Session, execute}; + use serde_json::json; + use texturecraft_geom::primitives; + + const PREVIOUS_MAPS: [BakedMap; 3] = [BakedMap::Normal, BakedMap::AmbientOcclusion, BakedMap::Height]; + const SELECTED_MAPS: [BakedMap; 2] = [BakedMap::AmbientOcclusion, BakedMap::Height]; + + fn partial_task(selected: &[BakedMap], resized: bool, excluded: bool) -> BakeTask { + let mut session = Session::new_project("Partial bake", primitives::udim_plane(), "builtin:udim_plane", None, 128).unwrap(); + execute(&mut session, "bake.settings", &json!({"resolution": 64, "rays": 2})).unwrap(); + if excluded { + execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": false})).unwrap(); + } + let mut task = session.bake_task(0).unwrap(); + task.tracer = None; + task.settings.maps.select(selected.iter().copied()); + let (width, height) = if resized { (64, 32) } else { (128, 64) }; + task.previous_maps = BakedMaps { + resolution: width, + maps: PREVIOUS_MAPS.into_iter().map(|map| (map, Arc::new(vec![0.25; width as usize * height * map.components()]))).collect(), + }; + task + } + + #[test] + fn streaming_allocates_only_truly_unchecked_resized_maps_once() { + for (selected, resized, excluded) in [ + (SELECTED_MAPS.as_slice(), true, true), + (PREVIOUS_MAPS.as_slice(), true, true), + (SELECTED_MAPS.as_slice(), false, true), + (SELECTED_MAPS.as_slice(), true, false), + ] { + let task = partial_task(selected, resized, excluded); + let whole = task.run(&Progress::new()).unwrap(); + super::super::preserve_tiles::take_retained_allocations(); + let mut allocations = Vec::new(); + let mut handed_over = Vec::new(); + let output = task + .run_streaming(&Progress::new(), &mut |map| { + allocations.extend(super::super::preserve_tiles::take_retained_allocations()); + assert!(allocations.iter().all(|map| !selected.contains(map)), "maps scheduled to bake must never allocate retained buffers"); + handed_over.push(map); + }) + .unwrap(); + allocations.extend(super::super::preserve_tiles::take_retained_allocations()); + let expected: Vec<_> = PREVIOUS_MAPS.into_iter().filter(|map| resized && excluded && !selected.contains(map)).collect(); + assert_eq!(allocations, expected, "each truly unchecked resized map must allocate exactly once"); + assert_eq!(output.maps.keys().collect::>(), whole.maps.keys().collect::>()); + for (map, pixels) in &whole.maps { + assert_eq!(*output.maps[map], *pixels, "{map:?} must preserve the ordinary bake's pixels"); + } + for map in handed_over { + assert!(Arc::ptr_eq(&map.data, &output.maps[&map.map]), "streaming must keep sharing the baked buffer"); + } + } + } + + #[test] + fn cancelling_a_partial_stream_does_not_resample_future_maps() { + let task = partial_task(&SELECTED_MAPS, true, true); + let whole = task.run(&Progress::new()).unwrap(); + super::super::preserve_tiles::take_retained_allocations(); + let progress = Progress::new(); + let mut handed_over = Vec::new(); + let result = task.run_streaming(&progress, &mut |map| { + handed_over.push(map); + progress.cancel(); + }); + assert!(result.is_err()); + assert_eq!(handed_over.len(), 1); + for map in handed_over { + assert_eq!(*map.data, whole.maps[&map.map], "cancellation leaves the handed-over map whole"); + } + assert_eq!(super::super::preserve_tiles::take_retained_allocations(), [BakedMap::Normal]); + } + + #[test] + fn an_empty_streaming_selection_keeps_the_ordinary_bake_behavior() { + let task = partial_task(&[], true, true); + super::super::preserve_tiles::take_retained_allocations(); + let whole = task.run(&Progress::new()); + let expected_allocations = super::super::preserve_tiles::take_retained_allocations(); + let output = task.run_streaming(&Progress::new(), &mut |_| panic!("an empty selection must not stream a map")); + assert_eq!(super::super::preserve_tiles::take_retained_allocations(), expected_allocations); + match (whole, output) { + (Ok(whole), Ok(output)) => { + assert_eq!((output.resolution, output.height), (whole.resolution, whole.height)); + assert_eq!(output.maps.keys().collect::>(), whole.maps.keys().collect::>()); + for (map, pixels) in whole.maps { + assert_eq!(*output.maps[&map], pixels); + } + } + (Err(whole), Err(output)) => assert_eq!(whole.to_string(), output.to_string()), + _ => panic!("empty streaming and ordinary bakes must agree"), + } + } +} diff --git a/crates/engine/src/bake/preserve_tiles.rs b/crates/engine/src/bake/preserve_tiles.rs index 27c74ae8..3f416aa0 100644 --- a/crates/engine/src/bake/preserve_tiles.rs +++ b/crates/engine/src/bake/preserve_tiles.rs @@ -42,6 +42,8 @@ pub(super) fn restore(output: &mut BakeOutput, previous: &BakedMaps, excluded_ti .ok_or_else(|| EngineError::Other("resized bake map exceeds the addressable size".into()))?; let mut pixels = Vec::new(); pixels.try_reserve_exact(count).map_err(|error| EngineError::Other(format!("cannot retain mesh map {}: {error}", map.id())))?; + #[cfg(test)] + RETAINED_ALLOCATIONS.with(|allocations| allocations.borrow_mut().push(*map)); for y in 0..size.1 { for x in 0..size.0 { let value = previous.sample(*map, x, y, size).unwrap_or_else(|| map.neutral()); @@ -52,3 +54,15 @@ pub(super) fn restore(output: &mut BakeOutput, previous: &BakedMaps, excluded_ti } Ok(()) } + +// Restoration is sequential on the calling thread. Record successful retained-buffer allocations +// only in unit tests, without a global allocator or interference from parallel test threads. +#[cfg(test)] +std::thread_local! { + static RETAINED_ALLOCATIONS: std::cell::RefCell> = const { std::cell::RefCell::new(Vec::new()) }; +} + +#[cfg(test)] +pub(super) fn take_retained_allocations() -> Vec { + RETAINED_ALLOCATIONS.with(|allocations| std::mem::take(&mut *allocations.borrow_mut())) +} From 7c440b1e3e04318bd0054670317fa7a860a36374 Mon Sep 17 00:00:00 2001 From: FredApps Date: Tue, 10 Nov 2026 09:39:28 +0100 Subject: [PATCH 39/64] Retain unchecked maps once per streamed bake --- crates/engine/src/bake/bake_task.rs | 10 ++++++++-- crates/engine/src/bake/preserve_tiles.rs | 14 ++++++++++++-- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/bake/bake_task.rs b/crates/engine/src/bake/bake_task.rs index 3c865253..24629b56 100644 --- a/crates/engine/src/bake/bake_task.rs +++ b/crates/engine/src/bake/bake_task.rs @@ -46,11 +46,15 @@ impl BakeTask { let total = maps.len(); let mut combined: Option = None; - for (index, map) in maps.into_iter().enumerate() { + for (index, map) in maps.iter().copied().enumerate() { let mut settings = self.settings.clone(); settings.maps.select([map]); let mut output = self.run_with(&settings, progress)?; let Some(data) = output.maps.remove(&map) else { continue }; + if combined.is_none() { + // Retain unchecked maps once, using the full selection rather than this one-map pass. + super::preserve_tiles::restore_unchecked(&mut output, &self.previous_maps, &self.excluded_tiles, &maps)?; + } let data = Arc::new(data); on_map(StreamedMap { map, index, total, resolution: output.resolution, height: output.height, data: data.clone() }); @@ -82,7 +86,9 @@ impl BakeTask { } pub fn run(&self, progress: &Progress) -> Result { - self.run_with(&self.settings, progress) + let mut output = self.run_with(&self.settings, progress)?; + super::preserve_tiles::restore_unchecked(&mut output, &self.previous_maps, &self.excluded_tiles, &[])?; + Ok(output) } fn run_with(&self, settings: &BakeSettings, progress: &Progress) -> Result { diff --git a/crates/engine/src/bake/preserve_tiles.rs b/crates/engine/src/bake/preserve_tiles.rs index 3f416aa0..f44a09a4 100644 --- a/crates/engine/src/bake/preserve_tiles.rs +++ b/crates/engine/src/bake/preserve_tiles.rs @@ -1,5 +1,6 @@ use texturecraft_bake::BakeOutput; use texturecraft_compose::BakedMaps; +use texturecraft_core::BakedMap; use crate::{EngineError, Result}; @@ -29,9 +30,18 @@ pub(super) fn restore(output: &mut BakeOutput, previous: &BakedMaps, excluded_ti } } - // Keep unchecked map outputs too when a partial bake changes the atlas dimensions + Ok(()) +} + +/// Retain only maps outside the full task selection, once per completed atlas. +/// A one-map streaming pass must not resample maps that are still scheduled to bake. +pub(super) fn restore_unchecked(output: &mut BakeOutput, previous: &BakedMaps, excluded_tiles: &[(u32, u32)], selected: &[BakedMap]) -> Result<()> { + if excluded_tiles.is_empty() { + return Ok(()); + } + let size = (output.resolution, output.height); for map in previous.maps.keys() { - if output.maps.contains_key(map) || (previous.resolution == size.0 && previous.height(*map) == size.1) { + if selected.contains(map) || output.maps.contains_key(map) || (previous.resolution == size.0 && previous.height(*map) == size.1) { continue; } From 65a00a31f912c2448dee06827d13c1573d182796 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Tue, 10 Nov 2026 03:44:52 -0500 Subject: [PATCH 40/64] Updated helpful PR guide to be more defense against memory leakages --- docs/helpful-pr-review-guidelines.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs/helpful-pr-review-guidelines.md b/docs/helpful-pr-review-guidelines.md index 6580c84f..098b6ae1 100644 --- a/docs/helpful-pr-review-guidelines.md +++ b/docs/helpful-pr-review-guidelines.md @@ -28,6 +28,7 @@ Use these preferences when reviewing and improving a PR. Follow repository requi - Prefer the smallest complete solution that is efficient and easy to understand - Look for repeated calculations, expensive iterations, unnecessary allocations, and redundant data access +- For loops, batches, and streaming operations, trace allocations and buffer lifetimes across multiple iterations, including outputs retained from earlier iterations. Identify work that belongs once per operation rather than once per item, using the full selection when making retention decisions - Consider caching, batching, and parallelism when measurements justify their complexity and memory cost - Measure relevant runtime, construction cost, and memory tradeoffs using representative workloads - Compare before and after with the same inputs, build settings, and environment; account for measurement variation and cold or warm state where relevant @@ -77,6 +78,7 @@ Use these preferences when reviewing and improving a PR. Follow repository requi - For naming, spacing, or organization findings, identify the location and the specific standard being missed - Order findings by severity and distinguish confirmed problems, hypotheses needing verification, and optional improvements - Give measured optimization results with workload, build, and environment details; do not describe an unmeasured change as faster +- For memory-related changes, verify allocation/resampling counts or peak live memory in representative multi-item cases. Final pixel equality and shared output buffers do not prove that temporary allocations are avoided - State remaining limitations and coverage gaps; if no actionable problems were found, say so without implying complete correctness - Before handing back edits, review the final diff for unintended behavior changes, unrelated edits, and claims unsupported by validation From 75388894945ea2b8bed57248ca1ed489775f73f4 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Tue, 10 Nov 2026 11:12:49 +0100 Subject: [PATCH 41/64] packaging(linux): refuse non-HTTPS redirects when fetching appimagetool --- packaging/linux/package.sh | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packaging/linux/package.sh b/packaging/linux/package.sh index 51021aab..865f40ca 100755 --- a/packaging/linux/package.sh +++ b/packaging/linux/package.sh @@ -113,7 +113,7 @@ if has appimage; then if [ -z "$TOOL" ]; then TOOL="$CARGO_TARGET_DIR/appimagetool-$ARCH.AppImage" if [ ! -x "$TOOL" ]; then - curl -fsSL -o "$TOOL" "https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-$ARCH.AppImage" + curl --proto '=https' -fsSL -o "$TOOL" "https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-$ARCH.AppImage" chmod +x "$TOOL" fi fi From 368731f7a424019b67130f13c8d65f97fcd5d2ea Mon Sep 17 00:00:00 2001 From: chasse20 Date: Tue, 10 Nov 2026 05:30:17 -0500 Subject: [PATCH 42/64] Fix Clippy checks and clean up affected functions --- crates/automation/src/security.rs | 19 +++-- crates/bake/src/cage/high_poly_reach.rs | 6 +- crates/bake/src/test/high_poly_reach.rs | 3 +- crates/bake/src/test/setting.rs | 7 ++ crates/bake/src/tests.rs | 22 +++--- crates/compose/src/display.rs | 88 ++++++++++++---------- crates/compose/src/eval.rs | 47 +++++++----- crates/engine/src/quick_mask.rs | 31 ++++---- crates/engine/tests/it/bake.rs | 19 ++--- crates/engine/tests/it/bake_tiles.rs | 5 ++ crates/formats/src/fonts.rs | 61 ++++++++------- crates/formats/src/mesh_export.rs | 43 ++++++----- crates/formats/src/mesh_export/usd.rs | 58 +++++++------- crates/formats/src/mesh_import/abc/mod.rs | 69 ++++++++++------- crates/formats/src/mesh_import/fbx.rs | 79 ++++++++++--------- crates/formats/src/mesh_import/gltf.rs | 66 ++++++++-------- crates/formats/src/mesh_import/mod.rs | 22 ++++-- crates/formats/src/mesh_import/obj.rs | 66 +++++++++------- crates/formats/src/mesh_import/usd/usdc.rs | 20 ++--- crates/formats/src/project_file/mod.rs | 64 +++++++++------- crates/geom/src/mesh.rs | 58 ++++++++------ crates/paint/src/particles.rs | 32 ++++---- crates/render/src/subdivide.rs | 67 ++++++++-------- 23 files changed, 538 insertions(+), 414 deletions(-) diff --git a/crates/automation/src/security.rs b/crates/automation/src/security.rs index 7613ecd5..63c12b0e 100644 --- a/crates/automation/src/security.rs +++ b/crates/automation/src/security.rs @@ -178,8 +178,11 @@ pub struct ConnectionLimiter(Arc); pub struct Permit(Arc); impl ConnectionLimiter { - pub fn try_acquire(&self, max: usize) -> Option { - self.0.try_update(Ordering::AcqRel, Ordering::Acquire, |n| (n < max).then_some(n + 1)).ok().map(|_| Permit(self.0.clone())) + pub fn try_acquire(&self, max_connections: usize) -> Option { + self.0 + .try_update(Ordering::AcqRel, Ordering::Acquire, |connections| (connections < max_connections).then_some(connections + 1)) + .ok() + .map(|_| Permit(self.0.clone())) } } @@ -328,10 +331,12 @@ mod tests { #[test] fn limiter_releases() { - let l = ConnectionLimiter::default(); - let p = l.try_acquire(1).unwrap(); - assert!(l.try_acquire(1).is_none()); - drop(p); - assert!(l.try_acquire(1).is_some()); + let limiter = ConnectionLimiter::default(); + + let permit = limiter.try_acquire(1).unwrap(); + assert!(limiter.try_acquire(1).is_none()); + + drop(permit); + assert!(limiter.try_acquire(1).is_some()); } } diff --git a/crates/bake/src/cage/high_poly_reach.rs b/crates/bake/src/cage/high_poly_reach.rs index f957ce49..2f461343 100644 --- a/crates/bake/src/cage/high_poly_reach.rs +++ b/crates/bake/src/cage/high_poly_reach.rs @@ -77,20 +77,21 @@ impl HighPolyReach { /// Each vertex's mesh-name key, from the first triangle that uses it fn vertex_keys(mesh: &Mesh, triangle_keys: &[u32]) -> Vec { let mut keys = vec![ANY; mesh.positions.len()]; - for (corners, &triangle_key) in mesh.indices.chunks_exact(3).zip(triangle_keys) { + for (corners, &triangle_key) in mesh.indices.as_chunks::<3>().0.iter().zip(triangle_keys) { for &corner in corners { if let Some(key) = keys.get_mut(corner as usize).filter(|key| **key == ANY) { *key = triangle_key; } } } + keys } /// Each vertex's sum of its triangles' winding normals, weighted by area: the side the bake's backface test sees as the front fn winding_normals(mesh: &Mesh) -> Vec { let mut normals = vec![Vec3::ZERO; mesh.positions.len()]; - for corners in mesh.indices.chunks_exact(3) { + for corners in mesh.indices.as_chunks::<3>().0 { let position = |corner: u32| mesh.positions.get(corner as usize).copied().unwrap_or(Vec3::ZERO); let winding_normal = (position(corners[1]) - position(corners[0])).cross(position(corners[2]) - position(corners[0])); for &corner in corners { @@ -99,5 +100,6 @@ fn winding_normals(mesh: &Mesh) -> Vec { } } } + normals } diff --git a/crates/bake/src/test/high_poly_reach.rs b/crates/bake/src/test/high_poly_reach.rs index e6d66d07..8a4f83c4 100644 --- a/crates/bake/src/test/high_poly_reach.rs +++ b/crates/bake/src/test/high_poly_reach.rs @@ -23,7 +23,7 @@ fn bumpy_high_poly() -> (Mesh, Vec) { let mut flipped = vec![false; mesh.positions.len()]; let mut unflipped = vec![false; mesh.positions.len()]; - for corners in mesh.indices.chunks_exact_mut(3) { + for corners in mesh.indices.as_chunks_mut::<3>().0 { let center_x = corners.iter().map(|&corner| mesh.positions[corner as usize].x).sum::() / 3.0; if center_x > FLIPPED_FROM_X { corners.swap(1, 2); @@ -32,6 +32,7 @@ fn bumpy_high_poly() -> (Mesh, Vec) { if center_x > FLIPPED_FROM_X { flipped[corner as usize] = true } else { unflipped[corner as usize] = true } } } + // Vertices on the border face both ways: neither answer is right for them let mixed = flipped.iter().zip(&unflipped).map(|(flipped, unflipped)| *flipped && *unflipped).collect(); (mesh, mixed) diff --git a/crates/bake/src/test/setting.rs b/crates/bake/src/test/setting.rs index 03a97b77..668338a7 100644 --- a/crates/bake/src/test/setting.rs +++ b/crates/bake/src/test/setting.rs @@ -41,13 +41,18 @@ fn matching_skips_a_closer_unrelated_high_mesh_and_backfaces() { parameters.cage.relative_to_bounding_box = false; parameters.maps.height.parameters.normalization = HeightNormalization::Manual; let height = |parameters: &BakeSettings, high: &Mesh| transfer(&low, high, None, parameters).unwrap().maps[&BakedMap::Height][128]; + assert!((height(¶meters, &high) - 0.54).abs() < 1e-5); + parameters.high_poly.match_mode = MeshMatchMode::ByMeshName; assert!((height(¶meters, &high) - 0.52).abs() < 1e-5); + for triangle in high.indices.as_chunks_mut::<3>().0 { triangle.swap(1, 2); } + assert_eq!(height(¶meters, &high), 0.5); + parameters.high_poly.ignore_backface = false; assert!((height(¶meters, &high) - 0.52).abs() < 1e-5); } @@ -159,9 +164,11 @@ fn position_axis_and_material_bounds_change_only_the_requested_space() { mesh.append(&distant); let mut parameters = settings(16, &[BakedMap::Position]); parameters.maps.position.parameters.axis = PositionAxis::X; + let global = run(&mesh, ¶meters).unwrap(); parameters.maps.position.parameters.scale = PositionNormalizationScale::PerMaterial; let local = run(&mesh, ¶meters).unwrap(); + assert!(global.maps[&BakedMap::Position].iter().all(|value| *value < 0.2)); assert!(local.maps[&BakedMap::Position].iter().any(|value| *value > 0.9)); assert!(local.maps[&BakedMap::Position].as_chunks::<3>().0.iter().all(|pixel| pixel[0] == pixel[1] && pixel[1] == pixel[2])); diff --git a/crates/bake/src/tests.rs b/crates/bake/src/tests.rs index 1bf7fa25..0c313462 100644 --- a/crates/bake/src/tests.rs +++ b/crates/bake/src/tests.rs @@ -100,18 +100,20 @@ fn open_quad_is_unoccluded() { #[test] fn inside_of_a_closed_box_is_occluded() { - let mut m = primitives::cube(2.0); - for t in m.indices.as_chunks_mut::<3>().0.iter_mut() { - t.swap(1, 2); + let mut mesh = primitives::cube(2.0); + for triangle in mesh.indices.as_chunks_mut::<3>().0 { + triangle.swap(1, 2); } - for n in &mut m.normals { - *n = -*n; + for normal in &mut mesh.normals { + *normal = -*normal; } - m.compute_tangents(); - let s = with_rays(settings(64, &[BakedMap::AmbientOcclusion]), 64, 4.0); - let out = run(&m, &s).unwrap(); - let ao = mean(covered_values(&m, &out, BakedMap::AmbientOcclusion).into_iter().map(|v| v.1)); - assert!(ao < 0.3, "{ao}"); + mesh.compute_tangents(); + let parameters = with_rays(settings(64, &[BakedMap::AmbientOcclusion]), 64, 4.0); + + let output = run(&mesh, ¶meters).unwrap(); + + let mean_occlusion = mean(covered_values(&mesh, &output, BakedMap::AmbientOcclusion).into_iter().map(|v| v.1)); + assert!(mean_occlusion < 0.3, "{mean_occlusion}"); } #[test] diff --git a/crates/compose/src/display.rs b/crates/compose/src/display.rs index 0b126594..5ebb667b 100644 --- a/crates/compose/src/display.rs +++ b/crates/compose/src/display.rs @@ -93,20 +93,21 @@ fn u8_of(v: u16) -> u8 { (v >> 8) as u8 } -/// Tile bytes (`TILE × TILE`, row-major) for `kind` from the composite, or None when the tile is -/// absent in every source (the GPU texture keeps its cleared default). -pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u32, ty: u32) -> Vec { - let bpt = kind.bytes_per_texel(); - let mut out = vec![0u8; TILE_AREA * bpt]; - let lut = srgb_lut(); - let get = |c: Channel| comp.channels.get(&c).and_then(|img| img.tile(tx, ty)); - let res = comp.resolution; +/// Tile bytes (`TILE × TILE`, row-major) for `kind`, using channel defaults for absent source tiles. +pub fn tile_bytes(composite: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u32, ty: u32) -> Vec { + let bytes_per_texel = kind.bytes_per_texel(); + let mut out = vec![0u8; TILE_AREA * bytes_per_texel]; + let srgb = srgb_lut(); + let get = |c: Channel| composite.channels.get(&c).and_then(|img| img.tile(tx, ty)); + let resolution = composite.resolution; let default16 = |c: Channel| texturecraft_texel::to_u16(c.default_value()[0]); - // A scalar channel's texel `i` as 8 bits (its default where the set lacks it). + + // A scalar channel's texel `i` as 8 bits (its default where the set lacks it) let scalar8 = |c: Channel| { let (t, d) = (get(c), default16(c)); move |i: usize| u8_of(t.and_then(|t| t.get(i).copied()).unwrap_or(d)) }; + match kind { DisplayKind::BaseColor | DisplayKind::Emissive | DisplayKind::Sheen => { let (c, alpha) = match kind { @@ -117,81 +118,87 @@ pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u3 let (src, alpha) = (get(c), scalar8(alpha)); let d = c.default_value().map(|v| (texturecraft_texel::linear_to_srgb(v) * 255.0 + 0.5) as u8); for i in 0..TILE_AREA { - let px = &mut out[i * 4..i * 4 + 4]; + let pixel = &mut out[i * 4..i * 4 + 4]; match src { Some(s) => { for k in 0..3 { - px[k] = lut[(s.get(i * 3 + k).copied().unwrap_or(0) >> 4) as usize]; + pixel[k] = srgb[(s.get(i * 3 + k).copied().unwrap_or(0) >> 4) as usize]; } } - None => px[..3].copy_from_slice(&d), + None => pixel[..3].copy_from_slice(&d), } - px[3] = alpha(i); + pixel[3] = alpha(i); } } DisplayKind::Lobes => { let lanes = [Channel::CoatWeight, Channel::CoatRoughness, Channel::AnisotropyLevel, Channel::AnisotropyAngle].map(scalar8); - for (i, px) in out.as_chunks_mut::<4>().0.iter_mut().enumerate() { - for (d, lane) in px.iter_mut().zip(&lanes) { + for (i, pixel) in out.as_chunks_mut::<4>().0.iter_mut().enumerate() { + for (d, lane) in pixel.iter_mut().zip(&lanes) { *d = lane(i); } } } DisplayKind::Extra => { let (n, transmission) = (get(Channel::CoatNormal), scalar8(Channel::Transmission)); - // Signed 8-bit around 128 so the flat normal packs exactly. - let snorm = |v: u16| (128.0 + 127.0 * (v as f32 / 65535.0 * 2.0 - 1.0)).round().clamp(0.0, 255.0) as u8; - // A TILE never straddles two atlas blocks. - let scale = (-32.0 * comp.block_scales.at(tx * TILE, ty * TILE).log2()).round().clamp(0.0, 255.0) as u8; - for (i, px) in out.as_chunks_mut::<4>().0.iter_mut().enumerate() { - for (k, d) in px.iter_mut().take(2).enumerate() { - *d = n.and_then(|t| t.get(i * 3 + k)).map_or(128, |v| snorm(*v)); + + // Signed 8-bit around 128 so the flat normal packs exactly + let pack_signed_normal = |v: u16| (128.0 + 127.0 * (v as f32 / 65535.0 * 2.0 - 1.0)).round().clamp(0.0, 255.0) as u8; + + // A TILE never straddles two atlas blocks + let scale = (-32.0 * composite.block_scales.at(tx * TILE, ty * TILE).log2()).round().clamp(0.0, 255.0) as u8; + for (i, pixel) in out.as_chunks_mut::<4>().0.iter_mut().enumerate() { + for (k, d) in pixel.iter_mut().take(2).enumerate() { + *d = n.and_then(|t| t.get(i * 3 + k)).map_or(128, |v| pack_signed_normal(*v)); } - px[2] = transmission(i); - px[3] = scale; + pixel[2] = transmission(i); + pixel[3] = scale; } } DisplayKind::Orm => { let (ao, m, s) = (get(Channel::AmbientOcclusion), get(Channel::Metallic), get(Channel::SpecularLevel)); - // Specular/glossiness sets: the viewport shades roughness = 1 − glossiness. - let gloss = comp.channels.contains_key(&Channel::Glossiness); + + // Specular/glossiness sets: the viewport shades roughness = 1 − glossiness + let gloss = composite.channels.contains_key(&Channel::Glossiness); let (r, r_default) = if gloss { (get(Channel::Glossiness), default16(Channel::Glossiness)) } else { (get(Channel::Roughness), default16(Channel::Roughness)) }; for i in 0..TILE_AREA { let (x, y) = (tx * TILE + (i as u32 % TILE), ty * TILE + (i as u32 / TILE)); - let baked_ao = baked.sample_working(BakedMap::AmbientOcclusion, x, y, (res, comp.height), &comp.block_scales).map_or(1.0, |value| value[0]); + let baked_ao = baked + .sample_working(BakedMap::AmbientOcclusion, x, y, (resolution, composite.height), &composite.block_scales) + .map_or(1.0, |value| value[0]); let ch_ao = ao.and_then(|a| a.get(i)).map(|v| *v as f32 / 65535.0).unwrap_or(1.0); - let px = &mut out[i * 4..i * 4 + 4]; - px[0] = ((baked_ao * ch_ao).clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + let pixel = &mut out[i * 4..i * 4 + 4]; + pixel[0] = ((baked_ao * ch_ao).clamp(0.0, 1.0) * 255.0 + 0.5) as u8; let v = r.and_then(|t| t.get(i).copied()).unwrap_or(r_default); - px[1] = u8_of(if gloss { 65535 - v } else { v }); - px[2] = u8_of(m.and_then(|t| t.get(i).copied()).unwrap_or(0)); - px[3] = u8_of(s.and_then(|t| t.get(i).copied()).unwrap_or(default16(Channel::SpecularLevel))); + pixel[1] = u8_of(if gloss { 65535 - v } else { v }); + pixel[2] = u8_of(m.and_then(|t| t.get(i).copied()).unwrap_or(0)); + pixel[3] = u8_of(s.and_then(|t| t.get(i).copied()).unwrap_or(default16(Channel::SpecularLevel))); } } DisplayKind::Normal => { - let (n, sheen_rough) = (get(Channel::Normal), scalar8(Channel::SheenRoughness)); + let (n, sheen_roughness) = (get(Channel::Normal), scalar8(Channel::SheenRoughness)); for i in 0..TILE_AREA { - let px = &mut out[i * 4..i * 4 + 4]; - // The baked normal is the base the painted normal details sit on (as in export). + let pixel = &mut out[i * 4..i * 4 + 4]; + + // The baked normal is the base the painted normal details sit on (as in export) let (x, y) = (tx * TILE + (i as u32 % TILE), ty * TILE + (i as u32 / TILE)); - let base = baked.sample_working(BakedMap::Normal, x, y, (res, comp.height), &comp.block_scales); + let base = baked.sample_working(BakedMap::Normal, x, y, (resolution, composite.height), &composite.block_scales); match (n, base) { (Some(t), None) => { - for (k, d) in px.iter_mut().take(3).enumerate() { + for (k, d) in pixel.iter_mut().take(3).enumerate() { *d = u8_of(t.get(i * 3 + k).copied().unwrap_or(0)); } } (detail, Some(base)) => { let detail = detail.map_or([0.5, 0.5, 1.0], |t| [0, 1, 2].map(|k| t.get(i * 3 + k).map_or(0.0, |v| *v as f32 / 65535.0))); let v = texturecraft_core::blend::rnm(base, detail); - for (d, v) in px.iter_mut().zip(v) { + for (d, v) in pixel.iter_mut().zip(v) { *d = (v.clamp(0.0, 1.0) * 255.0 + 0.5) as u8; } } - (None, None) => px[..3].copy_from_slice(&[128, 128, 255]), + (None, None) => pixel[..3].copy_from_slice(&[128, 128, 255]), } - px[3] = sheen_rough(i); + pixel[3] = sheen_roughness(i); } } DisplayKind::Height => { @@ -206,6 +213,7 @@ pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u3 } } } + out } diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 26d08f67..3a9404d3 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -2203,60 +2203,67 @@ pub type FlatTile = (Channel, (u32, u32), Vec); /// Flatten one paint or fill layer: its content (with content effects) times its mask, as /// premultiplied (value, coverage) tiles per enabled channel, ready to become a plain paint /// layer. Groups are not supported (None). -pub fn flatten_layer(inp: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Option> { - let set = inp.project.texture_set(inp.ts).ok()?; - if inp.project.content_layer(id)?.is_group() { +pub fn flatten_layer(inputs: &Inputs, id: LayerId, tiles: &[(u32, u32)]) -> Option> { + let set = inputs.project.texture_set(inputs.ts).ok()?; + if inputs.project.content_layer(id)?.is_group() { return None; } + let channels: Vec = set.channel_list(); - // Plan the layer forced visible so hidden layers flatten too. - let mut solo = inp.project.clone(); + + // Plan the layer forced visible so hidden layers flatten too + let mut solo = inputs.project.clone(); if let Some(l) = solo.layers.get_mut(&id) { l.visible = true; } - let solo_inp = Inputs { project: &solo, preview: None, block_scales: inp.block_scales.clone(), ..*inp }; - let fields = neighbourhood_fields(&solo_inp, &channels, tiles); + let visible_inputs = Inputs { project: &solo, preview: None, block_scales: inputs.block_scales.clone(), ..*inputs }; + let fields = neighbourhood_fields(&visible_inputs, &channels, tiles); + let out: Vec> = tiles .par_iter() .map(|&(tx, ty)| { - let nodes = plan(&solo_inp, &[id], &channels, tx, ty, 0, Some(&fields)); + let nodes = plan(&visible_inputs, &[id], &channels, tx, ty, 0, Some(&fields)); let Some(n) = nodes.first() else { return Vec::new() }; - let full = anchor_plan(&solo_inp, id, &channels, tx, ty, Some(&fields)); - let mut bufs: Vec<(Channel, Vec, bool)> = + let full = anchor_plan(&visible_inputs, id, &channels, tx, ty, Some(&fields)); + let mut buffers: Vec<(Channel, Vec, bool)> = n.chans.iter().filter_map(|c| Channel::ALL.get(c.ch).map(|ch| (*ch, vec![0u16; TILE_AREA * (c.comps + 1)], false))).collect(); - for (ch, buf, _) in &mut bufs { + for (ch, buffer, _) in &mut buffers { if ch.kind() == ChannelKind::Signed { - for px in buf.as_chunks_mut::<2>().0.iter_mut() { - px[0] = to_u16_signed(0.0); + for pixel in buffer.as_chunks_mut::<2>().0 { + pixel[0] = to_u16_signed(0.0); } } } - for (x, y, o) in tile_texels(inp.gbuf, tx, ty) { - let mut tex = Texel::new(&solo_inp, x, y, o, 0.0); + + for (x, y, o) in tile_texels(inputs.gbuf, tx, ty) { + let mut tex = Texel::new(&visible_inputs, x, y, o, 0.0); if !full.is_empty() { tex.anchors_below(&full, id); } let m = tex.node_mask(n); - for (c, (ch, buf, any)) in n.chans.iter().zip(bufs.iter_mut()) { + for (c, (ch, buffer, any)) in n.chans.iter().zip(buffers.iter_mut()) { let Some((v, cov)) = tex.content(&n.content, c) else { continue }; let a = (cov * m).clamp(0.0, 1.0); if a <= 0.0 { continue; } + *any = true; let comps = c.comps; - let Some(px) = buf.get_mut(o * (comps + 1)..(o + 1) * (comps + 1)) else { continue }; - for (slot, pv) in px.iter_mut().zip(v.iter().take(comps)) { + let Some(pixel) = buffer.get_mut(o * (comps + 1)..(o + 1) * (comps + 1)) else { continue }; + for (slot, pv) in pixel.iter_mut().zip(v.iter().take(comps)) { *slot = if ch.kind() == ChannelKind::Signed { to_u16_signed(pv * a) } else { to_u16(pv * a) }; } - if let Some(slot) = px.get_mut(comps) { + if let Some(slot) = pixel.get_mut(comps) { *slot = to_u16(a); } } } - bufs.into_iter().filter(|(_, _, any)| *any).map(|(ch, buf, _)| (ch, (tx, ty), buf)).collect() + + buffers.into_iter().filter(|(_, _, any)| *any).map(|(ch, buffer, _)| (ch, (tx, ty), buffer)).collect() }) .collect(); + Some(out.into_iter().flatten().collect()) } diff --git a/crates/engine/src/quick_mask.rs b/crates/engine/src/quick_mask.rs index 92d00962..93087c14 100644 --- a/crates/engine/src/quick_mask.rs +++ b/crates/engine/src/quick_mask.rs @@ -105,34 +105,37 @@ impl Session { /// Includes the stroke in progress. pub fn quick_mask_rgba(&self, ts: usize, size: u32) -> Option> { let cache = self.caches.get(ts)?; - let (w, h) = cache.size; - let size = size.clamp(1, w.max(h)); + let (width, height) = cache.size; + let size = size.clamp(1, width.max(height)); 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 lut = srgb_lut(); + let srgb = srgb_lut(); let inverted = self.quick_mask.inverted; let mut out = vec![255u8; size as usize * size as usize * 4]; + out.par_chunks_mut(size as usize * 4).enumerate().for_each(|(y, row)| { - let ty = (y as u64 * u64::from(h) / u64::from(size)) as u32; - for (x, px) in row.as_chunks_mut::<4>().0.iter_mut().enumerate() { - let tx = (x as u64 * u64::from(w) / u64::from(size)) as u32; - let mut m = from_u16(mask.get(tx, ty)[0]); + let ty = (y as u64 * u64::from(height) / u64::from(size)) 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 mut coverage = from_u16(mask.get(tx, ty)[0]); if let Some((alpha, opacity, erase)) = live { - let a = from_u16(alpha.get(tx, ty)[0]) * opacity; - m = if erase { m * (1.0 - a) } else { a + m * (1.0 - a) }; + let stroke_coverage = from_u16(alpha.get(tx, ty)[0]) * opacity; + coverage = if erase { coverage * (1.0 - stroke_coverage) } else { stroke_coverage + coverage * (1.0 - stroke_coverage) }; } - let blocked = if inverted { m } else { 1.0 - m }; + + let blocked = if inverted { coverage } else { 1.0 - coverage }; let raw = base.map(|b| b.get(tx, ty)).unwrap_or([32768; 4]); - let t = 0.55 * blocked; + let tint_amount = 0.55 * blocked; for (k, tint) in [0.9, 0.1, 0.15].into_iter().enumerate() { - let c = f32::from(lut.get(usize::from(raw[k] >> 4)).copied().unwrap_or(0)) / 255.0; - if let Some(slot) = px.get_mut(k) { - *slot = ((c + (tint - c) * t).clamp(0.0, 1.0) * 255.0 + 0.5) as u8; + let color = f32::from(srgb.get(usize::from(raw[k] >> 4)).copied().unwrap_or(0)) / 255.0; + if let Some(slot) = pixel.get_mut(k) { + *slot = ((color + (tint - color) * tint_amount).clamp(0.0, 1.0) * 255.0 + 0.5) as u8; } } } }); + Some(out) } } diff --git a/crates/engine/tests/it/bake.rs b/crates/engine/tests/it/bake.rs index 013834b6..85b0142c 100644 --- a/crates/engine/tests/it/bake.rs +++ b/crates/engine/tests/it/bake.rs @@ -10,17 +10,18 @@ fn plane_session() -> Session { Session::new_project("t", mesh, "builtin:plane", None, 256).unwrap() } -/// `mesh` as OBJ text, lifted by `dy`, keeping only vertices with x ≤ `max_x` (triangles that -/// lose a vertex are dropped), every vertex colored `rgb`. -fn obj(mesh: &Mesh, dy: f32, max_x: f32, rgb: [f32; 3]) -> String { - let mut s = String::from("o Part_high\n"); - for p in &mesh.positions { - s += &format!("v {} {} {} {} {} {}\n", p.x.min(max_x), p.y + dy, p.z, rgb[0], rgb[1], rgb[2]); +/// `mesh` as OBJ text, shifted by `offset_y`, with x clamped to `max_x` and every vertex colored `rgb`. +fn obj(mesh: &Mesh, offset_y: f32, max_x: f32, rgb: [f32; 3]) -> String { + let mut text = String::from("o Part_high\n"); + for position in &mesh.positions { + text += &format!("v {} {} {} {} {} {}\n", position.x.min(max_x), position.y + offset_y, position.z, rgb[0], rgb[1], rgb[2]); } - for t in mesh.indices.as_chunks::<3>().0 { - s += &format!("f {} {} {}\n", t[0] + 1, t[1] + 1, t[2] + 1); + + for triangle in mesh.indices.as_chunks::<3>().0 { + text += &format!("f {} {} {}\n", triangle[0] + 1, triangle[1] + 1, triangle[2] + 1); } - s + + text } fn temp_file(name: &str, text: &str) -> String { diff --git a/crates/engine/tests/it/bake_tiles.rs b/crates/engine/tests/it/bake_tiles.rs index a7f3f1a0..16851173 100644 --- a/crates/engine/tests/it/bake_tiles.rs +++ b/crates/engine/tests/it/bake_tiles.rs @@ -53,6 +53,7 @@ fn partial_bake_preserves_unchecked_tiles_and_uses_the_workers_selection() { execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": true})).unwrap(); execute(&mut session, "bake.tile.set", &json!({"tile": 1001, "enabled": false})).unwrap(); let before = session.doc.baked.clone(); + let output = task.run(&Progress::new()).unwrap(); session.apply_bake(0, output).unwrap(); @@ -61,6 +62,7 @@ fn partial_bake_preserves_unchecked_tiles_and_uses_the_workers_selection() { assert!(row[..32].iter().all(|value| *value > 0.99)); assert!(row[32..].iter().all(|value| *value == 0.25)); } + session.undo().unwrap(); assert_eq!(session.doc.baked, before); } @@ -76,7 +78,9 @@ fn partial_bake_resizes_retained_tiles_and_unchecked_map_outputs() { }, ); execute(&mut session, "bake.tile.set", &json!({"tile": 1002, "enabled": false})).unwrap(); + let result = execute(&mut session, "bake.run", &json!({"resolution": 64, "cpu": true})).unwrap(); + assert_eq!(result["baked"], json!([0])); let baked = &session.doc.baked[&0]; @@ -87,6 +91,7 @@ fn partial_bake_resizes_retained_tiles_and_unchecked_map_outputs() { } assert_eq!(baked.maps[&BakedMap::Normal].len(), 128 * 64 * 3); assert!(baked.maps[&BakedMap::Normal].iter().all(|value| *value == 0.4)); + let reopened = Session::from_project_bytes(&session.to_project_bytes().unwrap()).unwrap(); assert_eq!(reopened.doc.baked, session.doc.baked); } diff --git a/crates/formats/src/fonts.rs b/crates/formats/src/fonts.rs index ca7db930..fbd27985 100644 --- a/crates/formats/src/fonts.rs +++ b/crates/formats/src/fonts.rs @@ -72,34 +72,37 @@ fn collect(dir: &Path, depth: usize, out: &mut Vec) { /// The faces of the font file at `path` (each face of a collection). pub fn faces_of(path: &Path) -> std::io::Result> { - let mut f = std::fs::File::open(path)?; - let mut at = |offset: u64, len: usize| -> std::io::Result> { - f.seek(SeekFrom::Start(offset))?; - let mut buf = vec![0; len]; - f.read_exact(&mut buf)?; + let mut file = std::fs::File::open(path)?; + let mut read_at = |offset: u64, length: usize| -> std::io::Result> { + file.seek(SeekFrom::Start(offset))?; + let mut buf = vec![0; length]; + file.read_exact(&mut buf)?; Ok(buf) }; - let head = at(0, 12)?; - let offsets: Vec = if head.get(..4) == Some(b"ttcf") { - let n = u32_at(&head, 8).unwrap_or(0).min(MAX_FACES_PER_FILE); - let table = at(12, 4 * n as usize)?; - (0..n as usize).filter_map(|i| u32_at(&table, 4 * i)).map(u64::from).collect() + + let header = read_at(0, 12)?; + let offsets: Vec = if header.get(..4) == Some(b"ttcf") { + let face_count = u32_at(&header, 8).unwrap_or(0).min(MAX_FACES_PER_FILE); + let table = read_at(12, 4 * face_count as usize)?; + (0..face_count as usize).filter_map(|i| u32_at(&table, 4 * i)).map(u64::from).collect() } else { vec![0] }; + let mut faces = Vec::new(); for (index, offset) in offsets.into_iter().enumerate() { - let dir = at(offset, 12)?; - let tables = at(offset + 12, 16 * usize::from(u16_at(&dir, 4).unwrap_or(0)))?; - let Some(rec) = tables.as_chunks::<16>().0.iter().find(|r| r.get(..4) == Some(b"name")) else { continue }; - let (Some(off), Some(len)) = (u32_at(rec, 8), u32_at(rec, 12)) else { continue }; - let names = at(u64::from(off), len.min(MAX_NAME_TABLE) as usize)?; + let directory = read_at(offset, 12)?; + let tables = read_at(offset + 12, 16 * usize::from(u16_at(&directory, 4).unwrap_or(0)))?; + let Some(record) = tables.as_chunks::<16>().0.iter().find(|r| r.get(..4) == Some(b"name")) else { continue }; + let (Some(offset), Some(length)) = (u32_at(record, 8), u32_at(record, 12)) else { continue }; + let names = read_at(u64::from(offset), length.min(MAX_NAME_TABLE) as usize)?; let name = |ids: [u16; 2]| ids.iter().find_map(|id| name_string(&names, *id)); if let Some(family) = name([16, 1]) { let style = name([17, 2]).unwrap_or_else(|| "Regular".into()); faces.push(FontFace { family, style, path: path.to_path_buf(), index: index as u32 }); } } + Ok(faces) } @@ -113,30 +116,32 @@ fn u32_at(b: &[u8], o: usize) -> Option { /// Name `id` of a `name` table, in English when it has several languages: Windows and Unicode /// records are UTF-16BE, Macintosh ones single-byte (read as Latin-1). -fn name_string(t: &[u8], id: u16) -> Option { - let (count, base) = (usize::from(u16_at(t, 2)?), usize::from(u16_at(t, 4)?)); +fn name_string(table: &[u8], id: u16) -> Option { + let (count, base) = (usize::from(u16_at(table, 2)?), usize::from(u16_at(table, 4)?)); let mut best: Option<(u8, String)> = None; - for r in (0..count).filter_map(|i| t.get(6 + 12 * i..18 + 12 * i)) { - let (platform, language, name_id) = (u16_at(r, 0)?, u16_at(r, 4)?, u16_at(r, 6)?); - let (len, off) = (usize::from(u16_at(r, 8)?), usize::from(u16_at(r, 10)?)); - let Some(bytes) = t.get(base + off..base + off + len) else { continue }; + for record in (0..count).filter_map(|i| table.get(6 + 12 * i..18 + 12 * i)) { + let (platform, language, name_id) = (u16_at(record, 0)?, u16_at(record, 4)?, u16_at(record, 6)?); + let (length, offset) = (usize::from(u16_at(record, 8)?), usize::from(u16_at(record, 10)?)); + let Some(bytes) = table.get(base + offset..base + offset + length) else { continue }; if name_id != id { continue; } - let (rank, s) = match platform { + + let (rank, name) = match platform { 3 | 0 => { - let s = String::from_utf16_lossy(&bytes.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes([c[0], c[1]])).collect::>()); - (if language == 0x409 { 0 } else { 1 }, s) + let name = String::from_utf16_lossy(&bytes.as_chunks::<2>().0.iter().map(|c| u16::from_be_bytes(*c)).collect::>()); + (if language == 0x409 { 0 } else { 1 }, name) } 1 => (if language == 0 { 2 } else { 3 }, bytes.iter().map(|b| char::from(*b)).collect()), _ => continue, }; - let s = s.trim().to_string(); - if !s.is_empty() && best.as_ref().is_none_or(|(r, _)| rank < *r) { - best = Some((rank, s)); + let name = name.trim().to_string(); + if !name.is_empty() && best.as_ref().is_none_or(|(best_rank, _)| rank < *best_rank) { + best = Some((rank, name)); } } - best.map(|(_, s)| s) + + best.map(|(_, name)| name) } #[cfg(test)] diff --git a/crates/formats/src/mesh_export.rs b/crates/formats/src/mesh_export.rs index 454ceffd..404b09bb 100644 --- a/crates/formats/src/mesh_export.rs +++ b/crates/formats/src/mesh_export.rs @@ -67,47 +67,50 @@ pub fn obj_with_mtl(mesh: &Mesh, name: &str, stem: &str, textures: &[Vec) -> String { - let mut s = String::with_capacity(mesh.positions.len() * 96 + mesh.indices.len() * 12); - let _ = writeln!(s, "# {}, exported by TextureCraft", token(name)); + let mut text = String::with_capacity(mesh.positions.len() * 96 + mesh.indices.len() * 12); + let _ = writeln!(text, "# {}, exported by TextureCraft", token(name)); if let Some(lib) = mtllib { - let _ = writeln!(s, "mtllib {lib}"); + let _ = writeln!(text, "mtllib {lib}"); } - let _ = writeln!(s, "o {}", token(name)); + let _ = writeln!(text, "o {}", token(name)); for p in &mesh.positions { - let _ = writeln!(s, "v {} {} {}", p.x, p.y, p.z); + let _ = writeln!(text, "v {} {} {}", p.x, p.y, p.z); } + let uvs = mesh.uvs.len() == mesh.positions.len(); let normals = mesh.normals.len() == mesh.positions.len(); if uvs { for t in &mesh.uvs { - let _ = writeln!(s, "vt {} {}", t.x, 1.0 - t.y); + let _ = writeln!(text, "vt {} {}", t.x, 1.0 - t.y); } } if normals { for n in &mesh.normals { - let _ = writeln!(s, "vn {} {} {}", n.x, n.y, n.z); + let _ = writeln!(text, "vn {} {} {}", n.x, n.y, n.z); } } + let materials = unique_ids(&mesh.materials, token); - for sm in &parts(mesh, name) { - let material = materials.get(sm.material).map_or("default", String::as_str); - let _ = writeln!(s, "g {}\nusemtl {material}", token(&sm.name)); - let (a, b) = (sm.start as usize, sm.start as usize + sm.count as usize); - for tri in mesh.indices.get(a..b).unwrap_or_default().as_chunks::<3>().0 { - s.push('f'); - for i in tri { + for part in &parts(mesh, name) { + let material = materials.get(part.material).map_or("default", String::as_str); + let _ = writeln!(text, "g {}\nusemtl {material}", token(&part.name)); + let (a, b) = (part.start as usize, part.start as usize + part.count as usize); + for triangle in mesh.indices.get(a..b).unwrap_or_default().as_chunks::<3>().0 { + text.push('f'); + for i in triangle { let i = i + 1; let _ = match (uvs, normals) { - (true, true) => write!(s, " {i}/{i}/{i}"), - (true, false) => write!(s, " {i}/{i}"), - (false, true) => write!(s, " {i}//{i}"), - (false, false) => write!(s, " {i}"), + (true, true) => write!(text, " {i}/{i}/{i}"), + (true, false) => write!(text, " {i}/{i}"), + (false, true) => write!(text, " {i}//{i}"), + (false, false) => write!(text, " {i}"), }; } - s.push('\n'); + text.push('\n'); } } - s + + text } /// `id` of each material name, made unique with `_2`, `_3`… where two would be the same, also diff --git a/crates/formats/src/mesh_export/usd.rs b/crates/formats/src/mesh_export/usd.rs index 25c8f04c..2f57f7aa 100644 --- a/crates/formats/src/mesh_export/usd.rs +++ b/crates/formats/src/mesh_export/usd.rs @@ -166,60 +166,64 @@ fn identifier(s: &str, taken: &mut Vec) -> String { /// The export scene: `/` with the `Mesh` and `Materials`. `files[m]` are the texture /// file names (by slot) of material `m`. fn scene(mesh: &Mesh, name: &str, files: &[Vec<(usize, String)>]) -> Result { - let n = mesh.positions.len(); - if n == 0 || mesh.indices.len() < 3 { + let vertex_count = mesh.positions.len(); + if vertex_count == 0 || mesh.indices.len() < 3 { return Err(FormatError::Invalid("the mesh is empty".into())); } + let ints = |v: &[u32]| v.iter().map(|&i| i32::try_from(i).map_err(|_| FormatError::TooLarge("vertex index beyond 2^31".into()))).collect::>>(); let mut taken = Vec::new(); let root_name = identifier(name, &mut taken); let mut root = UsdPrim::new(&root_name, "Xform"); - let mut geo = UsdPrim::new(&identifier(&format!("{name}_mesh"), &mut taken), "Mesh"); - let mat_names: Vec = mesh.materials.iter().map(|m| identifier(m, &mut taken)).collect(); - let mat_path = |m: usize| mat_names.get(m).map(|id| format!("/{root_name}/Materials/{id}")); + let mut geometry = UsdPrim::new(&identifier(&format!("{name}_mesh"), &mut taken), "Mesh"); + let material_names: Vec = mesh.materials.iter().map(|m| identifier(m, &mut taken)).collect(); + let material_path = |m: usize| material_names.get(m).map(|id| format!("/{root_name}/Materials/{id}")); let (lo, hi) = mesh.bounds(); - // Faces in submesh order; subsets index them. - let mut tris: Vec = Vec::with_capacity(mesh.indices.len()); + + // Faces in submesh order; subsets index them + let mut indices: Vec = Vec::with_capacity(mesh.indices.len()); let mut faces_of: Vec> = vec![Vec::new(); mesh.materials.len()]; - for sm in parts(mesh, name) { - let range = mesh.indices.get(sm.start as usize..(sm.start as usize).saturating_add(sm.count as usize)).unwrap_or_default(); + for part in parts(mesh, name) { + let range = mesh.indices.get(part.start as usize..(part.start as usize).saturating_add(part.count as usize)).unwrap_or_default(); for t in range.as_chunks::<3>().0 { - if let Some(f) = faces_of.get_mut(sm.material) { - f.push(i32::try_from(tris.len() / 3).map_err(|_| FormatError::TooLarge("triangle count".into()))?); + if let Some(f) = faces_of.get_mut(part.material) { + f.push(i32::try_from(indices.len() / 3).map_err(|_| FormatError::TooLarge("triangle count".into()))?); } - tris.extend_from_slice(t); + indices.extend_from_slice(t); } } + let vertex = |mut a: UsdAttr| { a.interpolation = Some("vertex"); a }; - geo.attrs = vec![ + geometry.attrs = vec![ UsdAttr::new("extent", "float3[]", Some(UsdValue::Vec3fs(vec![lo.to_array(), hi.to_array()]))), - UsdAttr::new("faceVertexCounts", "int[]", Some(UsdValue::Ints(vec![3; tris.len() / 3]))), - UsdAttr::new("faceVertexIndices", "int[]", Some(UsdValue::Ints(ints(&tris)?))), + UsdAttr::new("faceVertexCounts", "int[]", Some(UsdValue::Ints(vec![3; indices.len() / 3]))), + UsdAttr::new("faceVertexIndices", "int[]", Some(UsdValue::Ints(ints(&indices)?))), UsdAttr::new("points", "point3f[]", Some(UsdValue::Vec3fs(mesh.positions.iter().map(|p| p.to_array()).collect()))), UsdAttr::new("subdivisionScheme", "token", Some(UsdValue::Token("none".into()))).uniform(), ]; - if mesh.normals.len() == n { - geo.attrs.push(vertex(UsdAttr::new("normals", "normal3f[]", Some(UsdValue::Vec3fs(mesh.normals.iter().map(|v| v.to_array()).collect()))))); + if mesh.normals.len() == vertex_count { + geometry.attrs.push(vertex(UsdAttr::new("normals", "normal3f[]", Some(UsdValue::Vec3fs(mesh.normals.iter().map(|v| v.to_array()).collect()))))); } - if mesh.uvs.len() == n { - // USD's st origin is bottom-left. + if mesh.uvs.len() == vertex_count { + // USD's st origin is bottom-left let st = mesh.uvs.iter().map(|t| [t.x, 1.0 - t.y]).collect(); - geo.attrs.push(vertex(UsdAttr::new("primvars:st", "texCoord2f[]", Some(UsdValue::Vec2fs(st))))); + geometry.attrs.push(vertex(UsdAttr::new("primvars:st", "texCoord2f[]", Some(UsdValue::Vec2fs(st))))); } + let used: Vec = (0..mesh.materials.len()).filter(|m| faces_of.get(*m).is_some_and(|f| !f.is_empty())).collect(); match used.as_slice() { [] => {} [m] => { - geo.binding_api = true; - geo.attrs.extend(mat_path(*m).map(|p| UsdAttr::rel("material:binding", p))); + geometry.binding_api = true; + geometry.attrs.extend(material_path(*m).map(|p| UsdAttr::rel("material:binding", p))); } _ => { for &m in &used { - let (Some(id), Some(path)) = (mat_names.get(m), mat_path(m)) else { continue }; + let (Some(id), Some(path)) = (material_names.get(m), material_path(m)) else { continue }; let mut subset = UsdPrim::new(id, "GeomSubset"); subset.binding_api = true; subset.attrs = vec![ @@ -228,18 +232,20 @@ fn scene(mesh: &Mesh, name: &str, files: &[Vec<(usize, String)>]) -> Result Ogawa<'a> { } /// The first sample of a scalar or array property as numbers (`extent` per item). - fn values(&mut self, p: &Prop) -> Result> { - let samples = self.group(p.group)?; + fn values(&mut self, property: &Prop) -> Result> { + let samples = self.group(property.group)?; let Some(&first) = samples.first() else { return Ok(Vec::new()) }; + let raw = self.data(first)?; let raw = if raw.is_empty() { raw } else { - raw.get(KEY_BYTES..).ok_or_else(|| malformed(KIND, format!("sample of \"{}\" is shorter than its key", p.name)))? + raw.get(KEY_BYTES..).ok_or_else(|| malformed(KIND, format!("sample of \"{}\" is shorter than its key", property.name)))? }; - let size = match p.pod { + + let value_bytes = match property.pod { 0..=2 => 1, 3 | 4 => 2, 5 | 6 | 10 => 4, 7 | 8 | 11 => 8, - other => return Err(FormatError::Unsupported(format!("Alembic property \"{}\" of data type {other}", p.name))), + other => return Err(FormatError::Unsupported(format!("Alembic property \"{}\" of data type {other}", property.name))), }; - self.charge((raw.len() / size).saturating_mul(8))?; - fn le(c: &[u8]) -> [u8; N] { - <[u8; N]>::try_from(c).unwrap_or([0; N]) - } - Ok(match p.pod { + self.charge((raw.len() / value_bytes).saturating_mul(8))?; + + Ok(match property.pod { 0 | 1 => raw.iter().map(|v| *v as f64).collect(), 2 => raw.iter().map(|v| *v as i8 as f64).collect(), - 3 => raw.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(le(c)) as f64).collect(), - 4 => raw.as_chunks::<2>().0.iter().map(|c| i16::from_le_bytes(le(c)) as f64).collect(), - 5 => raw.as_chunks::<4>().0.iter().map(|c| u32::from_le_bytes(le(c)) as f64).collect(), - 6 => raw.as_chunks::<4>().0.iter().map(|c| i32::from_le_bytes(le(c)) as f64).collect(), - 7 => raw.as_chunks::<8>().0.iter().map(|c| u64::from_le_bytes(le(c)) as f64).collect(), - 8 => raw.as_chunks::<8>().0.iter().map(|c| i64::from_le_bytes(le(c)) as f64).collect(), - 10 => raw.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(le(c)) as f64).collect(), - _ => raw.as_chunks::<8>().0.iter().map(|c| f64::from_le_bytes(le(c))).collect(), + 3 => raw.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c) as f64).collect(), + 4 => raw.as_chunks::<2>().0.iter().map(|c| i16::from_le_bytes(*c) as f64).collect(), + 5 => raw.as_chunks::<4>().0.iter().map(|c| u32::from_le_bytes(*c) as f64).collect(), + 6 => raw.as_chunks::<4>().0.iter().map(|c| i32::from_le_bytes(*c) as f64).collect(), + 7 => raw.as_chunks::<8>().0.iter().map(|c| u64::from_le_bytes(*c) as f64).collect(), + 8 => raw.as_chunks::<8>().0.iter().map(|c| i64::from_le_bytes(*c) as f64).collect(), + 10 => raw.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c) as f64).collect(), + _ => raw.as_chunks::<8>().0.iter().map(|c| f64::from_le_bytes(*c)).collect(), }) } @@ -491,21 +491,23 @@ impl Walk<'_, '_> { } fn mesh(&mut self, r: u64, world: Mat4, sets: &[(String, Vec)]) -> Result<()> { - let props = self.o.compound(r)?; + let properties = self.o.compound(r)?; let get = |o: &mut Ogawa, name: &str| -> Result> { - match find(&props, name) { + match find(&properties, name) { Some(p) => o.values(p), None => Err(malformed(KIND, format!("PolyMesh has no {name}"))), } }; + let p = get(&mut self.o, "P")?; let indices = get(&mut self.o, ".faceIndices")?; let counts = get(&mut self.o, ".faceCounts")?; check_vertices(p.len() / 3)?; let points: Vec = p.as_chunks::<3>().0.iter().map(|c| world.transform_point3(Vec3::new(c[0] as f32, c[1] as f32, c[2] as f32))).collect(); let n = [points.len(), counts.len(), indices.len()]; - let normals = self.param(&props, "N", n)?; - let uvs = self.param(&props, "uv", n)?; + let normals = self.param(&properties, "N", n)?; + let uvs = self.param(&properties, "uv", n)?; + let mut material = vec![None::; counts.len()]; for (s, (_, faces)) in sets.iter().enumerate() { for f in faces { @@ -514,19 +516,26 @@ impl Walk<'_, '_> { } } } - let nm = Mat3::from_mat4(world).inverse().transpose(); - // Alembic winds polygons clockwise; a mirroring transform flips them once more. + let normal_transform = Mat3::from_mat4(world).inverse().transpose(); + + // Alembic winds polygons clockwise; a mirroring transform flips them once more let keep_order = world.determinant() < 0.0; let (mut k, mut corners, mut bad_uvs) = (0usize, Vec::new(), 0usize); for (f, &count) in counts.iter().enumerate() { let end = (count >= 0.0).then(|| k.checked_add(count as usize)).flatten().filter(|e| *e <= indices.len()); let end = end.ok_or_else(|| malformed(KIND, format!("face {f} has {count} corners past the index list")))?; corners.clear(); - for (kk, &pi) in indices.iter().enumerate().take(end).skip(k) { - let p = points.get(pi as usize).filter(|_| pi >= 0.0).ok_or_else(|| malformed(KIND, format!("point index {pi} out of range")))?; - let pi = pi as usize; - let n = normals.as_ref().and_then(|l| l.get::<3>(kk, pi, f)).map(|[x, y, z]| nm * Vec3::new(x as f32, y as f32, z as f32)); - let uv = uvs.as_ref().map(|l| match l.get::<2>(kk, pi, f) { + for (corner_index, &point_index) in indices.iter().enumerate().take(end).skip(k) { + let p = points + .get(point_index as usize) + .filter(|_| point_index >= 0.0) + .ok_or_else(|| malformed(KIND, format!("point index {point_index} out of range")))?; + let point_index = point_index as usize; + let n = normals + .as_ref() + .and_then(|l| l.get::<3>(corner_index, point_index, f)) + .map(|[x, y, z]| normal_transform * Vec3::new(x as f32, y as f32, z as f32)); + let uv = uvs.as_ref().map(|l| match l.get::<2>(corner_index, point_index, f) { Some([u, v]) => Vec2::new(u as f32, 1.0 - v as f32), None => { bad_uvs += 1; @@ -542,9 +551,11 @@ impl Walk<'_, '_> { let name = material.get(f).copied().flatten().and_then(|s| sets.get(s)).map_or(DEFAULT_MATERIAL, |(n, _)| n.as_str()); self.sink.polygon(name, &corners)?; } + if bad_uvs > 0 { self.sink.warn(format!("{bad_uvs} polygon corners have no UV in the Alembic uv parameter (set to 0, 0)")); } + Ok(()) } } diff --git a/crates/formats/src/mesh_import/fbx.rs b/crates/formats/src/mesh_import/fbx.rs index 19d8cdad..5e975ba2 100644 --- a/crates/formats/src/mesh_import/fbx.rs +++ b/crates/formats/src/mesh_import/fbx.rs @@ -254,39 +254,39 @@ impl<'a> Binary<'a> { }) } - fn array(&mut self, ty: u8) -> Result> { + fn array(&mut self, value_type: u8) -> Result> { let (count, encoding, stored) = (self.u32()?, self.u32()?, self.u32()?); - let size = match ty { + let value_bytes = match value_type { b'd' | b'l' => 8, b'f' | b'i' => 4, _ => 1, }; - let len = count.checked_mul(size).ok_or_else(|| malformed(KIND, "array too large"))?; + let decoded_bytes = count.checked_mul(value_bytes).ok_or_else(|| malformed(KIND, "array too large"))?; self.budget.charge(count.saturating_mul(8))?; + let data = self.take(stored)?; let raw: Cow<[u8]> = match encoding { - 0 if stored == len => Cow::Borrowed(data), + 0 if stored == decoded_bytes => Cow::Borrowed(data), 1 => { let mut out = Vec::new(); flate2::read::ZlibDecoder::new(data) - .take(len as u64 + 1) + .take(decoded_bytes as u64 + 1) .read_to_end(&mut out) .map_err(|e| malformed(KIND, format!("bad compressed array: {e}")))?; - if out.len() != len { + if out.len() != decoded_bytes { return Err(malformed(KIND, "compressed array has the wrong length")); } + Cow::Owned(out) } _ => return Err(malformed(KIND, format!("array encoding {encoding} with {stored} bytes for {count} items"))), }; - fn le(c: &[u8]) -> [u8; N] { - <[u8; N]>::try_from(c).unwrap_or([0; N]) - } - Ok(match ty { - b'd' => raw.as_chunks::<8>().0.iter().map(|c| f64::from_le_bytes(le(c))).collect(), - b'l' => raw.as_chunks::<8>().0.iter().map(|c| i64::from_le_bytes(le(c)) as f64).collect(), - b'f' => raw.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(le(c)) as f64).collect(), - b'i' => raw.as_chunks::<4>().0.iter().map(|c| i32::from_le_bytes(le(c)) as f64).collect(), + + Ok(match value_type { + b'd' => raw.as_chunks::<8>().0.iter().map(|c| f64::from_le_bytes(*c)).collect(), + b'l' => raw.as_chunks::<8>().0.iter().map(|c| i64::from_le_bytes(*c) as f64).collect(), + b'f' => raw.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c) as f64).collect(), + b'i' => raw.as_chunks::<4>().0.iter().map(|c| i32::from_le_bytes(*c) as f64).collect(), _ => raw.iter().map(|b| *b as f64).collect(), }) } @@ -783,29 +783,34 @@ impl Layer<'_> { } } -fn add_geometry(sink: &mut PolygonSink, g: &Node, m: Mat4, slots: &[String]) -> Result<()> { - let verts = g.child("Vertices").map(Node::arr).unwrap_or_default(); - check_vertices(verts.len() / 3)?; - let points: Vec = verts.as_chunks::<3>().0.iter().map(|c| m.transform_point3(Vec3::new(c[0] as f32, c[1] as f32, c[2] as f32))).collect(); - let pvi = g.child("PolygonVertexIndex").map(Node::arr).unwrap_or_default(); - let normals = Layer::read(g, "LayerElementNormal", "Normals", "NormalsIndex"); - let uvs = Layer::read(g, "LayerElementUV", "UV", "UVIndex"); - let mats = Layer::read(g, "LayerElementMaterial", "Materials", ""); - let nm = Mat3::from_mat4(m).inverse().transpose(); - let flip = m.determinant() < 0.0; - let (mut corners, mut poly, mut bad_normals, mut bad_uvs) = (Vec::new(), 0usize, 0usize, 0usize); - for (k, &v) in pvi.iter().enumerate() { - // The last corner of each polygon is stored as -(index + 1). - let (cp, last) = if v < 0.0 { (-v - 1.0, true) } else { (v, false) }; - let p = points.get(cp as usize).filter(|_| cp.fract() == 0.0).ok_or_else(|| malformed(KIND, format!("polygon vertex index {v} out of range")))?; - let cp = cp as usize; +fn add_geometry(sink: &mut PolygonSink, geometry: &Node, transform: Mat4, slots: &[String]) -> Result<()> { + let vertices = geometry.child("Vertices").map(Node::arr).unwrap_or_default(); + check_vertices(vertices.len() / 3)?; + let points: Vec = vertices.as_chunks::<3>().0.iter().map(|c| transform.transform_point3(Vec3::new(c[0] as f32, c[1] as f32, c[2] as f32))).collect(); + let polygon_indices = geometry.child("PolygonVertexIndex").map(Node::arr).unwrap_or_default(); + let normals = Layer::read(geometry, "LayerElementNormal", "Normals", "NormalsIndex"); + let uvs = Layer::read(geometry, "LayerElementUV", "UV", "UVIndex"); + let materials = Layer::read(geometry, "LayerElementMaterial", "Materials", ""); + let normal_transform = Mat3::from_mat4(transform).inverse().transpose(); + let flip = transform.determinant() < 0.0; + let (mut corners, mut polygon_index, mut bad_normals, mut bad_uvs) = (Vec::new(), 0usize, 0usize, 0usize); + + for (k, &v) in polygon_indices.iter().enumerate() { + // The last corner of each polygon is stored as -(index + 1) + let (control_point, last) = if v < 0.0 { (-v - 1.0, true) } else { (v, false) }; + let p = points + .get(control_point as usize) + .filter(|_| control_point.fract() == 0.0) + .ok_or_else(|| malformed(KIND, format!("polygon vertex index {v} out of range")))?; + let control_point = control_point as usize; let n = normals.as_ref().and_then(|l| { - let n = l.get(k, cp, poly).map(|[x, y, z]| nm * Vec3::new(x as f32, y as f32, z as f32)); + let n = l.get(k, control_point, polygon_index).map(|[x, y, z]| normal_transform * Vec3::new(x as f32, y as f32, z as f32)); bad_normals += usize::from(n.is_none()); n }); - // A UV layer with holes keeps its layout: missing items read as 0, 0. - let uv = uvs.as_ref().map(|l| match l.get(k, cp, poly) { + + // A UV layer with holes keeps its layout: missing items read as 0, 0 + let uv = uvs.as_ref().map(|l| match l.get(k, control_point, polygon_index) { Some([u, v]) => Vec2::new(u as f32, 1.0 - v as f32), None => { bad_uvs += 1; @@ -813,22 +818,24 @@ fn add_geometry(sink: &mut PolygonSink, g: &Node, m: Mat4, slots: &[String]) -> } }); corners.push(Corner { p: *p, n, uv }); - if last || k + 1 == pvi.len() { + if last || k + 1 == polygon_indices.len() { if flip { corners.reverse(); } - let slot = mats.as_ref().and_then(|l| l.get(poly, poly, poly)).map_or(0.0, |[s]| s); + let slot = materials.as_ref().and_then(|l| l.get(polygon_index, polygon_index, polygon_index)).map_or(0.0, |[s]| s); let name = slots.get(slot as usize).filter(|_| slot >= 0.0).map_or("Default", String::as_str); sink.polygon(name, &corners)?; corners.clear(); - poly += 1; + polygon_index += 1; } } + if bad_normals > 0 { sink.warn(format!("{bad_normals} polygon corners have no normal in the FBX normal layer; normals were recomputed")); } if bad_uvs > 0 { sink.warn(format!("{bad_uvs} polygon corners have no UV in the FBX UV layer (set to 0, 0)")); } + Ok(()) } diff --git a/crates/formats/src/mesh_import/gltf.rs b/crates/formats/src/mesh_import/gltf.rs index 92f64077..21658033 100644 --- a/crates/formats/src/mesh_import/gltf.rs +++ b/crates/formats/src/mesh_import/gltf.rs @@ -96,33 +96,36 @@ struct Attrs { color_seen: bool, } -fn add_primitive(raw: &mut RawMesh, attrs: &mut Attrs, prim: &gltf::Primitive, m: Mat4, buffers: &[gltf::buffer::Data], part: &str) -> Result<()> { - if prim.mode() != Mode::Triangles { - raw.warnings.push(format!("skipped a primitive drawn as {:?} (only triangles are supported)", prim.mode())); +fn add_primitive(raw: &mut RawMesh, attrs: &mut Attrs, primitive: &gltf::Primitive, transform: Mat4, buffers: &[gltf::buffer::Data], part: &str) -> Result<()> { + if primitive.mode() != Mode::Triangles { + raw.warnings.push(format!("skipped a primitive drawn as {:?} (only triangles are supported)", primitive.mode())); return Ok(()); } - let Some(pacc) = prim.get(&Semantic::Positions) else { + + let Some(position_accessor) = primitive.get(&Semantic::Positions) else { raw.warnings.push("skipped a primitive without positions".into()); return Ok(()); }; - check_accessor(&pacc, buffers, Dimensions::Vec3, &[DataType::F32], "position")?; - let nacc = prim.get(&Semantic::Normals); - if let Some(a) = &nacc { + + check_accessor(&position_accessor, buffers, Dimensions::Vec3, &[DataType::F32], "position")?; + let normal_accessor = primitive.get(&Semantic::Normals); + if let Some(a) = &normal_accessor { check_accessor(a, buffers, Dimensions::Vec3, &[DataType::F32], "normal")?; } - let tacc = prim.get(&Semantic::TexCoords(0)); - if let Some(a) = &tacc { + let texcoord_accessor = primitive.get(&Semantic::TexCoords(0)); + if let Some(a) = &texcoord_accessor { check_accessor(a, buffers, Dimensions::Vec2, &[DataType::F32, DataType::U8, DataType::U16], "texcoord")?; } - let cacc = prim.get(&Semantic::Colors(0)); - if let Some(a) = &cacc { + let color_accessor = primitive.get(&Semantic::Colors(0)); + if let Some(a) = &color_accessor { let dims = if a.dimensions() == Dimensions::Vec3 { Dimensions::Vec3 } else { Dimensions::Vec4 }; check_accessor(a, buffers, dims, &[DataType::F32, DataType::U8, DataType::U16], "color")?; } - if let Some(a) = prim.indices() { + if let Some(a) = primitive.indices() { check_accessor(&a, buffers, Dimensions::Scalar, &[DataType::U8, DataType::U16, DataType::U32], "index")?; } - let reader = prim.reader(|b| buffers.get(b.index()).map(|d| &d.0[..])); + + let reader = primitive.reader(|b| buffers.get(b.index()).map(|d| &d.0[..])); let positions: Vec = reader.read_positions().ok_or_else(|| malformed(KIND, "unreadable positions"))?.map(Vec3::from).collect(); let n = positions.len(); check_vertices(raw.positions.len().saturating_add(n))?; @@ -134,38 +137,40 @@ fn add_primitive(raw: &mut RawMesh, attrs: &mut Attrs, prim: &gltf::Primitive, m if let Some(bad) = indices.iter().find(|i| **i as usize >= n) { return Err(malformed(KIND, format!("index {bad} out of range ({n} vertices)"))); } + check_triangles(raw.triangle_count(), indices.len() / 3)?; - let normals: Option> = nacc.and_then(|_| reader.read_normals()).map(|it| it.map(Vec3::from).collect()); - let texcoords: Option> = tacc.and_then(|_| reader.read_tex_coords(0)).map(|t| t.into_f32().map(Vec2::from).collect()); + let normals: Option> = normal_accessor.and_then(|_| reader.read_normals()).map(|it| it.map(Vec3::from).collect()); + let texcoords: Option> = texcoord_accessor.and_then(|_| reader.read_tex_coords(0)).map(|t| t.into_f32().map(Vec2::from).collect()); let colors: Option> = - cacc.and_then(|_| reader.read_colors(0)).map(|c| c.into_rgba_f32().map(Vec4::from).collect()).filter(|c: &Vec| c.len() == n); + color_accessor.and_then(|_| reader.read_colors(0)).map(|c| c.into_rgba_f32().map(Vec4::from).collect()).filter(|c: &Vec| c.len() == n); attrs.color_seen |= colors.is_some(); let color_of = |i: usize| colors.as_ref().and_then(|c| c.get(i)).copied().unwrap_or(Vec4::ONE); - let m3 = Mat3::from_mat4(m); - let nm = m3.inverse().transpose(); - let flip = m3.determinant() < 0.0; - let world: Vec = positions.iter().map(|p| m.transform_point3(*p)).collect(); - let name = match prim.material().index() { + let linear_transform = Mat3::from_mat4(transform); + let normal_transform = linear_transform.inverse().transpose(); + let flip = linear_transform.determinant() < 0.0; + let world: Vec = positions.iter().map(|p| transform.transform_point3(*p)).collect(); + let name = match primitive.material().index() { None => "Default".to_string(), - Some(i) => prim.material().name().map(str::to_string).unwrap_or_else(|| format!("Material_{i}")), + Some(i) => primitive.material().name().map(str::to_string).unwrap_or_else(|| format!("Material_{i}")), }; if !raw.base_colors.iter().any(|c| c.material == name) { - base_color(raw, &prim.material(), &name, buffers); + base_color(raw, &primitive.material(), &name, buffers); } let base = raw.positions.len() as u32; - let tex_ok = texcoords.as_ref().is_some_and(|t| t.len() == n); - if tex_ok { + let has_texcoords = texcoords.as_ref().is_some_and(|t| t.len() == n); + if has_texcoords { attrs.uv_seen.0 = true } else { attrs.uv_seen.1 = true } + let uv_of = |i: usize| texcoords.as_ref().and_then(|t| t.get(i)).copied().unwrap_or_default(); let raw_normals = raw.normals.get_or_insert_with(Vec::new); match normals.filter(|v| v.len() == n) { Some(nrm) => { raw.positions.extend_from_slice(&world); - raw_normals.extend(nrm.iter().map(|v| (nm * *v).try_normalize().unwrap_or(Vec3::Y))); + raw_normals.extend(nrm.iter().map(|v| (normal_transform * *v).try_normalize().unwrap_or(Vec3::Y))); attrs.uvs.extend((0..n).map(uv_of)); attrs.colors.extend((0..n).map(color_of)); let group = raw.group(&name, part); @@ -175,23 +180,24 @@ fn add_primitive(raw: &mut RawMesh, attrs: &mut Attrs, prim: &gltf::Primitive, m } } None => { - // glTF: flat normals when none are given, so every triangle gets its own corners. - let mut tris = Vec::with_capacity(indices.len()); + // glTF: flat normals when none are given, so every triangle gets its own corners + let mut triangles = Vec::with_capacity(indices.len()); for t in indices.as_chunks::<3>().0 { let order = if flip { [t[0], t[2], t[1]] } else { [t[0], t[1], t[2]] }; let p = order.map(|i| world.get(i as usize).copied().unwrap_or_default()); let face = (p[1] - p[0]).cross(p[2] - p[0]).try_normalize().unwrap_or(Vec3::Y); for (k, i) in order.iter().enumerate() { - tris.push(raw.positions.len() as u32); + triangles.push(raw.positions.len() as u32); raw.positions.push(p[k]); raw_normals.push(face); attrs.uvs.push(uv_of(*i as usize)); attrs.colors.push(color_of(*i as usize)); } } - raw.group(&name, part).extend_from_slice(&tris); + raw.group(&name, part).extend_from_slice(&triangles); } } + Ok(()) } diff --git a/crates/formats/src/mesh_import/mod.rs b/crates/formats/src/mesh_import/mod.rs index 7fd9b113..42497364 100644 --- a/crates/formats/src/mesh_import/mod.rs +++ b/crates/formats/src/mesh_import/mod.rs @@ -379,6 +379,7 @@ fn geometry(raw: RawMesh) -> Result<(Mesh, Vec, Option>)> { let RawMesh { positions, normals, uvs, colors, groups, warnings, diagonals, .. } = raw; check_vertices(positions.len())?; check_triangles(0, groups.iter().map(|(_, _, g)| g.len() / 3).sum())?; + let mut mesh = Mesh { positions, ..Mesh::default() }; let mut groups: Vec<(usize, String, Vec)> = groups .into_iter() @@ -398,9 +399,11 @@ fn geometry(raw: RawMesh) -> Result<(Mesh, Vec, Option>)> { mesh.indices.extend_from_slice(tris.get(..count as usize).unwrap_or_default()); mesh.submeshes.push(SubMesh { name, material, start, count }); } + if mesh.indices.is_empty() { return Err(FormatError::Invalid("the file contains no triangles".into())); } + if !diagonals.is_empty() { let diagonal = |a: u32, b: u32| diagonals.contains(&(a.min(b), a.max(b))); mesh.diagonals = mesh.indices.as_chunks::<3>().0.iter().map(|t| (0..3).map(|i| u8::from(diagonal(t[i], t[(i + 1) % 3])) << i).sum()).collect(); @@ -408,12 +411,15 @@ fn geometry(raw: RawMesh) -> Result<(Mesh, Vec, Option>)> { if let Some(bad) = mesh.indices.iter().find(|i| **i as usize >= mesh.positions.len()) { return Err(FormatError::Invalid(format!("vertex index {bad} out of range ({} vertices)", mesh.positions.len()))); } + if mesh.positions.iter().any(|p| !p.is_finite()) { return Err(FormatError::Invalid("the mesh has non-finite vertex positions".into())); } + if all_triangles_degenerate(&mesh) { return Err(FormatError::Invalid("every triangle of the mesh is degenerate (zero area)".into())); } + mesh.normals = match normals { Some(n) if n.len() == mesh.positions.len() => n.into_iter().map(|v| v.try_normalize().unwrap_or(Vec3::Y)).collect(), _ => smooth_normals(&mesh), @@ -421,6 +427,7 @@ fn geometry(raw: RawMesh) -> Result<(Mesh, Vec, Option>)> { if let Some(c) = colors.filter(|c| c.len() == mesh.positions.len()) { mesh.colors = c.into_iter().map(|v| if v.is_finite() { v.clamp(Vec4::ZERO, Vec4::ONE) } else { Vec4::ONE }).collect(); } + Ok((mesh, warnings, uvs)) } @@ -482,18 +489,19 @@ fn orbit_cameras(raw: &[RawCamera], mesh: &Mesh) -> Vec Vec { - let weld = weld_ids(&mesh.positions); - let mut acc = vec![Vec3::ZERO; mesh.positions.len()]; - for t in mesh.indices.as_chunks::<3>().0 { + let welded_vertices = weld_ids(&mesh.positions); + let mut normals = vec![Vec3::ZERO; mesh.positions.len()]; + for triangle in mesh.indices.as_chunks::<3>().0 { let p = |i: u32| mesh.positions.get(i as usize).copied().unwrap_or_default(); - let face = (p(t[1]) - p(t[0])).cross(p(t[2]) - p(t[0])); - for v in t { - if let Some(a) = weld.get(*v as usize).and_then(|w| acc.get_mut(*w as usize)) { + let face = (p(triangle[1]) - p(triangle[0])).cross(p(triangle[2]) - p(triangle[0])); + for v in triangle { + if let Some(a) = welded_vertices.get(*v as usize).and_then(|w| normals.get_mut(*w as usize)) { *a += face; } } } - weld.iter().map(|w| acc.get(*w as usize).and_then(|n| n.try_normalize()).unwrap_or(Vec3::Y)).collect() + + welded_vertices.iter().map(|w| normals.get(*w as usize).and_then(|n| n.try_normalize()).unwrap_or(Vec3::Y)).collect() } /// Inspects `mesh` and generates its UV report (overlaps, out-of-range UVs, warnings). diff --git a/crates/formats/src/mesh_import/obj.rs b/crates/formats/src/mesh_import/obj.rs index d6cc9eb8..44277208 100644 --- a/crates/formats/src/mesh_import/obj.rs +++ b/crates/formats/src/mesh_import/obj.rs @@ -13,8 +13,8 @@ pub(crate) fn read(bytes: &[u8]) -> Result { fn read_inner(bytes: &[u8]) -> Result { let text = String::from_utf8_lossy(bytes); - // Material names come from `usemtl` (MTL files are never read): tobj only assigns a face's - // material when a library defines it, so every library request gets a synthetic one. + + // A synthetic library lets tobj assign usemtl names without reading external MTL files let mut names: Vec<&str> = Vec::new(); for line in text.lines().map(str::trim) { if line.split_whitespace().next() == Some("usemtl") @@ -25,57 +25,64 @@ fn read_inner(bytes: &[u8]) -> Result { names.push(name.trim()); } } - let library: String = names.iter().map(|n| format!("newmtl {n}\n")).collect(); + + let library: String = names.iter().map(|name| format!("newmtl {name}\n")).collect(); let source = format!("mtllib texturecraft-usemtl.mtl\n{text}"); - // Polygons stay whole so the wireframe can show them; `RawMesh::polygon` triangulates. - let opts = tobj::LoadOptions { single_index: true, triangulate: false, ignore_points: true, ignore_lines: true }; + + // Polygons stay whole so the wireframe can show them; `RawMesh::polygon` triangulates + let options = tobj::LoadOptions { single_index: true, triangulate: false, ignore_points: true, ignore_lines: true }; let (models, materials) = - tobj::load_obj_buf(&mut source.as_bytes(), &opts, |_| tobj::load_mtl_buf(&mut library.as_bytes())).map_err(|e| malformed(KIND, e))?; + tobj::load_obj_buf(&mut source.as_bytes(), &options, |_| tobj::load_mtl_buf(&mut library.as_bytes())).map_err(|e| malformed(KIND, e))?; let materials = materials.unwrap_or_default(); let mut raw = RawMesh::default(); let (mut normals, mut uvs, mut colors) = (Some(Vec::new()), Some(Vec::new()), Vec::new()); let mut partial_uvs = false; for model in &models { - let m = &model.mesh; - let n = m.positions.len() / 3; - check_vertices(raw.positions.len().saturating_add(n))?; - // Corners per face; without arities every face is a triangle. - let arities: Vec = if m.face_arities.is_empty() { vec![3; m.indices.len() / 3] } else { m.face_arities.iter().map(|a| *a as usize).collect() }; + let mesh = &model.mesh; + let vertex_count = mesh.positions.len() / 3; + check_vertices(raw.positions.len().saturating_add(vertex_count))?; + + // Corners per face; without arities every face is a triangle + let arities: Vec = + if mesh.face_arities.is_empty() { vec![3; mesh.indices.len() / 3] } else { mesh.face_arities.iter().map(|a| *a as usize).collect() }; check_triangles(raw.triangle_count(), arities.iter().map(|a| a.saturating_sub(2)).sum())?; let base = raw.positions.len() as u32; - raw.positions.extend(m.positions.as_chunks::<3>().0.iter().map(|p| Vec3::new(p[0], p[1], p[2]))); - if m.normals.len() == n * 3 { + raw.positions.extend(mesh.positions.as_chunks::<3>().0.iter().map(|p| Vec3::new(p[0], p[1], p[2]))); + if mesh.normals.len() == vertex_count * 3 { if let Some(v) = &mut normals { - v.extend(m.normals.as_chunks::<3>().0.iter().map(|p| Vec3::new(p[0], p[1], p[2]))); + v.extend(mesh.normals.as_chunks::<3>().0.iter().map(|p| Vec3::new(p[0], p[1], p[2]))); } } else { normals = None; } - if m.texcoords.len() == n * 2 { + if mesh.texcoords.len() == vertex_count * 2 { if let Some(v) = &mut uvs { - // OBJ UVs have their origin bottom-left. - v.extend(m.texcoords.as_chunks::<2>().0.iter().map(|t| Vec2::new(t[0], 1.0 - t[1]))); + // OBJ UVs have their origin bottom-left + v.extend(mesh.texcoords.as_chunks::<2>().0.iter().map(|t| Vec2::new(t[0], 1.0 - t[1]))); } } else { - partial_uvs |= n > 0 && !m.indices.is_empty(); + partial_uvs |= vertex_count > 0 && !mesh.indices.is_empty(); uvs = None; } - // `v x y z r g b`: objects without colors are white. - match m.vertex_color.len() == n * 3 { - true => colors.extend(m.vertex_color.as_chunks::<3>().0.iter().map(|c| Vec4::new(c[0], c[1], c[2], 1.0))), - false => colors.extend(std::iter::repeat_n(Vec4::ONE, n)), + + // `v x y z r g b`: objects without colors are white + match mesh.vertex_color.len() == vertex_count * 3 { + true => colors.extend(mesh.vertex_color.as_chunks::<3>().0.iter().map(|c| Vec4::new(c[0], c[1], c[2], 1.0))), + false => colors.extend(std::iter::repeat_n(Vec4::ONE, vertex_count)), } - let name = match m.material_id { + + let name = match mesh.material_id { Some(id) => materials.get(id).map(|mat| mat.name.clone()).filter(|s| !s.is_empty()).unwrap_or_else(|| format!("Material_{id}")), None => "Default".to_string(), }; - if let Some(i) = m.indices.iter().find(|i| **i as usize >= n) { + if let Some(i) = mesh.indices.iter().find(|i| **i as usize >= vertex_count) { return Err(malformed(KIND, format!("face index {i} out of range"))); } - // tobj names models without `o`/`g` "unnamed_object"; an empty name takes the file stem. + + // tobj names models without `o`/`g` "unnamed_object"; an empty name takes the file stem let part = if model.name == "unnamed_object" { "" } else { model.name.as_str() }; - let (mut rest, mut corners) = (m.indices.as_slice(), Vec::new()); + let (mut rest, mut corners) = (mesh.indices.as_slice(), Vec::new()); for arity in arities { let Some((face, tail)) = rest.split_at_checked(arity) else { break }; rest = tail; @@ -86,11 +93,14 @@ fn read_inner(bytes: &[u8]) -> Result { } } } - if partial_uvs && models.iter().any(|m| !m.mesh.texcoords.is_empty()) { + + if partial_uvs && models.iter().any(|model| !model.mesh.texcoords.is_empty()) { raw.warnings.push("some objects have no UVs; the whole mesh was unwrapped automatically".into()); } + raw.normals = normals; raw.uvs = uvs; - raw.colors = models.iter().any(|m| !m.mesh.vertex_color.is_empty()).then_some(colors); + raw.colors = models.iter().any(|model| !model.mesh.vertex_color.is_empty()).then_some(colors); + Ok(raw) } diff --git a/crates/formats/src/mesh_import/usd/usdc.rs b/crates/formats/src/mesh_import/usd/usdc.rs index 9d3cc55d..221c7b4a 100644 --- a/crates/formats/src/mesh_import/usd/usdc.rs +++ b/crates/formats/src/mesh_import/usd/usdc.rs @@ -224,17 +224,19 @@ impl<'a> Crate<'a> { Ok(()) } - fn read_fields(&mut self, mut s: Cur, budget: &mut Budget) -> Result<()> { - let n = s.count(0)?; - let tokens = s.ints(n, 4, budget)?; - let size = s.u64()?; - let comp = s.bytes(usize::try_from(size).map_err(|_| truncated())?)?; - budget.take(n.saturating_mul(24))?; - let reps = codec::decompress(comp, n.saturating_mul(8))?; - if reps.len() != n * 8 { + fn read_fields(&mut self, mut section: Cur, budget: &mut Budget) -> Result<()> { + let count = section.count(0)?; + let tokens = section.ints(count, 4, budget)?; + let size = section.u64()?; + let compressed = section.bytes(usize::try_from(size).map_err(|_| truncated())?)?; + budget.take(count.saturating_mul(24))?; + let representations = codec::decompress(compressed, count.saturating_mul(8))?; + if representations.len() != count * 8 { return Err(malformed(KIND, "field values are truncated")); } - self.fields = tokens.iter().zip(reps.as_chunks::<8>().0.iter()).map(|(t, r)| (*t as u32, u64::from_le_bytes(*r))).collect(); + + self.fields = tokens.iter().zip(representations.as_chunks::<8>().0.iter()).map(|(t, r)| (*t as u32, u64::from_le_bytes(*r))).collect(); + Ok(()) } diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index 39f79583..0e1db163 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -293,44 +293,54 @@ fn expect_end(r: &mut impl Read, what: &str) -> Result<()> { } } -fn read_tiles(r: &mut impl Read, size: (u32, u32), comps: usize, budget: &mut Budget, what: &str) -> Result { - let (w, h, c, count) = read_header(r, what)?; - if (w, h) != size || c != comps { - return Err(malformed(KIND, format!("{what}: {w}×{h}×{c} does not match the texture set ({}×{}×{comps})", size.0, size.1))); +fn read_tiles(reader: &mut impl Read, size: (u32, u32), components: usize, budget: &mut Budget, what: &str) -> Result { + let (width, height, stored_components, count) = read_header(reader, what)?; + if (width, height) != size || stored_components != components { + return Err(malformed( + KIND, + format!("{what}: {width}×{height}×{stored_components} does not match the texture set ({}×{}×{components})", size.0, size.1), + )); } - let mut img = TileImage::new(w, h, comps); - if count > (img.tiles_x() as usize) * (img.tiles_y() as usize) { + + let mut image = TileImage::new(width, height, components); + if count > (image.tiles_x() as usize) * (image.tiles_y() as usize) { return Err(malformed(KIND, format!("{what}: {count} tiles is more than the image holds"))); } - let mut buf = vec![0u8; TILE_AREA * comps * 2]; - let mut pos = [0u8; 8]; + + let mut bytes = vec![0u8; TILE_AREA * components * 2]; + let mut position_bytes = [0u8; 8]; for _ in 0..count { - read_exact(r, &mut pos, what)?; - let (tx, ty) = (u32_at(&pos, 0), u32_at(&pos, 1)); - if tx >= img.tiles_x() || ty >= img.tiles_y() || img.is_allocated(tx, ty) { + read_exact(reader, &mut position_bytes, what)?; + let (tx, ty) = (u32_at(&position_bytes, 0), u32_at(&position_bytes, 1)); + if tx >= image.tiles_x() || ty >= image.tiles_y() || image.is_allocated(tx, ty) { return Err(malformed(KIND, format!("{what}: bad or repeated tile ({tx}, {ty})"))); } - read_exact(r, &mut buf, what)?; - budget.take(buf.len() as u64)?; - let data: Vec = buf.as_chunks::<2>().0.iter().map(|b| u16::from_le_bytes([b[0], b[1]])).collect(); - img.set_tile(tx, ty, Some(Arc::new(data))); + + read_exact(reader, &mut bytes, what)?; + budget.take(bytes.len() as u64)?; + let data: Vec = bytes.as_chunks::<2>().0.iter().map(|b| u16::from_le_bytes(*b)).collect(); + image.set_tile(tx, ty, Some(Arc::new(data))); } - expect_end(r, what)?; - Ok(img) + + expect_end(reader, what)?; + + Ok(image) } /// A baked map: (width, height, data). -fn read_baked(r: &mut impl Read, comps: usize, budget: &mut Budget, what: &str) -> Result<(u32, u32, Vec)> { - let (w, h, c, _) = read_header(r, what)?; - if w == 0 || h == 0 || u64::from(w) * u64::from(h) > MAX_TEXELS || c != comps { - return Err(malformed(KIND, format!("{what}: bad size {w}×{h}×{c}"))); +fn read_baked(reader: &mut impl Read, components: usize, budget: &mut Budget, what: &str) -> Result<(u32, u32, Vec)> { + let (width, height, stored_components, _) = read_header(reader, what)?; + if width == 0 || height == 0 || u64::from(width) * u64::from(height) > MAX_TEXELS || stored_components != components { + return Err(malformed(KIND, format!("{what}: bad size {width}×{height}×{stored_components}"))); } - let len = (w as usize) * (h as usize) * comps; - budget.take(len as u64 * 4)?; - let mut bytes = vec![0u8; len * 4]; - read_exact(r, &mut bytes, what)?; - expect_end(r, what)?; - Ok((w, h, bytes.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])).collect())) + + let value_count = (width as usize) * (height as usize) * components; + budget.take(value_count as u64 * 4)?; + let mut bytes = vec![0u8; value_count * 4]; + read_exact(reader, &mut bytes, what)?; + expect_end(reader, what)?; + + Ok((width, height, bytes.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect())) } /// Texture set holding a paint layer, a content effect or a mask effect id. diff --git a/crates/geom/src/mesh.rs b/crates/geom/src/mesh.rs index 63c0bb71..5680a499 100644 --- a/crates/geom/src/mesh.rs +++ b/crates/geom/src/mesh.rs @@ -199,18 +199,19 @@ impl Mesh { /// Area-weighted smooth normals over the index buffer. pub fn compute_normals(&mut self) { - let mut n = vec![Vec3::ZERO; self.positions.len()]; + let mut normals = vec![Vec3::ZERO; self.positions.len()]; for &[a, b, c] in self.indices.as_chunks::<3>().0 { let (a, b, c) = (a as usize, b as usize, c as usize); let (Some(pa), Some(pb), Some(pc)) = (self.positions.get(a), self.positions.get(b), self.positions.get(c)) else { continue }; let face = (*pb - *pa).cross(*pc - *pa); for v in [a, b, c] { - if let Some(x) = n.get_mut(v) { + if let Some(x) = normals.get_mut(v) { *x += face; } } } - self.normals = n.into_iter().map(|v| v.try_normalize().unwrap_or(Vec3::Y)).collect(); + + self.normals = normals.into_iter().map(|v| v.try_normalize().unwrap_or(Vec3::Y)).collect(); } /// MikkTSpace tangents (falls back to per-triangle tangents if generation fails). @@ -237,25 +238,27 @@ impl Mesh { } fn simple_tangents(&mut self) { - let mut acc = vec![Vec3::ZERO; self.positions.len()]; + let mut tangents = vec![Vec3::ZERO; self.positions.len()]; for &[a, b, c] in self.indices.as_chunks::<3>().0 { let (a, b, c) = (a as usize, b as usize, c as usize); let (Some(pa), Some(pb), Some(pc)) = (self.positions.get(a), self.positions.get(b), self.positions.get(c)) else { continue }; let (Some(ua), Some(ub), Some(uc)) = (self.uvs.get(a), self.uvs.get(b), self.uvs.get(c)) else { continue }; let (e1, e2) = (*pb - *pa, *pc - *pa); let (d1, d2) = (*ub - *ua, *uc - *ua); - let r = d1.x * d2.y - d2.x * d1.y; - if r.abs() < 1e-12 { + let determinant = d1.x * d2.y - d2.x * d1.y; + if determinant.abs() < 1e-12 { continue; } - let tan = (e1 * d2.y - e2 * d1.y) / r; + + let tangent = (e1 * d2.y - e2 * d1.y) / determinant; for v in [a, b, c] { - if let Some(x) = acc.get_mut(v) { - *x += tan; + if let Some(x) = tangents.get_mut(v) { + *x += tangent; } } } - self.tangents = acc.into_iter().map(|t| t.try_normalize().unwrap_or(Vec3::X).extend(1.0)).collect(); + + self.tangents = tangents.into_iter().map(|t| t.try_normalize().unwrap_or(Vec3::X).extend(1.0)).collect(); } /// The UV tiles material `m` covers: integer parts of its triangles' UV centroids (v down), @@ -280,39 +283,44 @@ impl Mesh { /// material's triangles using the vertex: piecewise maps (UV tiles of different sizes) then /// place a vertex on a tile border with its own triangle's tile. pub fn map_material_uvs_with(&mut self, m: usize, f: impl Fn(Vec2, Vec2) -> Vec2) { - let mine: Vec = self.triangles_of(m).collect(); - let mut is_mine = vec![false; self.triangle_count()]; - for t in &mine { - if let Some(x) = is_mine.get_mut(*t) { + let material_triangles: Vec = self.triangles_of(m).collect(); + let mut in_material = vec![false; self.triangle_count()]; + for t in &material_triangles { + if let Some(x) = in_material.get_mut(*t) { *x = true; } } + let mut shared = vec![false; self.positions.len()]; - for (_, tri) in self.indices.as_chunks::<3>().0.iter().enumerate().filter(|(t, _)| !is_mine.get(*t).copied().unwrap_or(false)) { + for (_, tri) in self.indices.as_chunks::<3>().0.iter().enumerate().filter(|(t, _)| !in_material.get(*t).copied().unwrap_or(false)) { for v in tri { if let Some(s) = shared.get_mut(*v as usize) { *s = true; } } } - let mut copies = std::collections::HashMap::new(); - for k in mine.iter().flat_map(|t| t * 3..t * 3 + 3) { + + let mut duplicates = std::collections::HashMap::new(); + for k in material_triangles.iter().flat_map(|t| t * 3..t * 3 + 3) { let Some(&v) = self.indices.get(k) else { continue }; - let v = if shared.get(v as usize).copied().unwrap_or(false) { *copies.entry(v).or_insert_with(|| self.duplicate_vertex(v as usize)) } else { v }; + let v = + if shared.get(v as usize).copied().unwrap_or(false) { *duplicates.entry(v).or_insert_with(|| self.duplicate_vertex(v as usize)) } else { v }; if let Some(i) = self.indices.get_mut(k) { *i = v; } } - // (vertex, centroid of its first triangle), each vertex once. - let mut verts = Vec::with_capacity(mine.len() * 3); - for t in &mine { + + // (vertex, centroid of its first triangle), each vertex once + let mut vertices = Vec::with_capacity(material_triangles.len() * 3); + for t in &material_triangles { let Some(tri) = self.tri(*t) else { continue }; let centroid = tri.iter().map(|v| self.uvs.get(*v).copied().unwrap_or_default()).sum::() / 3.0; - verts.extend(tri.map(|v| (v, centroid))); + vertices.extend(tri.map(|v| (v, centroid))); } - verts.sort_by_key(|(v, _)| *v); - verts.dedup_by_key(|(v, _)| *v); - for (v, centroid) in verts { + + vertices.sort_by_key(|(v, _)| *v); + vertices.dedup_by_key(|(v, _)| *v); + for (v, centroid) in vertices { if let Some(uv) = self.uvs.get_mut(v) { *uv = f(centroid, *uv); } diff --git a/crates/paint/src/particles.rs b/crates/paint/src/particles.rs index ad81732e..2bdb122f 100644 --- a/crates/paint/src/particles.rs +++ b/crates/paint/src/particles.rs @@ -78,16 +78,16 @@ mod tests { #[test] fn particles_slide_down_a_wall_deterministically() { - // A vertical wall: the plane rotated to face +Z. - let mut m = primitives::plane(2.0, 8); - for p in &mut m.positions { - *p = Vec3::new(p.x, -p.z, 0.0); + // A vertical wall: the plane rotated to face +Z + let mut mesh = primitives::plane(2.0, 8); + for position in &mut mesh.positions { + *position = Vec3::new(position.x, -position.z, 0.0); } - m.normals.fill(Vec3::Z); - let bvh = Bvh::new(&m); - let cam = OrbitCamera::default(); - let ctx = PickCtx { mesh: &m, bvh: &bvh, camera: &cam, viewport: Vec2::new(100.0, 100.0) }; - let s = Stamp { + mesh.normals.fill(Vec3::Z); + let bvh = Bvh::new(&mesh); + let camera = OrbitCamera::default(); + let context = PickCtx { mesh: &mesh, bvh: &bvh, camera: &camera, viewport: Vec2::new(100.0, 100.0) }; + let stamp = Stamp { center: Vec3::ZERO, normal: Vec3::Z, tangent: Vec3::X, @@ -99,12 +99,14 @@ mod tests { seed: 3, copy: false, }; - let p = Particles { enabled: true, count: 4, lifetime: 20, gravity: 1.0 }; - let a = emit(&ctx, &p, &s); - assert_eq!(a, emit(&ctx, &p, &s)); - assert_eq!(a.len(), 80); - let lowest = a.iter().map(|d| d.center.y).fold(f32::MAX, f32::min); + let particles = Particles { enabled: true, count: 4, lifetime: 20, gravity: 1.0 }; + + let dabs = emit(&context, &particles, &stamp); + + assert_eq!(dabs, emit(&context, &particles, &stamp)); + assert_eq!(dabs.len(), 80); + let lowest = dabs.iter().map(|d| d.center.y).fold(f32::MAX, f32::min); assert!(lowest < -0.4, "{lowest}"); - assert!(a.iter().all(|d| d.center.z.abs() < 1e-3)); + assert!(dabs.iter().all(|d| d.center.z.abs() < 1e-3)); } } diff --git a/crates/render/src/subdivide.rs b/crates/render/src/subdivide.rs index 3da5e465..283759a4 100644 --- a/crates/render/src/subdivide.rs +++ b/crates/render/src/subdivide.rs @@ -65,29 +65,31 @@ fn on_edge(verts: &[Vertex], (p, q): (u32, u32), k: u32, n: u32) -> Option (Vec, Vec, Vec) { - let n = 1u32 << level.min(MAX_LEVEL); - let (mut out_v, mut out_i, mut out_d) = (Vec::new(), Vec::new(), Vec::new()); +pub(crate) fn subdivide(vertices: &[Vertex], indices: &[u32], draws: &[Draw], level: u32) -> (Vec, Vec, Vec) { + let segments = 1u32 << level.min(MAX_LEVEL); + let (mut output_vertices, mut output_indices, mut output_draws) = (Vec::new(), Vec::new(), Vec::new()); + for &(start, count, material) in draws { - let first = out_i.len() as u32; - let tris = indices.get(start as usize..(start as usize).saturating_add(count as usize)).unwrap_or_default(); - for t in tris.as_chunks::<3>().0 { - let (Some(a), Some(b), Some(c)) = (verts.get(t[0] as usize), verts.get(t[1] as usize), verts.get(t[2] as usize)) else { continue }; - let base = out_v.len() as u32; - // Grid point (i, j), i + j <= n, row by row: row j holds n + 1 - j points. Points on - // the edges are computed the same way from both triangles sharing the edge (no cracks). - for j in 0..=n { - for i in 0..=n - j { + let first = output_indices.len() as u32; + let triangles = indices.get(start as usize..(start as usize).saturating_add(count as usize)).unwrap_or_default(); + for t in triangles.as_chunks::<3>().0 { + let (Some(a), Some(b), Some(c)) = (vertices.get(t[0] as usize), vertices.get(t[1] as usize), vertices.get(t[2] as usize)) else { continue }; + let base = output_vertices.len() as u32; + + // Row j holds segments + 1 - j points inside the triangle + // Shared edges use identical interpolation in both triangles to prevent cracks + for j in 0..=segments { + for i in 0..=segments - j { let edge = match (i, j) { (_, 0) => Some(((t[0], t[1]), i)), (0, _) => Some(((t[0], t[2]), j)), - _ if i + j == n => Some(((t[1], t[2]), j)), + _ if i + j == segments => Some(((t[1], t[2]), j)), _ => None, }; - let p = match edge.and_then(|(ends, k)| on_edge(verts, ends, k, n)) { + let p = match edge.and_then(|(ends, k)| on_edge(vertices, ends, k, segments)) { Some(p) => p, None => { - let w = [1.0 - (i + j) as f32 / n as f32, i as f32 / n as f32, j as f32 / n as f32]; + let w = [1.0 - (i + j) as f32 / segments as f32, i as f32 / segments as f32, j as f32 / segments as f32]; Vertex { pos: mix(a.pos, b.pos, c.pos, w), nrm: mix(a.nrm, b.nrm, c.nrm, w), @@ -96,39 +98,42 @@ pub(crate) fn subdivide(verts: &[Vertex], indices: &[u32], draws: &[Draw], level } } }; - out_v.push(Vertex { tan: [p.tan[0], p.tan[1], p.tan[2], a.tan[3]], ..p }); + output_vertices.push(Vertex { tan: [p.tan[0], p.tan[1], p.tan[2], a.tan[3]], ..p }); } } - let at = |i: u32, j: u32| base + j * (n + 1) - j * j.saturating_sub(1) / 2 + i; - for j in 0..n { - for i in 0..n - j { - out_i.extend_from_slice(&[at(i, j), at(i + 1, j), at(i, j + 1)]); - if i + j + 1 < n { - out_i.extend_from_slice(&[at(i + 1, j), at(i + 1, j + 1), at(i, j + 1)]); + + let at = |i: u32, j: u32| base + j * (segments + 1) - j * j.saturating_sub(1) / 2 + i; + for j in 0..segments { + for i in 0..segments - j { + output_indices.extend_from_slice(&[at(i, j), at(i + 1, j), at(i, j + 1)]); + if i + j + 1 < segments { + output_indices.extend_from_slice(&[at(i + 1, j), at(i + 1, j + 1), at(i, j + 1)]); } } } } - out_d.push((first, out_i.len() as u32 - first, material)); + output_draws.push((first, output_indices.len() as u32 - first, material)); } - (out_v, out_i, out_d) + + (output_vertices, output_indices, output_draws) } /// World length per unit of UV over the whole mesh (the square root of their area ratio): how /// far a height change moves the surface for the slope height-to-normal shows. -pub(crate) fn world_per_uv(verts: &[Vertex], indices: &[u32]) -> Option { - let (mut world, mut uv) = (0.0f64, 0.0f64); +pub(crate) fn world_per_uv(vertices: &[Vertex], indices: &[u32]) -> Option { + let (mut world_area, mut uv_area) = (0.0f64, 0.0f64); for t in indices.as_chunks::<3>().0 { - let (Some(a), Some(b), Some(c)) = (verts.get(t[0] as usize), verts.get(t[1] as usize), verts.get(t[2] as usize)) else { continue }; + let (Some(a), Some(b), Some(c)) = (vertices.get(t[0] as usize), vertices.get(t[1] as usize), vertices.get(t[2] as usize)) else { continue }; let d = |p: [f32; 3], q: [f32; 3]| [f64::from(q[0] - p[0]), f64::from(q[1] - p[1]), f64::from(q[2] - p[2])]; let (e1, e2) = (d(a.pos, b.pos), d(a.pos, c.pos)); let cross = [e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0]]; - world += (cross[0] * cross[0] + cross[1] * cross[1] + cross[2] * cross[2]).sqrt() * 0.5; + world_area += (cross[0] * cross[0] + cross[1] * cross[1] + cross[2] * cross[2]).sqrt() * 0.5; let (u1, u2) = ([b.uv[0] - a.uv[0], b.uv[1] - a.uv[1]], [c.uv[0] - a.uv[0], c.uv[1] - a.uv[1]]); - uv += f64::from(u1[0] * u2[1] - u1[1] * u2[0]).abs() * 0.5; + uv_area += f64::from(u1[0] * u2[1] - u1[1] * u2[0]).abs() * 0.5; } - let r = (world / uv).sqrt() as f32; - (uv > 1e-12 && r.is_finite() && r > 0.0).then_some(r) + + let scale = (world_area / uv_area).sqrt() as f32; + (uv_area > 1e-12 && scale.is_finite() && scale > 0.0).then_some(scale) } #[cfg(test)] From 2d0b8e6a48ffd6acae2a6fda4168da62b6e3b02b Mon Sep 17 00:00:00 2001 From: chasse20 Date: Tue, 10 Nov 2026 06:37:12 -0500 Subject: [PATCH 43/64] Fix thumbnail previews and cache retention --- crates/compose/src/eval.rs | 2 + crates/compose/src/eval/thumbnail.rs | 30 +++ crates/compose/src/thumb.rs | 102 +++++---- crates/engine/src/thumbs.rs | 330 ++++++++++++++++++++------- crates/engine/tests/it/thumbs.rs | 213 ++++++++++++----- crates/ui-egui/src/layer_panel.rs | 57 +++++ docs/architecture.md | 24 +- 7 files changed, 559 insertions(+), 199 deletions(-) create mode 100644 crates/compose/src/eval/thumbnail.rs diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index b43796e8..b9deb64f 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -2,6 +2,8 @@ //! tile by tile in parallel. This is the reference implementation (the oracle) for the viewport //! and for export. +pub(crate) mod thumbnail; + use std::borrow::Cow; use std::collections::{BTreeMap, HashMap}; use std::sync::Arc; diff --git a/crates/compose/src/eval/thumbnail.rs b/crates/compose/src/eval/thumbnail.rs new file mode 100644 index 00000000..92290afe --- /dev/null +++ b/crates/compose/src/eval/thumbnail.rs @@ -0,0 +1,30 @@ +//! Isolated folder evaluation with the original stack available for anchor inputs. + +use super::{Channel, ChannelKind, Composite, Inputs, LayerId, Texel, all_tiles, neighbourhood_fields, plan, tile_texels, to_u16, to_u16_signed}; + +/// Composite one layer over channel defaults, keeping anchors from the stack below it. +pub(crate) fn composite_layer(inputs: &Inputs, layer: LayerId, channel: Channel) -> Option { + let set = inputs.project.texture_set(inputs.ts).ok()?; + let channels = set.channel_list(); + let (width, height) = (inputs.gbuf.width, inputs.gbuf.height); + let tiles = all_tiles(width, height); + let fields = neighbourhood_fields(inputs, &channels, &tiles); + let mut composite = Composite::with_size(&[channel], width, height); + let output = composite.channels.get_mut(&channel)?; + + for (tile_x, tile_y) in tiles { + let nodes = plan(inputs, &[layer], &channels, tile_x, tile_y, 0, Some(&fields)); + let full_stack = if set.stack.as_slice() == [layer] { Vec::new() } else { plan(inputs, &set.stack, &channels, tile_x, tile_y, 0, Some(&fields)) }; + for (x, y, offset) in tile_texels(inputs.gbuf, tile_x, tile_y) { + let mut texel = Texel::new(inputs, x, y, offset, 0.0); + texel.anchors_below(&full_stack, layer); + let mut values = Channel::ALL.map(Channel::default_value); + texel.eval(&nodes, &mut values); + let value = values.get(channel.index()).copied().unwrap_or_else(|| channel.default_value()); + let encoded = value.map(|component| if channel.kind() == ChannelKind::Signed { to_u16_signed(component) } else { to_u16(component) }); + output.set(x, y, &encoded[..channel.components()]); + } + } + + Some(composite) +} diff --git a/crates/compose/src/thumb.rs b/crates/compose/src/thumb.rs index cec31bd4..b4c59a15 100644 --- a/crates/compose/src/thumb.rs +++ b/crates/compose/src/thumb.rs @@ -1,8 +1,8 @@ //! Small previews of one layer's content, one mask, or one effect stage, computed without //! touching the main composite. //! -//! Every thumbnail is the ordinary compositor run on a *cut* copy of the project: the texture -//! set's stack is replaced by the one layer, the layer is forced visible at Normal / 100 %, and +//! Every thumbnail is the ordinary compositor run on a *cut* copy of the project: only the +//! requested layer is drawn, forced visible at Normal / 100 %, and //! the layer's effect list is truncated after the effect being previewed. The evaluator is the //! same code the viewport uses (just on a small G-buffer), so a thumbnail always agrees with //! what the stack really computes. Nothing here mutates the caller's project. @@ -10,7 +10,7 @@ use texturecraft_core::{BlendMode, Channel, ChannelBlend, ChannelKind, LayerId, Project}; use texturecraft_texel::{TILE, from_u16, from_u16_signed, linear_to_srgb}; -use crate::eval::{Composite, FlatTile, Inputs, all_tiles, composite_tiles, flatten_layer, mask_image}; +use crate::eval::{Composite, FlatTile, Inputs, all_tiles, flatten_layer, mask_image}; /// Edge length (texels) the thumbnails are computed at. pub const THUMB_TEXELS: u32 = 64; @@ -55,16 +55,22 @@ pub fn render(inp: &Inputs, target: ThumbTarget) -> Option { } } -/// `project` cut down to the single layer `id` of texture set `ts`: only that layer is drawn, -/// visible, Normal at full opacity in `channel` (when given). -fn solo(project: &Project, ts: usize, id: LayerId, channel: Option) -> Option { +/// Force the requested layer visible, retaining the stack needed by anchor readers. +fn solo(project: &Project, texture_set: usize, id: LayerId, channel: Option) -> Option { let mut cut = project.clone(); - cut.texture_sets.get_mut(ts)?.stack = vec![id]; - let l = cut.layers.get_mut(&id)?; - l.visible = true; - if let Some(c) = channel { - *l.channels.get_mut(&c)? = ChannelBlend { mode: BlendMode::Normal, opacity: 1.0 }; + + // Ordinary previews need no neighbouring layers or their filter allocations + if !project.render_tree(&[id]).iter().any(|layer| crate::eval::reads_anchor(project, *layer)) { + cut.texture_sets.get_mut(texture_set)?.stack = vec![id]; } + + cut.layers.get_mut(&id)?.visible = true; + if let Some(channel) = channel { + // Instances inherit channels from their source + let owner = cut.content_layer(id)?.id; + *cut.layers.get_mut(&owner)?.channels.get_mut(&channel)? = ChannelBlend { mode: BlendMode::Normal, opacity: 1.0 }; + } + Some(cut) } @@ -79,38 +85,38 @@ fn truncate_after(list: &mut Vec, last: LayerId) -> b } } -fn content(inp: &Inputs, layer: LayerId, channel: Channel, upto: Option) -> Option { - let set = inp.project.texture_set(inp.ts).ok()?; +fn content(inputs: &Inputs, layer: LayerId, channel: Channel, through_effect: Option) -> Option { + let set = inputs.project.texture_set(inputs.ts).ok()?; if !set.channel_list().contains(&channel) { return None; } - // The layer whose content is drawn: an instance draws its source's effects. - let mut cut = solo(inp.project, inp.ts, layer, Some(channel))?; + + // An instance draws its source's effects + let mut cut = solo(inputs.project, inputs.ts, layer, Some(channel))?; let owner = cut.content_layer(layer)?.id; for id in [layer, owner] { - let l = cut.layers.get_mut(&id)?; - l.mask = None; - l.visible = true; - if let Some(b) = l.channels.get_mut(&channel) { - *b = ChannelBlend { mode: BlendMode::Normal, opacity: 1.0 }; - } + let content = cut.layers.get_mut(&id)?; + content.mask = None; + content.visible = true; } - if let Some(effect) = upto + + if let Some(effect) = through_effect && !truncate_after(&mut cut.layers.get_mut(&owner)?.content_effects, effect) { return None; } - let cut_inp = Inputs { project: &cut, preview: None, block_scales: inp.block_scales.clone(), ..*inp }; - let (w, h) = (inp.gbuf.width, inp.gbuf.height); - // A paint or fill layer shows its own coverage (transparent where nothing is painted); a - // folder shows its children composited over the channel's default. + + 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_inp, layer, &all_tiles(w, h))?; - return Some(encode_flat(&flat, channel, w, h)); + let flat = flatten_layer(&cut_inputs, layer, &all_tiles(width, height))?; + return Some(encode_flat(&flat, channel, width, height)); } - let mut comp = Composite::with_size(&set.channel_list(), w, h); - composite_tiles(&cut_inp, &mut comp, &all_tiles(w, h)); - Some(encode_channel(&comp, channel, inp)) + + let comp = crate::eval::thumbnail::composite_layer(&cut_inputs, layer, channel)?; + Some(encode_channel(&comp, channel, inputs)) } /// Encode the flattened (premultiplied value, coverage) tiles of `channel`: alpha is coverage. @@ -153,28 +159,30 @@ fn display(channel: Channel, v: [f32; 3]) -> [u8; 3] { } } -fn mask(inp: &Inputs, layer: LayerId, upto: Option) -> Option { - let mut cut = solo(inp.project, inp.ts, layer, None)?; +fn mask(inputs: &Inputs, layer: LayerId, through_effect: Option) -> Option { + let mut cut = solo(inputs.project, inputs.ts, layer, None)?; let owner = cut.mask_owner(layer); - let m = cut.layers.get_mut(&owner)?.mask.as_mut()?; - m.enabled = true; - if let Some(effect) = upto - && !truncate_after(&mut m.effects, effect) + let mask = cut.layers.get_mut(&owner)?.mask.as_mut()?; + mask.enabled = true; + if let Some(effect) = through_effect + && !truncate_after(&mut mask.effects, effect) { return None; } - let cut_inp = Inputs { project: &cut, preview: None, block_scales: inp.block_scales.clone(), ..*inp }; - let (w, h) = (inp.gbuf.width, inp.gbuf.height); - let gray = mask_image(&cut_inp, layer, w)?; - let mut rgba = Vec::with_capacity((w * h) as usize * 4); - for y in 0..h { - for x in 0..w { - let i = (y * w + x) as usize; - let g = gray.get(i).copied().unwrap_or(0); - rgba.extend_from_slice(&[g, g, g, if inp.gbuf.covered(i) { 255 } else { 0 }]); + + let cut_inputs = Inputs { project: &cut, preview: None, block_scales: inputs.block_scales.clone(), ..*inputs }; + let (width, height) = (inputs.gbuf.width, inputs.gbuf.height); + let gray = mask_image(&cut_inputs, layer, width)?; + let mut rgba = Vec::with_capacity((width * height) as usize * 4); + for y in 0..height { + for x in 0..width { + let offset = (y * width + x) as usize; + let value = gray.get(offset).copied().unwrap_or(0); + rgba.extend_from_slice(&[value, value, value, if inputs.gbuf.covered(offset) { 255 } else { 0 }]); } } - Some(ThumbImage { width: w, height: h, rgba }) + + Some(ThumbImage { width, height, rgba }) } /// Encode the composited `channel` for display: colors linear → sRGB, signed values 0 → mid diff --git a/crates/engine/src/thumbs.rs b/crates/engine/src/thumbs.rs index e9de02a3..5378aa06 100644 --- a/crates/engine/src/thumbs.rs +++ b/crates/engine/src/thumbs.rs @@ -64,21 +64,27 @@ impl ThumbSnapshot { }) } - /// Whether `s` would give the same thumbnails as this snapshot. - fn matches(&self, s: &Session, ts: usize) -> bool { - let same_pixels = self.pixels.layers.len() == s.doc.pixels.layers.len() - && self.pixels.masks.len() == s.doc.pixels.masks.len() - && self.pixels.layers.iter().all(|(k, v)| s.doc.pixels.layers.get(k) == Some(v)) - && self.pixels.masks.iter().all(|(k, v)| s.doc.pixels.masks.get(k) == Some(v)); - let none = BakedMaps::default(); - let baked = s.doc.baked.get(&ts).unwrap_or(&none); - self.ts == ts - && self.mesh_id == s.mesh_id - && self.project == s.doc.project + /// Whether `session` would give the same thumbnails as this snapshot. + fn matches(&self, session: &Session, texture_set: usize) -> bool { + let same_pixels = self.pixels.layers.len() == session.doc.pixels.layers.len() + && self.pixels.masks.len() == session.doc.pixels.masks.len() + && self.pixels.layers.iter().all(|(key, pixels)| session.doc.pixels.layers.get(key) == Some(pixels)) + && self.pixels.masks.iter().all(|(key, pixels)| session.doc.pixels.masks.get(key) == Some(pixels)); + let empty = BakedMaps::default(); + let baked = session.doc.baked.get(&texture_set).unwrap_or(&empty); + + // Copy-on-write maps change handles on edits; float equality would scan entire bakes + let same_baked = self.baked.resolution == baked.resolution + && self.baked.maps.len() == baked.maps.len() + && self.baked.maps.iter().all(|(map, pixels)| baked.maps.get(map).is_some_and(|current| Arc::ptr_eq(pixels, current))); + + self.ts == texture_set + && self.mesh_id == session.mesh_id + && self.project == session.doc.project && same_pixels - && self.baked == *baked - && self.images.len() == s.images.len() - && self.images.iter().all(|(k, v)| s.images.get(k).is_some_and(|o| Arc::ptr_eq(o, v))) + && same_baked + && self.images.len() == session.images.len() + && 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. @@ -195,7 +201,7 @@ pub struct ThumbService { tick: u64, versions: u64, queue: VecDeque, - in_flight: HashSet, + in_flight: HashSet<(u64, ThumbTarget)>, wanted: HashSet, gbufs: GbufCache, #[cfg(not(target_arch = "wasm32"))] @@ -238,139 +244,162 @@ impl ThumbService { } /// Start of a frame: forget what the last frame asked for and notice document changes. - pub fn begin_frame(&mut self, s: &Session, now: f64) { + pub fn begin_frame(&mut self, session: &Session, now: f64) { self.wanted.clear(); - let ts = s.ts(); - if self.seen == Some(s.revision) && self.snapshot.as_ref().is_some_and(|sn| sn.ts == ts && sn.mesh_id == s.mesh_id) { + let texture_set = session.ts(); + if self.seen == Some(session.revision) + && self.snapshot.as_ref().is_some_and(|snapshot| snapshot.ts == texture_set && snapshot.mesh_id == session.mesh_id) + { return; } - // While the document keeps changing, compare at the debounce pace (the first look is immediate). + + // Compare at the debounce pace while the document keeps changing if self.snapshot.is_some() && now - self.last_check < DEBOUNCE { return; } + self.last_check = now; - if self.snapshot.as_ref().is_some_and(|sn| sn.matches(s, ts)) { - self.seen = Some(s.revision); + if self.snapshot.as_ref().is_some_and(|snapshot| snapshot.matches(session, texture_set)) { + self.seen = Some(session.revision); return; } - self.snapshot = ThumbSnapshot::new(s, ts, &mut self.gbufs).map(Arc::new); - self.seen = Some(s.revision); - self.generation += 1; - // Jobs of the old snapshot are not worth running (those in flight are dropped on arrival). + + self.snapshot = ThumbSnapshot::new(session, texture_set, &mut self.gbufs).map(Arc::new); + self.seen = Some(session.revision); + self.generation = self.generation.wrapping_add(1); + + // Keep dispatched jobs counted until they finish, even when their snapshot is stale self.queue.clear(); - self.inline.clear(); - self.in_flight.clear(); - if let Some(sn) = &self.snapshot { - self.cache.retain(|t, _| sn.has(*t)); + for job in self.inline.drain(..) { + self.in_flight.remove(&(job.generation, job.target)); + } + + if let Some(snapshot) = &self.snapshot { + self.cache.retain(|target, _| snapshot.has(*target)); } else { self.cache.clear(); } } /// Whether the displayed pictures wait for a document comparison that is still debounced. - fn checked(&self, s: &Session) -> bool { - self.seen == Some(s.revision) + fn checked(&self, session: &Session) -> bool { + self.seen == Some(session.revision) } /// The picture for `target` (call for the rows on screen only). Queues work when the /// picture is missing or out of date. - pub fn get(&mut self, s: &Session, target: ThumbTarget) -> ThumbView { + pub fn get(&mut self, session: &Session, target: ThumbTarget) -> ThumbView { self.wanted.insert(target); - self.tick += 1; - let fresh = self.cache.get(&target).is_some_and(|e| e.generation == self.generation); - let checked = self.checked(s); - if !fresh && checked && self.snapshot.is_some() && !self.in_flight.contains(&target) && !self.queue.contains(&target) { + self.tick = self.tick.wrapping_add(1); + let fresh = self.cache.get(&target).is_some_and(|entry| entry.generation == self.generation); + let checked = self.checked(session); + if !fresh && checked && self.snapshot.is_some() && !self.in_flight.contains(&(self.generation, target)) && !self.queue.contains(&target) { self.queue.push_back(target); } - let tick = self.tick; + match self.cache.get_mut(&target) { - Some(e) => { - e.used = tick; - ThumbView { image: e.image.clone(), version: e.version, pending: !(fresh && checked) } + Some(entry) => { + entry.used = self.tick; + ThumbView { image: entry.image.clone(), version: entry.version, pending: !(fresh && checked) } } None => ThumbView { image: None, version: 0, pending: true }, } } - /// End of a frame: take finished pictures, drop queued rows nobody asked for, hand the worker - /// its next jobs. Returns whether more work is outstanding (ask for another frame). - pub fn poll(&mut self, s: &Session) -> bool { - self.collect(); - let wanted = &self.wanted; - self.queue.retain(|t| wanted.contains(t)); + /// End of a frame: collect results, discard unrequested rows, and dispatch new work. + /// Returns whether another frame is needed, including to display newly collected pictures. + pub fn poll(&mut self, session: &Session) -> bool { + let changed = self.collect(); + self.queue.retain(|target| self.wanted.contains(target)); self.dispatch(); self.trim(); - !self.queue.is_empty() || !self.in_flight.is_empty() || !self.inline.is_empty() || !self.checked(s) + + changed || !self.queue.is_empty() || !self.in_flight.is_empty() || !self.checked(session) } fn dispatch(&mut self) { let Some(snapshot) = self.snapshot.clone() else { return }; - while self.in_flight.len() + self.inline.len() < IN_FLIGHT { + + while self.in_flight.len() < IN_FLIGHT { let Some(target) = self.queue.pop_front() else { break }; let job = Job { snapshot: snapshot.clone(), generation: self.generation, target }; - self.in_flight.insert(target); - if !self.send(job) { - break; - } + self.in_flight.insert((job.generation, target)); + self.send(job); } } #[cfg(not(target_arch = "wasm32"))] - fn send(&mut self, job: Job) -> bool { + fn send(&mut self, job: Job) { if !self.spawned { self.spawned = true; self.worker = spawn_worker(); } + match &self.worker { - Some(w) => match w.tx.send(job) { - Ok(()) => true, - Err(e) => { - // The worker is gone: run this and the rest here. + Some(worker) => { + if let Err(error) = worker.tx.send(job) { + // A stopped worker cannot complete any of its outstanding jobs self.worker = None; - self.inline.push_back(e.0); - true + self.in_flight.clear(); + self.in_flight.insert((error.0.generation, error.0.target)); + self.inline.push_back(error.0); } - }, - None => { - self.inline.push_back(job); - true } + None => self.inline.push_back(job), } } #[cfg(target_arch = "wasm32")] - fn send(&mut self, job: Job) -> bool { + fn send(&mut self, job: Job) { self.inline.push_back(job); - true } - fn collect(&mut self) { - let mut done: Vec = Vec::new(); + fn collect(&mut self) -> bool { + let mut completed = Vec::new(); + let mut changed = false; #[cfg(not(target_arch = "wasm32"))] - if let Some(w) = &self.worker { - while let Ok(d) = w.rx.try_recv() { - done.push(d); + if let Some(worker) = &self.worker { + loop { + match worker.rx.try_recv() { + Ok(result) => completed.push(result), + Err(std::sync::mpsc::TryRecvError::Empty) => break, + Err(std::sync::mpsc::TryRecvError::Disconnected) => { + // Request another frame so wanted targets retry on the inline fallback + self.worker = None; + self.in_flight.clear(); + changed = true; + break; + } + } } } - // Without a thread one job runs per frame, so the interface keeps its pace. + + // Without a thread, bound each poll to one render if let Some(job) = self.inline.pop_front() { let image = job.snapshot.render(job.target); - done.push(Done { generation: job.generation, target: job.target, image }); + completed.push(Done { generation: job.generation, target: job.target, image }); } - for d in done { - self.rendered += 1; - // A picture of an older snapshot never replaces a newer one. - if d.generation != self.generation { + + for result in completed { + self.rendered = self.rendered.wrapping_add(1); + self.in_flight.remove(&(result.generation, result.target)); + + // A picture of an older snapshot never replaces a newer one + if result.generation != self.generation { continue; } - self.in_flight.remove(&d.target); - if !self.snapshot.as_ref().is_some_and(|sn| sn.has(d.target)) { + + if !self.snapshot.as_ref().is_some_and(|snapshot| snapshot.has(result.target)) { continue; } - self.versions += 1; - let entry = Entry { image: d.image.map(Arc::new), generation: d.generation, version: self.versions, used: self.tick }; - self.cache.insert(d.target, entry); + + 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 }; + self.cache.insert(result.target, entry); + changed = true; } + + changed } fn trim(&mut self) { @@ -395,3 +424,142 @@ impl ThumbService { !self.queue.is_empty() || !self.in_flight.is_empty() || !self.inline.is_empty() } } + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + use super::*; + use texturecraft_core::Channel; + use texturecraft_geom::primitives; + + #[test] + fn unchanged_baked_handles_match_even_with_non_finite_samples() { + let mut session = Session::new_project("thumb", primitives::plane(1.0, 1), "builtin:plane", None, 128).unwrap(); + 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(); + + assert!(snapshot.matches(&session, 0), "unchanged shared data must not invalidate every frame"); + + let map = session.doc.baked.get_mut(&0).unwrap().maps.get_mut(&texturecraft_core::BakedMap::Height).unwrap(); + Arc::make_mut(map)[0] = 0.5; + assert!(!snapshot.matches(&session, 0), "a copy-on-write edit must invalidate the snapshot"); + } + + #[test] + #[ignore] + fn benchmark_unchanged_4k_baked_snapshot() { + let mut session = Session::new_project("thumb", primitives::plane(1.0, 1), "builtin:plane", None, 128).unwrap(); + let baked = session.doc.baked.entry(0).or_default(); + 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 start = std::time::Instant::now(); + + for _ in 0..20 { + assert!(std::hint::black_box(&snapshot).matches(std::hint::black_box(&session), 0)); + } + + eprintln!("20 unchanged snapshot comparisons, 4K normal + AO (256 MiB): {:?}", start.elapsed()); + } + + #[test] + fn collecting_the_last_result_requests_a_frame_to_display_it() { + let session = Session::new_project("thumb", primitives::plane(1.0, 1), "builtin:plane", None, 128).unwrap(); + let target = ThumbTarget::Content { layer: session.selected_layer().unwrap(), channel: Channel::BaseColor }; + let (sender, jobs) = std::sync::mpsc::channel(); + let (results, receiver) = std::sync::mpsc::channel(); + let mut service = ThumbService { worker: Some(Worker { tx: sender, rx: receiver }), spawned: true, ..Default::default() }; + service.begin_frame(&session, 0.0); + service.get(&session, target); + assert!(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); + assert!(service.get(&session, target).image.is_none()); + let repaint = service.poll(&session); + + assert!(service.is_fresh(target)); + assert!(repaint, "the frame drew before collecting the final thumbnail"); + service.begin_frame(&session, 0.2); + assert!(service.get(&session, target).image.is_some()); + assert!(!service.poll(&session), "an idle cache must stop repainting"); + } + + #[test] + fn a_stopped_worker_retries_visible_targets_inline() { + let session = Session::new_project("thumb", primitives::plane(1.0, 1), "builtin:plane", None, 128).unwrap(); + let target = ThumbTarget::Content { layer: session.selected_layer().unwrap(), channel: Channel::BaseColor }; + let (sender, jobs) = std::sync::mpsc::channel(); + let (results, receiver) = std::sync::mpsc::channel(); + let mut service = ThumbService { worker: Some(Worker { tx: sender, rx: receiver }), spawned: true, ..Default::default() }; + service.begin_frame(&session, 0.0); + service.get(&session, target); + service.poll(&session); + + // Simulate a worker that stops with a dispatched request still outstanding + drop(jobs); + drop(results); + for frame in 1..=4 { + service.begin_frame(&session, f64::from(frame)); + service.get(&session, target); + service.poll(&session); + } + + assert!(service.get(&session, target).image.is_some()); + assert!(!service.busy()); + } + + #[test] + fn edits_keep_worker_jobs_and_retained_snapshots_bounded() { + let mut session = Session::new_project("thumb", primitives::plane(1.0, 1), "builtin:plane", None, 128).unwrap(); + let layer = session.selected_layer().unwrap(); + let target = ThumbTarget::Content { layer, channel: Channel::BaseColor }; + let (sender, jobs) = std::sync::mpsc::channel(); + let (results, receiver) = std::sync::mpsc::channel(); + let mut service = ThumbService { worker: Some(Worker { tx: sender, rx: receiver }), spawned: true, ..Default::default() }; + let mut snapshots = Vec::new(); + + // Hold the worker's receiver still while repeated edits each produce a new snapshot + for revision in 0..2_000 { + session.doc.pixels.layer_mut(layer, Channel::BaseColor, (128, 128)).set(0, 0, &[revision, 0, 0, u16::MAX]); + session.revision += 1; + service.begin_frame(&session, f64::from(revision)); + snapshots.push(Arc::downgrade(service.snapshot.as_ref().unwrap())); + service.get(&session, target); + service.poll(&session); + } + + let queued: Vec<_> = jobs.try_iter().collect(); + let retained = snapshots.iter().filter(|snapshot| snapshot.strong_count() > 0).count(); + let retained_pixel_bytes: usize = snapshots.iter().filter_map(std::sync::Weak::upgrade).map(|snapshot| snapshot.pixels.bytes()).sum(); + eprintln!("2,000 edits: {} queued jobs, {retained} live snapshots, {retained_pixel_bytes} retained pixel bytes", queued.len()); + assert!(queued.len() <= IN_FLIGHT, "{} queued jobs bypassed the worker limit", queued.len()); + assert!(retained <= IN_FLIGHT + 1, "{retained} document snapshots retained across edits"); + assert!(retained_pixel_bytes <= (IN_FLIGHT + 1) * texturecraft_texel::TILE_AREA * 4 * std::mem::size_of::()); + + // 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(); + } + + assert_eq!(snapshots.iter().filter(|snapshot| snapshot.strong_count() > 0).count(), 1, "completed jobs release stale snapshots"); + assert!(service.poll(&session)); + assert!(!service.is_fresh(target)); + let latest = jobs.try_recv().unwrap(); + assert_eq!(latest.generation, service.generation); + results.send(Done { generation: latest.generation, target, image: latest.snapshot.render(target) }).unwrap(); + drop(latest); + assert!(service.poll(&session)); + assert!(service.is_fresh(target)); + + let image = Arc::downgrade(service.cache.get(&target).unwrap().image.as_ref().unwrap()); + drop(service); + + assert!(snapshots.iter().all(|snapshot| snapshot.upgrade().is_none()), "dropping the cache releases its last snapshot"); + assert!(image.upgrade().is_none(), "dropping the cache releases the rendered image"); + assert!(jobs.try_recv().is_err()); + } +} diff --git a/crates/engine/tests/it/thumbs.rs b/crates/engine/tests/it/thumbs.rs index 203896d3..5e795a03 100644 --- a/crates/engine/tests/it/thumbs.rs +++ b/crates/engine/tests/it/thumbs.rs @@ -40,10 +40,20 @@ fn stack(s: &mut Session) -> Stack { } fn inputs<'a>(s: &'a Session, project: &'a texturecraft_engine::core::Project, gbuf: &'a UvGBuffer) -> Inputs<'a> { - let none = Default::default(); - // Leaked: the oracle only lives for the test. - let baked: &'a _ = Box::leak(Box::new(s.doc.baked.get(&0).cloned().unwrap_or(none))); - Inputs { project, ts: 0, mesh: &s.mesh, gbuf, pixels: &s.doc.pixels, baked, block_scales: Default::default(), preview: None, images: &s.images, bounds: s.mesh.bounds() } + static EMPTY_BAKED: std::sync::LazyLock = std::sync::LazyLock::new(Default::default); + let baked = s.doc.baked.get(&0).unwrap_or(&EMPTY_BAKED); + Inputs { + project, + ts: 0, + mesh: &s.mesh, + gbuf, + pixels: &s.doc.pixels, + baked, + block_scales: Default::default(), + preview: None, + images: &s.images, + bounds: s.mesh.bounds(), + } } /// The reference: the same sub-stack cut by hand and evaluated at 64 px with the ordinary CPU @@ -56,7 +66,6 @@ fn oracle(s: &Session, target: ThumbTarget) -> ThumbImage { ThumbTarget::Mask { layer } => (layer, None, Channel::BaseColor), ThumbTarget::Stage { effect, channel } => (p.effect(effect).unwrap().0, Some(effect), channel), }; - p.texture_sets[0].stack = vec![layer]; let l = p.layers.get_mut(&layer).unwrap(); l.visible = true; let in_mask = upto.is_some_and(|e| l.mask.as_ref().is_some_and(|m| m.effects.iter().any(|x| x.id == e))) || matches!(target, ThumbTarget::Mask { .. }); @@ -127,30 +136,34 @@ fn image(svc: &mut ThumbService, s: &Session, t: ThumbTarget) -> ThumbImage { #[test] fn thumbnails_equal_a_cpu_evaluation_of_the_same_sub_stack() { - let mut s = session(); - let st = stack(&mut s); - let base = Channel::BaseColor; + let mut session = session(); + let stack = stack(&mut session); + let base_color = Channel::BaseColor; let targets = [ - ThumbTarget::Content { layer: st.layer, channel: base }, - ThumbTarget::Content { layer: st.layer, channel: Channel::Roughness }, - ThumbTarget::Mask { layer: st.layer }, - ThumbTarget::Stage { effect: st.invert, channel: base }, - ThumbTarget::Stage { effect: st.posterize, channel: base }, - ThumbTarget::Stage { effect: st.gen_, channel: base }, + ThumbTarget::Content { layer: stack.layer, channel: base_color }, + ThumbTarget::Content { layer: stack.layer, channel: Channel::Roughness }, + ThumbTarget::Mask { layer: stack.layer }, + ThumbTarget::Stage { effect: stack.invert, channel: base_color }, + ThumbTarget::Stage { effect: stack.posterize, channel: base_color }, + ThumbTarget::Stage { effect: stack.gen_, channel: base_color }, ]; - let (mut svc, mut clock) = (ThumbService::new(), 0.0); - settle(&mut svc, &s, &targets, &mut clock); - for t in targets { - assert_eq!(image(&mut svc, &s, t), oracle(&s, t), "{t:?}"); + let (mut service, mut clock) = (ThumbService::new(), 0.0); + + settle(&mut service, &session, &targets, &mut clock); + + for target in targets { + assert_eq!(image(&mut service, &session, target), oracle(&session, target), "{target:?}"); } - // Sanity on the values themselves: the first stage is #336699 inverted (in linear light). - let inv = image(&mut svc, &s, targets[3]); - let px = inv.rgba.chunks_exact(4).find(|p| p[3] == 255).unwrap(); - let expect = |byte: f32| (linear_to_srgb(1.0 - texturecraft_engine::texel::srgb_to_linear(byte / 255.0)) * 255.0 + 0.5) as i32; - assert!((px[0] as i32 - expect(51.0)).abs() <= 1 && (px[2] as i32 - expect(153.0)).abs() <= 1, "{px:?}"); - // The mask thumbnail is gray and not flat (a position gradient on a black mask). - let m = image(&mut svc, &s, targets[2]); - let grays: Vec = m.rgba.chunks_exact(4).filter(|p| p[3] == 255).map(|p| p[0]).collect(); + + // The first stage inverts #336699 in linear light + let inverted = image(&mut service, &session, targets[3]); + let pixel = inverted.rgba.as_chunks::<4>().0.iter().find(|pixel| pixel[3] == 255).unwrap(); + let expected = |byte: f32| (linear_to_srgb(1.0 - texturecraft_engine::texel::srgb_to_linear(byte / 255.0)) * 255.0 + 0.5) as i32; + assert!((i32::from(pixel[0]) - expected(51.0)).abs() <= 1 && (i32::from(pixel[2]) - expected(153.0)).abs() <= 1, "{pixel:?}"); + + // A position generator must produce a nonuniform mask + let mask = image(&mut service, &session, targets[2]); + let grays: Vec = mask.rgba.as_chunks::<4>().0.iter().filter(|pixel| pixel[3] == 255).map(|pixel| pixel[0]).collect(); assert!(grays.iter().max() != grays.iter().min()); } @@ -266,52 +279,130 @@ fn a_result_of_an_older_document_never_replaces_a_newer_one() { #[test] fn only_requested_rows_render_and_the_cache_is_bounded() { - let mut s = session(); - let layers: Vec = (0..(CACHE_ENTRIES + 30)).map(|_| id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap(), "layer")).collect(); - let target = |l: LayerId| ThumbTarget::Content { layer: l, channel: Channel::BaseColor }; - let mut svc = ThumbService::new(); - // A frame asks for six rows, the next frame (scrolled) for only one of them. - svc.begin_frame(&s, 1.0); - for l in &layers[..6] { - svc.get(&s, target(*l)); + let mut session = session(); + let layers: Vec = (0..(CACHE_ENTRIES + 30)).map(|_| id(execute(&mut session, "layer.add.paint", &Value::Null).unwrap(), "layer")).collect(); + let target = |layer: LayerId| ThumbTarget::Content { layer, channel: Channel::BaseColor }; + let mut service = ThumbService::new(); + + // A frame asks for six rows, then scrolling leaves only one visible + service.begin_frame(&session, 1.0); + for layer in &layers[..6] { + service.get(&session, target(*layer)); } - svc.poll(&s); + service.poll(&session); let mut clock = 2.0; for _ in 0..300 { clock += 0.2; - svc.begin_frame(&s, clock); - svc.get(&s, target(layers[0])); - svc.poll(&s); + service.begin_frame(&session, clock); + service.get(&session, target(layers[0])); + service.poll(&session); std::thread::sleep(Duration::from_millis(1)); } - assert!(svc.is_fresh(target(layers[0]))); - // At most the rows already on their way (the in-flight limit) finished besides it. - let done = layers[..6].iter().filter(|l| svc.is_fresh(target(**l))).count(); - assert!(done <= 3, "{done} of the scrolled-away rows were rendered"); - // Scrolling through every layer keeps the cache within its limit. + + assert!(service.is_fresh(target(layers[0]))); + let completed = layers[..6].iter().filter(|layer| service.is_fresh(target(**layer))).count(); + assert!(completed <= 3, "{completed} of the scrolled-away rows were rendered"); + + // Scrolling through every layer evicts pictures and releases their allocations + let mut images = Vec::new(); for chunk in layers.chunks(12) { - let ts: Vec = chunk.iter().map(|l| target(*l)).collect(); - settle(&mut svc, &s, &ts, &mut clock); - assert!(svc.cached() <= CACHE_ENTRIES + 12, "{}", svc.cached()); + let targets: Vec = chunk.iter().map(|layer| target(*layer)).collect(); + settle(&mut service, &session, &targets, &mut clock); + for target in targets { + images.push(std::sync::Arc::downgrade(&service.get(&session, target).image.unwrap())); + } + assert!(service.cached() <= CACHE_ENTRIES, "{}", service.cached()); } clock += 0.2; - svc.begin_frame(&s, clock); - svc.poll(&s); - assert!(svc.cached() <= CACHE_ENTRIES, "{}", svc.cached()); + service.begin_frame(&session, clock); + service.poll(&session); + + assert!(service.cached() <= CACHE_ENTRIES, "{}", service.cached()); + assert!(images.len() > CACHE_ENTRIES); + assert!(images.first().unwrap().upgrade().is_none(), "the oldest image was evicted"); + assert_eq!(images.iter().filter(|image| image.strong_count() > 0).count(), service.cached()); + + drop(service); + + assert!(images.iter().all(|image| image.upgrade().is_none()), "closing the cache releases every picture"); } #[test] fn an_empty_paint_layer_is_transparent_and_a_folder_composites_its_children() { - let mut s = session(); - let paint = id(execute(&mut s, "layer.add.paint", &Value::Null).unwrap(), "layer"); - let fill = id(execute(&mut s, "layer.add.fill", &json!({"color": "#336699"})).unwrap(), "layer"); - let folder = id(execute(&mut s, "layer.group", &json!({"layer": fill.0})).unwrap(), "layer"); - let base = Channel::BaseColor; - let (p, f) = (ThumbTarget::Content { layer: paint, channel: base }, ThumbTarget::Content { layer: folder, channel: base }); - let (mut svc, mut clock) = (ThumbService::new(), 0.0); - settle(&mut svc, &s, &[p, f], &mut clock); - assert!(image(&mut svc, &s, p).rgba.chunks_exact(4).all(|px| px[3] == 0), "nothing painted: nothing shown"); - let folder_img = image(&mut svc, &s, f); - let px = folder_img.rgba.chunks_exact(4).find(|px| px[3] == 255).unwrap(); - assert!((px[0] as i32 - 51).abs() <= 1 && (px[2] as i32 - 153).abs() <= 1, "{px:?}"); + let mut session = session(); + let paint = id(execute(&mut session, "layer.add.paint", &Value::Null).unwrap(), "layer"); + let fill = id(execute(&mut session, "layer.add.fill", &json!({"color": "#336699"})).unwrap(), "layer"); + let folder = id(execute(&mut session, "layer.group", &json!({"layer": fill.0})).unwrap(), "layer"); + let paint_target = ThumbTarget::Content { layer: paint, channel: Channel::BaseColor }; + let folder_target = ThumbTarget::Content { layer: folder, channel: Channel::BaseColor }; + let (mut service, mut clock) = (ThumbService::new(), 0.0); + + settle(&mut service, &session, &[paint_target, folder_target], &mut clock); + + assert!(image(&mut service, &session, paint_target).rgba.as_chunks::<4>().0.iter().all(|pixel| pixel[3] == 0), "nothing painted: nothing shown"); + let folder_image = image(&mut service, &session, folder_target); + let pixel = folder_image.rgba.as_chunks::<4>().0.iter().find(|pixel| pixel[3] == 255).unwrap(); + assert!((i32::from(pixel[0]) - 51).abs() <= 1 && (i32::from(pixel[2]) - 153).abs() <= 1, "{pixel:?}"); +} + +#[test] +fn instances_preview_the_source_content_and_inherited_mask() { + use texturecraft_engine::thumbs::{GbufCache, ThumbSnapshot}; + + 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(); + + 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 }); + + assert!(preview == Some(source), "the instance inherits {channel:?} from its source"); + } + + assert_eq!(snapshot.render(ThumbTarget::Mask { layer: instance }), snapshot.render(ThumbTarget::Mask { layer: stack.layer })); +} + +#[test] +fn thumbnails_keep_anchor_inputs_from_lower_layers() { + use texturecraft_engine::thumbs::{GbufCache, ThumbSnapshot}; + + let mut session = session(); + execute(&mut session, "layer.add.fill", &json!({"height": 0.25})).unwrap(); + let anchor = id(execute(&mut session, "effect.add.anchor", &Value::Null).unwrap(), "effect"); + let layer = id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer"); + 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(); + + 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 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:?}"); + } +} + +#[test] +fn folder_thumbnails_keep_anchors_outside_the_folder() { + use texturecraft_engine::thumbs::{GbufCache, ThumbSnapshot}; + + let mut session = session(); + execute(&mut session, "layer.add.fill", &json!({"height": 0.25})).unwrap(); + let anchor = id(execute(&mut session, "effect.add.anchor", &Value::Null).unwrap(), "effect"); + let layer = id(execute(&mut session, "layer.add.fill", &Value::Null).unwrap(), "layer"); + 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 image = snapshot.render(ThumbTarget::Content { layer: folder, channel: Channel::Roughness }).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:?}"); } diff --git a/crates/ui-egui/src/layer_panel.rs b/crates/ui-egui/src/layer_panel.rs index a29fa288..27dc5f67 100644 --- a/crates/ui-egui/src/layer_panel.rs +++ b/crates/ui-egui/src/layer_panel.rs @@ -49,6 +49,9 @@ impl LayerPanel { pub(crate) fn begin(&mut self, session: &Session, now: f64) { self.frame += 1; self.service.begin_frame(session, now); + + // Deleted layer IDs must not accumulate in panel state + self.folded.retain(|(layer, _)| session.doc.project.layers.contains_key(&texturecraft_engine::core::LayerId(*layer))); } /// The texture of `target`, queuing its render (call only for rows that are on screen). @@ -85,3 +88,57 @@ impl LayerPanel { &self.service } } + +#[cfg(test)] +mod tests { + use super::*; + use texturecraft_engine::core::{Channel, LayerId}; + use texturecraft_engine::geom::primitives; + + #[test] + fn deleted_layers_release_their_fold_state() { + let mut session = Session::new_project("thumb", primitives::plane(1.0, 1), "builtin:plane", None, 128).unwrap(); + let layer = session.selected_layer().unwrap(); + let mut panel = LayerPanel::default(); + panel.folded.extend([(layer.0, false), (layer.0, true)]); + panel.begin(&session, 0.0); + assert_eq!(panel.folded.len(), 2, "existing layers keep their view settings"); + + texturecraft_engine::execute(&mut session, "layer.remove", &serde_json::json!({"layer": layer.0})).unwrap(); + panel.begin(&session, 1.0); + + assert!(panel.folded.is_empty(), "deleted layer IDs must not accumulate in view state"); + } + + #[test] + fn evicted_and_dropped_thumbnail_handles_release_textures() { + let session = Session::new_project("thumb", primitives::plane(1.0, 1), "builtin:plane", None, 128).unwrap(); + let context = Context::default(); + let initial_textures = context.tex_manager().read().num_allocated(); + let mut panel = LayerPanel::default(); + let mut evicted = Vec::new(); + panel.begin(&session, 0.0); + + // Simulate scrolling through more textures than the UI cache retains + for index in 0..CACHE_ENTRIES * 2 + 1 { + let target = ThumbTarget::Content { layer: LayerId(index as u64), channel: Channel::BaseColor }; + let image = egui::ColorImage::filled([64, 64], egui::Color32::WHITE); + let texture = context.load_texture("layer-thumb", image, TextureOptions::LINEAR); + evicted.push(texture.id()); + panel.textures.insert(target, (1, texture, panel.frame)); + } + let kept = evicted.pop().unwrap(); + panel.begin(&session, 1.0); + panel.begin(&session, 2.0); + panel.textures.values_mut().find(|(_, texture, _)| texture.id() == kept).unwrap().2 = panel.frame; + panel.end(&context, &session); + + assert_eq!(context.tex_manager().read().num_allocated(), initial_textures + 1); + assert!(evicted.iter().all(|id| context.tex_manager().read().meta(*id).is_none())); + assert!(context.tex_manager().read().meta(kept).is_some()); + + drop(panel); + + assert_eq!(context.tex_manager().read().num_allocated(), initial_textures); + } +} diff --git a/docs/architecture.md b/docs/architecture.md index 2756a942..2ddcd76b 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -73,21 +73,25 @@ normal channel and baked normals by reoriented normal mapping, and packs channel The Layers panel shows each layer's content (in the displayed channel), its mask and every effect stage as small pictures. `compose::thumb::render` runs the same compositor on a *cut* copy of the -project: the set's stack becomes the one layer, forced visible at Normal / 100 %, without its mask -for the content, and with its effect list truncated after the previewed effect (a hidden effect -shows the result it bypasses). Paint and fill layers are flattened to (value, coverage), so empty -texels are transparent; folders composite their children. Colors are encoded linear to sRGB, data -channels raw. Everything is evaluated on a 64 px G-buffer of the mesh (painted tiles are -resampled), never at the set's resolution, and the main composite is never touched. +project: the requested layer is forced visible at Normal / 100 %, without its mask for content, +and with its effect list truncated after the previewed effect (a hidden effect shows the result +it bypasses). Lower layers remain available when the preview reads anchor points; only the requested +layer is drawn. Instances use their source's channels. Paint and fill layers are flattened to +(value, coverage), so empty texels are transparent; folders composite their children. Colors are +encoded linear to sRGB, data channels raw. Everything is evaluated on a 64 px G-buffer of the mesh +(painted tiles are resampled), never at the set's resolution, and the main composite is never touched. `engine::thumbs::ThumbService` runs it off the UI thread: an immutable `ThumbSnapshot` (the project, copy-on-write pixel tiles, baked maps, images and the cached 64 px G-buffer) is rebuilt only when the document really differs (compared at most every 120 ms while it keeps changing), a worker thread renders one job at a time (inline, one per frame, on wasm32), results of an older -snapshot are dropped, and an LRU of 96 pictures keeps the out-of-date picture on screen until its -replacement arrives. Only rows on screen ask for pictures; queued rows that scrolled away are -dropped. On a 4096 set (`perf::bench_layer_thumbs_4k`) a snapshot costs 0.02 ms, a content picture -about 2.5 ms and a whole ten-layer panel (20 pictures) about 42 ms of worker time. +snapshot are dropped. At most two jobs, including stale generations, retain snapshots in the worker. +Collecting a result requests another frame to display it. An LRU of 96 pictures keeps the out-of-date +picture on screen until its replacement arrives. Only rows on screen ask for pictures; queued rows +that scrolled away are dropped. Baked-map changes are checked by shared buffer identity, without +scanning full-resolution float arrays on the UI thread. Run `perf::bench_layer_thumbs_4k` in release mode to measure snapshot +construction and content, mask and stage rendering on a ten-layer 4096 set. Run +`thumbs::tests::benchmark_unchanged_4k_baked_snapshot` to measure comparisons with 256 MiB of baked maps. ## Undo From 6f5c78d1736345cf57c2d42a599cfd71e3db567c Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Tue, 10 Nov 2026 06:40:08 -0500 Subject: [PATCH 44/64] Rendering mode: no flash when the camera moves, steadier frames, less grain while orbiting Orbiting in Rendering mode flashed a "Starting render" placeholder, got grainy and stuttered once the GPU was busy. Now: - the path tracer works at half size while the camera moves and keeps the last picture on screen until the full-size one has a few samples (no placeholder); - previous-size accumulation buffers are kept, so switching size does not reallocate; - the samples-per-frame controller uses a frame-time floor (1/75..1/30 s), cuts only when a frame takes 1.75x the floor and regrows after 6 frames; - texture loading counts as motion and texture take-in is throttled, so the scene is not rebuilt every frame while materials load; - environment lookups are cached. Tests cover the controller, the held picture, size switching and the quick-frames case. Co-Authored-By: Claude Sonnet 5.5 --- crates/render/src/gpu_trace.rs | 35 +- crates/render/src/trace.rs | 17 +- crates/ui-egui/src/render_mode.rs | 527 ++++++++++++++++++++++++++++-- 3 files changed, 546 insertions(+), 33 deletions(-) diff --git a/crates/render/src/gpu_trace.rs b/crates/render/src/gpu_trace.rs index 775fc026..30d4c676 100644 --- a/crates/render/src/gpu_trace.rs +++ b/crates/render/src/gpu_trace.rs @@ -113,6 +113,12 @@ pub struct GpuTracer { env: Option, materials: Option, acc: Option, + /// The accumulation buffers of the size before the last size change. Rendering switches + /// between two sizes (small while the camera moves, full when it stops), and allocating + /// ~100 MB of buffers on every switch costs tens of milliseconds, a visible hitch. + spare_acc: Option, + /// How many sets of accumulation buffers were allocated (for tests). + acc_allocations: u32, scene: Option, bind: Option, samples: u32, @@ -309,6 +315,8 @@ impl GpuTracer { env: None, materials: None, acc: None, + spare_acc: None, + acc_allocations: 0, scene: None, bind: None, samples: 0, @@ -323,6 +331,7 @@ impl GpuTracer { /// Free the scene and accumulation memory, keeping the compiled pipelines. pub fn release(&mut self) { (self.geometry, self.env, self.materials, self.acc, self.scene, self.bind) = (None, None, None, None, None, None); + self.spare_acc = None; self.samples = 0; } @@ -508,8 +517,16 @@ impl GpuTracer { } return Ok(()); } - self.acc = None; self.bind = None; + // Back to the size before the last change: reuse that set (cleared) instead of allocating. + if let Some(spare) = self.spare_acc.take_if(|a| (a.width, a.height) == (w, h)) { + for b in spare.acc.iter().chain(&spare.illum) { + encoder.clear_buffer(b, 0, None); + } + self.spare_acc = self.acc.replace(spare); + return Ok(()); + } + self.spare_acc = self.acc.take(); let bytes = u64::from(w) * u64::from(h) * 16; let limits = device.limits(); if bytes > limits.max_storage_buffer_binding_size.min(limits.max_buffer_size) { @@ -529,6 +546,7 @@ impl GpuTracer { acc: ["tc_acc_hit", "tc_acc_albedo", "tc_acc_normal", "tc_acc_env"].map(buf), illum: ["tc_illum_a", "tc_illum_b"].map(buf), })?); + self.acc_allocations += 1; Ok(()) } @@ -816,6 +834,21 @@ mod tests { bytemuck::cast_slice(&staging.slice(..).get_mapped_range().unwrap()).to_vec() } + #[test] + fn switching_between_two_sizes_reuses_the_accumulation_buffers() { + let Some((h, mut t)) = gpu() else { return }; + let mut enc = h.device.create_command_encoder(&Default::default()); + for (w, ht) in [(64, 48), (32, 24), (64, 48), (32, 24), (64, 48)] { + t.reset(&h.device, &mut enc, w, ht).unwrap(); + let a = t.acc.as_ref().unwrap(); + assert_eq!((a.width, a.height), (w, ht)); + } + assert_eq!(t.acc_allocations, 2, "two sizes, two allocations, however often it switches"); + t.reset(&h.device, &mut enc, 16, 16).unwrap(); + assert_eq!(t.acc_allocations, 3, "a third size allocates (and drops the oldest set)"); + h.queue.submit([enc.finish()]); + } + const WHITE: [(Channel, [f32; 3]); 3] = [(Channel::BaseColor, [1.0; 3]), (Channel::Metallic, [0.0; 3]), (Channel::Roughness, [0.5; 3])]; #[test] diff --git a/crates/render/src/trace.rs b/crates/render/src/trace.rs index a823a031..8839ba07 100644 --- a/crates/render/src/trace.rs +++ b/crates/render/src/trace.rs @@ -66,6 +66,9 @@ pub struct TraceScene { pub lens: Option<[f32; 2]>, } +/// Width of the built-in environments traced (texels). +const ENV_SIZE: u32 = 1024; + impl TraceScene { pub fn new(mesh: Arc, bvh: Arc, sets: Vec, env: Arc, env_rotation: f32) -> TraceScene { let mut tri_set = vec![usize::MAX; mesh.triangle_count()]; @@ -114,9 +117,19 @@ impl TraceScene { /// The scene as `display` shows it: the imported environment `env_image` (when the display /// names a resource and it decodes) or the built-in one, its rotation and the shading mode. pub fn for_display(mesh: Arc, bvh: Arc, sets: Vec, display: &DisplaySettings, env_image: Option<&ImageRes>) -> TraceScene { + TraceScene::for_display_env(mesh, bvh, sets, display, Arc::new(TraceScene::display_env(display, env_image))) + } + + /// The environment [`TraceScene::for_display`] traces under (building it takes a while: a + /// caller that rebuilds scenes often keeps it and passes it to [`TraceScene::for_display_env`]). + pub fn display_env(display: &DisplaySettings, env_image: Option<&ImageRes>) -> EnvImage { let imported = env_image.and_then(|i| EnvImage::from_rgba(i.width, i.height, &i.rgba, i.srgb)); - let env = imported.unwrap_or_else(|| crate::ibl::environment(&display.environment, 1024)); - let mut scene = TraceScene::new(mesh, bvh, sets, Arc::new(env), display.env_rotation.to_radians()); + imported.unwrap_or_else(|| crate::ibl::environment(&display.environment, ENV_SIZE)) + } + + /// [`TraceScene::for_display`] under `env`, from [`TraceScene::display_env`] of the same display. + pub fn for_display_env(mesh: Arc, bvh: Arc, sets: Vec, display: &DisplaySettings, env: Arc) -> TraceScene { + let mut scene = TraceScene::new(mesh, bvh, sets, env, display.env_rotation.to_radians()); scene.spec_gloss = display.spec_gloss; scene.set_scatter(display.scatter_color, display.scatter_radius); scene.ior = display.ior; diff --git a/crates/ui-egui/src/render_mode.rs b/crates/ui-egui/src/render_mode.rs index 80248a32..2e0a67a4 100644 --- a/crates/ui-egui/src/render_mode.rs +++ b/crates/ui-egui/src/render_mode.rs @@ -17,6 +17,7 @@ use egui::{Color32, ColorImage, Rect, RichText, TextureHandle, TextureOptions, U use texturecraft_engine::geom::{Bvh, Mesh, OrbitCamera}; use texturecraft_render::displace::trace_geometry; use texturecraft_render::gpu_trace::GpuTracer; +use texturecraft_render::ibl::EnvImage; use texturecraft_render::readback::Readback; use texturecraft_render::trace::{TraceDisplay, TraceScene, TraceSet, TraceSettings, Tracer}; use texturecraft_render::{Renderer, wgpu}; @@ -134,7 +135,199 @@ struct GpuView { status: Arc>, /// Samples per pixel per frame: grows while frames are quick, halves when they are slow. spp: u32, + /// What steers `spp`. + spp_control: SppControl, read: Arc>, + /// An image of this render was resolved into `texture` at least once, so a restart keeps + /// showing it (the previous camera's frame) until the new samples replace it. + has_image: bool, + /// The egui texture of the last image traced at the smaller moving size, shown instead of + /// `texture` while the full-size render is too grainy (see [`holds_previous`]). + held: Option, + /// When `held` started being shown (egui time, seconds): a restart while it is up (a display + /// slider dragged) resets `started`, so the hold is timed from this instead. + held_since: f64, +} + +/// While the camera moves, the GPU render is traced at this fraction of the view size per axis +/// (the image is stretched to the view). A quarter of the pixels means about four times the samples +/// per pixel in the same frame time, so an orbit shows a smooth image instead of one or two noisy +/// samples; a faster GPU affords more samples (see `GpuView::spp`) at the same size. +const MOVING_SCALE: f32 = 0.5; + +/// Seconds without a camera change after which the render returns to the full view size. +const MOTION_SETTLE_S: f64 = 0.2; + +/// While textures load, new tiles are taken into the render at most this often (seconds). Each +/// time restarts the render, so taking them in every frame leaves it forever one or two samples +/// deep (raw noise) until loading ends; this lets about a third of a second of samples build up +/// between restarts, at the price of a little delay before a new tile shows. +const LOADING_RESTART_S: f64 = 0.35; + +/// Most samples per frame while textures load (see [`LOADING_RESTART_S`]). The frame time is +/// then the compositor's, not the tracer's, so the count is not steered by it: it stays where it +/// was, at most this (cheap at the smaller loading size). +const LOADING_MAX_SPP: u32 = 8; + +/// Whether textures are still loading: tiles wait to be composited, or composited ones to be +/// uploaded (the GPU render copies the uploaded display textures). +fn textures_loading(s: &texturecraft_engine::Session) -> bool { + s.pending_tiles() > 0 || s.caches.iter().any(|c| !c.upload.is_empty()) +} + +/// Whether changed textures are taken into the render now: always, except while loading, when at +/// most every [`LOADING_RESTART_S`]. +fn take_in_textures(loading: bool, now: f64, last_sync: f64) -> bool { + !loading || now - last_sync >= LOADING_RESTART_S +} + +/// When the render returns to full size after the camera stops, the soft image traced while it +/// moved stays on screen until the full-size render has this many samples (it starts from none, +/// and its first few samples are grainy)... +const SETTLE_HOLD_SAMPLES: u32 = 8; + +/// ...or for this many seconds at most, so a slow GPU never leaves the soft image up for long. +const SETTLE_HOLD_MAX_S: f64 = 0.5; + +/// Whether the image from before the view returned to full size is still shown: the full-size +/// render has `samples` samples after `elapsed` seconds. +fn holds_previous(samples: u32, elapsed: f64) -> bool { + samples < SETTLE_HOLD_SAMPLES && elapsed < SETTLE_HOLD_MAX_S +} + +/// Most samples per pixel one frame adds. +const MAX_SPP: u32 = 16; + +/// Frames over which [`FrameFloor`] keeps the quickest frame time. +const FLOOR_FRAMES: usize = 30; + +/// The range the quickest frame time is held to (seconds): from 75 frames a second to 30, so a +/// run of slow frames never makes slow look normal. The quick end matters as much: frames that +/// are not paced by the display (or tiny ones while little is traced) can take 3 ms, and taking +/// that as the baseline cuts the samples per frame to one at the first frame that does real work, +/// which left the render grainy for seconds. Below this, frames count as quick, not as the target. +const FLOOR_RANGE_S: (f64, f64) = (1.0 / 75.0, 1.0 / 30.0); + +/// A frame quicker than this many times the quickest recent one adds one more sample next time. +/// With vsync, frames come at the display's refresh rate however light they are, so the limits +/// are relative to it (a fixed 1/90 s never let a 60 Hz display grow at all). +const SPP_GROW_BELOW: f64 = 1.25; + +/// A frame at least this many times the quickest recent one (a missed refresh with vsync is two; +/// wide enough that ordinary variation in a busy frame does not cut) cuts the samples per frame (by a +/// quarter, by the same ratio the frame overshoots when that is larger), so a slow frame is +/// followed by a short one, not a long one. With vsync a frame that misses the refresh takes two. +const SPP_CUT_ABOVE: f64 = 1.75; + +/// Frames after a cut during which the samples per frame do not grow again, so they settle +/// below the limit instead of climbing straight back to the frame that missed it (a hitch every +/// few frames). +const SPP_GROW_PAUSE_FRAMES: u32 = 6; + +/// The quickest of the last [`FLOOR_FRAMES`] frame times: about the display's refresh interval +/// while the GPU keeps up. +#[derive(Default)] +struct FrameFloor { + recent: std::collections::VecDeque, +} + +impl FrameFloor { + /// Record frame time `dt` (seconds); the quickest recent one, within [`FLOOR_RANGE_S`]. + fn push(&mut self, dt: f64) -> f64 { + if dt.is_finite() && dt > 0.0 { + if self.recent.len() >= FLOOR_FRAMES { + self.recent.pop_front(); + } + self.recent.push_back(dt); + } + self.recent.iter().copied().fold(FLOOR_RANGE_S.1, f64::min).clamp(FLOOR_RANGE_S.0, FLOOR_RANGE_S.1) + } +} + +/// Samples per pixel for the next frame, from the last frame's time `dt` and the quickest recent +/// one `floor` (seconds; see [`FrameFloor`]): one more while frames are quick, fewer when slow, +/// steady in between and for [`SPP_GROW_PAUSE_FRAMES`] after a cut (`since_cut` frames ago). +/// Steady between the two limits is what stops the count from climbing until the GPU backs up, +/// jumping down, and climbing again. +fn next_spp(spp: u32, dt: f64, floor: f64, since_cut: u32) -> u32 { + let cut_above = floor * SPP_CUT_ABOVE; + if dt >= cut_above { + let by_ratio = (f64::from(spp) * cut_above / dt) as u32; + by_ratio.min(spp * 3 / 4).max(1) + } else if dt < floor * SPP_GROW_BELOW && since_cut >= SPP_GROW_PAUSE_FRAMES { + (spp + 1).min(MAX_SPP) + } else { + spp + } +} + +/// What steers the GPU render's samples per pixel per frame (see [`next_spp`]). +struct SppControl { + floor: FrameFloor, + /// Frames since the samples per frame were last cut. + since_cut: u32, +} + +impl Default for SppControl { + /// A new render may grow from its first frame. + fn default() -> SppControl { + SppControl { floor: FrameFloor::default(), since_cut: SPP_GROW_PAUSE_FRAMES } + } +} + +impl SppControl { + /// The samples per frame after a frame of `dt` seconds traced with `spp`. + fn next(&mut self, spp: u32, dt: f64) -> u32 { + let floor = self.floor.push(dt); + let next = next_spp(spp, dt, floor, self.since_cut); + self.since_cut = if next < spp { 0 } else { self.since_cut.saturating_add(1) }; + next + } +} + +/// Samples per frame after the traced size changed from `old` to `new` pixels (frame time is +/// about proportional to samples times pixels). +fn rescale_spp(spp: u32, old: (u32, u32), new: (u32, u32)) -> u32 { + let (o, n) = (u64::from(old.0) * u64::from(old.1), (u64::from(new.0) * u64::from(new.1)).max(1)); + ((u64::from(spp) * o / n).max(1) as u32).min(MAX_SPP) +} + +/// Whether the camera is moving, for [`MOVING_SCALE`]. +#[derive(Default)] +struct Motion { + /// The camera as last seen (compared, never parsed). + camera: String, + /// When it last changed. The first frame counts as a change: a render that has just started + /// begins at the smaller size too (four times the samples at once, so it opens smooth + /// instead of as raw one-sample noise) and grows to full size like after any move. + last_change: Option, +} + +impl Motion { + /// Record `camera` at time `now` (seconds); true while it changed within [`MOTION_SETTLE_S`]. + /// `loading`: textures are still being composited. Each finished tile restarts the render, so + /// like a moving camera it keeps being redone from no samples, and is traced small for the + /// same reason (four times the samples per restart). + fn moving(&mut self, camera: &OrbitCamera, now: f64, loading: bool) -> bool { + if loading { + self.last_change = Some(now); + } + let c = format!("{camera:?}"); + if self.camera != c { + self.last_change = Some(now); + self.camera = c; + } + self.last_change.is_some_and(|t| now - t < MOTION_SETTLE_S) + } +} + +/// The size to trace at for a view of `full` pixels: smaller while the camera `moving`. +fn traced_size(full: (u32, u32), moving: bool) -> (u32, u32) { + if !moving { + return full; + } + let scale = |n: u32| ((n as f32 * MOVING_SCALE) as u32).clamp(16.min(n), n); + (scale(full.0), scale(full.1)) } /// The GPU tracer in egui's callback resources. @@ -144,6 +337,8 @@ struct TraceState { key: String, /// Samples in the resolved image (None: resolve again). resolved: Option, + /// When the tracer last took in changed textures (egui time, seconds). + last_sync: f64, } /// Traced geometry and the key of what it was built from. @@ -157,14 +352,22 @@ pub struct RenderView { /// Why the GPU tracer failed on the scene of this key (the CPU renders it instead). gpu_error: Option<(String, String)>, texture: Option, + motion: Motion, shown: Option<(u32, u32, Vec)>, samples: u32, elapsed: f64, /// The traced geometry (displaced or not) and what it was built from: changes to the display /// alone don't rebuild it. geometry: Mutex>, + /// The traced environment and what it was built from (see [`EnvKey`]): building one takes a + /// while, and the scene is rebuilt on every display change. + env: Mutex)>>, } +/// What a traced environment is built from: the display's environment name and the identity of +/// its imported image (0: none). +type EnvKey = (String, usize); + /// Viewport resolution of a CPU render (the web renders at half size: it has one thread). fn render_size(rect: Rect) -> (u32, u32) { let scale = if cfg!(target_arch = "wasm32") { 0.5 } else { 1.0 }; @@ -183,7 +386,8 @@ fn trace_scene(app: &TextureCraftApp) -> TraceScene { .map(|(ts, c)| TraceSet { material: ts.material, composite: c.composite.clone(), height_strength: ts.atlas_height_strength() }) .collect(); let env_image = d.environment_resource().and_then(|n| s.images.get(n)); - let revisions: Vec = s.caches.iter().map(|c| c.revision).collect(); + // Only displaced geometry depends on the composites (their heights). + let revisions: Vec = if d.displacement { s.caches.iter().map(|c| c.revision).collect() } else { Vec::new() }; let strengths: Vec = sets.iter().map(|t| t.height_strength).collect(); let key = format!("{}|{revisions:?}|{strengths:?}|{}", s.mesh_id, d.displacement); let mut cached = app.render.geometry.lock().unwrap_or_else(PoisonError::into_inner); @@ -195,7 +399,18 @@ fn trace_scene(app: &TextureCraftApp) -> TraceScene { (m, b) } }; - TraceScene::for_display(mesh, bvh, sets, d, env_image.map(|i| i.as_ref())) + drop(cached); + let env_key: EnvKey = (d.environment.clone(), env_image.map_or(0, |i| Arc::as_ptr(i) as usize)); + let mut env_cached = app.render.env.lock().unwrap_or_else(PoisonError::into_inner); + let env = match env_cached.as_ref() { + Some((k, e)) if *k == env_key => e.clone(), + _ => { + let e = Arc::new(TraceScene::display_env(d, env_image.map(|i| i.as_ref()))); + *env_cached = Some((env_key, e.clone())); + e + } + }; + TraceScene::for_display_env(mesh, bvh, sets, d, env) } fn settings(app: &TextureCraftApp) -> TraceSettings { @@ -217,16 +432,24 @@ fn work(app: &TextureCraftApp, size: (u32, u32)) -> Work { } } -/// What the traced scene depends on. -fn scene_key(app: &TextureCraftApp) -> String { - let s = &app.session; - let revisions: Vec = s.caches.iter().map(|c| c.revision).collect(); +/// What the traced scene depends on. `composites`: the texture-set composites too (their +/// revisions bump with every composited chunk, so while textures load this changes every frame). +fn scene_key(s: &texturecraft_engine::Session, composites: bool) -> String { + let revisions: Vec = if composites { s.caches.iter().map(|c| c.revision).collect() } else { Vec::new() }; format!("{}|{revisions:?}|{:?}", s.mesh_id, s.doc.project.display) } -/// What the render depends on; a change restarts it. -fn key(app: &TextureCraftApp, size: (u32, u32)) -> String { - format!("{}|{:?}|{size:?}|{:?}", scene_key(app), app.session.camera, app.ui.render) +/// [`scene_key`] of the GPU render. It takes texture changes in by copying the display textures +/// when their content changes (throttled while textures load, see [`take_in_textures`]), so the +/// composites only count when they displace the geometry. Restarting on every composited chunk +/// would rebuild the scene and reset the render every frame of a load. +fn gpu_scene_key(s: &texturecraft_engine::Session) -> String { + scene_key(s, s.doc.project.display.displacement) +} + +/// What the render of scene `scene_key` depends on; a change restarts it. +fn key(app: &TextureCraftApp, scene_key: &str, size: (u32, u32)) -> String { + format!("{scene_key}|{:?}|{size:?}|{:?}", app.session.camera, app.ui.render) } fn start(app: &TextureCraftApp, ctx: &egui::Context, key: String, size: (u32, u32)) -> Job { @@ -272,7 +495,8 @@ pub fn show(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect) { fn show_cpu(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect) { let ctx = ui.ctx().clone(); let size = render_size(rect); - let k = key(app, size); + // The CPU tracer reads the composites themselves: every change restarts it. + let k = key(app, &scene_key(&app.session, true), size); if app.render.job.as_ref().is_none_or(|j| j.key != k) { app.render.job = Some(start(app, &ctx, k, size)); app.render.samples = 0; @@ -299,10 +523,18 @@ fn show_cpu(app: &mut TextureCraftApp, ui: &mut Ui, rect: Rect) { app.render.shown = Some((f.width, f.height, f.rgba)); } } - let shown = app.render.texture.as_ref().filter(|_| app.render.samples > 0).map(TextureHandle::id); + let shown = app.render.texture.as_ref().filter(|_| show_image(true, app.render.samples)).map(TextureHandle::id); paint(ui, rect, shown); } +/// Whether the view shows the render image rather than the "Starting render..." placeholder. +/// `has_image`: an earlier frame of this render is on screen. A restart (the camera moved) resets +/// the sample count to 0 but keeps that frame up, so orbiting doesn't flash the placeholder. +/// Only the very first frame, before anything was traced, has nothing to show. +fn show_image(has_image: bool, samples: u32) -> bool { + has_image || samples > 0 +} + /// The render, or a placeholder until its first samples. fn paint(ui: &Ui, rect: Rect, texture: Option) { let tk = Tokens::get(ui.ctx()); @@ -321,7 +553,7 @@ fn paint(ui: &Ui, rect: Rect, texture: Option) { /// Trace on the GPU; false when it can't (no compute shaders, or it failed on this scene). fn show_gpu(app: &mut TextureCraftApp, ui: &Ui, rect: Rect) -> bool { let Some(rs) = app.render_state.clone() else { return false }; - let scene_key = scene_key(app); + let scene_key = gpu_scene_key(&app.session); if !GpuTracer::supported(&rs.device) || app.render.gpu_error.as_ref().is_some_and(|(k, _)| *k == scene_key) { return false; } @@ -332,30 +564,74 @@ fn show_gpu(app: &mut TextureCraftApp, ui: &Ui, rect: Rect) -> bool { } let ctx = ui.ctx().clone(); let now = ctx.input(|i| i.time); - let size = (rect.width().max(16.0) as u32, rect.height().max(16.0) as u32); - let key = key(app, size); + let full = (rect.width().max(16.0) as u32, rect.height().max(16.0) as u32); + let loading = textures_loading(&app.session); + let moving = app.render.motion.moving(&app.session.camera, now, loading); + if moving { + // Come back and restore the full size once the camera has been still, even with no input. + ctx.request_repaint_after(std::time::Duration::from_secs_f64(MOTION_SETTLE_S)); + } + let size = traced_size(full, moving); + let key = key(app, &scene_key, size); let mut g = match app.render.gpu.take() { Some(g) if g.size == size => g, old => { let out = GpuTracer::output_texture(&rs.device, size.0, size.1); let out_view = out.create_view(&Default::default()); // A resized view keeps its scene and egui texture id. - let (texture, scene_key, scene) = match old { + let old_has_image = old.as_ref().is_some_and(|o| o.has_image); + let old_spp = old.as_ref().map_or(1, |o| rescale_spp(o.spp, o.size, size)); + let mut held_since = old.as_ref().map_or(now, |o| o.held_since); + let growing = old.as_ref().is_some_and(|o| u64::from(o.size.0) * u64::from(o.size.1) < u64::from(size.0) * u64::from(size.1)); + let mut held = None; + let (texture, scene_key, scene, spp_control) = match old { + // Returning to full size: the old image stays up under its own texture id. + Some(old) if growing && old.has_image => { + let mut r = rs.renderer.write(); + if let Some(h) = old.held { + r.free_texture(&h); + } + held = Some(old.texture); + held_since = now; + (r.register_native_texture(&rs.device, &out_view, wgpu::FilterMode::Linear), old.scene_key, old.scene, old.spp_control) + } Some(old) => { - rs.renderer.write().update_egui_texture_from_wgpu_texture(&rs.device, &out_view, wgpu::FilterMode::Linear, old.texture); - (old.texture, old.scene_key, old.scene) + let mut r = rs.renderer.write(); + if let Some(h) = old.held { + r.free_texture(&h); + } + r.update_egui_texture_from_wgpu_texture(&rs.device, &out_view, wgpu::FilterMode::Linear, old.texture); + (old.texture, old.scene_key, old.scene, old.spp_control) } None => ( rs.renderer.write().register_native_texture(&rs.device, &out_view, wgpu::FilterMode::Linear), scene_key.clone(), Arc::new(trace_scene(app)), + SppControl::default(), ), }; - GpuView { size, scene_key, scene, key: String::new(), started: now, out, out_view, texture, status: Arc::default(), spp: 1, read: Arc::default() } + GpuView { + size, + scene_key, + scene, + key: String::new(), + started: now, + out, + out_view, + texture, + status: Arc::default(), + spp: old_spp, + spp_control, + read: Arc::default(), + has_image: old_has_image, + held, + held_since, + } } }; let (samples, error) = { let mut st = g.status.lock().unwrap_or_else(PoisonError::into_inner); + g.has_image |= st.samples > 0; if g.key != key { st.samples = 0; } @@ -377,15 +653,9 @@ fn show_gpu(app: &mut TextureCraftApp, ui: &Ui, rect: Rect) -> bool { } let max_samples = app.ui.render.max_samples.max(1); if samples < max_samples { - // Keep the UI near 60 fps: more samples while frames are quick, half as many when slow. - let dt = ctx.input(|i| i.stable_dt); - g.spp = if dt > 1.0 / 40.0 { - (g.spp / 2).max(1) - } else if dt < 1.0 / 60.0 { - (g.spp + 1).min(16) - } else { - g.spp - }; + // While textures load the frame time is the compositor's, not the tracer's: reading it + // would cut the samples to one. Keep them as they are (see `LOADING_MAX_SPP`). + g.spp = if loading { g.spp.min(LOADING_MAX_SPP) } else { g.spp_control.next(g.spp, f64::from(ctx.input(|i| i.stable_dt))) }; app.render.elapsed = now - g.started; ctx.request_repaint(); } @@ -401,6 +671,8 @@ fn show_gpu(app: &mut TextureCraftApp, ui: &Ui, rect: Rect) -> bool { display: display(app), max_samples, spp: g.spp, + loading, + now, size, out: g.out.clone(), out_view: g.out_view.clone(), @@ -408,7 +680,13 @@ fn show_gpu(app: &mut TextureCraftApp, ui: &Ui, rect: Rect) -> bool { read: g.read.clone(), }; ui.painter().add(egui_wgpu::Callback::new_paint_callback(rect, cb)); - paint(ui, rect, (samples > 0).then_some(g.texture)); + if g.held.is_some() + && !holds_previous(samples, now - g.held_since) + && let Some(h) = g.held.take() + { + rs.renderer.write().free_texture(&h); + } + paint(ui, rect, show_image(g.has_image, samples).then_some(g.held.unwrap_or(g.texture))); app.render.gpu = Some(g); true } @@ -461,6 +739,9 @@ struct TraceCallback { display: TraceDisplay, max_samples: u32, spp: u32, + /// Textures are still loading (see [`LOADING_RESTART_S`]) and the egui time of this frame. + loading: bool, + now: f64, size: (u32, u32), out: wgpu::Texture, out_view: wgpu::TextureView, @@ -482,7 +763,11 @@ impl TraceCallback { t.set_scene(device, queue, &self.scene)?; st.scene = Some(self.scene.clone()); } - if t.sync_materials(device, queue, encoder, renderer)? || st.key != self.key { + let take_in = take_in_textures(self.loading, self.now, st.last_sync); + if take_in { + st.last_sync = self.now; + } + if (take_in && t.sync_materials(device, queue, encoder, renderer)?) || st.key != self.key { t.reset(device, encoder, self.size.0, self.size.1)?; st.key.clone_from(&self.key); st.resolved = None; @@ -514,7 +799,7 @@ impl CallbackTrait for TraceCallback { ) -> Vec { let state = match resources.remove::() { Some(st) => Ok(st), - None => GpuTracer::new(device).map(|tracer| TraceState { tracer, scene: None, key: String::new(), resolved: None }), + 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::() { @@ -542,10 +827,15 @@ fn drop_gpu(app: &mut TextureCraftApp) { if let Some(rs) = &app.render_state { let mut r = rs.renderer.write(); r.free_texture(&g.texture); + if let Some(h) = g.held { + r.free_texture(&h); + } if let Some(st) = r.callback_resources.get_mut::() { st.tracer.release(); (st.scene, st.resolved) = (None, None); st.key.clear(); + // The materials went with the release: the next render takes textures in at once. + st.last_sync = f64::MIN; } } } @@ -638,3 +928,180 @@ pub fn stop(app: &mut TextureCraftApp) { drop_gpu(app); app.render = RenderView::default(); } + +#[cfg(test)] +mod tests { + use super::{ + FLOOR_FRAMES, FLOOR_RANGE_S, FrameFloor, LOADING_RESTART_S, MAX_SPP, MOTION_SETTLE_S, Motion, OrbitCamera, SETTLE_HOLD_MAX_S, SETTLE_HOLD_SAMPLES, + SPP_GROW_PAUSE_FRAMES, SppControl, gpu_scene_key, holds_previous, next_spp, rescale_spp, scene_key, show_image, take_in_textures, textures_loading, + traced_size, + }; + use texturecraft_engine::Session; + use texturecraft_engine::geom::primitives; + + fn session() -> Session { + let mut s = Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap(); + s.update(); + s + } + + /// Every composited chunk bumps a revision. The CPU render restarts on it (it reads the + /// composites); the GPU render does not (it copies the display textures when they change, + /// throttled while loading) unless the heights displace its geometry. + #[test] + fn composited_chunks_restart_the_gpu_render_only_when_displaced() { + let mut s = session(); + let (cpu, gpu) = (scene_key(&s, true), gpu_scene_key(&s)); + s.caches[0].revision += 1; + assert_ne!(scene_key(&s, true), cpu); + assert_eq!(gpu_scene_key(&s), gpu, "the GPU scene is kept while textures load"); + s.doc.project.display.displacement = true; + let displaced = gpu_scene_key(&s); + s.caches[0].revision += 1; + assert_ne!(gpu_scene_key(&s), displaced, "displaced geometry follows the heights"); + } + + /// Loading lasts until the composited tiles are uploaded too (the GPU render reads them). + #[test] + fn textures_load_until_their_tiles_are_uploaded() { + let mut s = session(); + s.caches[0].upload.clear(); + assert!(!textures_loading(&s)); + s.caches[0].upload.insert((0, 0)); + assert!(textures_loading(&s), "a tile waits to be uploaded"); + s.caches[0].upload.clear(); + s.caches[0].invalidate_all(); + assert!(textures_loading(&s), "tiles wait to be composited"); + } + + /// Orbiting restarts the render every frame (samples back to 0): the last image stays up. + #[test] + fn a_restart_keeps_the_previous_image_on_screen() { + assert!(show_image(true, 0), "restart with an earlier frame must not show the placeholder"); + assert!(show_image(true, 5)); + assert!(show_image(false, 1)); + } + + /// Before anything was traced there is nothing to show but the placeholder. + #[test] + fn a_moving_camera_traces_smaller_and_a_still_one_at_full_size() { + assert_eq!(traced_size((1600, 900), false), (1600, 900)); + assert_eq!(traced_size((1600, 900), true), (800, 450)); + // Tiny views are never made smaller than they are or than 16 pixels. + assert_eq!(traced_size((10, 10), true), (10, 10)); + assert_eq!(traced_size((20, 400), true), (16, 200)); + } + + #[test] + fn motion_starts_on_a_camera_change_and_settles_after_a_moment() { + let mut m = Motion::default(); + let mut cam = OrbitCamera::default(); + assert!(m.moving(&cam, 0.0, false), "a render that just started opens at the smaller size"); + assert!(!m.moving(&cam, 1.0, false)); + cam.yaw += 0.1; + assert!(m.moving(&cam, 2.0, false)); + assert!(m.moving(&cam, 2.0 + MOTION_SETTLE_S * 0.5, false)); + assert!(!m.moving(&cam, 2.0 + MOTION_SETTLE_S * 1.5, false)); + assert!(m.moving(&cam, 5.0, true), "textures still loading count as motion"); + assert!(m.moving(&cam, 5.0 + MOTION_SETTLE_S * 0.5, false), "and settle a moment after they finish"); + assert!(!m.moving(&cam, 5.0 + MOTION_SETTLE_S * 1.5, false)); + } + + #[test] + fn the_soft_image_stays_until_the_full_size_render_has_samples_or_time_runs_out() { + assert!(holds_previous(0, 0.0)); + assert!(holds_previous(SETTLE_HOLD_SAMPLES - 1, SETTLE_HOLD_MAX_S * 0.5)); + assert!(!holds_previous(SETTLE_HOLD_SAMPLES, 0.0), "enough samples: show the new render"); + assert!(!holds_previous(0, SETTLE_HOLD_MAX_S), "a slow GPU: don't hold it forever"); + } + + #[test] + fn samples_per_frame_grow_slowly_hold_in_between_and_drop_fast() { + let (floor, free) = (1.0 / 144.0, SPP_GROW_PAUSE_FRAMES); + assert_eq!(next_spp(4, floor, floor, free), 5, "frames at the refresh rate: one more"); + assert_eq!(next_spp(MAX_SPP, floor, floor, free), MAX_SPP); + assert_eq!(next_spp(4, floor, floor, 0), 4, "just after a cut: no growth yet"); + assert_eq!(next_spp(6, floor * 1.4, floor, free), 6, "between the limits: steady"); + assert_eq!(next_spp(8, floor * 2.5, floor, free), 5, "slow frame: cut by the overshoot (8 * 1.75/2.5), more than a quarter"); + assert_eq!(next_spp(8, floor * 1.7, floor, free), 8, "a little slow: steady, not a cut (cuts are for real overload)"); + assert_eq!(next_spp(8, floor * 1.8, floor, free), 6, "slightly over the limit: a quarter fewer"); + assert_eq!(next_spp(8, floor * 20.0, floor, free), 1, "very slow frame: by the overshoot, at least one"); + assert_eq!(next_spp(1, floor * 20.0, floor, free), 1); + } + + /// With vsync on a 60 Hz display every frame takes ~16.7 ms however light: that is the + /// refresh, not a slow GPU, so the samples grow; a missed refresh (two intervals) cuts them. + #[test] + fn samples_per_frame_grow_at_60_hz_and_drop_on_a_missed_refresh() { + let hz60 = 1.0 / 60.0; + let mut c = SppControl::default(); + let mut spp = 2; + for _ in 0..10 { + spp = c.next(spp, hz60); + } + assert_eq!(spp, 12, "one more per frame at the refresh rate"); + let cut = c.next(spp, 2.0 * hz60); + assert!(cut < spp && cut >= spp / 2, "a missed refresh cuts: {spp} -> {cut}"); + // No climb straight back to the frame that missed: steady for a while, then growth again. + let mut after = cut; + for _ in 0..SPP_GROW_PAUSE_FRAMES - 1 { + after = c.next(after, hz60); + } + assert_eq!(after, cut, "steady after the cut"); + for _ in 0..3 { + after = c.next(after, hz60); + } + assert!(after > cut, "then it grows again"); + } + + /// Frames that are not paced by the display (or take almost no work) can be a few ms; a frame + /// that then does real work must not read as slow and cut the samples to one (the render was + /// left grainy for seconds). + #[test] + fn a_few_very_quick_frames_do_not_collapse_the_samples_per_frame() { + let mut c = SppControl::default(); + for _ in 0..5 { + c.next(4, 0.003); + } + let working = 0.012; + let mut spp = 4; + for _ in 0..10 { + spp = c.next(spp, working); + } + assert!(spp >= 4, "12 ms frames after 3 ms ones are fine: {spp}"); + } + + #[test] + fn the_frame_floor_is_the_quickest_recent_frame_within_range() { + let mut f = FrameFloor::default(); + assert_eq!(f.push(1.0 / 60.0), 1.0 / 60.0); + assert_eq!(f.push(0.05), 1.0 / 60.0, "a slow frame does not raise it"); + assert_eq!(f.push(f64::NAN), 1.0 / 60.0, "a broken time is ignored"); + assert_eq!(f.push(0.0001), FLOOR_RANGE_S.0, "never below the quick end of the range"); + for _ in 0..FLOOR_FRAMES { + f.push(0.2); + } + assert_eq!(f.push(0.2), FLOOR_RANGE_S.1, "only recent frames count, and at most 1/30 s"); + } + + #[test] + fn samples_per_frame_follow_the_pixel_count_when_the_size_changes() { + assert_eq!(rescale_spp(12, (500, 400), (1000, 800)), 3, "four times the pixels: a quarter of the samples"); + assert_eq!(rescale_spp(3, (1000, 800), (500, 400)), 12); + assert_eq!(rescale_spp(1, (500, 400), (1000, 800)), 1, "never below one"); + assert_eq!(rescale_spp(16, (100, 100), (10, 10)), MAX_SPP, "never above the cap"); + } + + #[test] + fn loading_textures_are_taken_in_at_a_limited_rate() { + assert!(take_in_textures(false, 1.0, 1.0), "not loading: every frame"); + assert!(!take_in_textures(true, 1.0 + LOADING_RESTART_S * 0.5, 1.0)); + assert!(take_in_textures(true, 1.0 + LOADING_RESTART_S, 1.0)); + assert!(take_in_textures(true, 0.0, f64::MIN), "the first frame always"); + } + + #[test] + fn nothing_traced_yet_shows_the_placeholder() { + assert!(!show_image(false, 0)); + } +} From 208c645d0cea999371650f7c8738c7b325b52084 Mon Sep 17 00:00:00 2001 From: SteamSmith <341182916+SteamSmith@users.noreply.github.com> Date: Tue, 10 Nov 2026 06:40:11 -0500 Subject: [PATCH 45/64] Show a whole material at once: coarse first look, then the exact result Applying a material filled the model in tile by tile, and each apply made the next one slower. Now: - a big recomposite first draws a coarse look of every tile (sampled texels repeated across blocks), then refines to the exact result; - layers hidden behind an opaque layer are skipped (not when anchors or height masks are involved); - compositing and upload budgets adapt: larger when idle, smaller while the user is interacting, and uploads reserve time for conversion; - no coarse pass during a live stroke or with neighbourhood filters; - blending at full weight returns the blended value exactly. Tests: coarse-then-exact, hidden-layer culling gives identical pixels, coarse pass covers every tile, no coarse pass while a stroke is live. Co-Authored-By: Claude Sonnet 5.5 --- crates/compose/src/eval.rs | 159 ++++++++++++++++++- crates/compose/src/lib.rs | 4 +- crates/compose/tests/cache_and_instances.rs | 32 ++++ crates/core/src/blend.rs | 5 + crates/engine/src/inspect.rs | 5 + crates/engine/src/session.rs | 92 +++++++++-- crates/engine/tests/it/instances.rs | 6 +- crates/engine/tests/session.rs | 163 ++++++++++++++++++++ crates/ui-egui/src/gpu.rs | 69 ++++++++- crates/ui-egui/src/viewport.rs | 6 +- 10 files changed, 510 insertions(+), 31 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index 3a9404d3..459e5daf 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -801,6 +801,22 @@ fn fields_of(inp: &Inputs, channels: &[Channel], list: &[LayerId], tiles: &[(u32 out } +/// Whether texture set `ts` has a layer with a neighbourhood filter (blur, sharpen, warp…) in +/// its mask or content: a composite then precomputes [`neighbourhood_fields`] at full +/// resolution, so even a [`composite_tiles_coarse`] is not much cheaper than the exact one. +/// The same layers as `neighbourhood_fields` looks at (it may count a hidden one). +pub fn has_neighbourhood_filters(project: &Project, ts: usize) -> bool { + let Ok(set) = project.texture_set(ts) else { return false }; + let mut order = Vec::new(); + draw_order(project, &set.stack, 0, &mut order); + let res = set.resolution; + order.iter().any(|id| { + let mask = layer_mask(project, *id).is_some_and(|m| m.enabled && neighbourhood(&m.effects, res).is_some()); + let content = project.content_layer(*id).is_some_and(|l| !l.is_group() && neighbourhood(&l.content_effects, res).is_some()); + mask || content + }) +} + /// Build the curvature detail sizes every visible generator of `layers` reads, once, before tiles composite in parallel. fn prepare_curvature_sizes(inp: &Inputs, layers: &[LayerId]) { let visible = layers.iter().filter(|id| inp.project.layers.get(id).is_some_and(|layer| layer.visible)); @@ -897,10 +913,89 @@ fn mask_plan<'a>(inp: &Inputs<'a>, id: LayerId, mask: &'a Mask, tx: u32, ty: u32 } fn plan<'a>(inp: &Inputs<'a>, list: &[LayerId], channels: &[Channel], tx: u32, ty: u32, depth: usize, fields: Option<&'a Fields>) -> Vec> { + plan_with(inp, list, channels, tx, ty, depth, fields, false) +} + +/// [`plan`], leaving out what an opaque layer above hides when `cull` (see [`cull_hidden`]). +/// Only for lists that are evaluated whole and not looked into (no anchor or stop layer reads). +#[allow(clippy::too_many_arguments)] +fn plan_with<'a>( + inp: &Inputs<'a>, + list: &[LayerId], + channels: &[Channel], + tx: u32, + ty: u32, + depth: usize, + fields: Option<&'a Fields>, + cull: bool, +) -> Vec> { if depth > texturecraft_core::project::MAX_DEPTH { return Vec::new(); } - list.iter().filter_map(|id| plan_node(inp, *id, channels, tx, ty, depth, fields, true)).collect() + let mut nodes: Vec> = list.iter().filter_map(|id| plan_node(inp, *id, channels, tx, ty, depth, fields, true, cull)).collect(); + if cull { + cull_hidden(&mut nodes, channels); + } + nodes +} + +/// Whether node `n` hides everything below it in channel `ch`: it replaces the stack there at +/// every texel (full opacity, normal blend, no mask or geometry or height mask, a fill that +/// covers the whole surface with no content effects), or is a folder at full opacity holding +/// such a layer. +fn occludes(n: &Node, ch: usize) -> bool { + if n.mask.is_some() || n.parts.is_some() || n.height_mask.enabled { + return false; + } + let Some(c) = n.chans.iter().find(|c| c.ch == ch) else { return false }; + if c.opacity < 1.0 { + return false; + } + match &n.content { + Content::Fill(f) => c.blend == BlendMode::Normal && !matches!(f.projection, Projection::Decal(_)) && c.effects.is_empty() && c.start.is_none(), + Content::Group(kids) => kids.iter().any(|k| occludes(k, ch)), + Content::Paint { .. } => false, + } +} + +/// Whether `n` or a layer in it masks with its height. +fn uses_height_mask(n: &Node) -> bool { + n.height_mask.enabled || matches!(&n.content, Content::Group(kids) if kids.iter().any(uses_height_mask)) +} + +/// Take channel `ch` out of `n` (and what it holds), dropping what then draws nothing. +fn strip_channel(n: &mut Node, ch: usize) { + n.chans.retain(|c| c.ch != ch); + if let Content::Group(kids) = &mut n.content { + for k in kids.iter_mut() { + strip_channel(k, ch); + } + kids.retain(|k| !k.chans.is_empty()); + } +} + +/// Leave out the layers (per channel) that a layer above them hides completely: a stack that +/// grows by applying material after material would otherwise evaluate every one of them. The +/// result is identical. Channels with anchor points or height masks below the hiding layer +/// are left alone (they read other layers' values), and so are those under a hiding folder +/// that records an anchor point: its inner stack starts from what lies below it, so an anchor +/// under the hiding layer inside it holds the layers it hides. +fn cull_hidden(nodes: &mut Vec, channels: &[Channel]) { + for c in channels { + let ch = c.index(); + let Some(k) = nodes.iter().rposition(|n| occludes(n, ch)) else { continue }; + if nodes.get(k).is_some_and(|n| n.has_anchor) { + continue; + } + let Some(below) = nodes.get_mut(..k) else { continue }; + if below.iter().any(|n| n.has_anchor || (*c == Channel::Height && uses_height_mask(n))) { + continue; + } + for n in below.iter_mut() { + strip_channel(n, ch); + } + } + nodes.retain(|n| !n.chans.is_empty() || n.has_anchor); } /// The plan of layer `id` at `depth` (None where it draws nothing); a folder's children are @@ -915,6 +1010,7 @@ fn plan_node<'a>( depth: usize, fields: Option<&'a Fields>, kids: bool, + cull: bool, ) -> Option> { let own: &'a Layer = inp.project.layers.get(&id)?; // Instances draw their source's content (a missing source draws nothing). @@ -941,7 +1037,9 @@ fn plan_node<'a>( let content = match &layer.kind { LayerKind::Paint => Content::Paint { preview: previews(inp, PaintTarget::Layer(layer.id)) }, LayerKind::Fill(f) => Content::Fill(f), - LayerKind::Group { children, .. } => Content::Group(if kids { plan(inp, children, channels, tx, ty, depth + 1, fields) } else { Vec::new() }), + LayerKind::Group { children, .. } => { + Content::Group(if kids { plan_with(inp, children, channels, tx, ty, depth + 1, fields, cull) } else { Vec::new() }) + } // `content_layer` already followed instance links. LayerKind::Instance { .. } => return None, }; @@ -988,8 +1086,8 @@ fn plan_levels<'a>(inp: &Inputs<'a>, levels: &[Level], channels: &[Channel], tx: .iter() .enumerate() .map(|(d, l)| LevelPlan { - below: if warm { Vec::new() } else { plan(inp, &l.below, channels, tx, ty, d, Some(fields)) }, - at: plan_node(inp, l.at, channels, tx, ty, d, Some(fields), d == last), + below: if warm { Vec::new() } else { plan_with(inp, &l.below, channels, tx, ty, d, Some(fields), true) }, + at: plan_node(inp, l.at, channels, tx, ty, d, Some(fields), d == last, false), above: plan(inp, &l.above, channels, tx, ty, d, Some(fields)), }) .collect() @@ -1658,6 +1756,35 @@ pub fn composite_tiles(inp: &Inputs, out: &mut Composite, tiles: &[(u32, u32)]) composite_tiles_cached(inp, out, tiles, None); } +/// The strides a coarse composite ([`composite_tiles_coarse`]) takes, coarsest first: texels +/// per block side, one evaluated per block. Each divides the rows of a band and a tile, so a +/// block never crosses bands or tiles. A big recomposite shows them in this order before the +/// exact composite. One level: a coarse pass costs about the same at any stride (writing, +/// padding and uploading the full-resolution tiles dominate once one texel in 64 is +/// evaluated; measured 4096², 3217 tiles: 139 ms at 16, 150 at 8, 254 at 4, 2.1 s exact), so +/// a second level would only add that cost again before the exact composite. +pub const COARSE_STRIDES: [u32; 1] = [8]; + +/// A quick look at `tiles`: [`composite_tiles`] evaluating one texel in every `stride` by `stride` +/// block (its first covered texel) and repeating it over the block's covered texels (a texel only +/// depends on its own position, so the evaluated ones are exact; the rest are as blocky as a +/// lower resolution), about `stride`² times fewer evaluations. A `stride` that does not divide a band and a tile composites exactly. A later +/// [`composite_tiles`] of the same tiles gives the exact result. +pub fn composite_tiles_coarse(inp: &Inputs, out: &mut Composite, tiles: &[(u32, u32)], stride: u32) { + let Ok(set) = inp.project.texture_set(inp.ts) else { return }; + if (inp.gbuf.width, inp.gbuf.height) != (out.resolution, out.height) { + return; + } + let step = if stride > 0 && BAND.is_multiple_of(stride) && TILE.is_multiple_of(stride) { stride } else { 1 }; + let mut blocks: BTreeMap<(u32, u32), Vec<(u32, u32)>> = BTreeMap::new(); + for t in tiles { + blocks.entry((t.1 / BLOCK, t.0 / BLOCK)).or_default().push(*t); + } + for block in blocks.values() { + composite_block(inp, &set.stack, out, block, None, 0, step); + } +} + /// Tiles per side of the blocks a composite works through (bounds neighbourhood-filter memory). const BLOCK: u32 = 16; @@ -1686,7 +1813,7 @@ pub fn composite_tiles_cached(inp: &Inputs, out: &mut Composite, tiles: &[(u32, None => 0, }; let cached = below.as_deref().zip(split.as_deref()); - let records = composite_block(inp, &set.stack, out, block, cached, quota); + let records = composite_block(inp, &set.stack, out, block, cached, quota, 1); if let Some(b) = below.as_deref_mut() { for t in block { b.touch(*t); @@ -1717,6 +1844,7 @@ fn composite_block( tiles: &[(u32, u32)], below: Option<(&BelowCache, &[Level])>, quota: usize, + step: u32, ) -> Vec<((u32, u32), Vec)> { let channels: Vec = inp.project.texture_set(inp.ts).map(|s| s.channel_list()).unwrap_or_default(); let (w, h) = (out.resolution, out.height); @@ -1746,7 +1874,7 @@ fn composite_block( let warm = cached((tx, ty)).and_then(|b| b.get(band as usize)); let record = warm.is_none() && recorded.contains(&(tx, ty)); let levels = split.map(|l| plan_levels(inp, l, &channels, tx, ty, &fields, warm.is_some())); - let nodes = if levels.is_none() { plan(inp, stack, &channels, tx, ty, 0, Some(&fields)) } else { Vec::new() }; + let nodes = if levels.is_none() { plan_with(inp, stack, &channels, tx, ty, 0, Some(&fields), true) } else { Vec::new() }; let rows = (BAND * TILE) as usize; let mut accs = vec![defaults; nlev]; let mut masks = vec![0.0f32; nlev]; @@ -1770,11 +1898,17 @@ fn composite_block( let mut bufs: Vec> = channels.iter().map(|c| vec![0u16; rows * c.components()]).collect(); let mut anchors = Vec::new(); let mut any = false; + // Coarse: per `step`-wide block of the current block row, the value of its first + // covered texel (evaluated), repeated over the block's other covered texels. + let mut sampled: Vec> = vec![None; if step > 1 { (TILE / step) as usize } else { 0 }]; for ly in band * BAND..(band + 1) * BAND { let y = ty * TILE + ly; if y >= h { break; } + if step > 1 && ly % step == 0 { + sampled.fill(None); + } for lx in 0..TILE { let x = tx * TILE + lx; if x >= w { @@ -1786,7 +1920,12 @@ fn composite_block( let ob = ((ly - band * BAND) * TILE + lx) as usize; let covered = inp.gbuf.tri.get(gi).is_some_and(|t| *t != NO_TRI); let mut acc = defaults; - if covered { + let block = if step > 1 { sampled.get_mut((lx / step) as usize) } else { None }; + let repeated = block.as_ref().and_then(|b| **b); + if covered && let Some(a) = repeated { + any = true; + acc = a; + } else if covered { any = true; let mut tex = Texel::new(inp, x, y, o, stroke_at(preview_tile, o)); // Reuse one anchor buffer per band. @@ -1818,6 +1957,12 @@ fn composite_block( anchors = tex.anchors; anchors.clear(); } + if covered + && repeated.is_none() + && let Some(slot) = block + { + *slot = Some(acc); + } for (l, buf) in lanes.iter().zip(&mut bufs) { let v = acc.get(l.ch).copied().unwrap_or([0.0; 3]); for (k, x) in v.iter().take(l.n).enumerate() { diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index fe57e611..3ec1ab94 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -19,7 +19,7 @@ pub mod store; pub use below::{BelowCache, StackKey}; pub use display::{DisplayKind, tile_bytes}; pub use eval::{ - Composite, Inputs, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles, effect_histogram, flatten_layer, - mask_at, mask_image, pad_tiles, + COARSE_STRIDES, Composite, Inputs, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, composite_tiles_coarse, + covered_tiles, effect_histogram, flatten_layer, has_neighbourhood_filters, mask_at, mask_image, pad_tiles, }; pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore}; diff --git a/crates/compose/tests/cache_and_instances.rs b/crates/compose/tests/cache_and_instances.rs index d7df0258..50d125a6 100644 --- a/crates/compose/tests/cache_and_instances.rs +++ b/crates/compose/tests/cache_and_instances.rs @@ -573,3 +573,35 @@ fn gathering_filters_composite_identically_in_any_grouping_and_cached() { assert!(!check_cached(&f, 0, hot).is_empty()); } } + +/// A folder that hides the layers below it but records an anchor point inside (under its own +/// hiding layer) keeps them: its inner stack starts from them, so the anchor holds them. +#[test] +fn layers_under_a_hiding_folder_with_an_anchor_are_not_culled() { + let mut f = fixture(); + let only = |f: &mut Fixture, id: LayerId, c: Channel| f.project.layer_mut(id).unwrap().channels.retain(|x, _| *x == c); + let low = add(&mut f, 0, fill(&[(Channel::BaseColor, Source::Uniform([0.9; 3]))]), None); + only(&mut f, low, Channel::BaseColor); + let group = add(&mut f, 0, LayerKind::Group { children: vec![], collapsed: false }, None); + // Inside: a half-opacity fill recording anchor A, then an opaque fill hiding everything. + let anchored = put(&mut f, 0, Some(group), fill(&[(Channel::BaseColor, Source::Uniform([0.5; 3]))]), None); + only(&mut f, anchored, Channel::BaseColor); + blend(&mut f, anchored, BlendMode::Normal, 0.5); + let anchor = effect(&mut f, EffectKind::Anchor); + let anchor_id = anchor.id; + f.project.layer_mut(anchored).unwrap().content_effects.push(anchor); + let hiding = put(&mut f, 0, Some(group), fill(&[(Channel::BaseColor, Source::Uniform([0.1; 3]))]), None); + only(&mut f, hiding, Channel::BaseColor); + // Above the folder, roughness reads the base color held by A. + let reader = add(&mut f, 0, fill(&[(Channel::Roughness, Source::Anchor { anchor: anchor_id, channel: Channel::BaseColor })]), None); + only(&mut f, reader, Channel::Roughness); + let out = reference(&f, 0); + let rough = out.value(Channel::Roughness, 128, 128)[0]; + // A = 0.5 at half opacity over the low layer's 0.9. + assert!((rough - 0.7).abs() < 2e-3, "the anchor holds the layer under the folder: {rough}"); + assert!((out.value(Channel::BaseColor, 128, 128)[0] - 0.1).abs() < 2e-3); + // The same stack with an (unread) anchor on the low layer is never culled: identical. + let keep = effect(&mut f, EffectKind::Anchor); + f.project.layer_mut(low).unwrap().content_effects.push(keep); + assert!(reference(&f, 0) == out, "culling changed the composite"); +} diff --git a/crates/core/src/blend.rs b/crates/core/src/blend.rs index 5f165cdb..c7fa7e64 100644 --- a/crates/core/src/blend.rs +++ b/crates/core/src/blend.rs @@ -350,6 +350,11 @@ pub fn blend3(mode: BlendMode, a: [f32; 3], b: [f32; 3]) -> [f32; 3] { /// Mix `blended` over `a` by weight `w` (coverage × opacity × mask). pub fn mix3(a: [f32; 3], blended: [f32; 3], w: f32) -> [f32; 3] { + // A full-weight blend is exactly the blended value (`a + (b - a)` can be an ulp off it): what + // lies under it does not leak in, so skipping the layers it hides changes nothing at all. + if w >= 1.0 { + return blended; + } [a[0] + (blended[0] - a[0]) * w, a[1] + (blended[1] - a[1]) * w, a[2] + (blended[2] - a[2]) * w] } diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 2db27946..603e7b17 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -193,5 +193,10 @@ pub fn session(s: &Session) -> Value { "history": { "undo": s.undo_label(), "redo": s.redo_label(), "depth": s.history_labels().len() }, "memoryBytes": s.memory().total(), "pendingTiles": s.pending_tiles(), + // Tiles with no look of the current composite yet, tiles shown from a coarse pass only + // (their exact composite pending), and the coarsest stride shown (0: none). + "dirtyTiles": s.caches.iter().map(|c| c.dirty.len()).sum::(), + "coarseTiles": s.caches.iter().map(|c| c.refine.len()).sum::(), + "coarsestStride": s.caches.iter().flat_map(|c| c.refine.values().copied()).max().unwrap_or(0), }) } diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 64ebec69..6b721a79 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -4,7 +4,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; use serde::{Deserialize, Serialize}; -use texturecraft_compose::{BakedMaps, BelowCache, Composite, PaintTarget, PixelStore, StackKey, StrokePreview, covered_tiles, pad_tiles}; +use texturecraft_compose::{BakedMaps, BelowCache, COARSE_STRIDES, Composite, PaintTarget, PixelStore, StackKey, StrokePreview, covered_tiles, pad_tiles}; use texturecraft_core::{Channel, Layer, LayerId, LayerKind, Project, TextureSet}; use texturecraft_geom::glam::Vec2; use texturecraft_geom::{Bvh, Mesh, OrbitCamera, UvGBuffer}; @@ -43,14 +43,24 @@ pub struct SetCache { /// Tiles to recomposite at low priority: what they show is already right (a committed /// stroke's live preview), but it was composited from the stroke, not the layer pixels. pub settle: BTreeSet<(u32, u32)>, + /// Tiles shown from a coarse pass ([`texturecraft_compose::composite_tiles_coarse`]) with + /// the stride they were composited at; they still need the finer ones and the exact one. A + /// big recomposite (a material applied) first looks right everywhere at a small part of the + /// cost, then sharpens level by level ([`texturecraft_compose::COARSE_STRIDES`]), each level + /// over every tile before the next, so the surface is always at one consistent level. + pub refine: BTreeMap<(u32, u32), u32>, + /// The dirty tiles go through a coarse pass: decided when a big recomposite starts and + /// kept until `dirty` drains, so its last few tiles do not go exact at the full price. + pub coarse_pass: bool, /// Tiles whose display textures must be re-uploaded. pub upload: BTreeSet<(u32, u32)>, /// Bumps on every composite change (thumbnails, exports, caches). pub revision: u64, /// Everything but the layer being edited, per tile (repaints evaluate only that layer). pub below: BelowCache, - /// Tiles per composite chunk that fit the last frame's budget (0: not measured yet). - pub chunk: usize, + /// Wall-clock milliseconds per tile of the last exact composite chunk (0: not measured + /// yet): the first chunk of a budgeted update is sized from it and that update's budget. + pub tile_ms: f64, } impl SetCache { @@ -69,10 +79,12 @@ impl SetCache { composite: Composite { block_scales: ts.block_scales(), ..Composite::with_size(&ts.channel_list(), w, h) }, dirty: all.clone(), settle: BTreeSet::new(), + refine: BTreeMap::new(), + coarse_pass: false, upload: all, revision: 0, below: BelowCache::default(), - chunk: 0, + tile_ms: 0.0, } } @@ -715,23 +727,60 @@ impl Session { carried: s.canvas.pickup.as_ref().map(|p| p.values.clone()).unwrap_or_default(), }) }); + // A coarse look first only when there is a frame budget to spread a big change over, and + // never under a live stroke (it keeps the exact, cached repaint of the hot layer). + let coarse_allowed = budget_ms.is_finite() && self.stroke.is_none(); let active = self.ts(); let order = std::iter::once(active).chain((0..self.caches.len()).filter(|ts| *ts != active)); let mut changed = false; for ts in order { let Some(cache) = self.caches.get_mut(ts) else { continue }; cache.below.set_hot(hot); - cache.below.pass = cache.dirty.len() + cache.settle.len(); + cache.below.pass = cache.dirty.len() + cache.settle.len() + cache.refine.len(); // Instances in sets of the stroke's size show the live stroke too. let preview = preview.as_ref().filter(|_| Some(cache.size) == stroke_size); - // Start at the size that fit the budget last time: with a heavy stack (smart - // materials at 8K) one tile per thread alone would take several frames' budget. - let mut chunk = if budget_ms.is_finite() && cache.chunk > 0 { cache.chunk } else { first }; + // Start at the size this budget fits at the last measured pace: with a heavy stack + // (smart materials at 8K) one tile per thread alone would take several frames' + // budget. Never above one tile per thread: work can turn heavy from one frame to the + // next. + let exact_chunk = + |cache: &SetCache| if budget_ms.is_finite() && cache.tile_ms > 0.0 { ((budget_ms / cache.tile_ms) as usize).clamp(1, first) } else { first }; + let mut chunk = exact_chunk(cache); + // A stack with neighbourhood filters computes them at full resolution even for a + // coarse composite, so it gains little from one: straight to the exact composite. + let may_coarse = coarse_allowed && !cache.dirty.is_empty() && !texturecraft_compose::has_neighbourhood_filters(&self.doc.project, ts); + // The stride of the previous chunk (1: exact), to restart the chunk size on a change. + let mut last_stride = 1; loop { if cache.dirty.is_empty() { - if cache.settle.is_empty() || clock() - start >= budget_ms.min(SETTLE_BUDGET_MS) { - break; + cache.coarse_pass = false; + } + // The work of this chunk: fresh dirty tiles (coarsest look or exact), the next + // level of the coarsest refining tiles, or settling tiles. + let (stride, refining, settling): (u32, Option, bool) = if !cache.dirty.is_empty() { + // A big change gets a coarse look first, for the whole of it. + if may_coarse && cache.dirty.len() > COARSE_MIN_TILES { + cache.coarse_pass = true; } + let coarse = may_coarse && cache.coarse_pass; + (if coarse { COARSE_STRIDES[0] } else { 1 }, None, false) + } else if let Some(at) = cache.refine.values().copied().max() { + (finer_stride(at), Some(at), false) + } else if !cache.settle.is_empty() && clock() - start < budget_ms.min(SETTLE_BUDGET_MS) { + (1, None, true) + } else { + break; + }; + // A level costs about its stride² less per texel than the exact composite: a + // new level starts at the exact pace, and the chunks grow from what it measures. + if stride != last_stride { + chunk = exact_chunk(cache); + last_stride = stride; + } + if let Some(at) = refining { + let mut level: BTreeSet<(u32, u32)> = cache.refine.iter().filter(|(_, s)| **s == at).map(|(t, _)| *t).collect(); + cache.dirty.extend(next_chunk(&mut level, chunk)); + } else if settling { // Small chunks: the settle slice of the budget is short. cache.dirty.extend(next_chunk(&mut cache.settle, chunk.min(first))); } @@ -739,6 +788,7 @@ impl Session { let tiles = next_chunk(&mut cache.dirty, chunk); for t in &tiles { cache.settle.remove(t); + cache.refine.remove(t); } let empty = BakedMaps::default(); let inputs = texturecraft_compose::Inputs { @@ -753,7 +803,12 @@ impl Session { images: &self.images, bounds: self.mesh.bounds(), }; - texturecraft_compose::composite_tiles_cached(&inputs, &mut cache.composite, &tiles, Some(&mut cache.below)); + if stride > 1 { + texturecraft_compose::composite_tiles_coarse(&inputs, &mut cache.composite, &tiles, stride); + cache.refine.extend(tiles.iter().map(|t| (*t, stride))); + } else { + texturecraft_compose::composite_tiles_cached(&inputs, &mut cache.composite, &tiles, Some(&mut cache.below)); + } // The composited tiles and the neighbours their padding reached change. let padded = pad_tiles(&mut cache.composite, &cache.dilation, &tiles); cache.upload.extend(tiles.iter().copied().chain(padded)); @@ -763,9 +818,8 @@ impl Session { let left = budget_ms - (now - start); // As many tiles as fit in what is left, at the pace of this chunk. let per_tile = (now - t0) / tiles.len().max(1) as f64; - if budget_ms.is_finite() && per_tile > 0.0 { - // Never above one tile per thread: work can turn heavy from one frame to the next. - cache.chunk = ((budget_ms / per_tile) as usize).clamp(1, first); + if budget_ms.is_finite() && per_tile > 0.0 && stride == 1 { + cache.tile_ms = per_tile; } if left <= 0.0 { return changed; @@ -782,7 +836,7 @@ impl Session { /// Tiles still waiting to be composited, over every texture set (settling ones included). pub fn pending_tiles(&self) -> usize { - self.caches.iter().map(|c| c.dirty.len() + c.settle.len()).sum() + self.caches.iter().map(|c| c.dirty.len() + c.settle.len() + c.refine.len()).sum() } /// The layer a stroke target belongs to (an effect's owner). @@ -894,6 +948,9 @@ impl Memory { /// Most tiles per composite chunk (a 1024² region). const CHUNK: usize = 256; +/// A recomposite of more tiles than this (a material applied, not a brush stroke) is shown from +/// a coarse pass first when it is spread over frames. +const COARSE_MIN_TILES: usize = 64; /// The most a budgeted update spends on settling tiles (what they show is already right). pub const SETTLE_BUDGET_MS: f64 = 6.0; @@ -912,6 +969,11 @@ fn next_chunk(dirty: &mut BTreeSet<(u32, u32)>, n: usize) -> Vec<(u32, u32)> { tiles } +/// The stride of the level after `stride` in [`COARSE_STRIDES`] (1: the exact composite). +fn finer_stride(stride: u32) -> u32 { + COARSE_STRIDES.iter().copied().find(|s| *s < stride).unwrap_or(1) +} + /// Valid texture set resolutions: powers of two from 128 to 8192. pub fn check_resolution(r: u32) -> Result { if (128..=8192).contains(&r) && r.is_power_of_two() { diff --git a/crates/engine/tests/it/instances.rs b/crates/engine/tests/it/instances.rs index b9f14bcd..f3a1b594 100644 --- a/crates/engine/tests/it/instances.rs +++ b/crates/engine/tests/it/instances.rs @@ -220,10 +220,12 @@ fn budgeted_updates_spread_work_and_end_identical() { s.caches[0].invalidate_all(); // A clock that is always over budget: one chunk per call. let mut calls = 0; + // Progress: a tile is two steps from done while dirty (coarse look, then exact), one when refining. + let steps = |s: &texturecraft_engine::Session| 2 * s.caches[0].dirty.len() + s.caches[0].refine.len() + s.caches[0].settle.len(); while s.pending_tiles() > 0 { - let before = s.pending_tiles(); + let before = steps(&s); s.update_for(0.0, || 1.0); - assert!(s.pending_tiles() < before); + assert!(steps(&s) < before); calls += 1; } assert!(calls > 1, "the work was spread over calls"); diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 4dd04032..89f27beb 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -446,3 +446,166 @@ fn curvature_generators_take_a_mode_and_detail_sizes() { assert!(dirt.is_err(), "only curvature generators have a mode"); assert_eq!(execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string(), inspect, "failed commands leave the project unchanged"); } + +/// A material applied over frames first looks right everywhere from a coarse pass (the sampled +/// texels are exact, the rest repeat them), then the tiles fill in to the exact composite. +#[test] +fn a_big_recomposite_shows_a_coarse_look_first_then_the_exact_one() { + let make = || { + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 2048).unwrap(); + s.viewport = texturecraft_engine::geom::glam::Vec2::new(400.0, 400.0); + s.update(); + execute(&mut s, "material.apply", &json!({"material": "steel_painted_worn"})).unwrap(); + s + }; + let mut exact = make(); + exact.update(); + assert_eq!(exact.pending_tiles(), 0, "an unbudgeted update goes straight to the exact composite"); + let exact = exact.caches[0].composite.clone(); + + let mut s = make(); + let t = std::cell::Cell::new(0.0); + let clock = || { + t.set(t.get() + 2.0); + t.get() + }; + let covered = s.caches[0].covered_tiles.len(); + assert!(covered > 100, "a big change: {covered} tiles"); + while !s.caches[0].dirty.is_empty() { + s.update_for(30.0, clock); + } + assert!(s.caches[0].refine.len() > 100 && s.pending_tiles() > 0, "everything has a coarse look, the exact one is pending"); + let coarse = s.caches[0].composite.clone(); + assert_ne!(coarse, exact, "the coarse look is not the exact one"); + // Where the coarse pass sampled (a block's first covered texel, its corner where covered), it + // is exact; the others repeat the sample of their block. + let c = Channel::BaseColor; + let stride = texturecraft_engine::compose::COARSE_STRIDES[0]; + let (mut sampled, mut repeated, mut checked) = (0, 0, 0); + for y in (0..2048).step_by(7) { + for x in (0..2048).step_by(5) { + let (ax, ay) = (x - x % stride, y - y % stride); + if x == ax && y == ay { + if coarse.value(c, x, y) == exact.value(c, x, y) { + sampled += 1; + } + checked += 1; + } else if coarse.value(c, x, y) == coarse.value(c, ax, ay) { + repeated += 1; + } + } + } + assert!(checked > 100 && sampled * 10 >= checked * 9, "sampled texels are exact: {sampled} of {checked}"); + assert!(repeated > 1000, "the others repeat their sample: {repeated}"); + while s.pending_tiles() > 0 { + s.update_for(30.0, clock); + } + assert_eq!(s.caches[0].composite, exact, "the refined composite is the exact one"); +} + +/// Layers an opaque layer above hides are not evaluated: a material applied over others +/// composites exactly like the same material applied alone, in the channels it sets. +#[test] +fn layers_hidden_by_an_opaque_material_are_left_out_without_changing_the_result() { + let make = |materials: &[&str]| { + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 512).unwrap(); + s.viewport = texturecraft_engine::geom::glam::Vec2::new(400.0, 400.0); + for m in materials { + execute(&mut s, "material.apply", &json!({"material": m})).unwrap(); + } + s.update(); + s.caches[0].composite.clone() + }; + let alone = make(&["gold_polished"]); + let stacked = make(&["steel_painted_worn", "copper", "gold_polished"]); + let underneath = make(&["steel_painted_worn", "copper"]); + assert_ne!(alone, underneath, "the materials differ"); + for c in [Channel::BaseColor, Channel::Roughness, Channel::Metallic] { + let (mut compared, mut differing) = (0, 0); + for y in (0..512).step_by(3) { + for x in (0..512).step_by(3) { + compared += 1; + if alone.value(c, x, y) != stacked.value(c, x, y) { + differing += 1; + } + } + } + assert!(compared > 1000 && differing == 0, "{c:?}: {differing} of {compared} texels differ"); + } +} + +/// A clock that advances 2 ms per reading, for budgeted updates. +fn ticking() -> impl Fn() -> f64 { + let t = std::cell::Cell::new(0.0); + move || { + t.set(t.get() + 2.0); + t.get() + } +} + +/// A big change goes through the coarse pass to its last tile (the decision is kept for the +/// whole pass): its tail does not go exact at the full price while the rest waits for detail. +#[test] +fn the_coarse_pass_covers_every_tile_of_a_big_change() { + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 1024).unwrap(); + s.update(); + execute(&mut s, "material.apply", &json!({"material": "steel_painted_worn"})).unwrap(); + let dirty = s.caches[0].dirty.len(); + assert!(dirty > 100, "a big change: {dirty} tiles"); + // A clock always over budget: one chunk per call. + let mut calls = 0; + while !s.caches[0].dirty.is_empty() { + s.update_for(0.0, || 1.0); + let c = &s.caches[0]; + assert_eq!(c.refine.len() + c.dirty.len(), dirty, "no tile went exact during the coarse pass"); + calls += 1; + } + assert!(calls > 1, "the pass was spread over calls"); + s.update_for(0.0, || 1.0); + assert!(!s.caches[0].coarse_pass, "the pass ended with its tiles"); + let clock = ticking(); + // A small change after it goes straight to the exact composite. + let some: Vec<(u32, u32)> = s.caches[0].covered_tiles.iter().copied().take(10).collect(); + s.update(); + s.caches[0].dirty.extend(some); + s.update_for(30.0, &clock); + assert!(s.caches[0].refine.is_empty() && s.caches[0].dirty.is_empty(), "a few tiles are composited exactly"); +} + +/// Under a live stroke the compositor keeps the exact (cached) repaint: no coarse pass. +#[test] +fn no_coarse_pass_while_a_stroke_is_live() { + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 1024).unwrap(); + s.update(); + s.begin_stroke_uv(texturecraft_engine::geom::glam::Vec2::new(0.5, 0.5), 1.0).unwrap(); + s.caches[0].invalidate_all(); + assert!(s.caches[0].dirty.len() > 100); + let clock = ticking(); + while !s.caches[0].dirty.is_empty() { + s.update_for(30.0, &clock); + assert!(s.caches[0].refine.is_empty(), "nothing went coarse under the stroke"); + } + s.end_stroke().unwrap(); +} + +/// A stack with a neighbourhood filter (blur) computes it at full resolution even for a coarse +/// look, which then saves little: such a stack goes straight to the exact composite. +#[test] +fn stacks_with_neighbourhood_filters_skip_the_coarse_pass() { + use texturecraft_engine::core::{Effect, EffectKind, Filter}; + let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 1024).unwrap(); + s.update(); + execute(&mut s, "material.apply", &json!({"material": "copper"})).unwrap(); + s.update(); + assert!(!texturecraft_engine::compose::has_neighbourhood_filters(&s.doc.project, 0)); + let top = *s.doc.project.texture_sets[0].stack.last().unwrap(); + let id = s.doc.project.alloc_id(); + s.doc.project.layer_mut(top).unwrap().content_effects.push(Effect::new(id, EffectKind::Filter(Filter::Blur { radius: 8.0 }))); + assert!(texturecraft_engine::compose::has_neighbourhood_filters(&s.doc.project, 0)); + s.caches[0].invalidate_all(); + let clock = ticking(); + while !s.caches[0].dirty.is_empty() { + s.update_for(30.0, &clock); + assert!(s.caches[0].refine.is_empty(), "nothing went coarse"); + } +} diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index 944a8ecd..7811577b 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -93,11 +93,29 @@ pub struct GpuLink { pub adapter: String, /// Most tiles waiting to be composited since compositing last caught up (progress). composite_total: usize, + /// Consecutive frames without user input (see [`frame_budgets`]). + idle_frames: u32, bake_scene: BakeSceneLink, } -/// Compositing time per frame: a full recomposite of a large texture set spreads over frames. +/// The compositing and whole-frame budgets in milliseconds after `idle_frames` frames without +/// user input: the responsive pair while the user works, the longer pair once they have stopped. +fn frame_budgets(idle_frames: u32) -> (f64, f64) { + if idle_frames >= IDLE_FRAMES_BEFORE_BOOST { (IDLE_COMPOSITE_BUDGET_MS, IDLE_FRAME_BUDGET_MS) } else { (COMPOSITE_BUDGET_MS, FRAME_BUDGET_MS) } +} + +/// Compositing time per frame while the user is working: a full recomposite of a large texture +/// set spreads over frames. const COMPOSITE_BUDGET_MS: f64 = 30.0; +/// Compositing time per frame once the user has stopped touching the app: the compositor scales +/// with the machine's cores, so a longer slice finishes sooner on a fast PC (a frame then takes +/// longer, but nothing is being dragged or painted that would feel it). +const IDLE_COMPOSITE_BUDGET_MS: f64 = 100.0; +/// [`FRAME_BUDGET_MS`] while idle: the idle compositing slice plus the usual rest of the frame. +const IDLE_FRAME_BUDGET_MS: f64 = IDLE_COMPOSITE_BUDGET_MS + (FRAME_BUDGET_MS - COMPOSITE_BUDGET_MS); +/// Frames without input (about 0.2 s at 60 fps) before the longer idle slices start, so a short +/// pause between strokes or drags keeps the responsive budget. +const IDLE_FRAMES_BEFORE_BOOST: u32 = 12; /// The most a frame spends on the scene (with the work already done this frame, such as a /// stroke's commit): compositing and display conversion leave the rest for the next frames, so /// a large (8K) texture set never stalls one frame. @@ -109,6 +127,10 @@ const UPLOAD_CHUNK: usize = 64; /// 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; +/// CPU cost of converting one display tile of one kind for upload ([`tile_bytes`], measured at +/// ~6 µs: 8192 in 50 ms on a 24-thread desktop): with [`UPLOAD_MS_PER_TILE`], what a tile still +/// waiting for upload will cost this frame. +const CONVERT_MS_PER_TILE: f64 = 0.006; pub fn init(rs: &egui_wgpu::RenderState, ctx: &egui::Context) -> GpuLink { let reset = Arc::new(AtomicBool::new(false)); @@ -140,6 +162,7 @@ pub fn init(rs: &egui_wgpu::RenderState, ctx: &egui::Context) -> GpuLink { aux: BTreeMap::new(), adapter: format!("{} ({:?})", info.name, info.backend), composite_total: 0, + idle_frames: 0, bake_scene: BakeSceneLink::default(), } } @@ -162,13 +185,28 @@ impl GpuLink { } /// Collect everything the GPU needs this frame, running the compositor first: `bake` is what bake mode's 3D view draws besides the low poly, `spent_ms` the time this frame already took - pub fn sync(&mut self, session: &mut Session, aux_map: Option, bake: Option, shift: u32, spent_ms: f64) -> SceneSync { + pub fn sync( + &mut self, + session: &mut Session, + aux_map: Option, + bake: Option, + shift: u32, + spent_ms: f64, + user_active: bool, + ) -> SceneSync { let start_ms = crate::now_ms(); let mut queued = 0usize; - let time_left_ms = |queued: usize| FRAME_BUDGET_MS - spent_ms - (crate::now_ms() - start_ms) - queued as f64 * UPLOAD_MS_PER_TILE; + self.idle_frames = if user_active { 0 } else { self.idle_frames.saturating_add(1) }; + let (composite_budget_ms, frame_budget_ms) = frame_budgets(self.idle_frames); + let time_left_ms = |queued: usize| frame_budget_ms - spent_ms - (crate::now_ms() - start_ms) - queued as f64 * UPLOAD_MS_PER_TILE; let pending = session.pending_tiles(); self.composite_total = if pending == 0 { 0 } else { self.composite_total.max(pending) }; - session.update_for(COMPOSITE_BUDGET_MS.min(time_left_ms(0)).max(MIN_SLICE_MS), crate::now_ms); + // Tiles composited earlier and still waiting to be uploaded go first: a big change's + // coarse look is composited in a frame or two, and showing it whole matters more than + // compositing on (otherwise it appears a chunk of tiles per frame). + let backlog = session.caches.iter().map(|c| c.upload.len()).sum::() * DisplayKind::ALL.len(); + let backlog_ms = backlog as f64 * (UPLOAD_MS_PER_TILE + CONVERT_MS_PER_TILE); + session.update_for(composite_budget_ms.min(time_left_ms(0) - backlog_ms).max(MIN_SLICE_MS), crate::now_ms); let mut out = SceneSync::default(); if self.lost.swap(false, Ordering::AcqRel) { @@ -410,3 +448,26 @@ impl CallbackTrait for ViewCallback { gpu.renderer.blit_prepared(pass, self.frame.view_id); } } + +#[cfg(test)] +mod tests { + use super::*; + + /// While the user is working (or just stopped) a frame keeps the responsive budgets. + #[test] + fn budgets_stay_short_while_the_user_is_active() { + assert_eq!(frame_budgets(0), (COMPOSITE_BUDGET_MS, FRAME_BUDGET_MS)); + assert_eq!(frame_budgets(IDLE_FRAMES_BEFORE_BOOST - 1), (COMPOSITE_BUDGET_MS, FRAME_BUDGET_MS)); + } + + /// After a pause the compositor gets the longer slice, and the frame budget grows with it so the + /// display uploads keep their usual share. + #[test] + fn budgets_grow_once_the_user_is_idle() { + let (composite, frame) = frame_budgets(IDLE_FRAMES_BEFORE_BOOST); + assert_eq!(composite, IDLE_COMPOSITE_BUDGET_MS); + assert!(composite > COMPOSITE_BUDGET_MS); + assert_eq!(frame - composite, FRAME_BUDGET_MS - COMPOSITE_BUDGET_MS, "the non-compositing share of a frame is unchanged"); + assert_eq!(frame_budgets(u32::MAX), (composite, frame), "stays boosted"); + } +} diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index f3087537..be6c87da 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -317,7 +317,11 @@ fn add_callback(app: &mut TextureCraftApp, ui: &Ui, rect: Rect, mut frame: Frame let scene = match (sync.0.take(), app.gpu.as_mut()) { (Some(aux), Some(gpu_link)) => { let sync_start_ms = crate::now_ms(); - let scene = gpu_link.sync(&mut app.session, aux, bake, u32::from(app.ui.prefs.viewport_texture.min(2)), f64::from(app.profiler.logic_ms)); + // Pointer, key and scroll input all count: the compositor then keeps frames short. + let user_active = + ui.ctx().input(|i| i.pointer.is_moving() || i.pointer.any_down() || !i.events.is_empty() || i.smooth_scroll_delta != egui::Vec2::ZERO); + let scene = + gpu_link.sync(&mut app.session, aux, bake, u32::from(app.ui.prefs.viewport_texture.min(2)), f64::from(app.profiler.logic_ms), user_active); let reports = gpu_link.take_reports(); app.profiler.sync_ms += (crate::now_ms() - sync_start_ms) as f32; gpu_report_toasts(app, reports); From 9de96cfee4dcfab788f2ba981dfd23a6e7c69eb3 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Tue, 10 Nov 2026 14:30:38 +0100 Subject: [PATCH 46/64] FreeBSD CI: run the GPU crates' tests one at a time (#379) * FreeBSD CI: run the GPU crates' tests one at a time The FreeBSD VM's software Vulkan driver crashes (SIGSEGV) when several tests create a wgpu device at once. texturecraft-render's lib and headless tests, and earlier texturecraft-automation's, died this way in every FreeBSD run since Nov 6, with no render or dependency change. photocraft already serializes its GPU tests for the same reason; do the same for the crates that open a device. * FreeBSD CI: test the whole workspace one test at a time Excluding the GPU crates from the parallel run changed feature unification, and winit then built without its X11/Wayland backends (compile_error on FreeBSD). Run the whole workspace in one cargo test with --test-threads=1 instead. --- .github/workflows/freebsd.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/freebsd.yml b/.github/workflows/freebsd.yml index 9f64bbdd..442b9fd7 100644 --- a/.github/workflows/freebsd.yml +++ b/.github/workflows/freebsd.yml @@ -33,4 +33,9 @@ jobs: uses: storytold/craft-common-actions/.github/workflows/freebsd.yml@main with: craft-fonts-ref: aced4137c022f1f587624d48e81ec77e1914a9cc + # The VM's software Vulkan driver crashes (SIGSEGV) when several tests set up a device at + # once (photocraft serializes its GPU tests for the same reason), so tests run one at a + # time. The whole workspace is tested in one command: excluding packages would change + # feature unification and build winit without its X11/Wayland backends. + cargo-test-extra-args: "-- --test-threads=1" run-package-check: true From 4a3e5c41b443ca744181fee97105f6423f788038 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Tue, 10 Nov 2026 20:44:42 +0100 Subject: [PATCH 47/64] Return test setup errors before assertions --- crates/engine/src/thumbs.rs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/crates/engine/src/thumbs.rs b/crates/engine/src/thumbs.rs index ba655be7..6cd6e2a2 100644 --- a/crates/engine/src/thumbs.rs +++ b/crates/engine/src/thumbs.rs @@ -431,8 +431,8 @@ mod tests { use texturecraft_core::Channel; use texturecraft_geom::primitives; - fn test_session() -> Session { - Session::new_project("thumb", primitives::plane(1.0, 1), "builtin:plane", None, 128).unwrap() + fn test_session() -> crate::Result { + Session::new_project("thumb", primitives::plane(1.0, 1), "builtin:plane", None, 128) } fn held_worker() -> (ThumbService, std::sync::mpsc::Receiver, std::sync::mpsc::Sender) { @@ -444,7 +444,7 @@ mod tests { #[test] fn unchanged_baked_handles_match_even_with_non_finite_samples() { - let mut session = test_session(); + let mut session = test_session().unwrap(); let baked = session.doc.baked.entry(0).or_default(); baked.resolution = 1; baked.maps.insert(texturecraft_core::BakedMap::Height, Arc::new(vec![f32::NAN])); @@ -460,7 +460,7 @@ mod tests { #[test] #[ignore] fn benchmark_unchanged_4k_baked_snapshot() { - let mut session = test_session(); + let mut session = test_session().unwrap(); let baked = session.doc.baked.entry(0).or_default(); baked.resolution = 4096; baked.maps.insert(texturecraft_core::BakedMap::Normal, Arc::new(vec![0.5; 4096 * 4096 * 3])); @@ -477,7 +477,7 @@ mod tests { #[test] fn collecting_the_last_result_requests_a_frame_to_display_it() { - let session = test_session(); + 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.begin_frame(&session, 0.0); @@ -499,7 +499,7 @@ mod tests { #[test] fn a_stopped_worker_retries_visible_targets_inline() { - let session = test_session(); + 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.begin_frame(&session, 0.0); @@ -521,7 +521,7 @@ mod tests { #[test] fn edits_keep_worker_jobs_and_retained_snapshots_bounded() { - let mut session = test_session(); + let mut session = test_session().unwrap(); let layer = session.selected_layer().unwrap(); let target = ThumbTarget::Content { layer, channel: Channel::BaseColor }; let (mut service, jobs, results) = held_worker(); From d664dc239cd005b4ff7b0ea9f17bf2ad02809cdd Mon Sep 17 00:00:00 2001 From: Chris Hassebrook Date: Tue, 10 Nov 2026 16:08:27 -0500 Subject: [PATCH 48/64] Revert "Show a whole material at once: coarse first look, then the exact result" --- crates/compose/src/eval.rs | 159 +------------------ crates/compose/src/lib.rs | 4 +- crates/compose/tests/cache_and_instances.rs | 32 ---- crates/core/src/blend.rs | 5 - crates/engine/src/inspect.rs | 5 - crates/engine/src/session.rs | 92 ++--------- crates/engine/tests/it/instances.rs | 6 +- crates/engine/tests/session.rs | 163 -------------------- crates/ui-egui/src/gpu.rs | 69 +-------- crates/ui-egui/src/viewport.rs | 6 +- 10 files changed, 31 insertions(+), 510 deletions(-) diff --git a/crates/compose/src/eval.rs b/crates/compose/src/eval.rs index a60beb6f..b8299438 100644 --- a/crates/compose/src/eval.rs +++ b/crates/compose/src/eval.rs @@ -803,22 +803,6 @@ fn fields_of(inp: &Inputs, channels: &[Channel], list: &[LayerId], tiles: &[(u32 out } -/// Whether texture set `ts` has a layer with a neighbourhood filter (blur, sharpen, warp…) in -/// its mask or content: a composite then precomputes [`neighbourhood_fields`] at full -/// resolution, so even a [`composite_tiles_coarse`] is not much cheaper than the exact one. -/// The same layers as `neighbourhood_fields` looks at (it may count a hidden one). -pub fn has_neighbourhood_filters(project: &Project, ts: usize) -> bool { - let Ok(set) = project.texture_set(ts) else { return false }; - let mut order = Vec::new(); - draw_order(project, &set.stack, 0, &mut order); - let res = set.resolution; - order.iter().any(|id| { - let mask = layer_mask(project, *id).is_some_and(|m| m.enabled && neighbourhood(&m.effects, res).is_some()); - let content = project.content_layer(*id).is_some_and(|l| !l.is_group() && neighbourhood(&l.content_effects, res).is_some()); - mask || content - }) -} - /// Build the curvature detail sizes every visible generator of `layers` reads, once, before tiles composite in parallel. fn prepare_curvature_sizes(inp: &Inputs, layers: &[LayerId]) { let visible = layers.iter().filter(|id| inp.project.layers.get(id).is_some_and(|layer| layer.visible)); @@ -915,89 +899,10 @@ fn mask_plan<'a>(inp: &Inputs<'a>, id: LayerId, mask: &'a Mask, tx: u32, ty: u32 } fn plan<'a>(inp: &Inputs<'a>, list: &[LayerId], channels: &[Channel], tx: u32, ty: u32, depth: usize, fields: Option<&'a Fields>) -> Vec> { - plan_with(inp, list, channels, tx, ty, depth, fields, false) -} - -/// [`plan`], leaving out what an opaque layer above hides when `cull` (see [`cull_hidden`]). -/// Only for lists that are evaluated whole and not looked into (no anchor or stop layer reads). -#[allow(clippy::too_many_arguments)] -fn plan_with<'a>( - inp: &Inputs<'a>, - list: &[LayerId], - channels: &[Channel], - tx: u32, - ty: u32, - depth: usize, - fields: Option<&'a Fields>, - cull: bool, -) -> Vec> { if depth > texturecraft_core::project::MAX_DEPTH { return Vec::new(); } - let mut nodes: Vec> = list.iter().filter_map(|id| plan_node(inp, *id, channels, tx, ty, depth, fields, true, cull)).collect(); - if cull { - cull_hidden(&mut nodes, channels); - } - nodes -} - -/// Whether node `n` hides everything below it in channel `ch`: it replaces the stack there at -/// every texel (full opacity, normal blend, no mask or geometry or height mask, a fill that -/// covers the whole surface with no content effects), or is a folder at full opacity holding -/// such a layer. -fn occludes(n: &Node, ch: usize) -> bool { - if n.mask.is_some() || n.parts.is_some() || n.height_mask.enabled { - return false; - } - let Some(c) = n.chans.iter().find(|c| c.ch == ch) else { return false }; - if c.opacity < 1.0 { - return false; - } - match &n.content { - Content::Fill(f) => c.blend == BlendMode::Normal && !matches!(f.projection, Projection::Decal(_)) && c.effects.is_empty() && c.start.is_none(), - Content::Group(kids) => kids.iter().any(|k| occludes(k, ch)), - Content::Paint { .. } => false, - } -} - -/// Whether `n` or a layer in it masks with its height. -fn uses_height_mask(n: &Node) -> bool { - n.height_mask.enabled || matches!(&n.content, Content::Group(kids) if kids.iter().any(uses_height_mask)) -} - -/// Take channel `ch` out of `n` (and what it holds), dropping what then draws nothing. -fn strip_channel(n: &mut Node, ch: usize) { - n.chans.retain(|c| c.ch != ch); - if let Content::Group(kids) = &mut n.content { - for k in kids.iter_mut() { - strip_channel(k, ch); - } - kids.retain(|k| !k.chans.is_empty()); - } -} - -/// Leave out the layers (per channel) that a layer above them hides completely: a stack that -/// grows by applying material after material would otherwise evaluate every one of them. The -/// result is identical. Channels with anchor points or height masks below the hiding layer -/// are left alone (they read other layers' values), and so are those under a hiding folder -/// that records an anchor point: its inner stack starts from what lies below it, so an anchor -/// under the hiding layer inside it holds the layers it hides. -fn cull_hidden(nodes: &mut Vec, channels: &[Channel]) { - for c in channels { - let ch = c.index(); - let Some(k) = nodes.iter().rposition(|n| occludes(n, ch)) else { continue }; - if nodes.get(k).is_some_and(|n| n.has_anchor) { - continue; - } - let Some(below) = nodes.get_mut(..k) else { continue }; - if below.iter().any(|n| n.has_anchor || (*c == Channel::Height && uses_height_mask(n))) { - continue; - } - for n in below.iter_mut() { - strip_channel(n, ch); - } - } - nodes.retain(|n| !n.chans.is_empty() || n.has_anchor); + list.iter().filter_map(|id| plan_node(inp, *id, channels, tx, ty, depth, fields, true)).collect() } /// The plan of layer `id` at `depth` (None where it draws nothing); a folder's children are @@ -1012,7 +917,6 @@ fn plan_node<'a>( depth: usize, fields: Option<&'a Fields>, kids: bool, - cull: bool, ) -> Option> { let own: &'a Layer = inp.project.layers.get(&id)?; // Instances draw their source's content (a missing source draws nothing). @@ -1039,9 +943,7 @@ fn plan_node<'a>( let content = match &layer.kind { LayerKind::Paint => Content::Paint { preview: previews(inp, PaintTarget::Layer(layer.id)) }, LayerKind::Fill(f) => Content::Fill(f), - LayerKind::Group { children, .. } => { - Content::Group(if kids { plan_with(inp, children, channels, tx, ty, depth + 1, fields, cull) } else { Vec::new() }) - } + LayerKind::Group { children, .. } => Content::Group(if kids { plan(inp, children, channels, tx, ty, depth + 1, fields) } else { Vec::new() }), // `content_layer` already followed instance links. LayerKind::Instance { .. } => return None, }; @@ -1088,8 +990,8 @@ fn plan_levels<'a>(inp: &Inputs<'a>, levels: &[Level], channels: &[Channel], tx: .iter() .enumerate() .map(|(d, l)| LevelPlan { - below: if warm { Vec::new() } else { plan_with(inp, &l.below, channels, tx, ty, d, Some(fields), true) }, - at: plan_node(inp, l.at, channels, tx, ty, d, Some(fields), d == last, false), + below: if warm { Vec::new() } else { plan(inp, &l.below, channels, tx, ty, d, Some(fields)) }, + at: plan_node(inp, l.at, channels, tx, ty, d, Some(fields), d == last), above: plan(inp, &l.above, channels, tx, ty, d, Some(fields)), }) .collect() @@ -1758,35 +1660,6 @@ pub fn composite_tiles(inp: &Inputs, out: &mut Composite, tiles: &[(u32, u32)]) composite_tiles_cached(inp, out, tiles, None); } -/// The strides a coarse composite ([`composite_tiles_coarse`]) takes, coarsest first: texels -/// per block side, one evaluated per block. Each divides the rows of a band and a tile, so a -/// block never crosses bands or tiles. A big recomposite shows them in this order before the -/// exact composite. One level: a coarse pass costs about the same at any stride (writing, -/// padding and uploading the full-resolution tiles dominate once one texel in 64 is -/// evaluated; measured 4096², 3217 tiles: 139 ms at 16, 150 at 8, 254 at 4, 2.1 s exact), so -/// a second level would only add that cost again before the exact composite. -pub const COARSE_STRIDES: [u32; 1] = [8]; - -/// A quick look at `tiles`: [`composite_tiles`] evaluating one texel in every `stride` by `stride` -/// block (its first covered texel) and repeating it over the block's covered texels (a texel only -/// depends on its own position, so the evaluated ones are exact; the rest are as blocky as a -/// lower resolution), about `stride`² times fewer evaluations. A `stride` that does not divide a band and a tile composites exactly. A later -/// [`composite_tiles`] of the same tiles gives the exact result. -pub fn composite_tiles_coarse(inp: &Inputs, out: &mut Composite, tiles: &[(u32, u32)], stride: u32) { - let Ok(set) = inp.project.texture_set(inp.ts) else { return }; - if (inp.gbuf.width, inp.gbuf.height) != (out.resolution, out.height) { - return; - } - let step = if stride > 0 && BAND.is_multiple_of(stride) && TILE.is_multiple_of(stride) { stride } else { 1 }; - let mut blocks: BTreeMap<(u32, u32), Vec<(u32, u32)>> = BTreeMap::new(); - for t in tiles { - blocks.entry((t.1 / BLOCK, t.0 / BLOCK)).or_default().push(*t); - } - for block in blocks.values() { - composite_block(inp, &set.stack, out, block, None, 0, step); - } -} - /// Tiles per side of the blocks a composite works through (bounds neighbourhood-filter memory). const BLOCK: u32 = 16; @@ -1815,7 +1688,7 @@ pub fn composite_tiles_cached(inp: &Inputs, out: &mut Composite, tiles: &[(u32, None => 0, }; let cached = below.as_deref().zip(split.as_deref()); - let records = composite_block(inp, &set.stack, out, block, cached, quota, 1); + let records = composite_block(inp, &set.stack, out, block, cached, quota); if let Some(b) = below.as_deref_mut() { for t in block { b.touch(*t); @@ -1846,7 +1719,6 @@ fn composite_block( tiles: &[(u32, u32)], below: Option<(&BelowCache, &[Level])>, quota: usize, - step: u32, ) -> Vec<((u32, u32), Vec)> { let channels: Vec = inp.project.texture_set(inp.ts).map(|s| s.channel_list()).unwrap_or_default(); let (w, h) = (out.resolution, out.height); @@ -1876,7 +1748,7 @@ fn composite_block( let warm = cached((tx, ty)).and_then(|b| b.get(band as usize)); let record = warm.is_none() && recorded.contains(&(tx, ty)); let levels = split.map(|l| plan_levels(inp, l, &channels, tx, ty, &fields, warm.is_some())); - let nodes = if levels.is_none() { plan_with(inp, stack, &channels, tx, ty, 0, Some(&fields), true) } else { Vec::new() }; + let nodes = if levels.is_none() { plan(inp, stack, &channels, tx, ty, 0, Some(&fields)) } else { Vec::new() }; let rows = (BAND * TILE) as usize; let mut accs = vec![defaults; nlev]; let mut masks = vec![0.0f32; nlev]; @@ -1900,17 +1772,11 @@ fn composite_block( let mut bufs: Vec> = channels.iter().map(|c| vec![0u16; rows * c.components()]).collect(); let mut anchors = Vec::new(); let mut any = false; - // Coarse: per `step`-wide block of the current block row, the value of its first - // covered texel (evaluated), repeated over the block's other covered texels. - let mut sampled: Vec> = vec![None; if step > 1 { (TILE / step) as usize } else { 0 }]; for ly in band * BAND..(band + 1) * BAND { let y = ty * TILE + ly; if y >= h { break; } - if step > 1 && ly % step == 0 { - sampled.fill(None); - } for lx in 0..TILE { let x = tx * TILE + lx; if x >= w { @@ -1922,12 +1788,7 @@ fn composite_block( let ob = ((ly - band * BAND) * TILE + lx) as usize; let covered = inp.gbuf.tri.get(gi).is_some_and(|t| *t != NO_TRI); let mut acc = defaults; - let block = if step > 1 { sampled.get_mut((lx / step) as usize) } else { None }; - let repeated = block.as_ref().and_then(|b| **b); - if covered && let Some(a) = repeated { - any = true; - acc = a; - } else if covered { + if covered { any = true; let mut tex = Texel::new(inp, x, y, o, stroke_at(preview_tile, o)); // Reuse one anchor buffer per band. @@ -1959,12 +1820,6 @@ fn composite_block( anchors = tex.anchors; anchors.clear(); } - if covered - && repeated.is_none() - && let Some(slot) = block - { - *slot = Some(acc); - } for (l, buf) in lanes.iter().zip(&mut bufs) { let v = acc.get(l.ch).copied().unwrap_or([0.0; 3]); for (k, x) in v.iter().take(l.n).enumerate() { diff --git a/crates/compose/src/lib.rs b/crates/compose/src/lib.rs index 0475fb8f..46c3c6b5 100644 --- a/crates/compose/src/lib.rs +++ b/crates/compose/src/lib.rs @@ -20,8 +20,8 @@ pub mod thumb; pub use below::{BelowCache, StackKey}; pub use display::{DisplayKind, tile_bytes}; pub use eval::{ - COARSE_STRIDES, Composite, Inputs, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, composite_tiles_coarse, - covered_tiles, effect_histogram, flatten_layer, has_neighbourhood_filters, mask_at, mask_image, pad_tiles, + Composite, Inputs, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles, effect_histogram, flatten_layer, + mask_at, mask_image, pad_tiles, }; pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore}; pub use thumb::{THUMB_TEXELS, ThumbImage, ThumbTarget}; diff --git a/crates/compose/tests/cache_and_instances.rs b/crates/compose/tests/cache_and_instances.rs index 50d125a6..d7df0258 100644 --- a/crates/compose/tests/cache_and_instances.rs +++ b/crates/compose/tests/cache_and_instances.rs @@ -573,35 +573,3 @@ fn gathering_filters_composite_identically_in_any_grouping_and_cached() { assert!(!check_cached(&f, 0, hot).is_empty()); } } - -/// A folder that hides the layers below it but records an anchor point inside (under its own -/// hiding layer) keeps them: its inner stack starts from them, so the anchor holds them. -#[test] -fn layers_under_a_hiding_folder_with_an_anchor_are_not_culled() { - let mut f = fixture(); - let only = |f: &mut Fixture, id: LayerId, c: Channel| f.project.layer_mut(id).unwrap().channels.retain(|x, _| *x == c); - let low = add(&mut f, 0, fill(&[(Channel::BaseColor, Source::Uniform([0.9; 3]))]), None); - only(&mut f, low, Channel::BaseColor); - let group = add(&mut f, 0, LayerKind::Group { children: vec![], collapsed: false }, None); - // Inside: a half-opacity fill recording anchor A, then an opaque fill hiding everything. - let anchored = put(&mut f, 0, Some(group), fill(&[(Channel::BaseColor, Source::Uniform([0.5; 3]))]), None); - only(&mut f, anchored, Channel::BaseColor); - blend(&mut f, anchored, BlendMode::Normal, 0.5); - let anchor = effect(&mut f, EffectKind::Anchor); - let anchor_id = anchor.id; - f.project.layer_mut(anchored).unwrap().content_effects.push(anchor); - let hiding = put(&mut f, 0, Some(group), fill(&[(Channel::BaseColor, Source::Uniform([0.1; 3]))]), None); - only(&mut f, hiding, Channel::BaseColor); - // Above the folder, roughness reads the base color held by A. - let reader = add(&mut f, 0, fill(&[(Channel::Roughness, Source::Anchor { anchor: anchor_id, channel: Channel::BaseColor })]), None); - only(&mut f, reader, Channel::Roughness); - let out = reference(&f, 0); - let rough = out.value(Channel::Roughness, 128, 128)[0]; - // A = 0.5 at half opacity over the low layer's 0.9. - assert!((rough - 0.7).abs() < 2e-3, "the anchor holds the layer under the folder: {rough}"); - assert!((out.value(Channel::BaseColor, 128, 128)[0] - 0.1).abs() < 2e-3); - // The same stack with an (unread) anchor on the low layer is never culled: identical. - let keep = effect(&mut f, EffectKind::Anchor); - f.project.layer_mut(low).unwrap().content_effects.push(keep); - assert!(reference(&f, 0) == out, "culling changed the composite"); -} diff --git a/crates/core/src/blend.rs b/crates/core/src/blend.rs index c7fa7e64..5f165cdb 100644 --- a/crates/core/src/blend.rs +++ b/crates/core/src/blend.rs @@ -350,11 +350,6 @@ pub fn blend3(mode: BlendMode, a: [f32; 3], b: [f32; 3]) -> [f32; 3] { /// Mix `blended` over `a` by weight `w` (coverage × opacity × mask). pub fn mix3(a: [f32; 3], blended: [f32; 3], w: f32) -> [f32; 3] { - // A full-weight blend is exactly the blended value (`a + (b - a)` can be an ulp off it): what - // lies under it does not leak in, so skipping the layers it hides changes nothing at all. - if w >= 1.0 { - return blended; - } [a[0] + (blended[0] - a[0]) * w, a[1] + (blended[1] - a[1]) * w, a[2] + (blended[2] - a[2]) * w] } diff --git a/crates/engine/src/inspect.rs b/crates/engine/src/inspect.rs index 603e7b17..2db27946 100644 --- a/crates/engine/src/inspect.rs +++ b/crates/engine/src/inspect.rs @@ -193,10 +193,5 @@ pub fn session(s: &Session) -> Value { "history": { "undo": s.undo_label(), "redo": s.redo_label(), "depth": s.history_labels().len() }, "memoryBytes": s.memory().total(), "pendingTiles": s.pending_tiles(), - // Tiles with no look of the current composite yet, tiles shown from a coarse pass only - // (their exact composite pending), and the coarsest stride shown (0: none). - "dirtyTiles": s.caches.iter().map(|c| c.dirty.len()).sum::(), - "coarseTiles": s.caches.iter().map(|c| c.refine.len()).sum::(), - "coarsestStride": s.caches.iter().flat_map(|c| c.refine.values().copied()).max().unwrap_or(0), }) } diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 6b721a79..64ebec69 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -4,7 +4,7 @@ use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; use serde::{Deserialize, Serialize}; -use texturecraft_compose::{BakedMaps, BelowCache, COARSE_STRIDES, Composite, PaintTarget, PixelStore, StackKey, StrokePreview, covered_tiles, pad_tiles}; +use texturecraft_compose::{BakedMaps, BelowCache, Composite, PaintTarget, PixelStore, StackKey, StrokePreview, covered_tiles, pad_tiles}; use texturecraft_core::{Channel, Layer, LayerId, LayerKind, Project, TextureSet}; use texturecraft_geom::glam::Vec2; use texturecraft_geom::{Bvh, Mesh, OrbitCamera, UvGBuffer}; @@ -43,24 +43,14 @@ pub struct SetCache { /// Tiles to recomposite at low priority: what they show is already right (a committed /// stroke's live preview), but it was composited from the stroke, not the layer pixels. pub settle: BTreeSet<(u32, u32)>, - /// Tiles shown from a coarse pass ([`texturecraft_compose::composite_tiles_coarse`]) with - /// the stride they were composited at; they still need the finer ones and the exact one. A - /// big recomposite (a material applied) first looks right everywhere at a small part of the - /// cost, then sharpens level by level ([`texturecraft_compose::COARSE_STRIDES`]), each level - /// over every tile before the next, so the surface is always at one consistent level. - pub refine: BTreeMap<(u32, u32), u32>, - /// The dirty tiles go through a coarse pass: decided when a big recomposite starts and - /// kept until `dirty` drains, so its last few tiles do not go exact at the full price. - pub coarse_pass: bool, /// Tiles whose display textures must be re-uploaded. pub upload: BTreeSet<(u32, u32)>, /// Bumps on every composite change (thumbnails, exports, caches). pub revision: u64, /// Everything but the layer being edited, per tile (repaints evaluate only that layer). pub below: BelowCache, - /// Wall-clock milliseconds per tile of the last exact composite chunk (0: not measured - /// yet): the first chunk of a budgeted update is sized from it and that update's budget. - pub tile_ms: f64, + /// Tiles per composite chunk that fit the last frame's budget (0: not measured yet). + pub chunk: usize, } impl SetCache { @@ -79,12 +69,10 @@ impl SetCache { composite: Composite { block_scales: ts.block_scales(), ..Composite::with_size(&ts.channel_list(), w, h) }, dirty: all.clone(), settle: BTreeSet::new(), - refine: BTreeMap::new(), - coarse_pass: false, upload: all, revision: 0, below: BelowCache::default(), - tile_ms: 0.0, + chunk: 0, } } @@ -727,60 +715,23 @@ impl Session { carried: s.canvas.pickup.as_ref().map(|p| p.values.clone()).unwrap_or_default(), }) }); - // A coarse look first only when there is a frame budget to spread a big change over, and - // never under a live stroke (it keeps the exact, cached repaint of the hot layer). - let coarse_allowed = budget_ms.is_finite() && self.stroke.is_none(); let active = self.ts(); let order = std::iter::once(active).chain((0..self.caches.len()).filter(|ts| *ts != active)); let mut changed = false; for ts in order { let Some(cache) = self.caches.get_mut(ts) else { continue }; cache.below.set_hot(hot); - cache.below.pass = cache.dirty.len() + cache.settle.len() + cache.refine.len(); + cache.below.pass = cache.dirty.len() + cache.settle.len(); // Instances in sets of the stroke's size show the live stroke too. let preview = preview.as_ref().filter(|_| Some(cache.size) == stroke_size); - // Start at the size this budget fits at the last measured pace: with a heavy stack - // (smart materials at 8K) one tile per thread alone would take several frames' - // budget. Never above one tile per thread: work can turn heavy from one frame to the - // next. - let exact_chunk = - |cache: &SetCache| if budget_ms.is_finite() && cache.tile_ms > 0.0 { ((budget_ms / cache.tile_ms) as usize).clamp(1, first) } else { first }; - let mut chunk = exact_chunk(cache); - // A stack with neighbourhood filters computes them at full resolution even for a - // coarse composite, so it gains little from one: straight to the exact composite. - let may_coarse = coarse_allowed && !cache.dirty.is_empty() && !texturecraft_compose::has_neighbourhood_filters(&self.doc.project, ts); - // The stride of the previous chunk (1: exact), to restart the chunk size on a change. - let mut last_stride = 1; + // Start at the size that fit the budget last time: with a heavy stack (smart + // materials at 8K) one tile per thread alone would take several frames' budget. + let mut chunk = if budget_ms.is_finite() && cache.chunk > 0 { cache.chunk } else { first }; loop { if cache.dirty.is_empty() { - cache.coarse_pass = false; - } - // The work of this chunk: fresh dirty tiles (coarsest look or exact), the next - // level of the coarsest refining tiles, or settling tiles. - let (stride, refining, settling): (u32, Option, bool) = if !cache.dirty.is_empty() { - // A big change gets a coarse look first, for the whole of it. - if may_coarse && cache.dirty.len() > COARSE_MIN_TILES { - cache.coarse_pass = true; + if cache.settle.is_empty() || clock() - start >= budget_ms.min(SETTLE_BUDGET_MS) { + break; } - let coarse = may_coarse && cache.coarse_pass; - (if coarse { COARSE_STRIDES[0] } else { 1 }, None, false) - } else if let Some(at) = cache.refine.values().copied().max() { - (finer_stride(at), Some(at), false) - } else if !cache.settle.is_empty() && clock() - start < budget_ms.min(SETTLE_BUDGET_MS) { - (1, None, true) - } else { - break; - }; - // A level costs about its stride² less per texel than the exact composite: a - // new level starts at the exact pace, and the chunks grow from what it measures. - if stride != last_stride { - chunk = exact_chunk(cache); - last_stride = stride; - } - if let Some(at) = refining { - let mut level: BTreeSet<(u32, u32)> = cache.refine.iter().filter(|(_, s)| **s == at).map(|(t, _)| *t).collect(); - cache.dirty.extend(next_chunk(&mut level, chunk)); - } else if settling { // Small chunks: the settle slice of the budget is short. cache.dirty.extend(next_chunk(&mut cache.settle, chunk.min(first))); } @@ -788,7 +739,6 @@ impl Session { let tiles = next_chunk(&mut cache.dirty, chunk); for t in &tiles { cache.settle.remove(t); - cache.refine.remove(t); } let empty = BakedMaps::default(); let inputs = texturecraft_compose::Inputs { @@ -803,12 +753,7 @@ impl Session { images: &self.images, bounds: self.mesh.bounds(), }; - if stride > 1 { - texturecraft_compose::composite_tiles_coarse(&inputs, &mut cache.composite, &tiles, stride); - cache.refine.extend(tiles.iter().map(|t| (*t, stride))); - } else { - texturecraft_compose::composite_tiles_cached(&inputs, &mut cache.composite, &tiles, Some(&mut cache.below)); - } + texturecraft_compose::composite_tiles_cached(&inputs, &mut cache.composite, &tiles, Some(&mut cache.below)); // The composited tiles and the neighbours their padding reached change. let padded = pad_tiles(&mut cache.composite, &cache.dilation, &tiles); cache.upload.extend(tiles.iter().copied().chain(padded)); @@ -818,8 +763,9 @@ impl Session { let left = budget_ms - (now - start); // As many tiles as fit in what is left, at the pace of this chunk. let per_tile = (now - t0) / tiles.len().max(1) as f64; - if budget_ms.is_finite() && per_tile > 0.0 && stride == 1 { - cache.tile_ms = per_tile; + if budget_ms.is_finite() && per_tile > 0.0 { + // Never above one tile per thread: work can turn heavy from one frame to the next. + cache.chunk = ((budget_ms / per_tile) as usize).clamp(1, first); } if left <= 0.0 { return changed; @@ -836,7 +782,7 @@ impl Session { /// Tiles still waiting to be composited, over every texture set (settling ones included). pub fn pending_tiles(&self) -> usize { - self.caches.iter().map(|c| c.dirty.len() + c.settle.len() + c.refine.len()).sum() + self.caches.iter().map(|c| c.dirty.len() + c.settle.len()).sum() } /// The layer a stroke target belongs to (an effect's owner). @@ -948,9 +894,6 @@ impl Memory { /// Most tiles per composite chunk (a 1024² region). const CHUNK: usize = 256; -/// A recomposite of more tiles than this (a material applied, not a brush stroke) is shown from -/// a coarse pass first when it is spread over frames. -const COARSE_MIN_TILES: usize = 64; /// The most a budgeted update spends on settling tiles (what they show is already right). pub const SETTLE_BUDGET_MS: f64 = 6.0; @@ -969,11 +912,6 @@ fn next_chunk(dirty: &mut BTreeSet<(u32, u32)>, n: usize) -> Vec<(u32, u32)> { tiles } -/// The stride of the level after `stride` in [`COARSE_STRIDES`] (1: the exact composite). -fn finer_stride(stride: u32) -> u32 { - COARSE_STRIDES.iter().copied().find(|s| *s < stride).unwrap_or(1) -} - /// Valid texture set resolutions: powers of two from 128 to 8192. pub fn check_resolution(r: u32) -> Result { if (128..=8192).contains(&r) && r.is_power_of_two() { diff --git a/crates/engine/tests/it/instances.rs b/crates/engine/tests/it/instances.rs index f3a1b594..b9f14bcd 100644 --- a/crates/engine/tests/it/instances.rs +++ b/crates/engine/tests/it/instances.rs @@ -220,12 +220,10 @@ fn budgeted_updates_spread_work_and_end_identical() { s.caches[0].invalidate_all(); // A clock that is always over budget: one chunk per call. let mut calls = 0; - // Progress: a tile is two steps from done while dirty (coarse look, then exact), one when refining. - let steps = |s: &texturecraft_engine::Session| 2 * s.caches[0].dirty.len() + s.caches[0].refine.len() + s.caches[0].settle.len(); while s.pending_tiles() > 0 { - let before = steps(&s); + let before = s.pending_tiles(); s.update_for(0.0, || 1.0); - assert!(steps(&s) < before); + assert!(s.pending_tiles() < before); calls += 1; } assert!(calls > 1, "the work was spread over calls"); diff --git a/crates/engine/tests/session.rs b/crates/engine/tests/session.rs index 89f27beb..4dd04032 100644 --- a/crates/engine/tests/session.rs +++ b/crates/engine/tests/session.rs @@ -446,166 +446,3 @@ fn curvature_generators_take_a_mode_and_detail_sizes() { assert!(dirt.is_err(), "only curvature generators have a mode"); assert_eq!(execute(&mut state, "project.inspect", &Value::Null).unwrap().to_string(), inspect, "failed commands leave the project unchanged"); } - -/// A material applied over frames first looks right everywhere from a coarse pass (the sampled -/// texels are exact, the rest repeat them), then the tiles fill in to the exact composite. -#[test] -fn a_big_recomposite_shows_a_coarse_look_first_then_the_exact_one() { - let make = || { - let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 2048).unwrap(); - s.viewport = texturecraft_engine::geom::glam::Vec2::new(400.0, 400.0); - s.update(); - execute(&mut s, "material.apply", &json!({"material": "steel_painted_worn"})).unwrap(); - s - }; - let mut exact = make(); - exact.update(); - assert_eq!(exact.pending_tiles(), 0, "an unbudgeted update goes straight to the exact composite"); - let exact = exact.caches[0].composite.clone(); - - let mut s = make(); - let t = std::cell::Cell::new(0.0); - let clock = || { - t.set(t.get() + 2.0); - t.get() - }; - let covered = s.caches[0].covered_tiles.len(); - assert!(covered > 100, "a big change: {covered} tiles"); - while !s.caches[0].dirty.is_empty() { - s.update_for(30.0, clock); - } - assert!(s.caches[0].refine.len() > 100 && s.pending_tiles() > 0, "everything has a coarse look, the exact one is pending"); - let coarse = s.caches[0].composite.clone(); - assert_ne!(coarse, exact, "the coarse look is not the exact one"); - // Where the coarse pass sampled (a block's first covered texel, its corner where covered), it - // is exact; the others repeat the sample of their block. - let c = Channel::BaseColor; - let stride = texturecraft_engine::compose::COARSE_STRIDES[0]; - let (mut sampled, mut repeated, mut checked) = (0, 0, 0); - for y in (0..2048).step_by(7) { - for x in (0..2048).step_by(5) { - let (ax, ay) = (x - x % stride, y - y % stride); - if x == ax && y == ay { - if coarse.value(c, x, y) == exact.value(c, x, y) { - sampled += 1; - } - checked += 1; - } else if coarse.value(c, x, y) == coarse.value(c, ax, ay) { - repeated += 1; - } - } - } - assert!(checked > 100 && sampled * 10 >= checked * 9, "sampled texels are exact: {sampled} of {checked}"); - assert!(repeated > 1000, "the others repeat their sample: {repeated}"); - while s.pending_tiles() > 0 { - s.update_for(30.0, clock); - } - assert_eq!(s.caches[0].composite, exact, "the refined composite is the exact one"); -} - -/// Layers an opaque layer above hides are not evaluated: a material applied over others -/// composites exactly like the same material applied alone, in the channels it sets. -#[test] -fn layers_hidden_by_an_opaque_material_are_left_out_without_changing_the_result() { - let make = |materials: &[&str]| { - let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 512).unwrap(); - s.viewport = texturecraft_engine::geom::glam::Vec2::new(400.0, 400.0); - for m in materials { - execute(&mut s, "material.apply", &json!({"material": m})).unwrap(); - } - s.update(); - s.caches[0].composite.clone() - }; - let alone = make(&["gold_polished"]); - let stacked = make(&["steel_painted_worn", "copper", "gold_polished"]); - let underneath = make(&["steel_painted_worn", "copper"]); - assert_ne!(alone, underneath, "the materials differ"); - for c in [Channel::BaseColor, Channel::Roughness, Channel::Metallic] { - let (mut compared, mut differing) = (0, 0); - for y in (0..512).step_by(3) { - for x in (0..512).step_by(3) { - compared += 1; - if alone.value(c, x, y) != stacked.value(c, x, y) { - differing += 1; - } - } - } - assert!(compared > 1000 && differing == 0, "{c:?}: {differing} of {compared} texels differ"); - } -} - -/// A clock that advances 2 ms per reading, for budgeted updates. -fn ticking() -> impl Fn() -> f64 { - let t = std::cell::Cell::new(0.0); - move || { - t.set(t.get() + 2.0); - t.get() - } -} - -/// A big change goes through the coarse pass to its last tile (the decision is kept for the -/// whole pass): its tail does not go exact at the full price while the rest waits for detail. -#[test] -fn the_coarse_pass_covers_every_tile_of_a_big_change() { - let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 1024).unwrap(); - s.update(); - execute(&mut s, "material.apply", &json!({"material": "steel_painted_worn"})).unwrap(); - let dirty = s.caches[0].dirty.len(); - assert!(dirty > 100, "a big change: {dirty} tiles"); - // A clock always over budget: one chunk per call. - let mut calls = 0; - while !s.caches[0].dirty.is_empty() { - s.update_for(0.0, || 1.0); - let c = &s.caches[0]; - assert_eq!(c.refine.len() + c.dirty.len(), dirty, "no tile went exact during the coarse pass"); - calls += 1; - } - assert!(calls > 1, "the pass was spread over calls"); - s.update_for(0.0, || 1.0); - assert!(!s.caches[0].coarse_pass, "the pass ended with its tiles"); - let clock = ticking(); - // A small change after it goes straight to the exact composite. - let some: Vec<(u32, u32)> = s.caches[0].covered_tiles.iter().copied().take(10).collect(); - s.update(); - s.caches[0].dirty.extend(some); - s.update_for(30.0, &clock); - assert!(s.caches[0].refine.is_empty() && s.caches[0].dirty.is_empty(), "a few tiles are composited exactly"); -} - -/// Under a live stroke the compositor keeps the exact (cached) repaint: no coarse pass. -#[test] -fn no_coarse_pass_while_a_stroke_is_live() { - let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 1024).unwrap(); - s.update(); - s.begin_stroke_uv(texturecraft_engine::geom::glam::Vec2::new(0.5, 0.5), 1.0).unwrap(); - s.caches[0].invalidate_all(); - assert!(s.caches[0].dirty.len() > 100); - let clock = ticking(); - while !s.caches[0].dirty.is_empty() { - s.update_for(30.0, &clock); - assert!(s.caches[0].refine.is_empty(), "nothing went coarse under the stroke"); - } - s.end_stroke().unwrap(); -} - -/// A stack with a neighbourhood filter (blur) computes it at full resolution even for a coarse -/// look, which then saves little: such a stack goes straight to the exact composite. -#[test] -fn stacks_with_neighbourhood_filters_skip_the_coarse_pass() { - use texturecraft_engine::core::{Effect, EffectKind, Filter}; - let mut s = Session::new_project("t", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 1024).unwrap(); - s.update(); - execute(&mut s, "material.apply", &json!({"material": "copper"})).unwrap(); - s.update(); - assert!(!texturecraft_engine::compose::has_neighbourhood_filters(&s.doc.project, 0)); - let top = *s.doc.project.texture_sets[0].stack.last().unwrap(); - let id = s.doc.project.alloc_id(); - s.doc.project.layer_mut(top).unwrap().content_effects.push(Effect::new(id, EffectKind::Filter(Filter::Blur { radius: 8.0 }))); - assert!(texturecraft_engine::compose::has_neighbourhood_filters(&s.doc.project, 0)); - s.caches[0].invalidate_all(); - let clock = ticking(); - while !s.caches[0].dirty.is_empty() { - s.update_for(30.0, &clock); - assert!(s.caches[0].refine.is_empty(), "nothing went coarse"); - } -} diff --git a/crates/ui-egui/src/gpu.rs b/crates/ui-egui/src/gpu.rs index 7811577b..944a8ecd 100644 --- a/crates/ui-egui/src/gpu.rs +++ b/crates/ui-egui/src/gpu.rs @@ -93,29 +93,11 @@ pub struct GpuLink { pub adapter: String, /// Most tiles waiting to be composited since compositing last caught up (progress). composite_total: usize, - /// Consecutive frames without user input (see [`frame_budgets`]). - idle_frames: u32, bake_scene: BakeSceneLink, } -/// The compositing and whole-frame budgets in milliseconds after `idle_frames` frames without -/// user input: the responsive pair while the user works, the longer pair once they have stopped. -fn frame_budgets(idle_frames: u32) -> (f64, f64) { - if idle_frames >= IDLE_FRAMES_BEFORE_BOOST { (IDLE_COMPOSITE_BUDGET_MS, IDLE_FRAME_BUDGET_MS) } else { (COMPOSITE_BUDGET_MS, FRAME_BUDGET_MS) } -} - -/// Compositing time per frame while the user is working: a full recomposite of a large texture -/// set spreads over frames. +/// Compositing time per frame: a full recomposite of a large texture set spreads over frames. const COMPOSITE_BUDGET_MS: f64 = 30.0; -/// Compositing time per frame once the user has stopped touching the app: the compositor scales -/// with the machine's cores, so a longer slice finishes sooner on a fast PC (a frame then takes -/// longer, but nothing is being dragged or painted that would feel it). -const IDLE_COMPOSITE_BUDGET_MS: f64 = 100.0; -/// [`FRAME_BUDGET_MS`] while idle: the idle compositing slice plus the usual rest of the frame. -const IDLE_FRAME_BUDGET_MS: f64 = IDLE_COMPOSITE_BUDGET_MS + (FRAME_BUDGET_MS - COMPOSITE_BUDGET_MS); -/// Frames without input (about 0.2 s at 60 fps) before the longer idle slices start, so a short -/// pause between strokes or drags keeps the responsive budget. -const IDLE_FRAMES_BEFORE_BOOST: u32 = 12; /// The most a frame spends on the scene (with the work already done this frame, such as a /// stroke's commit): compositing and display conversion leave the rest for the next frames, so /// a large (8K) texture set never stalls one frame. @@ -127,10 +109,6 @@ const UPLOAD_CHUNK: usize = 64; /// 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; -/// CPU cost of converting one display tile of one kind for upload ([`tile_bytes`], measured at -/// ~6 µs: 8192 in 50 ms on a 24-thread desktop): with [`UPLOAD_MS_PER_TILE`], what a tile still -/// waiting for upload will cost this frame. -const CONVERT_MS_PER_TILE: f64 = 0.006; pub fn init(rs: &egui_wgpu::RenderState, ctx: &egui::Context) -> GpuLink { let reset = Arc::new(AtomicBool::new(false)); @@ -162,7 +140,6 @@ pub fn init(rs: &egui_wgpu::RenderState, ctx: &egui::Context) -> GpuLink { aux: BTreeMap::new(), adapter: format!("{} ({:?})", info.name, info.backend), composite_total: 0, - idle_frames: 0, bake_scene: BakeSceneLink::default(), } } @@ -185,28 +162,13 @@ impl GpuLink { } /// Collect everything the GPU needs this frame, running the compositor first: `bake` is what bake mode's 3D view draws besides the low poly, `spent_ms` the time this frame already took - pub fn sync( - &mut self, - session: &mut Session, - aux_map: Option, - bake: Option, - shift: u32, - spent_ms: f64, - user_active: bool, - ) -> SceneSync { + pub fn sync(&mut self, session: &mut Session, aux_map: Option, bake: Option, shift: u32, spent_ms: f64) -> SceneSync { let start_ms = crate::now_ms(); let mut queued = 0usize; - self.idle_frames = if user_active { 0 } else { self.idle_frames.saturating_add(1) }; - let (composite_budget_ms, frame_budget_ms) = frame_budgets(self.idle_frames); - let time_left_ms = |queued: usize| frame_budget_ms - spent_ms - (crate::now_ms() - start_ms) - queued as f64 * UPLOAD_MS_PER_TILE; + let time_left_ms = |queued: usize| FRAME_BUDGET_MS - spent_ms - (crate::now_ms() - start_ms) - queued as f64 * UPLOAD_MS_PER_TILE; let pending = session.pending_tiles(); self.composite_total = if pending == 0 { 0 } else { self.composite_total.max(pending) }; - // Tiles composited earlier and still waiting to be uploaded go first: a big change's - // coarse look is composited in a frame or two, and showing it whole matters more than - // compositing on (otherwise it appears a chunk of tiles per frame). - let backlog = session.caches.iter().map(|c| c.upload.len()).sum::() * DisplayKind::ALL.len(); - let backlog_ms = backlog as f64 * (UPLOAD_MS_PER_TILE + CONVERT_MS_PER_TILE); - session.update_for(composite_budget_ms.min(time_left_ms(0) - backlog_ms).max(MIN_SLICE_MS), crate::now_ms); + session.update_for(COMPOSITE_BUDGET_MS.min(time_left_ms(0)).max(MIN_SLICE_MS), crate::now_ms); let mut out = SceneSync::default(); if self.lost.swap(false, Ordering::AcqRel) { @@ -448,26 +410,3 @@ impl CallbackTrait for ViewCallback { gpu.renderer.blit_prepared(pass, self.frame.view_id); } } - -#[cfg(test)] -mod tests { - use super::*; - - /// While the user is working (or just stopped) a frame keeps the responsive budgets. - #[test] - fn budgets_stay_short_while_the_user_is_active() { - assert_eq!(frame_budgets(0), (COMPOSITE_BUDGET_MS, FRAME_BUDGET_MS)); - assert_eq!(frame_budgets(IDLE_FRAMES_BEFORE_BOOST - 1), (COMPOSITE_BUDGET_MS, FRAME_BUDGET_MS)); - } - - /// After a pause the compositor gets the longer slice, and the frame budget grows with it so the - /// display uploads keep their usual share. - #[test] - fn budgets_grow_once_the_user_is_idle() { - let (composite, frame) = frame_budgets(IDLE_FRAMES_BEFORE_BOOST); - assert_eq!(composite, IDLE_COMPOSITE_BUDGET_MS); - assert!(composite > COMPOSITE_BUDGET_MS); - assert_eq!(frame - composite, FRAME_BUDGET_MS - COMPOSITE_BUDGET_MS, "the non-compositing share of a frame is unchanged"); - assert_eq!(frame_budgets(u32::MAX), (composite, frame), "stays boosted"); - } -} diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index be6c87da..f3087537 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -317,11 +317,7 @@ fn add_callback(app: &mut TextureCraftApp, ui: &Ui, rect: Rect, mut frame: Frame let scene = match (sync.0.take(), app.gpu.as_mut()) { (Some(aux), Some(gpu_link)) => { let sync_start_ms = crate::now_ms(); - // Pointer, key and scroll input all count: the compositor then keeps frames short. - let user_active = - ui.ctx().input(|i| i.pointer.is_moving() || i.pointer.any_down() || !i.events.is_empty() || i.smooth_scroll_delta != egui::Vec2::ZERO); - let scene = - gpu_link.sync(&mut app.session, aux, bake, u32::from(app.ui.prefs.viewport_texture.min(2)), f64::from(app.profiler.logic_ms), user_active); + let scene = gpu_link.sync(&mut app.session, aux, bake, u32::from(app.ui.prefs.viewport_texture.min(2)), f64::from(app.profiler.logic_ms)); let reports = gpu_link.take_reports(); app.profiler.sync_ms += (crate::now_ms() - sync_start_ms) as f32; gpu_report_toasts(app, reports); From 21b30466483314155ae586d1fe68af08032d6f50 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Tue, 10 Nov 2026 18:58:27 -0500 Subject: [PATCH 49/64] packaging: use [[ for bash tests (SonarCloud S7688) (#403) * packaging: use [[ for bash tests (SonarCloud S7688) Behaviour-preserving: `[[ ]]` in place of `[ ]` for bash tests (SonarCloud shell:S7688). Every script has a bash shebang; no test uses `-a`/`-o`, escaped parentheses or an unquoted pattern on the right of `=`. `bash -n` passes on each script; the rest is left to CI. Clears all 70 open issues: `packaging/{linux,macos,freebsd,web}/*.sh`. * packaging/web: parse the wasm size override as base 10 under [[ Inside [[ ]], -gt evaluates its operands arithmetically: a leading zero reads as octal and other text as an expression. Read the override as a base-10 number, as photocraft does. --- packaging/freebsd/package.sh | 16 ++++++++-------- packaging/linux/apprun-test.sh | 20 ++++++++++---------- packaging/linux/flatpak-bundle.sh | 8 ++++---- packaging/linux/package.sh | 16 ++++++++-------- packaging/macos/import-cert.sh | 6 +++--- packaging/macos/package.sh | 24 ++++++++++++------------ packaging/macos/verify.sh | 26 +++++++++++++------------- packaging/web/package.sh | 12 ++++++------ 8 files changed, 64 insertions(+), 64 deletions(-) diff --git a/packaging/freebsd/package.sh b/packaging/freebsd/package.sh index c9929b40..bf2b46ca 100755 --- a/packaging/freebsd/package.sh +++ b/packaging/freebsd/package.sh @@ -20,7 +20,7 @@ APP_ID=ai.storyteller.texturecraft SKIP_BUILD=0 DRY_RUN=0 -while [ $# -gt 0 ]; do +while [[ $# -gt 0 ]]; do case "$1" in --skip-build) SKIP_BUILD=1; shift ;; --dry-run) DRY_RUN=1; SKIP_BUILD=1; shift ;; @@ -37,14 +37,14 @@ case "$MACHINE" in *) echo "unsupported architecture $MACHINE" >&2; exit 2 ;; esac ARCH="$HOST_ARCH" -if [ -n "${CARGO_BUILD_TARGET:-}" ]; then +if [[ -n "${CARGO_BUILD_TARGET:-}" ]]; then case "$CARGO_BUILD_TARGET" in aarch64-unknown-freebsd) ARCH=aarch64 ;; x86_64-unknown-freebsd) ARCH=x86_64 ;; *) echo "error: unsupported FreeBSD target $CARGO_BUILD_TARGET" >&2; exit 2 ;; esac fi -if [ "$DRY_RUN" = 0 ] && [ "$(uname -s)" != FreeBSD ]; then +if [[ "$DRY_RUN" = 0 ]] && [[ "$(uname -s)" != FreeBSD ]]; then echo "error: build on FreeBSD (or pass --dry-run to check the tree layout)" >&2 exit 2 fi @@ -54,7 +54,7 @@ echo "==> TextureCraft $VERSION for FreeBSD $ARCH" # The release VM has 12 GB; full parallelism on the biggest crates runs it out of memory. export CARGO_BUILD_JOBS="${CARGO_BUILD_JOBS:-4}" -if [ "$SKIP_BUILD" = 0 ]; then +if [[ "$SKIP_BUILD" = 0 ]]; then (cd "$ROOT" && cargo build --release --locked -p texturecraft -p texturecraft-cli) fi WORK="$CARGO_TARGET_DIR/freebsd-package" @@ -64,7 +64,7 @@ mkdir -p "$WORK" BIN="$CARGO_TARGET_DIR/${CARGO_BUILD_TARGET:+$CARGO_BUILD_TARGET/}release" OUT_DIR="$DIST" -if [ "$DRY_RUN" = 1 ]; then +if [[ "$DRY_RUN" = 1 ]]; then # Stub binaries, and the tarball stays in the work dir so dist/ only ever holds real builds. BIN="$WORK/stub-bin" OUT_DIR="$WORK" @@ -92,7 +92,7 @@ copy_docs "$STAGE/share/doc/texturecraft" for f in bin/texturecraft bin/texturecraft-cli "share/applications/$APP_ID.desktop" \ "share/icons/hicolor/256x256/apps/$APP_ID.png" "share/icons/hicolor/scalable/apps/$APP_ID.svg" \ share/doc/texturecraft/LICENSE-MIT share/doc/texturecraft/LICENSE-APACHE; do - if [ ! -e "$STAGE/$f" ]; then echo "error: $f is missing from the package" >&2; exit 1; fi + if [[ ! -e "$STAGE/$f" ]]; then echo "error: $f is missing from the package" >&2; exit 1; fi done # ---- .tar.gz ------------------------------------------------------------------------------------ @@ -100,10 +100,10 @@ mkdir -p "$OUT_DIR" tar -C "$WORK" -czf "$OUT_DIR/$BASENAME.tar.gz" "$BASENAME" echo "wrote $OUT_DIR/$BASENAME.tar.gz" -if [ -z "${CARGO_BUILD_TARGET:-}" ] || [ "$DRY_RUN" = 1 ]; then +if [[ -z "${CARGO_BUILD_TARGET:-}" ]] || [[ "$DRY_RUN" = 1 ]]; then "$STAGE/bin/texturecraft-cli" --version fi -if [ "$DRY_RUN" = 1 ]; then +if [[ "$DRY_RUN" = 1 ]]; then echo "==> dry run: tarball contents" tar -tzvf "$OUT_DIR/$BASENAME.tar.gz" fi diff --git a/packaging/linux/apprun-test.sh b/packaging/linux/apprun-test.sh index 0668cc80..cfb9548e 100755 --- a/packaging/linux/apprun-test.sh +++ b/packaging/linux/apprun-test.sh @@ -37,10 +37,10 @@ fail() { # 1. Launch works and passes arguments through. out="$("$APPDIR/AppRun" open model.glb)" || fail "AppRun exited non-zero" -[ "$out" = "stub: open model.glb" ] || fail "arguments not forwarded: $out" +[[ "$out" = "stub: open model.glb" ]] || fail "arguments not forwarded: $out" DESKTOP="$XDG_DATA_HOME/applications/$APP_ID.desktop" -[ -f "$DESKTOP" ] || fail "desktop entry not installed" +[[ -f "$DESKTOP" ]] || fail "desktop entry not installed" # 2. Exec rewritten to the AppImage (quoted, spaces intact), TryExec dropped, # everything else preserved from the packaged entry. @@ -55,15 +55,15 @@ fi # 3. Icons landed under the name the .desktop entry references. for f in "16x16/apps/$APP_ID.png" "256x256/apps/$APP_ID.png" "scalable/apps/$APP_ID.svg"; do - [ -f "$XDG_DATA_HOME/icons/hicolor/$f" ] || fail "icon missing: $f" + [[ -f "$XDG_DATA_HOME/icons/hicolor/$f" ]] || fail "icon missing: $f" done # 4. Idempotent: a second launch must not rewrite anything (inode unchanged). before="$(stat -c %i "$DESKTOP")" out="$("$APPDIR/AppRun")" || fail "second launch exited non-zero" -[ "$out" = "stub: " ] || fail "second launch output: $out" +[[ "$out" = "stub: " ]] || fail "second launch output: $out" after="$(stat -c %i "$DESKTOP")" -[ "$before" = "$after" ] || fail "desktop entry rewritten although unchanged" +[[ "$before" = "$after" ]] || fail "desktop entry rewritten although unchanged" # 5. Moving the AppImage refreshes Exec. mv "$APPIMAGE" "$TMP/moved.AppImage" @@ -74,25 +74,25 @@ grep -Fxq "Exec=\"$(readlink -f "$APPIMAGE")\" %F" "$DESKTOP" || fail "Exec not # 6. Opt-out installs nothing. rm -rf "$XDG_DATA_HOME" TEXTURECRAFT_NO_DESKTOP_INTEGRATION=1 "$APPDIR/AppRun" >/dev/null || fail "opt-out launch exited non-zero" -[ ! -e "$XDG_DATA_HOME" ] || fail "opt-out still integrated" +[[ ! -e "$XDG_DATA_HOME" ]] || fail "opt-out still integrated" # 7. An unwritable data dir never blocks the launch. mkdir -p "$TMP/ro" && chmod a-w "$TMP/ro" out="$(XDG_DATA_HOME="$TMP/ro/data" "$APPDIR/AppRun" out.txt)" || fail "launch blocked by unwritable data dir" -[ "$out" = "stub: out.txt" ] || fail "stub not run against unwritable data dir: $out" +[[ "$out" = "stub: out.txt" ]] || fail "stub not run against unwritable data dir: $out" chmod u+w "$TMP/ro" # 8. No $APPIMAGE (extracted AppDir): launch only, nothing installed. rm -rf "$XDG_DATA_HOME" env -u APPIMAGE "$APPDIR/AppRun" >/dev/null || fail "extracted-AppDir launch exited non-zero" -[ ! -e "$XDG_DATA_HOME" ] || fail "integrated without $APPIMAGE" +[[ ! -e "$XDG_DATA_HOME" ]] || fail "integrated without $APPIMAGE" # 9. A path that would need Exec escaping (here a `$`): launch only, nothing installed. rm -rf "$XDG_DATA_HOME" odd="$TMP/odd\$(id).AppImage" : >"$odd" out="$(APPIMAGE="$odd" "$APPDIR/AppRun" x)" || fail "launch with an odd path exited non-zero" -[ "$out" = "stub: x" ] || fail "odd path: $out" -[ ! -e "$XDG_DATA_HOME" ] || fail "integrated an AppImage path that needs escaping" +[[ "$out" = "stub: x" ]] || fail "odd path: $out" +[[ ! -e "$XDG_DATA_HOME" ]] || fail "integrated an AppImage path that needs escaping" echo "AppRun desktop integration ok" diff --git a/packaging/linux/flatpak-bundle.sh b/packaging/linux/flatpak-bundle.sh index 29601bea..4e884d84 100755 --- a/packaging/linux/flatpak-bundle.sh +++ b/packaging/linux/flatpak-bundle.sh @@ -26,7 +26,7 @@ if [[ "$VERSION" == *-* ]]; then OCI_REPO=""; fi TEST=1 OCI=0 TARBALL="" -while [ $# -gt 0 ]; do +while [[ $# -gt 0 ]]; do case "$1" in --no-test) TEST=0; shift ;; --oci) OCI=1; shift ;; @@ -44,7 +44,7 @@ case "$ARCH" in esac BASENAME="texturecraft-$VERSION-linux-$ARCH" TARBALL="${TARBALL:-$DIST/$BASENAME.tar.gz}" -[ -f "$TARBALL" ] || { echo "error: $TARBALL not found (run packaging/linux/package.sh --formats tar first)" >&2; exit 1; } +[[ -f "$TARBALL" ]] || { echo "error: $TARBALL not found (run packaging/linux/package.sh --formats tar first)" >&2; exit 1; } for tool in flatpak flatpak-builder; do command -v "$tool" >/dev/null || { echo "error: $tool not found (apt install flatpak flatpak-builder librsvg2-common)" >&2; exit 1; } done @@ -55,7 +55,7 @@ WORK="$CARGO_TARGET_DIR/flatpak-bundle" rm -rf "$WORK" mkdir -p "$WORK/stage" tar -xzf "$TARBALL" -C "$WORK/stage" --strip-components=1 -[ -x "$WORK/stage/bin/texturecraft" ] || { echo "error: $TARBALL has no bin/texturecraft" >&2; exit 1; } +[[ -x "$WORK/stage/bin/texturecraft" ]] || { echo "error: $TARBALL has no bin/texturecraft" >&2; exit 1; } cp "$HERE/flatpak/ai.storyteller.TextureCraft.bundle.yml" "$WORK/$APP_ID.yml" flatpak remote-add --user --if-not-exists flathub "$FLATHUB" @@ -83,7 +83,7 @@ if [[ "$OCI" = 1 ]]; then echo "wrote OCI layout to $OUT_OCI" fi -if [ "$TEST" = 1 ]; then +if [[ "$TEST" = 1 ]]; then flatpak install --user -y --noninteractive --reinstall "$OUT" flatpak info --user "$APP_ID" flatpak run --command=texturecraft-cli "$APP_ID" --version diff --git a/packaging/linux/package.sh b/packaging/linux/package.sh index 865f40ca..a5a3ffd1 100755 --- a/packaging/linux/package.sh +++ b/packaging/linux/package.sh @@ -21,7 +21,7 @@ APP_ID=ai.storyteller.texturecraft SKIP_BUILD=0 FORMATS="appimage deb rpm tar" -while [ $# -gt 0 ]; do +while [[ $# -gt 0 ]]; do case "$1" in --skip-build) SKIP_BUILD=1; shift ;; --formats) FORMATS="$2"; shift 2 ;; @@ -42,7 +42,7 @@ BASENAME="texturecraft-$VERSION-linux-$ARCH" echo "==> TextureCraft $VERSION for Linux $ARCH ($FORMATS)" -if [ "$SKIP_BUILD" = 0 ]; then +if [[ "$SKIP_BUILD" = 0 ]]; then (cd "$ROOT" && cargo build --release --locked -p texturecraft -p texturecraft-cli ${CROSS_TARGET:+--target "$CROSS_TARGET"}) fi BIN="$CARGO_TARGET_DIR/${CROSS_TARGET:+$CROSS_TARGET/}release" @@ -89,7 +89,7 @@ if has deb || has rpm; then # nfpm expands env vars in fields like `version` and `arch`, but not in `contents[].src`. sed "s|\${STAGE}|$STAGE|g" "$HERE/nfpm.yaml" >"$WORK/nfpm.yaml" # The riscv64 cross sysroot is Ubuntu 24.04, whose glibc floor is 2.39. - if [ "$ARCH" = riscv64 ]; then sed -i "s/libc6 (>= 2.35)/libc6 (>= 2.39)/" "$WORK/nfpm.yaml"; fi + if [[ "$ARCH" = riscv64 ]]; then sed -i "s/libc6 (>= 2.35)/libc6 (>= 2.39)/" "$WORK/nfpm.yaml"; fi for fmt in deb rpm; do if has "$fmt"; then (cd "$ROOT" && nfpm package -f "$WORK/nfpm.yaml" -p "$fmt" -t "$DIST/$BASENAME.$fmt"); fi done @@ -110,9 +110,9 @@ if has appimage; then ln -s "$APP_ID.png" "$APPDIR/.DirIcon" TOOL="${APPIMAGETOOL:-$(command -v appimagetool || true)}" - if [ -z "$TOOL" ]; then + if [[ -z "$TOOL" ]]; then TOOL="$CARGO_TARGET_DIR/appimagetool-$ARCH.AppImage" - if [ ! -x "$TOOL" ]; then + if [[ ! -x "$TOOL" ]]; then curl --proto '=https' -fsSL -o "$TOOL" "https://github.com/AppImage/appimagetool/releases/download/continuous/appimagetool-$ARCH.AppImage" chmod +x "$TOOL" fi @@ -135,15 +135,15 @@ if has appimage; then # package) appimagetool also writes the .zsync, into its working directory, hence the cd. (cd "$DIST" && ARCH="$ARCH" APPIMAGE_EXTRACT_AND_RUN=1 "$TOOL" --no-appstream -u "$UPDATE_INFO" "$APPDIR" "$OUT") echo "wrote $OUT" - if [ -s "$OUT.zsync" ]; then + if [[ -s "$OUT.zsync" ]]; then echo "wrote $OUT.zsync" else warn "zsyncmake not found, so $OUT.zsync was not written; AppImage delta updates need it" fi fi -if [ -n "${CROSS_TARGET:-}" ]; then - if [ -n "${EMULATOR:-}" ]; then "$EMULATOR" "$STAGE/usr/bin/texturecraft-cli" --version; fi +if [[ -n "${CROSS_TARGET:-}" ]]; then + if [[ -n "${EMULATOR:-}" ]]; then "$EMULATOR" "$STAGE/usr/bin/texturecraft-cli" --version; fi else "$STAGE/usr/bin/texturecraft-cli" --version fi diff --git a/packaging/macos/import-cert.sh b/packaging/macos/import-cert.sh index 249dfed1..9a414085 100755 --- a/packaging/macos/import-cert.sh +++ b/packaging/macos/import-cert.sh @@ -12,7 +12,7 @@ umask 077 # shellcheck source=../env.sh . "$(dirname "${BASH_SOURCE[0]}")/../env.sh" -if [ -z "${APPLE_CERTIFICATE:-}" ]; then +if [[ -z "${APPLE_CERTIFICATE:-}" ]]; then warn "APPLE_CERTIFICATE is not set: macOS builds will be ad-hoc signed and not notarized" exit 0 fi @@ -36,13 +36,13 @@ security set-key-partition-list -S apple-tool:,apple:,codesign: -s -k "$KC_PASS" security list-keychains -d user -s "$KEYCHAIN" $(security list-keychains -d user | tr -d '"') IDENTITY="$(security find-identity -v -p codesigning "$KEYCHAIN" | awk '/Developer ID Application/ { print $2; exit }')" -if [ -z "$IDENTITY" ]; then +if [[ -z "$IDENTITY" ]]; then security find-identity -v -p codesigning "$KEYCHAIN" >&2 echo "error: no 'Developer ID Application' identity in APPLE_CERTIFICATE" >&2 exit 1 fi echo "Imported signing identity $IDENTITY" -if [ -n "${GITHUB_ENV:-}" ]; then +if [[ -n "${GITHUB_ENV:-}" ]]; then { echo "MACOS_SIGN_IDENTITY=$IDENTITY"; echo "MACOS_KEYCHAIN=$KEYCHAIN"; } >>"$GITHUB_ENV" else echo "MACOS_SIGN_IDENTITY=$IDENTITY" diff --git a/packaging/macos/package.sh b/packaging/macos/package.sh index c39774e3..36298423 100755 --- a/packaging/macos/package.sh +++ b/packaging/macos/package.sh @@ -19,7 +19,7 @@ HERE="$ROOT/packaging/macos" ARCH=universal SKIP_BUILD=0 -while [ $# -gt 0 ]; do +while [[ $# -gt 0 ]]; do case "$1" in --arch) ARCH="$2"; shift 2 ;; --skip-build) SKIP_BUILD=1; shift ;; @@ -44,9 +44,9 @@ DMG="$DIST/texturecraft-$VERSION-macos-$ARCH.dmg" CLI_ZIP="$DIST/texturecraft-cli-$VERSION-macos-$ARCH.zip" NOTARIZE=0 -if [ "$IDENTITY" = "-" ]; then +if [[ "$IDENTITY" = "-" ]]; then warn "macOS: ad-hoc signing (no MACOS_SIGN_IDENTITY); artifacts are not notarized" -elif [ -n "${APPLE_ID:-}" ] && [ -n "${APPLE_PASSWORD:-}" ] && [ -n "${APPLE_TEAM_ID:-}" ]; then +elif [[ -n "${APPLE_ID:-}" ]] && [[ -n "${APPLE_PASSWORD:-}" ]] && [[ -n "${APPLE_TEAM_ID:-}" ]]; then NOTARIZE=1 else warn "macOS: APPLE_ID / APPLE_PASSWORD / APPLE_TEAM_ID incomplete; signed but not notarized" @@ -55,7 +55,7 @@ fi echo "==> TextureCraft $VERSION for macOS ($ARCH), identity: $IDENTITY, notarize: $NOTARIZE" # ---- build ------------------------------------------------------------------------------------- -if [ "$SKIP_BUILD" = 0 ]; then +if [[ "$SKIP_BUILD" = 0 ]]; then args=() for t in "${TARGETS[@]}"; do args+=(--target "$t"); done (cd "$ROOT" && cargo build --release --locked -p texturecraft -p texturecraft-cli "${args[@]}") @@ -74,9 +74,9 @@ done sign() { # Hardened runtime + secure timestamp for a real identity; ad-hoc can't be timestamped. local ts=(--timestamp) - [ "$IDENTITY" = "-" ] && ts=(--timestamp=none) + [[ "$IDENTITY" = "-" ]] && ts=(--timestamp=none) local kc=() - [ -n "${MACOS_KEYCHAIN:-}" ] && kc=(--keychain "$MACOS_KEYCHAIN") + [[ -n "${MACOS_KEYCHAIN:-}" ]] && kc=(--keychain "$MACOS_KEYCHAIN") codesign --force --sign "$IDENTITY" ${kc[@]+"${kc[@]}"} "${ts[@]}" "$@" } @@ -88,8 +88,8 @@ notarize() { echo "$out" id="$(printf '%s' "$out" | plutil -extract id raw -o - - 2>/dev/null || true)" status="$(printf '%s' "$out" | plutil -extract status raw -o - - 2>/dev/null || true)" - if [ "$status" != "Accepted" ]; then - if [ -n "$id" ]; then + if [[ "$status" != "Accepted" ]]; then + if [[ -n "$id" ]]; then xcrun notarytool log "$id" --apple-id "$APPLE_ID" --password "$APPLE_PASSWORD" --team-id "$APPLE_TEAM_ID" || true fi echo "error: notarization of $(basename "$file") failed (status: ${status:-unknown})" >&2 @@ -103,7 +103,7 @@ stapler_retry() { local action="$1" target="$2" try for try in 1 2 3 4; do xcrun stapler "$action" "$target" && return 0 - [ "$try" = 4 ] && break + [[ "$try" = 4 ]] && break echo "stapler $action failed (try $try of 4); retrying in $((try * 20)) s" >&2 sleep $((try * 20)) done @@ -131,7 +131,7 @@ sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP/Contents/ sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP" codesign --verify --strict --deep --verbose=2 "$APP" -if [ "$NOTARIZE" = 1 ]; then +if [[ "$NOTARIZE" = 1 ]]; then ditto -c -k --keepParent "$APP" "$WORK/TextureCraft-notarize.zip" notarize "$WORK/TextureCraft-notarize.zip" stapler_retry staple "$APP" @@ -153,7 +153,7 @@ hdiutil convert "$WORK/raw.dmg" -format UDZO -imagekey zlib-level=9 -o "$DMG" rm -f "$WORK/raw.dmg" sign "$DMG" codesign --verify --strict --verbose=2 "$DMG" -if [ "$NOTARIZE" = 1 ]; then +if [[ "$NOTARIZE" = 1 ]]; then notarize "$DMG" stapler_retry staple "$DMG" stapler_retry validate "$DMG" @@ -174,7 +174,7 @@ rm -f "$CLI_ZIP" ditto -c -k --keepParent "$CLI_DIR" "$CLI_ZIP" # notarytool accepts a zip of the bare binary. A bare Mach-O can't carry a stapled ticket, so # Gatekeeper looks the notarization up online when a quarantined copy first runs. -if [ "$NOTARIZE" = 1 ]; then notarize "$CLI_ZIP"; fi +if [[ "$NOTARIZE" = 1 ]]; then notarize "$CLI_ZIP"; fi "$WORK/bin/texturecraft-cli" --version echo "==> done (check the artifacts as shipped with packaging/macos/verify.sh --arch $ARCH)" diff --git a/packaging/macos/verify.sh b/packaging/macos/verify.sh index 948107f0..110622db 100755 --- a/packaging/macos/verify.sh +++ b/packaging/macos/verify.sh @@ -23,7 +23,7 @@ set -euo pipefail . "$(dirname "${BASH_SOURCE[0]}")/../env.sh" ARCH=universal -while [ $# -gt 0 ]; do +while [[ $# -gt 0 ]]; do case "$1" in --arch) ARCH="$2"; shift 2 ;; -h | --help) sed -n '2,20p' "$0"; exit 0 ;; @@ -41,13 +41,13 @@ DMG="$DIST/texturecraft-$VERSION-macos-$ARCH.dmg" CLI_ZIP="$DIST/texturecraft-cli-$VERSION-macos-$ARCH.zip" IDENTITY="${MACOS_SIGN_IDENTITY:--}" STRICT=0 -if [ "$IDENTITY" != "-" ] && [ -n "${APPLE_ID:-}" ] && [ -n "${APPLE_PASSWORD:-}" ] && [ -n "${APPLE_TEAM_ID:-}" ]; then +if [[ "$IDENTITY" != "-" ]] && [[ -n "${APPLE_ID:-}" ]] && [[ -n "${APPLE_PASSWORD:-}" ]] && [[ -n "${APPLE_TEAM_ID:-}" ]]; then STRICT=1 fi FAILED=0 fail() { - if [ "$STRICT" = 1 ]; then + if [[ "$STRICT" = 1 ]]; then echo "error: $*" >&2 FAILED=1 else @@ -58,13 +58,13 @@ fail() { # spctl's online ticket lookup can lag a few seconds behind notarytool's "Accepted". assess() { local out attempt tries=1 - [ "$STRICT" = 1 ] && tries=5 + [[ "$STRICT" = 1 ]] && tries=5 for attempt in $(seq "$tries"); do if out="$(spctl "$@" 2>&1)"; then printf '%s\n' "$out" return 0 fi - [ "$attempt" = "$tries" ] || sleep 10 + [[ "$attempt" = "$tries" ]] || sleep 10 done printf '%s\n' "$out" return 1 @@ -75,7 +75,7 @@ stapler_validate() { local target="$1" try for try in 1 2 3 4; do xcrun stapler validate "$target" && return 0 - [ "$try" = 4 ] && break + [[ "$try" = 4 ]] && break echo "stapler validate failed (try $try of 4); retrying in $((try * 20)) s" >&2 sleep $((try * 20)) done @@ -83,7 +83,7 @@ stapler_validate() { } for f in "$DMG" "$CLI_ZIP"; do - if [ ! -f "$f" ]; then + if [[ ! -f "$f" ]]; then echo "error: missing $f" >&2 exit 1 fi @@ -96,7 +96,7 @@ trap 'rm -rf "$WORK"' EXIT echo "==> $(basename "$CLI_ZIP")" ditto -x -k "$CLI_ZIP" "$WORK/cli" CLI="$WORK/cli/texturecraft-cli-$VERSION-macos-$ARCH/texturecraft-cli" -if [ ! -x "$CLI" ]; then +if [[ ! -x "$CLI" ]]; then echo "error: $(basename "$CLI_ZIP") has no executable texturecraft-cli-$VERSION-macos-$ARCH/texturecraft-cli" >&2 exit 1 fi @@ -120,7 +120,7 @@ printf '%s\n' "$details" | grep -q '^Authority=Developer ID Application:' \ || fail "texturecraft-cli is not signed with a Developer ID Application identity" printf '%s\n' "$details" | grep -q '^Timestamp=' \ || fail "texturecraft-cli signature has no secure timestamp" -if [ -n "${APPLE_TEAM_ID:-}" ]; then +if [[ -n "${APPLE_TEAM_ID:-}" ]]; then printf '%s\n' "$details" | grep -qx "TeamIdentifier=$APPLE_TEAM_ID" \ || fail "texturecraft-cli is signed by a different team" fi @@ -137,24 +137,24 @@ fi # ---- DMG --------------------------------------------------------------------------------------- echo "==> $(basename "$DMG")" codesign --verify --strict --verbose=2 "$DMG" -if [ "$STRICT" = 1 ]; then +if [[ "$STRICT" = 1 ]]; then stapler_validate "$DMG" || fail "no notarization ticket stapled to the DMG" assess --assess --type open --context context:primary-signature -vv "$DMG" \ || fail "Gatekeeper rejects the DMG" fi -if [ "$FAILED" != 0 ]; then +if [[ "$FAILED" != 0 ]]; then echo "error: macOS artifacts failed verification" >&2 exit 1 fi -if [ "$STRICT" = 1 ]; then +if [[ "$STRICT" = 1 ]]; then result="signed (Developer ID, hardened runtime), notarized; DMG stapled" else result="signature intact; Developer ID and notarization not required (no signing secrets)" fi echo "==> verified: $result" -if [ -n "${GITHUB_STEP_SUMMARY:-}" ]; then +if [[ -n "${GITHUB_STEP_SUMMARY:-}" ]]; then { echo "- macOS \`$(basename "$DMG")\`, \`$(basename "$CLI_ZIP")\`: $result" } >>"$GITHUB_STEP_SUMMARY" diff --git a/packaging/web/package.sh b/packaging/web/package.sh index baecbc0d..7b5a4915 100755 --- a/packaging/web/package.sh +++ b/packaging/web/package.sh @@ -11,13 +11,13 @@ set -euo pipefail . "$(dirname "${BASH_SOURCE[0]}")/../env.sh" HERE="$ROOT/packaging/web" -if [ "${1:-}" != "--skip-build" ]; then +if [[ "${1:-}" != "--skip-build" ]]; then command -v trunk >/dev/null || { echo "error: trunk not found (cargo install trunk --locked)" >&2; exit 1; } (cd "$ROOT/apps/texturecraft-web" && trunk build --release) fi SITE="$ROOT/dist/web" -[ -f "$SITE/index.html" ] || { echo "error: $SITE/index.html missing; run without --skip-build" >&2; exit 1; } +[[ -f "$SITE/index.html" ]] || { echo "error: $SITE/index.html missing; run without --skip-build" >&2; exit 1; } # Paths must be relative so the site works under any prefix (public_url = "./" in Trunk.toml). if grep -Eq '(src|href)="/[^/]' "$SITE/index.html"; then echo "error: $SITE/index.html has root-absolute URLs; it would break when served from a sub-path" >&2 @@ -27,19 +27,19 @@ fi # Size gate: Cloudflare Pages/Workers reject any single file over 25 MiB, and other # hosts and CDNs have similar caps. Fail well before that so a regression shows up here, not at # upload time. Override with TEXTURECRAFT_WASM_MAX_BYTES only to investigate. -MAX_WASM_BYTES="${TEXTURECRAFT_WASM_MAX_BYTES:-25165824}" # 24 MiB +MAX_WASM_BYTES=$((10#${TEXTURECRAFT_WASM_MAX_BYTES:-25165824})) # 24 MiB WASM_COUNT=0 for wasm in "$SITE"/*.wasm; do - [ -f "$wasm" ] || continue + [[ -f "$wasm" ]] || continue WASM_COUNT=$((WASM_COUNT + 1)) size=$(wc -c <"$wasm" | tr -d ' ') echo "$(basename "$wasm"): $size bytes ($((size / 1048576)) MiB; limit $MAX_WASM_BYTES)" - if [ "$size" -gt "$MAX_WASM_BYTES" ]; then + if [[ "$size" -gt "$MAX_WASM_BYTES" ]]; then echo "error: $(basename "$wasm") is $size bytes, over the $MAX_WASM_BYTES-byte limit (Cloudflare's per-file cap is 25 MiB)" >&2 exit 1 fi done -[ "$WASM_COUNT" -gt 0 ] || { echo "error: no .wasm in $SITE" >&2; exit 1; } +[[ "$WASM_COUNT" -gt 0 ]] || { echo "error: no .wasm in $SITE" >&2; exit 1; } NAME="texturecraft-web-$VERSION" WORK="$CARGO_TARGET_DIR/web-package" From bf76e5f8526d3fa085c0fd0bf9f4ee03d3a58cc5 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Tue, 10 Nov 2026 18:59:18 -0500 Subject: [PATCH 50/64] Reject stale decal effect frames --- crates/ui-egui/src/viewport.rs | 142 ++++++++++++++++++++++++++++++++- 1 file changed, 140 insertions(+), 2 deletions(-) diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index 4032418c..5eb9846a 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -816,20 +816,25 @@ impl DecalFrame { use texturecraft_engine::StackTarget; use texturecraft_engine::compose::pattern::{decal_axes, decal_corners}; use texturecraft_engine::core::{EffectKind, Fill, LayerKind, Projection}; + if app.ui.mode != crate::state::Mode::Painting { return None; } let layers = &app.session.doc.project; + let selected = app.session.selected_layer()?; let (layer, effect, decal) = match app.session.target { StackTarget::Content => { - let layer = app.session.selected_layer().and_then(|id| layers.content_layer(id))?; + let layer = layers.content_layer(selected)?; let LayerKind::Fill(Fill { projection: Projection::Decal(decal), .. }) = &layer.kind else { return None }; (layer.id, None, decal) } StackTarget::Effect(effect) => { - let (owner, mask_effect) = layers.effect(effect)?; + // Only the selected layer's effective mask may supply a decal frame, including an instance's inherited mask + let owner = layers.mask_owner(selected); + let mask = layers.layer(owner).ok()?.mask.as_ref()?; + let mask_effect = mask.effects.iter().find(|candidate| candidate.id == effect)?; let EffectKind::Fill { projection: Projection::Decal(decal), .. } = &mask_effect.kind else { return None }; (owner, Some(effect), decal) @@ -1618,6 +1623,139 @@ fn bake_paint_overlay(app: &TextureCraftApp, ui: &Ui, painter: &egui::Painter, t mod tests { use super::*; + /// A selected mask decal on the ball, with another texture set available for selection tests + fn decal_frame_app(render: bool) -> egui_kittest::Harness<'static, TextureCraftApp> { + let session = + Session::new_project("Decal selection", texturecraft_engine::geom::primitives::material_ball(), "builtin:material_ball", None, 256).unwrap(); + let builder = egui_kittest::Harness::builder().with_size(vec2(1600.0, 960.0)); + let builder = if render { builder.wgpu() } else { builder }; + let mut harness = builder.build_eframe(|context| TextureCraftApp::new(context, session)); + harness.run_steps(4); + let mut png = Vec::new(); + image::RgbaImage::from_pixel(4, 4, image::Rgba([255, 255, 255, 255])).write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).unwrap(); + let image = harness.state_mut().session.import_resource_bytes("decal.png", png).unwrap(); + harness.state_mut().run("layer.add.decal", json!({"image": image, "channel": "mask", "size": 0.5})).unwrap(); + harness.run_steps(2); + assert_eq!(harness.state().session.ts(), 0); + assert!(DecalFrame::of(harness.state(), harness.state().viewport_rect).is_some()); + harness + } + + /// Move a primary-button drag through enough frames to reach the viewport's decal handles + fn drag_decal_handle(harness: &mut egui_kittest::Harness<'_, TextureCraftApp>, from: Pos2, to: Pos2) { + let modifiers = egui::Modifiers::NONE; + harness.hover_at(from); + harness.event(egui::Event::PointerButton { pos: from, button: PointerButton::Primary, pressed: true, modifiers }); + harness.run_steps(2); + for step in 1..=4 { + harness.hover_at(from.lerp(to, step as f32 / 4.0)); + harness.run_steps(1); + } + harness.event(egui::Event::PointerButton { pos: to, button: PointerButton::Primary, pressed: false, modifiers }); + harness.run_steps(2); + } + + #[test] + fn decal_frame_rejects_a_stale_effect_after_failed_layer_selection() { + use texturecraft_engine::{StackTarget, execute}; + + for texture_set in [0, 1] { + let mut harness = decal_frame_app(false); + let original = DecalFrame::of(harness.state(), harness.state().viewport_rect).unwrap(); + let effect = original.effect.unwrap(); + let session = &mut harness.state_mut().session; + execute(session, "textureSet.select", &json!({"ts": texture_set})).unwrap(); + let other = execute(session, "layer.add.paint", &json!({"name": "Other layer"})).unwrap()["layer"].clone(); + execute(session, "layer.select", &json!({"layer": original.layer.0, "target": effect.0})).unwrap(); + + let selected = execute(session, "layer.select", &json!({"layer": other, "target": effect.0})); + + assert!(selected.is_err()); + assert_eq!(session.ts(), texture_set); + assert_eq!(session.selected_layer().unwrap().0, other.as_u64().unwrap()); + assert_eq!(session.target, StackTarget::Effect(effect), "the failed selection leaves the previous effect target"); + assert!(DecalFrame::of(harness.state(), harness.state().viewport_rect).is_none(), "a stale effect must not show a decal frame"); + + drag_decal_handle(&mut harness, original.corners[1], original.center + (original.corners[1] - original.center) * 1.5); + drag_decal_handle(&mut harness, original.knob, original.knob + vec2(40.0, 0.0)); + + let effect = &harness.state().session.doc.project.effect(effect).unwrap().1.kind; + assert!( + matches!(effect, texturecraft_engine::core::EffectKind::Fill { projection: texturecraft_engine::core::Projection::Decal(decal), .. } if *decal == original.decal) + ); + } + } + + #[test] + fn decal_frame_keeps_an_instances_inherited_mask_effect_editable() { + use texturecraft_engine::execute; + + let mut harness = decal_frame_app(false); + let original = DecalFrame::of(harness.state(), harness.state().viewport_rect).unwrap(); + let effect = original.effect.unwrap(); + let session = &mut harness.state_mut().session; + let instance = execute(session, "layer.instance", &json!({"layer": original.layer.0, "ts": 1})).unwrap()["layer"].clone(); + + // The source effect remains a valid inherited target when selection changes to its instance + assert!(execute(session, "layer.select", &json!({"layer": instance, "target": effect.0})).is_err()); + + assert_eq!(session.ts(), 1); + assert_eq!(session.selected_layer().unwrap().0, instance.as_u64().unwrap()); + let inherited = DecalFrame::of(harness.state(), harness.state().viewport_rect).unwrap(); + assert_eq!((inherited.layer, inherited.effect, inherited.decal), (original.layer, original.effect, original.decal)); + + drag_decal_handle(&mut harness, inherited.corners[1], inherited.center + (inherited.corners[1] - inherited.center) * 1.5); + + let edited = DecalFrame::of(harness.state(), harness.state().viewport_rect).unwrap(); + assert!(edited.decal.size[0] > original.decal.size[0], "scaling an inherited decal edits its source"); + } + + #[test] + fn decal_frame_rejects_a_source_mask_overridden_by_the_selected_instance() { + use texturecraft_engine::execute; + + let mut harness = decal_frame_app(false); + let original = DecalFrame::of(harness.state(), harness.state().viewport_rect).unwrap(); + let effect = original.effect.unwrap(); + let session = &mut harness.state_mut().session; + let instance = execute(session, "layer.instance", &json!({"layer": original.layer.0, "ts": 1})).unwrap()["layer"].clone(); + execute(session, "mask.add.black", &json!({"layer": instance})).unwrap(); + execute(session, "layer.select", &json!({"layer": original.layer.0, "target": effect.0})).unwrap(); + + assert!(execute(session, "layer.select", &json!({"layer": instance, "target": effect.0})).is_err()); + + assert!(DecalFrame::of(harness.state(), harness.state().viewport_rect).is_none(), "an override hides the source's mask decal"); + } + + #[test] + #[ignore = "requires an offscreen GPU adapter and TC_UI_SNAPSHOTS"] + fn decal_frame_selection_snapshots() { + use texturecraft_engine::execute; + + let Some(directory) = std::env::var_os("TC_UI_SNAPSHOTS").map(std::path::PathBuf::from) else { return }; + + std::fs::create_dir_all(&directory).unwrap(); + let mut harness = decal_frame_app(true); + let original = DecalFrame::of(harness.state(), harness.state().viewport_rect).unwrap(); + let effect = original.effect.unwrap(); + let session = &mut harness.state_mut().session; + let instance = execute(session, "layer.instance", &json!({"layer": original.layer.0, "ts": 1})).unwrap()["layer"].clone(); + assert!(execute(session, "layer.select", &json!({"layer": instance, "target": effect.0})).is_err()); + harness.run_steps(6); + + assert!(DecalFrame::of(harness.state(), harness.state().viewport_rect).is_some()); + harness.render().unwrap().save(directory.join("decal-frame-inherited.png")).unwrap(); + + let session = &mut harness.state_mut().session; + let other = execute(session, "layer.add.paint", &json!({"name": "Other layer"})).unwrap()["layer"].clone(); + execute(session, "layer.select", &json!({"layer": original.layer.0, "target": effect.0})).unwrap(); + assert!(execute(session, "layer.select", &json!({"layer": other, "target": effect.0})).is_err()); + harness.run_steps(6); + + assert!(DecalFrame::of(harness.state(), harness.state().viewport_rect).is_none()); + harness.render().unwrap().save(directory.join("decal-frame-stale.png")).unwrap(); + } + #[test] fn live_bake_preview_hides_setup_overlays_and_restores_their_preferences() { let session = texturecraft_engine::sample_session(256, 64).unwrap(); From 2f2ba103be59b27d10b7ff8b5849a05e5cd0d95d Mon Sep 17 00:00:00 2001 From: chasse20 Date: Tue, 10 Nov 2026 20:39:32 -0500 Subject: [PATCH 51/64] Fix non-Linux path benchmark imports --- crates/engine/tests/it/path_perf.rs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/crates/engine/tests/it/path_perf.rs b/crates/engine/tests/it/path_perf.rs index 7c103b18..8c81a9ea 100644 --- a/crates/engine/tests/it/path_perf.rs +++ b/crates/engine/tests/it/path_perf.rs @@ -3,8 +3,8 @@ use std::time::{Duration, Instant}; use serde_json::json; -use texturecraft_engine::geom::{glam::Vec2, primitives}; -use texturecraft_engine::{Session, execute}; +use texturecraft_engine::execute; +use texturecraft_engine::geom::glam::Vec2; fn median_ms(samples: &mut [Duration]) -> f64 { samples.sort_unstable(); @@ -72,6 +72,9 @@ fn resident_kib() -> usize { #[test] #[ignore = "release memory soak: 1,000 edits across 100 canceled previews"] fn path_preview_memory_soak() { + use texturecraft_engine::Session; + use texturecraft_engine::geom::primitives; + let mut session = Session::new_project("Path soak", primitives::sphere(1.0, 48, 24), "builtin:sphere", None, 512).unwrap(); session.viewport = Vec2::splat(400.0); session.update(); From 0886db98f81e305b68cc4800aacaeb3672b2baa1 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Tue, 10 Nov 2026 20:49:34 -0500 Subject: [PATCH 52/64] Fix moved fill copies on curved surfaces --- crates/engine/src/path_tool.rs | 59 +++++++++++++++++++----------- crates/engine/tests/it/symmetry.rs | 21 +++++++++++ 2 files changed, 59 insertions(+), 21 deletions(-) diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index a922489d..b9f894e6 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -11,7 +11,7 @@ use std::collections::{BTreeMap, BTreeSet}; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; use texturecraft_core::{Channel, Effect, EffectKind, LayerId, Mask, MaskBackground, PathShape}; -use texturecraft_geom::glam::{Vec2, Vec3}; +use texturecraft_geom::glam::{Mat3, Vec2, Vec3}; use texturecraft_geom::{OrbitCamera, surface_at}; use texturecraft_paint::{BrushSettings, Lasso, fill_coverage, spline}; @@ -26,6 +26,8 @@ pub const MAX_PATH_POINTS: usize = 4096; const STEP_PX: f32 = 2.0; const STEP_UV: f32 = 0.001; const MIN_PROJECTIVE_W: f32 = 1e-6; +// Match the minimum world-space scale used by brush stamps +const MIN_BRUSH_SCALE: f32 = 1e-4; // Allow ray hits to differ slightly from transformed texel positions const RAY_HIT_RELATIVE_TOLERANCE: f32 = 0.001; @@ -455,57 +457,72 @@ impl Session { /// Fill the inside of `polygon` (viewport pixels over the visible surface, or texture coordinates); returns the touched tiles fn lasso_fill(&mut self, polygon: Vec, uv: bool, viewport: Vec2) -> Result { let texture_set = self.ts(); - let (gbuf, mut canvas) = self.fill_canvas(texture_set)?; - let width = gbuf.width.max(1); + let (uv_buffer, mut canvas) = self.fill_canvas(texture_set)?; + let width = uv_buffer.width.max(1); if uv { - let lasso = Lasso::new(polygon.iter().map(|point| *point * Vec2::new(width as f32, gbuf.height as f32)).collect()); - fill_coverage(&mut canvas, &gbuf, |texel, _| lasso.coverage(Vec2::new((texel as u32 % width) as f32 + 0.5, (texel as u32 / width) as f32 + 0.5))); + let lasso = Lasso::new(polygon.iter().map(|point| *point * Vec2::new(width as f32, uv_buffer.height as f32)).collect()); + fill_coverage(&mut canvas, &uv_buffer, |texel, _| { + lasso.coverage(Vec2::new((texel as u32 % width) as f32 + 0.5, (texel as u32 / width) as f32 + 0.5)) + }); } else { let lasso = Lasso::new(polygon); - let view_proj = self.camera.view_proj(viewport.x.max(1.0) / viewport.y.max(1.0)); - let inverse_view_proj = view_proj.inverse(); - let (backface_culling, mesh, bvh) = (self.tool.brush.backface_culling, &self.mesh, &self.bvh); + let view_projection = self.camera.view_proj(viewport.x.max(1.0) / viewport.y.max(1.0)); + let inverse_view_projection = view_projection.inverse(); + let (mesh, bvh) = (&self.mesh, &self.bvh); + let brush = self.tool.brush.sanitized(); // A visible source inside the lasso can paint each symmetry copy let (bounds_min, bounds_max) = mesh.bounds(); - let symmetry = self.tool.brush.sanitized().symmetry; + let symmetry = brush.symmetry; let symmetry_origin = symmetry.origin((bounds_min + bounds_max) * 0.5); let inverses: Vec<_> = symmetry.transforms().iter().map(|transform| transform.inverse()).collect(); - fill_coverage(&mut canvas, &gbuf, |texel, _| { - let Some(surface) = gbuf.surface(mesh, texel) else { return 0.0 }; + // Copies can leave the source surface, within the same depth allowed for brush stamps + let copy_depth = brush.size * (bounds_max - bounds_min).length().max(MIN_BRUSH_SCALE) * brush.depth; + let eye = self.camera.eye(); + let camera_distance = self.camera.distance.max(MIN_BRUSH_SCALE); + + fill_coverage(&mut canvas, &uv_buffer, |texel, _| { + let Some(surface) = uv_buffer.surface(mesh, texel) else { return 0.0 }; let mut best = 0.0f32; for inverse in &inverses { let position = symmetry_origin + *inverse * (surface.pos - symmetry_origin); - let clip = view_proj * position.extend(1.0); + let clip = view_projection * position.extend(1.0); if clip.w <= MIN_PROJECTIVE_W { continue; } - let ndc = Vec2::new(clip.x, clip.y) / clip.w; - let coverage = lasso.coverage(to_pixels(ndc, viewport)); + let normalized_screen = Vec2::new(clip.x, clip.y) / clip.w; + let coverage = lasso.coverage(to_pixels(normalized_screen, viewport)); if coverage <= best { continue; } // Use the source surface normal; a copy may face away from the camera - let near_clip = inverse_view_proj * ndc.extend(0.0).extend(1.0); + let near_clip = inverse_view_projection * normalized_screen.extend(0.0).extend(1.0); let origin = near_clip.truncate() / near_clip.w; let to_surface = position - origin; let distance = to_surface.length(); let Some(direction) = to_surface.try_normalize() else { continue }; - let Some(hit) = bvh - .closest(origin, direction, distance * (1.0 + RAY_HIT_RELATIVE_TOLERANCE)) - .filter(|hit| hit.t >= distance * (1.0 - RAY_HIT_RELATIVE_TOLERANCE)) - else { - continue; + let Some(hit) = bvh.closest(origin, direction, distance * (1.0 + RAY_HIT_RELATIVE_TOLERANCE)) else { continue }; + + // Keep identity copies exact and reject occluders beyond the bounded displacement + let off_surface = if *inverse == Mat3::IDENTITY { + 0.0 + } else if brush.screen_space { + copy_depth * (origin + direction * hit.t).distance(eye) / camera_distance + } else { + copy_depth }; + if hit.t < distance * (1.0 - RAY_HIT_RELATIVE_TOLERANCE) - off_surface { + continue; + } let Some(source) = surface_at(mesh, hit.tri, hit.u, hit.v) else { continue }; - if backface_culling && source.nrm.dot(direction) >= 0.0 { + if brush.backface_culling && source.nrm.dot(direction) >= 0.0 { continue; } diff --git a/crates/engine/tests/it/symmetry.rs b/crates/engine/tests/it/symmetry.rs index 5072ff58..329c6f49 100644 --- a/crates/engine/tests/it/symmetry.rs +++ b/crates/engine/tests/it/symmetry.rs @@ -98,6 +98,27 @@ fn a_closed_path_fill_mirrors_around_the_moved_plane() { assert!(!red_at(&session, Vec3::new(-inside.x, inside.y, 0.0)), "nothing across the mesh center"); } +#[test] +fn a_closed_path_fill_reaches_a_curved_copy_across_a_moved_plane() { + let mut session = session(primitives::sphere(1.0, 48, 24)); + + // Occlusion must still protect the rear surface when normal-based culling is disabled + execute(&mut session, "tool.brush", &json!({"symmetryX": true, "symmetryOffset": [0.1, 0.0, 0.0], "backfaceCulling": false})).unwrap(); + let inside = surface(&session, 185.0, 200.0); + let mirrored_x = 0.2 - inside.x; + let copy = Vec3::new(mirrored_x, inside.y, (1.0 - mirrored_x * mirrored_x - inside.y * inside.y).sqrt()); + + let square = json!([[175, 190], [195, 190], [195, 210], [175, 210]]); + execute(&mut session, "tool.path", &json!({"points": square, "closed": true, "fill": true, "commit": true})).unwrap(); + + assert!(red_at(&session, inside), "the filled lasso"); + assert!(red_at(&session, copy), "its copy where the sphere curves away across x = 0.1"); + + session.camera.yaw = std::f32::consts::PI; + assert!(!red_at(&session, Vec3::new(copy.x, copy.y, -copy.z)), "the hidden back of the copy stays clean"); + assert!(!red_at(&session, Vec3::new(inside.x, inside.y, -inside.z)), "the hidden back of the source stays clean"); +} + /// How much redder than green a texel must be to count as painted (faded edges included) const PAINTED_TINT: f32 = 0.05; From 9c359bacfc17a3b108f7aa17e1047b4500017609 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Tue, 10 Nov 2026 20:59:11 -0500 Subject: [PATCH 53/64] Fix Escape handling for hidden rail popups --- crates/ui-egui/src/menus.rs | 8 +- crates/ui-egui/src/rail_popup.rs | 8 +- .../tests/it/color_selection_editor.rs | 25 +++++++ crates/ui-egui/tests/it/rail.rs | 75 ++++++++++++++++++- 4 files changed, 108 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 9f49118e..b4dffdd7 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -322,14 +322,14 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { if crate::keymap::capturing(ctx) || (ctx.memory(|memory| memory.focused().is_some()) && ctx.egui_wants_keyboard_input()) { return; } + #[cfg(not(target_arch = "wasm32"))] if crate::updates_ui::blocks_input(app) { return; } - // The dispatcher reads Copy, Cut and Paste as their chords. A pasted image is Ctrl+V here, and - // Shift+Delete and Shift+Insert (Cut and Paste on Windows) are Ctrl+X and Ctrl+V unless - // something is bound to them. + // The dispatcher reads clipboard events as shortcuts; a pasted image also means Ctrl+V + // Unless bound, Shift+Delete and Shift+Insert become Ctrl+X and Ctrl+V ctx.input_mut(|input| { let held = input.modifiers; let aliases: Vec<_> = input @@ -365,7 +365,7 @@ pub fn shortcuts(app: &mut TextureCraftApp, ctx: &egui::Context) { if !popup_open && app.properties_popup.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { app.properties_popup = None; - } else if !popup_open && app.ui.rail_panel.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { + } else if !popup_open && crate::rail_popup::is_visible(app) && input.consume_key(Modifiers::NONE, Key::Escape) { app.ui.rail_panel = None; } else if !popup_open && app.picking_id_color.is_some() && input.consume_key(Modifiers::NONE, Key::Escape) { crate::id_color_pick::IdColorPick::end(app); diff --git a/crates/ui-egui/src/rail_popup.rs b/crates/ui-egui/src/rail_popup.rs index cb449540..afe85f1a 100644 --- a/crates/ui-egui/src/rail_popup.rs +++ b/crates/ui-egui/src/rail_popup.rs @@ -67,6 +67,11 @@ pub(crate) fn is_rail_panel(panel: Panel) -> bool { RAIL_PANELS.iter().any(|(rail_panel, _, _)| *rail_panel == panel) } +/// Whether the rail's open popup is visible in the current UI mode +pub(crate) fn is_visible(app: &TextureCraftApp) -> bool { + app.ui.rail_panel.is_some() && !app.ui.hide_ui && app.ui.mode != Mode::Baking +} + /// Record the rail's strip before its icons, so the popup can line up with them pub(crate) fn begin_rail(ctx: &egui::Context, strip: Rect) { ctx.data_mut(|data| { @@ -125,10 +130,9 @@ pub(crate) fn blocks_paint_input(app: &TextureCraftApp, ctx: &egui::Context) -> // Both views must ignore the release, which would otherwise start a single-dab stroke let closing = ctx.data(|data| data.get_temp::(closing_id)).unwrap_or(false); - let open = app.ui.rail_panel.is_some() && !app.ui.hide_ui && app.ui.mode != Mode::Baking; // A shortcut may open the panel during a stroke; let that existing stroke finish - !app.session.stroke_active() && (open || closing) + !app.session.stroke_active() && (is_visible(app) || closing) } /// Draw the open popup beside its icon; a press outside it closes it, as for a menu (Escape does too, in `menus.rs`) diff --git a/crates/ui-egui/tests/it/color_selection_editor.rs b/crates/ui-egui/tests/it/color_selection_editor.rs index 81c34868..eb80adf6 100644 --- a/crates/ui-egui/tests/it/color_selection_editor.rs +++ b/crates/ui-egui/tests/it/color_selection_editor.rs @@ -164,6 +164,31 @@ fn escape_cancels_the_pick_without_editing_colors() { assert_eq!(harness.state().session.history_labels(), history); } +#[test] +fn escape_cancels_id_picking_with_a_hidden_rail_popup() { + let (mut harness, effect) = app_with_color_selection(true); + harness.get_by_label(&pick_color_label()).click(); + harness.run_steps(3); + let context = harness.ctx.clone(); + texturecraft_ui_egui::menus::invoke(harness.state_mut(), &context, "ui.view.log"); + harness.run_steps(3); + harness.get_by_role_and_label(egui::Role::Button, "Close"); + harness.key_press(egui::Key::Tab); + harness.run_steps(3); + assert!(harness.state().ui.hide_ui); + assert!(harness.query_by_role_and_label(egui::Role::Button, "Close").is_none()); + assert!(harness.state().picking_id_color.is_some()); + let history = harness.state().session.history_labels(); + + harness.key_press(egui::Key::Escape); + harness.run_steps(3); + + assert!(harness.state().picking_id_color.is_none(), "one Escape cancels ID picking despite the hidden popup"); + assert_eq!(harness.state().session.view, ViewMode::Material); + assert_eq!(colors(&harness, effect), vec![FIRST, SECOND, THIRD]); + assert_eq!(harness.state().session.history_labels(), history); +} + #[test] fn picking_from_the_popup_closes_it_before_the_viewport_click() { use texturecraft_ui_egui::properties_popup::{self, PropertiesPopup}; diff --git a/crates/ui-egui/tests/it/rail.rs b/crates/ui-egui/tests/it/rail.rs index 747367b1..d2ef2052 100644 --- a/crates/ui-egui/tests/it/rail.rs +++ b/crates/ui-egui/tests/it/rail.rs @@ -2,7 +2,7 @@ use egui::{Event, Modifiers, PointerButton, Pos2, Role}; use egui_kittest::Harness; -use egui_kittest::kittest::{NodeT, Queryable}; +use egui_kittest::kittest::{NodeT, Queryable, by}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; use texturecraft_ui_egui::state::ViewLayout; @@ -91,7 +91,7 @@ fn drag(harness: &mut Harness<'_, TextureCraftApp>, from: Pos2, to: Pos2) { /// The popup's Close button, left of the rail (the window's own Close sits above the rail) fn popup_close_button(harness: &Harness<'_, TextureCraftApp>) -> Option { harness - .get_all_by_role(Role::Button) + .query_all(by().role(Role::Button)) .find(|button| button.rect().max.x < RAIL_LEFT_EDGE && button.accesskit_node().label().as_deref() == Some("Close")) .map(|button| button.rect()) } @@ -364,3 +364,74 @@ fn opening_a_rail_popup_during_a_stroke_still_finishes_the_stroke() { assert!(!harness.state().session.stroke_active()); assert_eq!(harness.state().session.history_labels().len(), history + 1); } + +#[test] +fn escape_cancels_a_stroke_with_a_hidden_rail_popup() { + let mut harness = app(); + texturecraft_engine::execute(&mut harness.state_mut().session, "layer.add.paint", &serde_json::Value::Null).unwrap(); + harness.state_mut().ui.layout = ViewLayout::Only3D; + harness.run_steps(SETTLE_FRAMES); + click_rail(&mut harness, "Log"); + harness.key_press(egui::Key::Tab); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.state().ui.hide_ui); + assert!(popup_closed(&harness)); + let center = harness.state().viewport_rect.center(); + let history = harness.state().session.history_labels(); + harness.drag_at(center); + harness.run_steps(FRAMES_PER_DRAG_EVENT); + harness.hover_at(center + egui::vec2(20.0, 0.0)); + harness.run_steps(FRAMES_PER_DRAG_EVENT); + assert!(harness.state().session.stroke_active()); + + harness.key_press(egui::Key::Escape); + harness.run_steps(SETTLE_FRAMES); + + assert!(!harness.state().session.stroke_active(), "one Escape cancels the stroke despite the hidden popup"); + harness.drop_at(center + egui::vec2(30.0, 0.0)); + harness.run_steps(SETTLE_FRAMES); + assert_eq!(harness.state().session.history_labels(), history, "the canceled stroke must not be committed on release"); +} + +#[test] +fn escape_cancels_a_path_with_a_hidden_rail_popup() { + for stored_path in [false, true] { + let mut harness = app(); + texturecraft_engine::execute(&mut harness.state_mut().session, "layer.add.paint", &serde_json::Value::Null).unwrap(); + let path = texturecraft_engine::execute( + &mut harness.state_mut().session, + "tool.path", + &serde_json::json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]], "commit": stored_path}), + ) + .unwrap(); + if stored_path { + texturecraft_engine::execute( + &mut harness.state_mut().session, + "path.edit", + &serde_json::json!({"effect": path["committed"]["effect"], "index": 0}), + ) + .unwrap(); + } + harness.run_steps(SETTLE_FRAMES); + click_rail(&mut harness, "Log"); + harness.key_press(egui::Key::Tab); + harness.run_steps(SETTLE_FRAMES); + assert!(harness.state().ui.hide_ui); + assert!(popup_closed(&harness)); + assert_eq!(harness.state().session.tool.path.points.len(), 2); + assert_eq!(harness.state().session.tool.path.editing.is_some(), stored_path); + let history = harness.state().session.history_labels(); + + harness.key_press(egui::Key::Escape); + harness.run_steps(SETTLE_FRAMES); + + assert!(harness.state().session.tool.path.points.is_empty(), "one Escape clears the path despite the hidden popup"); + assert!(harness.state().session.tool.path.editing.is_none()); + assert_eq!(harness.state().session.history_labels(), history); + + harness.key_press(egui::Key::Tab); + harness.run_steps(SETTLE_FRAMES); + + assert!(popup_shows(&harness, "Log"), "showing the UI restores its remembered popup"); + } +} From f17e524776a39e92ddd3ee4d8baf0d41332d2764 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Tue, 10 Nov 2026 21:07:57 -0500 Subject: [PATCH 54/64] Fix path undo repaint and restore Apply --- crates/engine/src/path_tool.rs | 35 +++++---- crates/engine/src/session.rs | 14 +++- crates/engine/tests/it/path_perf.rs | 4 ++ crates/engine/tests/it/path_tool.rs | 90 ++++++++++++++++++++++-- crates/ui-egui/src/i18n/ar.rs | 1 + crates/ui-egui/src/i18n/de.rs | 1 + crates/ui-egui/src/i18n/es.rs | 1 + crates/ui-egui/src/i18n/fr.rs | 1 + crates/ui-egui/src/i18n/it.rs | 1 + crates/ui-egui/src/i18n/ja.rs | 1 + crates/ui-egui/src/i18n/ko.rs | 1 + crates/ui-egui/src/i18n/pt_br.rs | 1 + crates/ui-egui/src/i18n/zh_hans.rs | 1 + crates/ui-egui/src/path_surface_cache.rs | 1 + crates/ui-egui/src/toolbar.rs | 5 ++ crates/ui-egui/tests/it/path_in_view.rs | 34 +++++++++ 16 files changed, 170 insertions(+), 22 deletions(-) diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index e0c23a40..84c7ca5e 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -166,6 +166,7 @@ pub fn specs() -> Vec { ] } +/// Set the curve from command parameters, then preview or commit it in the supplied viewport fn path(s: &mut Session, p: &Value) -> Result { const CMD: &str = "tool.path"; if s.tool.tool != Tool::Path { @@ -232,6 +233,7 @@ fn path_ref(s: &Session, cmd: &str, p: &Value) -> Result<(LayerId, usize, PathSh Ok((eid, i, shape)) } +/// Finish any draft and load a stored path's geometry and paint settings for live editing fn edit_path(s: &mut Session, p: &Value) -> Result { const CMD: &str = "path.edit"; let (eid, index, shape) = path_ref(s, CMD, p)?; @@ -249,6 +251,7 @@ fn edit_path(s: &mut Session, p: &Value) -> Result { Ok(json!({ "effect": eid.0, "index": index, "points": s.tool.path.points.len() })) } +/// Remove one stored curve and repaint its sublayer as an atomic document edit fn remove_path(s: &mut Session, p: &Value) -> Result { const CMD: &str = "path.remove"; let (eid, index, _) = path_ref(s, CMD, p)?; @@ -592,27 +595,31 @@ impl Session { self.tool.tool == Tool::Path && steps.iter().any(|s| !s.same_curve(&self.tool.path)) } - /// Undo (`back`) or redo the edited path's last point change, false when there is none; with no points left the path is gone - pub(crate) fn step_path(&mut self, back: bool) -> bool { + /// Undo (`back`) or redo a point change and repaint before returning; failure preserves the curve and history + pub(crate) fn step_path(&mut self, back: bool) -> Result { if self.tool.tool != Tool::Path { - return false; + return Ok(false); } - let (from, to) = if back { (&mut self.path_steps.0, &mut self.path_steps.1) } else { (&mut self.path_steps.1, &mut self.path_steps.0) }; - // A checkpoint taken by a press that changed nothing isn't a step - while from.last().is_some_and(|s| s.same_curve(&self.tool.path)) { - from.pop(); - } - let Some(state) = from.pop() else { return false }; + // Skip no-change checkpoints without consuming history until the repaint succeeds + let from = if back { &self.path_steps.0 } else { &self.path_steps.1 }; + let Some((index, state)) = from.iter().enumerate().rfind(|(_, state)| !state.same_curve(&self.tool.path)) else { return Ok(false) }; let path = &mut self.tool.path; - let now = std::mem::replace(path, PathState { editing: path.editing, edited: path.edited, ..state }); - to.push(now); + let previous = std::mem::replace(path, PathState { editing: path.editing, edited: path.edited, ..state.clone() }); + if let Err(error) = self.path_live() { + self.tool.path = previous; + return Err(error); + } if self.tool.path.points.is_empty() { self.stop_path_edit(); + } else { + let (from, to) = if back { (&mut self.path_steps.0, &mut self.path_steps.1) } else { (&mut self.path_steps.1, &mut self.path_steps.0) }; + from.truncate(index); + to.push(previous); } - true + Ok(true) } /// Apply a new path being placed (as Enter would) and end the edit of a stored one, e.g. before the active texture set changes @@ -989,7 +996,7 @@ mod tests { session.tool.path.points = vec![Vec3::ZERO; MAX_PATH_POINTS]; session.path_checkpoint(); assert!(!session.path_step_pending(true)); - assert!(!session.step_path(true)); + assert!(!session.step_path(true).unwrap()); for index in 0..crate::session::MAX_HISTORY + 10 { session.path_checkpoint(); @@ -999,7 +1006,7 @@ mod tests { assert_eq!(session.path_steps.0.len(), crate::session::MAX_HISTORY); assert_eq!(session.path_steps.0.iter().map(|state| state.points.len()).sum::(), crate::session::MAX_HISTORY * MAX_PATH_POINTS); session.path_checkpoint(); - assert!(session.step_path(true), "a no-change checkpoint does not consume an undo"); + assert!(session.step_path(true).unwrap(), "a no-change checkpoint does not consume an undo"); assert_eq!(session.tool.path.points[0].x, (crate::session::MAX_HISTORY + 9) as f32); } diff --git a/crates/engine/src/session.rs b/crates/engine/src/session.rs index 61b1f238..41bfacbb 100644 --- a/crates/engine/src/session.rs +++ b/crates/engine/src/session.rs @@ -647,24 +647,32 @@ impl Session { } } + /// Whether a point edit, an uncommitted path preview, or a document edit can be undone pub fn can_undo(&self) -> bool { !self.undo.is_empty() || self.path_draft.is_some() || self.path_step_pending(true) } + + /// Whether a point edit or document edit can be restored pub fn can_redo(&self) -> bool { !self.redo.is_empty() || self.path_step_pending(false) } + + /// Label of the next undo action, giving an active path's point edits and preview priority pub fn undo_label(&self) -> Option<&str> { if self.path_draft.is_some() || self.path_step_pending(true) { return Some(crate::path_tool::NEW_PATH_LABEL); } self.undo.last().map(|(l, _)| l.as_str()) } + + /// Label of the next redo action, giving an active path's point history priority pub fn redo_label(&self) -> Option<&str> { if self.path_step_pending(false) { return Some(crate::path_tool::NEW_PATH_LABEL); } self.redo.last().map(|(l, _)| l.as_str()) } + /// The undone steps, the next one to redo first. pub fn redo_labels(&self) -> Vec { self.redo.iter().rev().map(|(l, _)| l.clone()).collect() @@ -673,13 +681,14 @@ impl Session { self.undo.iter().map(|(l, _)| l.clone()).collect() } + /// Undo a point edit, cancel an uncommitted path, or restore a document snapshot, in that order pub fn undo(&mut self) -> Result { // A stroke, a box fill or an edited path under way would otherwise write over the restored document self.cancel_stroke(); self.end_polygon_fill_box(); // While a path is edited, undo steps back through its point changes first - if self.step_path(true) { + if self.step_path(true)? { return Ok(crate::path_tool::NEW_PATH_LABEL.to_string()); } @@ -699,12 +708,13 @@ impl Session { Ok(label) } + /// Restore a point edit and its pixels before considering document redo pub fn redo(&mut self) -> Result { // A stroke, a box fill or an edited path under way would otherwise write over the restored document self.cancel_stroke(); self.end_polygon_fill_box(); - if self.step_path(false) { + if self.step_path(false)? { return Ok(crate::path_tool::NEW_PATH_LABEL.to_string()); } diff --git a/crates/engine/tests/it/path_perf.rs b/crates/engine/tests/it/path_perf.rs index 8c81a9ea..ac09c302 100644 --- a/crates/engine/tests/it/path_perf.rs +++ b/crates/engine/tests/it/path_perf.rs @@ -6,11 +6,13 @@ use serde_json::json; use texturecraft_engine::execute; use texturecraft_engine::geom::glam::Vec2; +/// Sort a nonempty timing sample in place and report its middle value in milliseconds fn median_ms(samples: &mut [Duration]) -> f64 { samples.sort_unstable(); samples[samples.len() / 2].as_secs_f64() * 1_000.0 } +/// Separate repaint cost from dirty-tile and full-set compositing across representative brush sizes #[test] #[ignore = "release benchmark: two texture resolutions and brush sizes"] fn path_preview_timings() { @@ -62,12 +64,14 @@ fn path_preview_timings() { } } +/// Observe resident memory without treating allocator-retained pages as a leak #[cfg(target_os = "linux")] fn resident_kib() -> usize { let status = std::fs::read_to_string("/proc/self/status").unwrap(); status.lines().find_map(|line| line.strip_prefix("VmRSS:").and_then(|rest| rest.split_whitespace().next()).and_then(|n| n.parse().ok())).unwrap() } +/// Check that repeated canceled previews release tile buffers and leave no document history #[cfg(target_os = "linux")] #[test] #[ignore = "release memory soak: 1,000 edits across 100 canceled previews"] diff --git a/crates/engine/tests/it/path_tool.rs b/crates/engine/tests/it/path_tool.rs index 93c1ff93..77b2edbd 100644 --- a/crates/engine/tests/it/path_tool.rs +++ b/crates/engine/tests/it/path_tool.rs @@ -517,6 +517,7 @@ fn preview_uses_the_commands_explicit_viewport() { assert_eq!(preview, path_pixels(&direct)); } +/// Headless history commands must restore geometry and pixels before any frame or subsequent edit #[test] fn stored_point_edits_undo_and_redo_in_order_without_selection_steps() { let mut session = session(wall()); @@ -524,33 +525,110 @@ fn stored_point_edits_undo_and_redo_in_order_without_selection_steps() { let effect = texturecraft_engine::core::LayerId(report["committed"]["effect"].as_u64().unwrap()); execute(&mut session, "path.edit", &json!({"effect": effect.0, "index": 0})).unwrap(); let original = session.tool.path.points.clone(); + let original_pixels = session.doc.pixels.clone(); let history = session.history_labels().len(); session.insert_path_point(1, Vec3::new(0.5, 0.5, 0.0)); session.path_live().unwrap(); let inserted = session.tool.path.points.clone(); + let inserted_pixels = session.doc.pixels.clone(); session.move_path_point(1, Vec3::new(0.5, 0.6, 0.0), true); session.move_path_point(1, Vec3::new(0.5, 0.7, 0.0), false); session.path_live().unwrap(); let moved = session.tool.path.points.clone(); + let moved_pixels = session.doc.pixels.clone(); session.remove_selected_path_point(); session.path_live().unwrap(); let removed = session.tool.path.points.clone(); + let removed_pixels = session.doc.pixels.clone(); - for expected in [&moved, &inserted, &original] { - session.undo().unwrap(); - session.path_live().unwrap(); + for (expected, pixels) in [(&moved, &moved_pixels), (&inserted, &inserted_pixels), (&original, &original_pixels)] { + execute(&mut session, "edit.undo", &Value::Null).unwrap(); assert_eq!(&session.tool.path.points, expected); assert_eq!(session.paths(effect).unwrap()[0].points, expected.iter().map(|point| point.to_array()).collect::>()); + assert_eq!(session.doc.pixels.layers, pixels.layers); + assert_eq!(session.doc.pixels.masks, pixels.masks); } session.select_path_point(0); assert!(session.can_redo(), "selection must preserve point redo"); - for expected in [&inserted, &moved, &removed] { - session.redo().unwrap(); - session.path_live().unwrap(); + for (expected, pixels) in [(&inserted, &inserted_pixels), (&moved, &moved_pixels), (&removed, &removed_pixels)] { + execute(&mut session, "edit.redo", &Value::Null).unwrap(); assert_eq!(&session.tool.path.points, expected); + assert_eq!(session.paths(effect).unwrap()[0].points, expected.iter().map(|point| point.to_array()).collect::>()); + assert_eq!(session.doc.pixels.layers, pixels.layers); + assert_eq!(session.doc.pixels.masks, pixels.masks); } assert_eq!(session.history_labels().len(), history + 1, "all point edits share one document step"); + + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + execute(&mut session, "layer.add.paint", &Value::Null).unwrap(); + execute(&mut session, "edit.undo", &Value::Null).unwrap(); + assert_eq!(session.paths(effect).unwrap()[0].points, moved.iter().map(|point| point.to_array()).collect::>()); + assert_eq!(session.doc.pixels.layers, moved_pixels.layers, "a subsequent command keeps the undone path pixels"); +} + +/// A bad path above the edited one must not consume undo or redo when repainting fails +#[test] +fn point_history_repaint_errors_preserve_the_edit_and_can_be_retried() { + use texturecraft_engine::core::{EffectKind, LayerId}; + + let mut session = session(wall()); + let report = execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]], "commit": true})).unwrap(); + let effect = LayerId(report["committed"]["effect"].as_u64().unwrap()); + execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.8], [0.8, 0.8]], "commit": true})).unwrap(); + let paint = session.paths(effect).unwrap()[1].paint.clone(); + execute(&mut session, "path.edit", &json!({"effect": effect.0, "index": 0})).unwrap(); + let original = session.tool.path.points.clone(); + session.move_path_point(0, Vec3::new(0.2, 0.3, 0.0), true); + session.path_live().unwrap(); + let moved = session.tool.path.points.clone(); + + for (command, expected) in [("edit.undo", &original), ("edit.redo", &moved)] { + let EffectKind::Path(paths) = &mut session.doc.project.effect_mut(effect).unwrap().kind else { panic!("path sublayer") }; + paths[1].paint = Value::Null; + let before = session.doc.clone(); + let path = session.tool.path.clone(); + let history = (session.history_labels(), session.redo_labels()); + + let error = execute(&mut session, command, &Value::Null).unwrap_err(); + + assert!(error.to_string().contains("unreadable path settings"), "{error}"); + assert_eq!(session.tool.path, path); + assert_eq!(session.doc.project, before.project); + assert_eq!(session.doc.pixels.layers, before.pixels.layers); + assert_eq!((session.history_labels(), session.redo_labels()), history); + + let EffectKind::Path(paths) = &mut session.doc.project.effect_mut(effect).unwrap().kind else { panic!("path sublayer") }; + paths[1].paint = paint.clone(); + execute(&mut session, command, &Value::Null).unwrap(); + assert_eq!(&session.tool.path.points, expected, "the failed step remains available"); + assert_eq!(session.paths(effect).unwrap()[0].points, expected.iter().map(|point| point.to_array()).collect::>()); + } +} + +/// Point history repaints an uncommitted preview without creating document undo steps +#[test] +fn draft_point_history_repaints_immediately_and_undoing_all_points_cancels() { + let mut session = session(wall()); + execute(&mut session, "tool.select", &json!({"tool": "path"})).unwrap(); + let before = session.doc.clone(); + let history = session.history_labels(); + session.append_path_point(Vec3::new(0.2, 0.5, 0.0), true); + session.path_live().unwrap(); + let one_point = session.doc.clone(); + session.append_path_point(Vec3::new(0.8, 0.5, 0.0), true); + session.path_live().unwrap(); + let two_points = session.doc.clone(); + + for (command, expected) in [("edit.undo", &one_point), ("edit.redo", &two_points), ("edit.undo", &one_point), ("edit.undo", &before)] { + execute(&mut session, command, &Value::Null).unwrap(); + + assert_eq!(session.doc.project, expected.project); + assert_eq!(session.doc.pixels.layers, expected.pixels.layers); + assert_eq!(session.history_labels(), history); + } + assert!(session.tool.path.points.is_empty()); + assert!(session.tool.path.editing.is_none()); } #[test] diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 902ab3e7..d6441751 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -84,6 +84,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Anisotropy level", "مستوى تباين الخواص"), ("Antialiasing", "تنعيم الحواف"), ("Aperture", "فتحة العدسة"), + ("Apply", "تطبيق"), ("ArtCraft website...", "موقع ArtCraft الإلكتروني..."), ("Assets", "الأصول"), ("Auto", "تلقائي"), diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 10d0224f..5fe3f757 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -87,6 +87,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Anisotropy level", "Anisotropiestärke"), ("Antialiasing", "Kantenglättung"), ("Aperture", "Blende"), + ("Apply", "Anwenden"), ("ArtCraft website...", "ArtCraft-Website..."), ("Assets", "Assets"), ("Auto", "Auto"), diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index 9d933b5a..99bd5ded 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -84,6 +84,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Anisotropy level", "Nivel de anisotropía"), ("Antialiasing", "Antialiasing"), ("Aperture", "Apertura"), + ("Apply", "Aplicar"), ("ArtCraft website...", "Sitio web de ArtCraft..."), ("Assets", "Recursos"), ("Auto", "Auto"), diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index 5e31ba0c..3b1628a7 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -90,6 +90,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Anisotropy level", "Niveau d'anisotropie"), ("Antialiasing", "Anticrénelage"), ("Aperture", "Ouverture"), + ("Apply", "Appliquer"), ("ArtCraft website...", "Site web d'ArtCraft..."), ("Assets", "Ressources"), ("Auto", "Auto"), diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index cbcafb67..b3407b5d 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -87,6 +87,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Anisotropy level", "Livello anisotropia"), ("Antialiasing", "Antialiasing"), ("Aperture", "Apertura"), + ("Apply", "Applica"), ("ArtCraft website...", "Sito web di ArtCraft..."), ("Assets", "Risorse"), ("Auto", "Auto"), diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 492dd84b..51cba39d 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -90,6 +90,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Anisotropy level", "異方性レベル"), ("Antialiasing", "アンチエイリアス"), ("Aperture", "絞り"), + ("Apply", "適用"), ("ArtCraft website...", "ArtCraft ウェブサイト..."), ("Assets", "アセット"), ("Auto", "自動"), diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 9961d9eb..114f576d 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -87,6 +87,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Anisotropy level", "이방성 레벨"), ("Antialiasing", "안티앨리어싱"), ("Aperture", "조리개"), + ("Apply", "적용"), ("ArtCraft website...", "ArtCraft 웹사이트..."), ("Assets", "에셋"), ("Auto", "자동"), diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index d99c3e55..ee92fbc1 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -87,6 +87,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Anisotropy level", "Nível de anisotropia"), ("Antialiasing", "Antisserrilhamento"), ("Aperture", "Abertura"), + ("Apply", "Aplicar"), ("ArtCraft website...", "Site da ArtCraft..."), ("Assets", "Recursos"), ("Auto", "Auto"), diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index c1194cf5..54719ab9 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -75,6 +75,7 @@ pub const TABLE: &[(&str, &str)] = &[ ("Anisotropy level", "各向异性强度"), ("Antialiasing", "抗锯齿"), ("Aperture", "光圈"), + ("Apply", "应用"), ("ArtCraft website...", "ArtCraft 网站..."), ("Assets", "资产"), ("Auto", "自动"), diff --git a/crates/ui-egui/src/path_surface_cache.rs b/crates/ui-egui/src/path_surface_cache.rs index e16e3a36..9b216083 100644 --- a/crates/ui-egui/src/path_surface_cache.rs +++ b/crates/ui-egui/src/path_surface_cache.rs @@ -17,6 +17,7 @@ pub(crate) struct PathSurfaceCache { } impl PathSurfaceCache { + /// Reuse an unchanged curve and retain it for this pass; UV or missing paths have no surface curve pub(crate) fn get(&mut self, session: &Session, effect: LayerId, index: usize) -> Option { let shape = session.paths(effect)?.get(index)?; let key = (session.mesh_id, effect, index); diff --git a/crates/ui-egui/src/toolbar.rs b/crates/ui-egui/src/toolbar.rs index e9e6fc60..133240d6 100644 --- a/crates/ui-egui/src/toolbar.rs +++ b/crates/ui-egui/src/toolbar.rs @@ -328,6 +328,7 @@ pub fn path_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui) { let path = &app.session.tool.path; let (closed, fill) = (path.closed, path.fill); let selected = path.selected.is_some_and(|i| i < path.points.len()); + let has_points = !path.points.is_empty(); if icon_button(ui, ic::POLYGON, tr("Closed path"), closed, button_size).clicked() { app.session.set_path_closed(!closed); } @@ -340,6 +341,10 @@ pub fn path_controls(app: &mut TextureCraftApp, ui: &mut egui::Ui) { if ui.add_enabled_ui(selected, |ui| icon_button(ui, ic::BACKSPACE, tr("Remove point"), false, button_size)).inner.clicked() { app.session.remove_selected_path_point(); } + + if ui.add_enabled_ui(has_points, |ui| icon_button(ui, ic::CHECK, tr("Apply"), false, button_size)).inner.clicked() { + app.run("tool.path", json!({"commit": true})); + } } pub fn tool_shelf(app: &mut TextureCraftApp, ui: &mut egui::Ui) { diff --git a/crates/ui-egui/tests/it/path_in_view.rs b/crates/ui-egui/tests/it/path_in_view.rs index d044ff4d..8604ced8 100644 --- a/crates/ui-egui/tests/it/path_in_view.rs +++ b/crates/ui-egui/tests/it/path_in_view.rs @@ -2,6 +2,7 @@ use egui::{Event, Key, Modifiers, PointerButton, Pos2, pos2}; use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; use serde_json::json; use texturecraft_engine::core::LayerId; use texturecraft_engine::execute; @@ -15,6 +16,7 @@ const A: Pos2 = pos2(600.0, 500.0); const B: Pos2 = pos2(700.0, 500.0); const C: Pos2 = pos2(800.0, 500.0); +/// A Path tool session whose texture fills the test pointer coordinates in the 2D view fn harness() -> AppHarness<'static> { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); execute(&mut session, "layer.add.paint", &serde_json::Value::Null).unwrap(); @@ -26,6 +28,7 @@ fn harness() -> AppHarness<'static> { h } +/// Advance one input frame, optionally changing the primary button's state fn pointer(h: &mut AppHarness<'_>, pos: Pos2, pressed: Option) { let events = &mut h.input_mut().events; events.push(Event::PointerMoved(pos)); @@ -35,12 +38,14 @@ fn pointer(h: &mut AppHarness<'_>, pos: Pos2, pressed: Option) { h.step(); } +/// Send a complete pointer click and allow the resulting preview to update fn click(h: &mut AppHarness<'_>, at: Pos2) { pointer(h, at, Some(true)); pointer(h, at, Some(false)); h.run_steps(2); } +/// Move through several frames so the test exercises drag grouping as well as its final position fn drag(h: &mut AppHarness<'_>, from: Pos2, to: Pos2) { pointer(h, from, Some(true)); for k in 1..=6 { @@ -50,6 +55,7 @@ fn drag(h: &mut AppHarness<'_>, from: Pos2, to: Pos2) { h.run_steps(2); } +/// Dispatch an unmodified tool key and settle the resulting UI state fn key(h: &mut AppHarness<'_>, key: Key) { h.input_mut().events.push(Event::Key { key, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE }); h.run_steps(2); @@ -85,6 +91,34 @@ fn placing_points_previews_the_path_and_enter_applies_it_as_one_step() { assert_eq!(path_sublayers(&h), vec![(eid, 1)]); } +/// Applying with the pointer commits the preview without leaving the current texture set +#[test] +fn apply_button_commits_the_path_in_the_current_texture_set() { + let mut h = harness(); + assert!(h.get_all_by_label("Apply").next().unwrap().accesskit_node().is_disabled()); + let steps = h.state().session.history_labels().len(); + let texture_set = h.state().session.ts(); + for at in [A, B, C] { + click(&mut h, at); + } + let paths = path_sublayers(&h); + let preview = h.state().session.doc.pixels.layers.clone(); + + // Path controls share the horizontally scrolling brush toolbar + h.get_all_by_label("Apply").next().unwrap().scroll_to_me(); + h.run_steps(30); + assert!(!h.get_all_by_label("Apply").next().unwrap().accesskit_node().is_disabled()); + h.get_all_by_label("Apply").next().unwrap().click(); + h.run_steps(2); + + assert_eq!(h.state().session.ts(), texture_set); + assert_eq!(h.state().session.history_labels().len(), steps + 1); + assert!(h.state().session.tool.path.points.is_empty()); + assert_eq!(path_sublayers(&h), paths); + assert_eq!(h.state().session.doc.pixels.layers, preview); + assert!(h.get_all_by_label("Apply").next().unwrap().accesskit_node().is_disabled()); +} + #[test] fn clicking_an_applied_path_edits_it_and_dragging_a_point_changes_it() { let mut h = harness(); From f7be672c92c7e25c9f3e1639e3c2e229af7ee2e8 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Tue, 10 Nov 2026 21:12:29 -0500 Subject: [PATCH 55/64] Extend rays for displaced fill copies --- crates/engine/src/path_tool.rs | 13 +++++++-- crates/engine/tests/it/symmetry.rs | 45 ++++++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index b9f894e6..72683132 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -483,6 +483,10 @@ impl Session { let eye = self.camera.eye(); let camera_distance = self.camera.distance.max(MIN_BRUSH_SCALE); + // Bound the search using the farthest bounding-box corner; acceptance still uses the actual hit + let max_copy_depth = + if brush.screen_space { copy_depth * (bounds_min - eye).abs().max((bounds_max - eye).abs()).length() / camera_distance } else { copy_depth }; + fill_coverage(&mut canvas, &uv_buffer, |texel, _| { let Some(surface) = uv_buffer.surface(mesh, texel) else { return 0.0 }; let mut best = 0.0f32; @@ -506,17 +510,20 @@ impl Session { let to_surface = position - origin; let distance = to_surface.length(); let Some(direction) = to_surface.try_normalize() else { continue }; - let Some(hit) = bvh.closest(origin, direction, distance * (1.0 + RAY_HIT_RELATIVE_TOLERANCE)) else { continue }; + let is_copy = *inverse != Mat3::IDENTITY; + let max_distance = distance * (1.0 + RAY_HIT_RELATIVE_TOLERANCE); + let search_depth = if is_copy { max_copy_depth } else { 0.0 }; + let Some(hit) = bvh.closest(origin, direction, max_distance + search_depth) else { continue }; // Keep identity copies exact and reject occluders beyond the bounded displacement - let off_surface = if *inverse == Mat3::IDENTITY { + let off_surface = if !is_copy { 0.0 } else if brush.screen_space { copy_depth * (origin + direction * hit.t).distance(eye) / camera_distance } else { copy_depth }; - if hit.t < distance * (1.0 - RAY_HIT_RELATIVE_TOLERANCE) - off_surface { + if hit.t < distance * (1.0 - RAY_HIT_RELATIVE_TOLERANCE) - off_surface || hit.t > max_distance + off_surface { continue; } diff --git a/crates/engine/tests/it/symmetry.rs b/crates/engine/tests/it/symmetry.rs index 329c6f49..6beb03cc 100644 --- a/crates/engine/tests/it/symmetry.rs +++ b/crates/engine/tests/it/symmetry.rs @@ -119,6 +119,51 @@ fn a_closed_path_fill_reaches_a_curved_copy_across_a_moved_plane() { assert!(!red_at(&session, Vec3::new(inside.x, inside.y, -inside.z)), "the hidden back of the source stays clean"); } +#[test] +fn a_closed_path_fill_reaches_a_copy_in_front_of_the_source_surface() { + for ortho in [false, true] { + for screen_space in [false, true] { + let mut session = session(primitives::sphere(1.0, 48, 24)); + session.camera.ortho = ortho; + execute(&mut session, "tool.brush", &json!({"size": 10, "screenSpace": screen_space, "symmetryX": true, "symmetryOffset": [0.1, 0.0, 0.0]})) + .unwrap(); + let inside = surface(&session, 235.0, 200.0); + let mirrored_x = 0.2 - inside.x; + let copy = Vec3::new(mirrored_x, inside.y, (1.0 - mirrored_x * mirrored_x - inside.y * inside.y).sqrt()); + assert!(copy.z > inside.z + 0.01, "the copy must be nearer the camera than its source"); + + let square = json!([[225, 190], [245, 190], [245, 210], [225, 210]]); + execute(&mut session, "tool.path", &json!({"points": square, "closed": true, "fill": true, "commit": true})).unwrap(); + + assert!(red_at(&session, inside), "the filled lasso"); + assert!(red_at(&session, copy), "the ray must reach the source: ortho={ortho}, screen_space={screen_space}"); + } + } +} + +#[test] +fn screen_space_fill_copy_depth_is_limited_at_the_source_hit() { + // The source hit allows about 0.071 world units; the search bound allows about 0.122 + for (displacement, painted) in [(-0.074, false), (0.068, true), (0.1, false)] { + let mut session = session(wall()); + session.camera.ortho = true; + session.camera.distance = 1.0; + execute( + &mut session, + "tool.brush", + &json!({"size": 10, "screenSpace": true, "symmetryRadial": 2, "symmetryAxis": "y", "symmetryOffset": [0.0, 0.0, displacement * 0.5]}), + ) + .unwrap(); + let inside = surface(&session, 265.0, 200.0); + + let square = json!([[250, 180], [280, 180], [280, 220], [250, 220]]); + execute(&mut session, "tool.path", &json!({"points": square, "closed": true, "fill": true, "commit": true})).unwrap(); + + assert!(red_at(&session, inside), "the filled lasso"); + assert_eq!(red_at(&session, Vec3::new(-inside.x, inside.y, 0.0)), painted, "source displacement {displacement}"); + } +} + /// How much redder than green a texel must be to count as painted (faded edges included) const PAINTED_TINT: f32 = 0.05; From 4612e1aa8705d33a9d3489d891723103814656ab Mon Sep 17 00:00:00 2001 From: chasse20 Date: Tue, 10 Nov 2026 21:32:02 -0500 Subject: [PATCH 56/64] Handle texture deltas in path cache test --- crates/ui-egui/src/viewport.rs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/viewport.rs b/crates/ui-egui/src/viewport.rs index da04c4d4..0974eba7 100644 --- a/crates/ui-egui/src/viewport.rs +++ b/crates/ui-egui/src/viewport.rs @@ -1885,7 +1885,7 @@ mod tests { // Every path in the selection stays warm, and leaving it releases every sampled buffer for _ in 0..4 { - let _ = context.run_ui(Default::default(), |ui| { + let output = context.run_ui(Default::default(), |ui| { for index in 0..8 { let surface = stored_surface(harness.state(), ui, effect, index).unwrap(); assert!(surface.iter().map(Vec::len).sum::() > 10); @@ -1896,22 +1896,26 @@ mod tests { } } }); + + // This cache lifecycle test has no renderer to consume texture updates + output.drop_without_applying_deltas(); } let EffectKind::Path(paths) = &mut harness.state_mut().session.doc.project.effect_mut(effect).unwrap().kind else { panic!("path effect") }; for path in paths { path.viewport = [800.0, 800.0]; } - let _ = context.run_ui(Default::default(), |ui| { + let output = context.run_ui(Default::default(), |ui| { for (index, previous) in previous.iter_mut().enumerate() { let surface = stored_surface(harness.state(), ui, effect, index).unwrap(); assert!(previous.upgrade().is_none(), "editing a path releases its obsolete samples"); *previous = Arc::downgrade(&surface); } }); + output.drop_without_applying_deltas(); for _ in 0..2 { - let _ = context.run_pass(Default::default(), |_| {}); + context.run_pass(Default::default(), |_| {}).drop_without_applying_deltas(); } assert!(previous.iter().all(|surface| surface.upgrade().is_none()), "unused path surfaces must be freed while the window stays open"); From 885dbd1f0a21cfde73eeb04eea6c065c4a97a6a6 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Tue, 10 Nov 2026 21:45:32 -0500 Subject: [PATCH 57/64] Fix native-only items in wasm builds --- crates/engine/src/brush_preset_cmds.rs | 4 +++- crates/engine/src/file_cmds.rs | 4 ++-- crates/engine/src/link_cmds.rs | 4 +++- crates/engine/src/materialx_cmds.rs | 4 +++- crates/engine/src/text_cmds.rs | 1 + crates/ui-egui/src/windows.rs | 16 +++++++++++----- 6 files changed, 23 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/brush_preset_cmds.rs b/crates/engine/src/brush_preset_cmds.rs index 0ebfa070..2a83b3e1 100644 --- a/crates/engine/src/brush_preset_cmds.rs +++ b/crates/engine/src/brush_preset_cmds.rs @@ -3,7 +3,9 @@ use serde_json::{Value, json}; use texturecraft_paint::BrushSettings; -use texturecraft_paint::presets::{PRESETS, find_preset, with_stroke_of}; +#[cfg(not(target_arch = "wasm32"))] +use texturecraft_paint::presets::with_stroke_of; +use texturecraft_paint::presets::{PRESETS, find_preset}; use crate::commands::{CommandSpec, always, bad, strp}; use crate::tool_cmds::brush_json; diff --git a/crates/engine/src/file_cmds.rs b/crates/engine/src/file_cmds.rs index ae2f00b5..a728fd6c 100644 --- a/crates/engine/src/file_cmds.rs +++ b/crates/engine/src/file_cmds.rs @@ -3,8 +3,8 @@ use serde_json::{Value, json}; #[cfg(not(target_arch = "wasm32"))] -use texturecraft_core::PROJECT_EXT; -use texturecraft_core::{NormalFormat, Project, TextureSet}; +use texturecraft_core::{NormalFormat, PROJECT_EXT}; +use texturecraft_core::{Project, TextureSet}; use texturecraft_formats::{ExportInput, ExportOptions, ExportedFile, FileFormat, Padding, ProjectFile}; use texturecraft_geom::{Mesh, primitives}; diff --git a/crates/engine/src/link_cmds.rs b/crates/engine/src/link_cmds.rs index 7829efd2..36daf9a3 100644 --- a/crates/engine/src/link_cmds.rs +++ b/crates/engine/src/link_cmds.rs @@ -8,7 +8,9 @@ use std::sync::Arc; use serde_json::{Map, Value, json}; use texturecraft_core::{BakedMap, Channel, Fill, Layer, LayerId, LayerKind, LinkParam, MaterialLink, Source}; -use texturecraft_formats::mcmat::{MCMAT_EXT, MCRAFT_EXT, PortableMaterial, is_mcraft, read_mcmat}; +#[cfg(not(target_arch = "wasm32"))] +use texturecraft_formats::mcmat::MCMAT_EXT; +use texturecraft_formats::mcmat::{MCRAFT_EXT, PortableMaterial, is_mcraft, read_mcmat}; use crate::commands::{CommandSpec, bad, boolp, has_layer, layer_param, strp}; use crate::materials::Place; diff --git a/crates/engine/src/materialx_cmds.rs b/crates/engine/src/materialx_cmds.rs index 06c5ba75..68792d5c 100644 --- a/crates/engine/src/materialx_cmds.rs +++ b/crates/engine/src/materialx_cmds.rs @@ -14,7 +14,9 @@ use serde_json::{Value, json}; use texturecraft_core::{Channel, Fill, Layer, LayerKind, Projection, Source}; use texturecraft_formats::materialx_read::{Material, Value as Mtlx}; -use crate::commands::{CommandSpec, always, bad, strp}; +use crate::commands::{CommandSpec, always}; +#[cfg(not(target_arch = "wasm32"))] +use crate::commands::{bad, strp}; use crate::{EngineError, Result, Session, cmd}; pub fn specs() -> Vec { diff --git a/crates/engine/src/text_cmds.rs b/crates/engine/src/text_cmds.rs index fbc4705b..7f39bd2a 100644 --- a/crates/engine/src/text_cmds.rs +++ b/crates/engine/src/text_cmds.rs @@ -25,6 +25,7 @@ pub fn specs() -> Vec { /// Fonts bundled with the app (egui's), used when nothing is installed or in the browser. const BUILT_IN: [(&str, &[u8]); 2] = [("Ubuntu Light", epaint_default_fonts::UBUNTU_LIGHT), ("Hack", epaint_default_fonts::HACK_REGULAR)]; /// Families tried, in order, when no font is asked for. +#[cfg(not(target_arch = "wasm32"))] const DEFAULT_FAMILIES: [&str; 6] = ["Arial", "Segoe UI", "Helvetica", "Liberation Sans", "DejaVu Sans", "Noto Sans"]; /// Largest font file read. #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 068cd0bf..22d03f93 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -384,6 +384,7 @@ pub(crate) fn history(app: &mut TextureCraftApp, ui: &mut Ui) { /// What the start window was asked for. enum Start { Menu(&'static str), + #[cfg(not(target_arch = "wasm32"))] Recent(String), Close, } @@ -393,7 +394,9 @@ fn start(app: &mut TextureCraftApp, ctx: &egui::Context) { if !app.ui.windows.start { return; } - let tk = Tokens::get(ctx); + + #[cfg(not(target_arch = "wasm32"))] + let tokens = Tokens::get(ctx); let mut open = true; let mut action = None; dialog("start", "TextureCraft", &mut open).min_width(380.0).show(ctx, |ui| { @@ -405,11 +408,12 @@ fn start(app: &mut TextureCraftApp, ctx: &egui::Context) { action = Some(Start::Menu("file.open")); } }); + #[cfg(not(target_arch = "wasm32"))] if file_dialogs_available() { ui.add_space(8.0); ui.label(caption(tr("Recent projects"))); if app.ui.recent.is_empty() { - ui.label(RichText::new(tr("No recent projects yet")).color(tk.text_dim)); + ui.label(RichText::new(tr("No recent projects yet")).color(tokens.text_dim)); } for path in &app.ui.recent { let name = std::path::Path::new(path).file_name().and_then(|n| n.to_str()).unwrap_or(path); @@ -433,15 +437,17 @@ fn start(app: &mut TextureCraftApp, ctx: &egui::Context) { }); }); }); - if let Some(a) = action { + + if let Some(action) = action { app.ui.windows.start = false; - match a { + match action { Start::Menu(id) => crate::menus::invoke(app, ctx, id), #[cfg(not(target_arch = "wasm32"))] Start::Recent(path) => open_path(app, &path), - _ => {} + Start::Close => {} } } + if !open { app.ui.windows.start = false; } From 906b22630f686db66184e766d864c86ffe70a466 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Tue, 10 Nov 2026 21:59:49 -0500 Subject: [PATCH 58/64] Fix History jumps through pending path edits --- crates/engine/src/path_tool.rs | 29 ++++++ crates/ui-egui/src/windows.rs | 3 +- crates/ui-egui/tests/it/history_panel.rs | 109 +++++++++++++++++++++++ 3 files changed, 140 insertions(+), 1 deletion(-) diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index 84c7ca5e..d252d430 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -595,6 +595,35 @@ impl Session { self.tool.tool == Tool::Path && steps.iter().any(|s| !s.same_curve(&self.tool.path)) } + /// Undo calls needed to move back through document history, including pending path operations. + /// With zero document steps, only an uncommitted draft is canceled; stored edits stay applied. + pub fn history_undo_steps(&self, document_steps: usize) -> usize { + if document_steps == 0 && self.path_draft.is_none() { + return 0; + } + + let mut steps = document_steps; + let mut current = &self.tool.path; + if self.tool.tool == Tool::Path { + for state in self.path_steps.0.iter().rev() { + if state.same_curve(current) { + continue; + } + + steps = steps.saturating_add(1); + + // Restoring an empty curve cancels the draft and clears point history in the same undo + if state.points.is_empty() { + return steps; + } + + current = state; + } + } + + steps.saturating_add(usize::from(self.path_draft.is_some())) + } + /// Undo (`back`) or redo a point change and repaint before returning; failure preserves the curve and history pub(crate) fn step_path(&mut self, back: bool) -> Result { if self.tool.tool != Tool::Path { diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 068cd0bf..8359b80b 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -367,7 +367,8 @@ pub(crate) fn history(app: &mut TextureCraftApp, ui: &mut Ui) { // Each row is the state after that many steps let steps = done_count - row as i64; if ui.selectable_label(steps == 0, text).on_hover_text(tr("Return to this step")).clicked() { - jump = steps; + // Undo consumes point edits and drafts before the document rows shown here + jump = if steps >= 0 { app.session.history_undo_steps(steps as usize) as i64 } else { steps }; } } }); diff --git a/crates/ui-egui/tests/it/history_panel.rs b/crates/ui-egui/tests/it/history_panel.rs index b3f134f0..6a1988b3 100644 --- a/crates/ui-egui/tests/it/history_panel.rs +++ b/crates/ui-egui/tests/it/history_panel.rs @@ -3,9 +3,118 @@ use egui_kittest::Harness; use egui_kittest::kittest::Queryable; use serde_json::json; +use texturecraft_engine::geom::glam::Vec3; +use texturecraft_engine::{Session, execute}; use texturecraft_ui_egui::TextureCraftApp; use texturecraft_ui_egui::docking::Panel; +/// Show document history so row clicks exercise the same command dispatch as the application +fn history_harness(session: Session) -> Harness<'static, TextureCraftApp> { + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.dock.focus(Panel::History); + harness.run_steps(4); + harness +} + +/// Three document rows provide an intermediate target that detects both short and excessive jumps +fn renamed_session() -> Session { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + for name in ["Step A", "Step B", "Step C"] { + execute(&mut session, "layer.rename", &json!({"name": name})).unwrap(); + } + session +} + +/// Canceling a preview can be its own undo or part of undoing the first placed point +#[test] +fn history_jump_accounts_for_drafts_with_and_without_an_empty_checkpoint() { + for placed in [false, true] { + let mut session = renamed_session(); + let layer = session.selected_layer().unwrap(); + let effect_count = session.doc.project.layer(layer).unwrap().content_effects.len(); + if placed { + execute(&mut session, "tool.select", &json!({"tool": "path"})).unwrap(); + for point in [Vec3::new(0.2, 0.5, 0.0), Vec3::new(0.5, 0.3, 0.0), Vec3::new(0.8, 0.5, 0.0)] { + session.append_path_point(point, true); + session.path_live().unwrap(); + } + } else { + execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]]})).unwrap(); + session.move_path_point(0, Vec3::new(0.2, 0.3, 0.0), true); + session.path_live().unwrap(); + } + session.path_checkpoint(); + let mut harness = history_harness(session); + + harness.get_all_by_label("Rename layer").next().unwrap().click(); + harness.run_steps(3); + + assert_eq!(harness.state().session.doc.project.layer(layer).unwrap().name, "Step A"); + assert_eq!(harness.state().session.history_labels().len(), 1); + assert_eq!(harness.state().session.redo_labels().len(), 2); + assert!(harness.state().session.tool.path.points.is_empty()); + assert_eq!(harness.state().session.doc.project.layer(layer).unwrap().content_effects.len(), effect_count); + } +} + +/// A row jump traverses point history, while the Undo and Redo buttons still take one point step +#[test] +fn history_jump_accounts_for_stored_point_edits_without_changing_single_steps() { + let mut session = renamed_session(); + let layer = session.selected_layer().unwrap(); + let report = execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]], "commit": true})).unwrap(); + execute(&mut session, "path.edit", &json!({"effect": report["committed"]["effect"], "index": 0})).unwrap(); + let original = session.tool.path.points.clone(); + session.move_path_point(0, Vec3::new(0.2, 0.3, 0.0), true); + session.path_live().unwrap(); + let moved = session.tool.path.points.clone(); + session.move_path_point(0, original[0], true); + session.path_live().unwrap(); + session.path_checkpoint(); + let done = session.history_labels().len(); + let mut harness = history_harness(session); + + harness.get_by_label(&format!("{} Undo", egui_phosphor::regular::ARROW_COUNTER_CLOCKWISE)).click(); + harness.run_steps(3); + assert_eq!(harness.state().session.tool.path.points, moved); + assert_eq!(harness.state().session.history_labels().len(), done); + harness.get_by_label(&format!("{} Redo", egui_phosphor::regular::ARROW_CLOCKWISE)).click(); + harness.run_steps(3); + assert_eq!(harness.state().session.tool.path.points, original); + assert_eq!(harness.state().session.history_labels().len(), done); + + harness.get_by_label("Edit path 1").click(); + harness.run_steps(3); + assert_eq!(harness.state().session.tool.path.points, original); + assert_eq!(harness.state().session.history_labels().len(), done); + + harness.get_all_by_label("Rename layer").next().unwrap().click(); + harness.run_steps(3); + + assert_eq!(harness.state().session.doc.project.layer(layer).unwrap().name, "Step A"); + assert_eq!(harness.state().session.history_labels().len(), 1); + assert_eq!(harness.state().session.redo_labels().len(), done - 1); + assert!(harness.state().session.tool.path.points.is_empty()); +} + +/// Returning to the current document row cancels a draft without undoing a document step +#[test] +fn clicking_the_current_history_row_cancels_a_draft() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = session.selected_layer().unwrap(); + let effect_count = session.doc.project.layer(layer).unwrap().content_effects.len(); + execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]]})).unwrap(); + let mut harness = history_harness(session); + + harness.get_by_label("Project opened").click(); + harness.run_steps(3); + + assert!(harness.state().session.tool.path.points.is_empty()); + assert!(harness.state().session.history_labels().is_empty()); + assert!(harness.state().session.redo_labels().is_empty()); + assert_eq!(harness.state().session.doc.project.layer(layer).unwrap().content_effects.len(), effect_count); +} + #[test] fn clicking_a_history_step_returns_to_it() { let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); From 565ae84dea4445f8e4d347c1e9081b946e6f93bb Mon Sep 17 00:00:00 2001 From: chasse20 Date: Tue, 10 Nov 2026 22:11:57 -0500 Subject: [PATCH 59/64] Preserve combined mirror and radial symmetry --- crates/paint/src/brush.rs | 2 +- crates/ui-egui/src/symmetry/mod.rs | 59 ++++---- crates/ui-egui/src/symmetry/settings_popup.rs | 70 +++++----- crates/ui-egui/tests/it/symmetry.rs | 129 ++++++++++++++++-- crates/ui-egui/tests/ui_snapshots.rs | 8 ++ 5 files changed, 186 insertions(+), 82 deletions(-) diff --git a/crates/paint/src/brush.rs b/crates/paint/src/brush.rs index 31443e8a..5bb3f911 100644 --- a/crates/paint/src/brush.rs +++ b/crates/paint/src/brush.rs @@ -145,7 +145,7 @@ pub struct Symmetry { /// Radial copies around `axis`, spread over `angle_span` (0 or 1: off; at most [`MAX_RADIAL_COPIES`]) #[serde(default)] pub radial: u8, - /// Axis of radial symmetry (0 = X, 1 = Y, 2 = Z), also the one axis the settings popup mirrors on + /// Axis of radial symmetry (0 = X, 1 = Y, 2 = Z), independent of the mirror axes #[serde(default = "radial_axis")] pub axis: u8, /// Where the mirror planes and the radial axis cross, relative to the mesh center (world units) diff --git a/crates/ui-egui/src/symmetry/mod.rs b/crates/ui-egui/src/symmetry/mod.rs index 78655fa7..9c492896 100644 --- a/crates/ui-egui/src/symmetry/mod.rs +++ b/crates/ui-egui/src/symmetry/mod.rs @@ -21,7 +21,7 @@ use crate::TextureCraftApp; use crate::i18n::tr; use crate::widgets::{icon_badge_dropdown_button, icon_button}; -/// Radial copies a brush gets when it switches to radial symmetry +/// Radial copies a brush gets when radial symmetry is enabled const DEFAULT_RADIAL_COUNT: u8 = 6; /// Whether `tool` paints symmetry copies @@ -34,38 +34,11 @@ pub(crate) fn shown(app: &TextureCraftApp) -> bool { app.ui.mode == crate::state::Mode::Painting && applies_to(app.session.tool.tool) && app.session.tool.brush.symmetry.any() } -/// The axis the popup shows: the radial axis, or the first mirror axis -fn current_axis(symmetry: &Symmetry) -> usize { - if symmetry.radial > 1 { - return symmetry.axis_index(); - } - - [symmetry.x, symmetry.y, symmetry.z].iter().position(|on| *on).unwrap_or(symmetry.axis_index()) -} - -/// The world axes the plane (mirror) or the axis (radial) can move along +/// The world axes any active mirror plane or radial axis can move along, even while symmetry is disabled pub(crate) fn movable_axes(symmetry: &Symmetry) -> [bool; 3] { - // The popup's type, also while the toggle is off - if symmetry.radial > 1 { - let axis = symmetry.axis_index(); - return [0, 1, 2].map(|other| other != axis); - } - - [symmetry.x, symmetry.y, symmetry.z] -} - -/// Mirror on one axis, or radial copies around it -fn set_mode(symmetry: &mut Symmetry, radial: bool, axis: usize) { - symmetry.axis = axis as u8; - if radial { - (symmetry.x, symmetry.y, symmetry.z) = (false, false, false); - if symmetry.radial <= 1 { - symmetry.radial = DEFAULT_RADIAL_COUNT; - } - } else { - (symmetry.x, symmetry.y, symmetry.z) = (axis == 0, axis == 1, axis == 2); - symmetry.radial = 0; - } + let mirrors = [symmetry.x, symmetry.y, symmetry.z]; + let radial_axis = symmetry.axis_index(); + [0, 1, 2].map(|axis| mirrors[axis] || (symmetry.radial > 1 && axis != radial_axis)) } /// The toolbar's Symmetry toggle: turning it on with nothing set mirrors on X @@ -77,7 +50,7 @@ fn toggle(symmetry: &mut Symmetry) { symmetry.enabled = true; if !symmetry.x && !symmetry.y && !symmetry.z && symmetry.radial <= 1 { - set_mode(symmetry, false, 0); + symmetry.x = true; } } @@ -119,7 +92,7 @@ pub(crate) fn toolbar_controls(app: &mut TextureCraftApp, ui: &mut Ui) { open = !open; } - // egui's single popup slot is needed by the Type dropdown and color picker inside this popup + // egui's single popup slot is needed by the color picker inside this popup let shown = egui::Popup::from_response(&response) .id(popup_id) .open_bool(&mut open) @@ -138,3 +111,21 @@ pub(crate) fn toolbar_controls(app: &mut TextureCraftApp, ui: &mut Ui) { ui.data_mut(|data| data.insert_temp(popup_id, open)); } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn combined_symmetry_can_move_every_active_plane_and_axis() { + for enabled in [true, false] { + for axis in 0..3 { + let symmetry = Symmetry { enabled, x: axis == 0, y: axis == 1, z: axis == 2, radial: 5, axis, ..Symmetry::default() }; + + let movable = movable_axes(&symmetry); + + assert_eq!(movable, [true; 3], "the mirror plane still moves along the radial axis: {symmetry:?}"); + } + } + } +} diff --git a/crates/ui-egui/src/symmetry/settings_popup.rs b/crates/ui-egui/src/symmetry/settings_popup.rs index 063c45cd..4d11e82a 100644 --- a/crates/ui-egui/src/symmetry/settings_popup.rs +++ b/crates/ui-egui/src/symmetry/settings_popup.rs @@ -1,9 +1,9 @@ -//! The symmetry settings popup: type, axis, axis position, radial settings and display +//! The symmetry settings popup: independent mirror and radial copies, their position and display use egui::{Align, Color32, Layout, Stroke, Ui, vec2}; use texturecraft_engine::paint::{FULL_TURN_DEGREES, MAX_RADIAL_COPIES, Symmetry}; -use super::{current_axis, movable_axes, set_mode}; +use super::{DEFAULT_RADIAL_COUNT, movable_axes}; use crate::TextureCraftApp; use crate::i18n::tr; use crate::widgets::{color_swatch, section, slider}; @@ -11,12 +11,12 @@ use crate::widgets::{color_swatch, section, slider}; /// The popup's width (points) const POPUP_WIDTH: f32 = 340.0; -/// Width of the label column of the Type and Axis rows +/// Width of the radial Axis row's label column const LABEL_WIDTH: f32 = 64.0; const AXIS_NAMES: [&str; 3] = ["X", "Y", "Z"]; -/// Space between the Type and Axis rows and the first section +/// Space between the mirror section and the radial toggle const SECTIONS_GAP: f32 = 4.0; /// The color square's width (points) and the Manipulator size slider's range @@ -29,46 +29,38 @@ const PREVIEW_SIZE: f32 = 96.0; /// The popup's content, applying brush changes through the engine and display preferences in place pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui) { ui.set_width(POPUP_WIDTH); - let (lo, hi) = app.session.mesh.bounds(); - let half_extent = (hi - lo) * 0.5; + let (minimum, maximum) = app.session.mesh.bounds(); + let half_extent = (maximum - minimum) * 0.5; let display = &mut app.ui.symmetry; let mut edited = app.session.tool.brush.symmetry; let symmetry = &mut edited; - let radial = symmetry.radial > 1; - let axis = current_axis(symmetry); - - labelled_row(ui, tr("Type"), |ui| { - let type_name = if radial { tr("Radial symmetry") } else { tr("Mirror symmetry") }; - egui::ComboBox::from_id_salt("symmetry_type").width(ui.available_width()).selected_text(type_name).show_ui(ui, |ui| { - if ui.selectable_label(!radial, tr("Mirror symmetry")).clicked() { - set_mode(symmetry, false, axis); - } - if ui.selectable_label(radial, tr("Radial symmetry")).clicked() { - set_mode(symmetry, true, axis); + section(ui, "symmetry_mirror", tr("Mirror symmetry"), true, |ui| { + ui.horizontal(|ui| { + let cell = vec2(ui.available_width() / AXIS_NAMES.len() as f32, ui.spacing().interact_size.y); + for (name, enabled) in AXIS_NAMES.into_iter().zip([&mut symmetry.x, &mut symmetry.y, &mut symmetry.z]) { + ui.allocate_ui_with_layout(cell, Layout::left_to_right(Align::Center), |ui| { + ui.checkbox(enabled, name); + }); } }); }); - labelled_row(ui, tr("Axis"), |ui| { - let cell = vec2(ui.available_width() / AXIS_NAMES.len() as f32, ui.spacing().interact_size.y); - for (choice, name) in AXIS_NAMES.into_iter().enumerate() { - ui.allocate_ui_with_layout(cell, Layout::left_to_right(Align::Center), |ui| { - if ui.radio(axis == choice, name).clicked() { - set_mode(symmetry, radial, choice); - } - }); - } - }); ui.add_space(SECTIONS_GAP); - let movable = movable_axes(symmetry); - section(ui, "symmetry_axis_position", tr("Axis position"), true, |ui| { - for (along, name) in AXIS_NAMES.into_iter().enumerate() { - ui.add_enabled_ui(movable[along], |ui| slider(ui, name, &mut symmetry.offset[along], -half_extent[along]..=half_extent[along], 2)); - } - }); + let mut radial = symmetry.radial > 1; + if ui.checkbox(&mut radial, tr("Radial symmetry")).changed() { + symmetry.radial = if radial { DEFAULT_RADIAL_COUNT } else { 0 }; + } if radial { section(ui, "symmetry_radial", tr("Radial settings"), true, |ui| { + labelled_row(ui, tr("Axis"), |ui| { + let cell = vec2(ui.available_width() / AXIS_NAMES.len() as f32, ui.spacing().interact_size.y); + for (axis, name) in AXIS_NAMES.into_iter().enumerate() { + ui.allocate_ui_with_layout(cell, Layout::left_to_right(Align::Center), |ui| { + ui.radio_value(&mut symmetry.axis, axis as u8, name); + }); + } + }); ui.horizontal_top(|ui| { let sliders_width = ui.available_width() - PREVIEW_SIZE - ui.spacing().item_spacing.x; ui.allocate_ui_with_layout(vec2(sliders_width, PREVIEW_SIZE), Layout::top_down(Align::Min), |ui| { @@ -83,15 +75,23 @@ pub(super) fn show(app: &mut TextureCraftApp, ui: &mut Ui) { }); } + let movable = movable_axes(symmetry); + section(ui, "symmetry_axis_position", tr("Axis position"), true, |ui| { + for (axis, name) in AXIS_NAMES.into_iter().enumerate() { + ui.add_enabled_ui(movable[axis], |ui| slider(ui, name, &mut symmetry.offset[axis], -half_extent[axis]..=half_extent[axis], 2)); + } + }); + section(ui, "symmetry_display", tr("Display"), true, |ui| { ui.horizontal(|ui| { ui.label(tr("Symmetry color display")); ui.with_layout(Layout::right_to_left(Align::Center), |ui| color_swatch(ui, "symmetry_color", &mut display.color, COLOR_SWATCH_WIDTH)); }); + if symmetry.x || symmetry.y || symmetry.z { + ui.checkbox(&mut display.show_plane, tr("Show plane")); + } if radial { ui.checkbox(&mut display.show_axis, tr("Show axis")); - } else { - ui.checkbox(&mut display.show_plane, tr("Show plane")); } ui.checkbox(&mut display.show_intersection, tr("Show intersection")); ui.checkbox(&mut display.show_cursor, tr("Show cursor")); diff --git a/crates/ui-egui/tests/it/symmetry.rs b/crates/ui-egui/tests/it/symmetry.rs index 6fcab311..2d6181be 100644 --- a/crates/ui-egui/tests/it/symmetry.rs +++ b/crates/ui-egui/tests/it/symmetry.rs @@ -2,7 +2,7 @@ use egui::{Event, Modifiers, PointerButton, Pos2}; use egui_kittest::Harness; -use egui_kittest::kittest::Queryable; +use egui_kittest::kittest::{Queryable, by}; use serde_json::{Value, json}; use texturecraft_engine::Tool; use texturecraft_engine::geom::glam::Vec3; @@ -62,6 +62,29 @@ fn brush(harness: &mut Harness<'_, TextureCraftApp>) -> Value { texturecraft_engine::execute(&mut harness.state_mut().session, "tool.brush", &json!({})).unwrap() } +/// The number field beside a uniquely labelled slider +fn number_field<'a>(harness: &'a Harness<'_, TextureCraftApp>, label: &str) -> egui_kittest::Node<'a> { + let row = harness.get_by_label(label).rect().center().y; + harness.get_all(by().role(egui::accesskit::Role::TextInput)).find(|node| (node.rect().center().y - row).abs() < 4.0).unwrap() +} + +/// Type a complete value in the number field beside a uniquely labelled slider +fn set_number(harness: &mut Harness<'_, TextureCraftApp>, label: &str, value: &str) { + let length = number_field(harness, label).value().unwrap().len(); + number_field(harness, label).focus(); + harness.run_steps(2); + harness.key_press(egui::Key::End); + harness.run_steps(1); + for _ in 0..length { + harness.key_press(egui::Key::Backspace); + harness.run_steps(1); + } + number_field(harness, label).type_text(value); + harness.run_steps(1); + harness.key_press(egui::Key::Enter); + harness.run_steps(2); +} + /// Where world `point` is in the 3D view fn on_screen(harness: &Harness<'_, TextureCraftApp>, point: Vec3) -> Pos2 { let rect = harness.state().viewport_rect; @@ -82,9 +105,11 @@ fn the_toolbar_popup_and_manipulator_change_the_brush_symmetry() { harness.get_by_label("Symmetry settings").click(); harness.run_steps(2); - harness.get_by_role_and_label(egui::accesskit::Role::RadioButton, "Y").click(); + harness.get_by_role_and_label(egui::accesskit::Role::CheckBox, "X").click(); harness.run_steps(2); - assert_eq!(brush(&mut harness)["symmetry"], json!([false, true, false]), "one axis at a time"); + harness.get_by_role_and_label(egui::accesskit::Role::CheckBox, "Y").click(); + harness.run_steps(2); + assert_eq!(brush(&mut harness)["symmetry"], json!([false, true, false]), "mirror axes can be toggled independently"); harness.get_by_label("Symmetry settings").click(); harness.state_mut().ui.symmetry.show_manipulator = true; @@ -116,25 +141,22 @@ fn the_toolbar_popup_and_manipulator_change_the_brush_symmetry() { } #[test] -fn the_type_dropdown_and_color_picker_open_inside_the_settings_popup() { +fn the_color_picker_opens_inside_the_combined_symmetry_popup() { let mut harness = app_harness(); harness.get_by_label("Symmetry").click(); harness.run_steps(2); harness.get_by_label("Symmetry settings").click(); harness.run_steps(2); - // The Type dropdown shows its choice as its value - harness.get_by_value("Mirror symmetry").click(); - harness.run_steps(2); harness.get_by_label("Radial symmetry").click(); harness.run_steps(2); - assert_eq!(brush(&mut harness)["radialSymmetry"], json!({"copies": 6, "axis": "x"}), "radial around the axis mirror X used"); - assert!(harness.query_by_value("Radial symmetry").is_some(), "the Type dropdown shows the active mode"); - assert!(harness.query_by_label("Angle span").is_some(), "the popup stays open after the dropdown"); + assert_eq!(brush(&mut harness)["radialSymmetry"], json!({"copies": 6, "axis": "y"})); + assert_eq!(brush(&mut harness)["symmetry"], json!([true, false, false])); + assert!(harness.query_by_label("Angle span").is_some(), "the popup stays open after enabling radial symmetry"); - // The color square sits at the right end of its row, the popup's width from the Type label + // The color square sits at the right end of its row let row = harness.get_by_label("Symmetry color display").rect(); - let left = harness.get_by_label("Type").rect().left(); + let left = harness.get_by_label("Radial symmetry").rect().left(); click_at(&mut harness, egui::pos2(left + POPUP_WIDTH - COLOR_SWATCH_WIDTH / 2.0, row.center().y)); harness.run_steps(2); assert!(harness.query_by_label("Copy RGB values").is_some(), "the color picker opened"); @@ -147,6 +169,89 @@ fn the_type_dropdown_and_color_picker_open_inside_the_settings_popup() { assert!(harness.query_by_label("Show cursor").is_none(), "a click elsewhere closes the popup"); } +#[test] +fn radial_axis_edits_preserve_combined_symmetry() { + let mut harness = app_harness(); + harness + .state_mut() + .run("tool.brush", json!({"symmetryX": true, "symmetryZ": true, "symmetryRadial": 5, "symmetryAxis": "y", "symmetryAngleSpan": 215})) + .unwrap(); + harness.get_by_label("Symmetry settings").click(); + harness.run_steps(2); + let revision = harness.state().session.revision; + let history = harness.state().session.history_labels(); + + harness.get_by_role_and_label(egui::accesskit::Role::RadioButton, "Z").click(); + harness.run_steps(2); + + let settings = brush(&mut harness); + assert_eq!(settings["symmetry"], json!([true, false, true]), "editing radial symmetry must preserve every mirror axis"); + assert_eq!(settings["radialSymmetry"], json!({"copies": 5, "axis": "z"})); + assert_eq!(settings["symmetryAngleSpan"], json!(215.0)); + assert!(harness.state().session.revision > revision, "the edit runs the brush command"); + assert_eq!(harness.state().session.history_labels(), history); +} + +#[test] +fn the_popup_creates_and_edits_mirror_and_radial_copies_independently() { + let mut harness = app_harness(); + harness.state_mut().run("tool.brush", json!({"symmetryOn": false})).unwrap(); + harness.get_by_label("Symmetry settings").click(); + harness.run_steps(2); + let history = harness.state().session.history_labels(); + + for axis in ["X", "Z"] { + harness.get_by_role_and_label(egui::accesskit::Role::CheckBox, axis).click(); + harness.run_steps(2); + } + harness.get_by_label("Radial symmetry").click(); + harness.run_steps(2); + + let settings = brush(&mut harness); + assert_eq!(settings["symmetry"], json!([true, false, true])); + assert_eq!(settings["radialSymmetry"], json!({"copies": 6, "axis": "y"})); + assert_eq!(settings["symmetryOn"], json!(false), "editing settings preserves the master toggle"); + assert!(harness.query_by_label("Show plane").is_some()); + assert!(harness.query_by_label("Show axis").is_some()); + + set_number(&mut harness, "Count", "9"); + set_number(&mut harness, "Angle span", "180"); + + let settings = brush(&mut harness); + assert_eq!(settings["symmetry"], json!([true, false, true]), "radial edits keep both mirror axes"); + assert_eq!(settings["radialSymmetry"], json!({"copies": 9, "axis": "y"})); + assert_eq!(settings["symmetryAngleSpan"], json!(180.0)); + + for axis in ["X", "Y", "Z"] { + harness.get_by_role_and_label(egui::accesskit::Role::CheckBox, axis).click(); + harness.run_steps(2); + } + + let settings = brush(&mut harness); + assert_eq!(settings["symmetry"], json!([false, true, false])); + assert_eq!(settings["radialSymmetry"], json!({"copies": 9, "axis": "y"}), "mirror edits keep the radial settings"); + assert_eq!(settings["symmetryAngleSpan"], json!(180.0)); + + harness.get_by_label("Symmetry").click(); + harness.run_steps(2); + let combined = harness.state().session.tool.brush.symmetry; + assert!(combined.enabled); + assert_eq!(combined.transforms().len(), 18, "the engine receives both symmetry settings"); + harness.get_by_label("Symmetry").click(); + harness.run_steps(2); + assert_eq!(harness.state().session.tool.brush.symmetry, texturecraft_engine::paint::Symmetry { enabled: false, ..combined }); + + harness.get_by_label("Symmetry settings").click(); + harness.run_steps(2); + harness.get_by_label("Radial symmetry").click(); + harness.run_steps(2); + + let settings = brush(&mut harness); + assert_eq!(settings["symmetry"], json!([false, true, false]), "disabling radial symmetry keeps the mirror"); + assert_eq!(settings["radialSymmetry"], json!({"copies": 0, "axis": "y"})); + assert_eq!(harness.state().session.history_labels(), history); +} + #[test] fn clicking_a_symmetry_handle_does_not_paint() { let mut harness = app_harness(); diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 7636c8eb..8ea8ff1c 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -32,6 +32,7 @@ fn save(h: &mut Harness<'_, TextureCraftApp>, dir: &Path, name: &str) { #[ignore] fn symmetry_snapshots() { let Some(output_dir) = std::env::var_os("TC_UI_SNAPSHOTS").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&output_dir).unwrap(); let session = texturecraft_engine::sample_session(1024, 256).unwrap(); let mut harness = @@ -47,10 +48,17 @@ fn symmetry_snapshots() { harness.state_mut().ui.prefs.brightness = brightness; save(&mut harness, &output_dir, &format!("symmetry-mirror-{name}")); } + harness.state_mut().run("tool.brush", serde_json::json!({"symmetryY": false, "symmetryRadial": 6, "symmetryAxis": "y", "symmetryAngleSpan": 240})).unwrap(); harness.state_mut().ui.symmetry.show_axis = true; harness.state_mut().ui.prefs.brightness = Brightness::MediumDark; save(&mut harness, &output_dir, "symmetry-radial"); + + harness.state_mut().run("tool.brush", serde_json::json!({"symmetryX": true, "symmetryY": true})).unwrap(); + for (brightness, name) in [(Brightness::MediumDark, "medium"), (Brightness::Dark, "dark"), (Brightness::Light, "light")] { + harness.state_mut().ui.prefs.brightness = brightness; + save(&mut harness, &output_dir, &format!("symmetry-combined-{name}")); + } } #[test] From 76b9a30f630258604fd655fa3c24ccd4e9b7bb96 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Tue, 10 Nov 2026 22:23:51 -0500 Subject: [PATCH 60/64] Guard stored paths and fix History redo jumps --- crates/engine/src/path_tool.rs | 59 ++++++++++++++++------- crates/engine/tests/it/path_tool.rs | 60 ++++++++++++++++++++++++ crates/ui-egui/src/windows.rs | 8 +++- crates/ui-egui/tests/it/history_panel.rs | 44 +++++++++++++++++ crates/ui-egui/tests/it/path_in_view.rs | 26 ++++++++++ 5 files changed, 178 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/path_tool.rs b/crates/engine/src/path_tool.rs index d252d430..60eee97f 100644 --- a/crates/engine/src/path_tool.rs +++ b/crates/engine/src/path_tool.rs @@ -532,6 +532,11 @@ impl Session { return None; } + // A click in the other view must not replace a committed path's coordinate space + if self.tool.path.editing.is_some() && self.path_draft.is_none() && self.tool.path.uv != uv { + return None; + } + self.path_checkpoint(); self.tool.path.push(point, uv); self.tool.path.selected = self.tool.path.points.len().checked_sub(1); @@ -602,26 +607,46 @@ impl Session { return 0; } - let mut steps = document_steps; - let mut current = &self.tool.path; - if self.tool.tool == Tool::Path { - for state in self.path_steps.0.iter().rev() { - if state.same_curve(current) { - continue; - } + let (point_steps, clears_path) = self.path_steps_before_document(true); + let cancel_draft = self.path_draft.is_some() && !clears_path; + document_steps.saturating_add(point_steps).saturating_add(usize::from(cancel_draft)) + } - steps = steps.saturating_add(1); - - // Restoring an empty curve cancels the draft and clears point history in the same undo - if state.points.is_empty() { - return steps; - } - - current = state; - } + /// Redo calls needed to move forward through document history, including pending point edits. + /// Unlike undo, document redo cancels any remaining draft in the same call. + pub fn history_redo_steps(&self, document_steps: usize) -> usize { + if document_steps == 0 { + return 0; } - steps.saturating_add(usize::from(self.path_draft.is_some())) + document_steps.saturating_add(self.path_steps_before_document(false).0) + } + + /// Count pending point steps and whether their last step clears the path + fn path_steps_before_document(&self, back: bool) -> (usize, bool) { + if self.tool.tool != Tool::Path { + return (0, false); + } + + let states = if back { &self.path_steps.0 } else { &self.path_steps.1 }; + let mut steps = 0usize; + let mut current = &self.tool.path; + for state in states.iter().rev() { + if state.same_curve(current) { + continue; + } + + steps = steps.saturating_add(1); + + // Restoring an empty curve cancels the draft and clears point history in the same step + if state.points.is_empty() { + return (steps, true); + } + + current = state; + } + + (steps, false) } /// Undo (`back`) or redo a point change and repaint before returning; failure preserves the curve and history diff --git a/crates/engine/tests/it/path_tool.rs b/crates/engine/tests/it/path_tool.rs index 77b2edbd..bb4ea764 100644 --- a/crates/engine/tests/it/path_tool.rs +++ b/crates/engine/tests/it/path_tool.rs @@ -517,6 +517,66 @@ fn preview_uses_the_commands_explicit_viewport() { assert_eq!(preview, path_pixels(&direct)); } +/// An opposite-view placement must preserve the stored curve, painted pixels and point redo +#[test] +fn stored_paths_ignore_point_placement_from_the_other_view() { + for uv in [false, true] { + let mut session = session(wall()); + let params = + if uv { json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]], "commit": true}) } else { json!({"points": [[140, 210], [260, 210]], "commit": true}) }; + let report = execute(&mut session, "tool.path", ¶ms).unwrap(); + execute(&mut session, "path.edit", &json!({"effect": report["committed"]["effect"], "index": 0})).unwrap(); + let (effect, index) = session.tool.path.editing.unwrap(); + let uv_point = Vec3::new(0.5, 0.6, 0.0); + let world_point = session.pick(Vec2::new(200.0, 240.0), session.viewport).unwrap().pos; + assert_eq!(session.append_path_point(if uv { uv_point } else { world_point }, uv), Some(2)); + session.path_live().unwrap(); + let extended = session.tool.path.points.clone(); + session.undo().unwrap(); + let before = session.doc.clone(); + let path = session.tool.path.clone(); + let history = session.history_labels(); + + let placed = session.append_path_point(if uv { world_point } else { uv_point }, !uv); + session.path_live().unwrap(); + + assert_eq!(session.paths(effect).unwrap()[index].uv, uv, "the stored path must keep its coordinate space"); + assert_eq!(placed, None); + assert_eq!(session.tool.path, path); + assert_eq!(session.doc.project, before.project); + assert_eq!(session.doc.pixels.layers, before.pixels.layers); + assert_eq!(session.doc.pixels.masks, before.pixels.masks); + assert_eq!(session.history_labels(), history); + assert!(session.can_redo(), "ignored placement must preserve point redo"); + + session.redo().unwrap(); + assert_eq!(session.tool.path.points, extended); + } +} + +/// A new, uncommitted curve can still switch views and cancel without changing the document +#[test] +fn draft_paths_can_switch_to_the_other_view() { + for uv in [false, true] { + let mut session = session(wall()); + let before = session.doc.clone(); + let history = session.history_labels(); + let params = if uv { json!({"uvPoints": [[0.2, 0.5], [0.8, 0.5]]}) } else { json!({"points": [[140, 210], [260, 210]]}) }; + execute(&mut session, "tool.path", ¶ms).unwrap(); + let point = if uv { session.pick(Vec2::new(200.0, 240.0), session.viewport).unwrap().pos } else { Vec3::new(0.5, 0.6, 0.0) }; + + assert_eq!(session.append_path_point(point, !uv), Some(0)); + session.path_live().unwrap(); + + assert_eq!(session.tool.path.points, vec![point]); + assert_eq!(session.tool.path.uv, !uv); + assert_eq!(session.history_labels(), history); + session.cancel_path(); + assert_eq!(session.doc.project, before.project); + assert_eq!(session.doc.pixels.layers, before.pixels.layers); + } +} + /// Headless history commands must restore geometry and pixels before any frame or subsequent edit #[test] fn stored_point_edits_undo_and_redo_in_order_without_selection_steps() { diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index 8359b80b..9cc8a5f9 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -367,8 +367,12 @@ pub(crate) fn history(app: &mut TextureCraftApp, ui: &mut Ui) { // Each row is the state after that many steps let steps = done_count - row as i64; if ui.selectable_label(steps == 0, text).on_hover_text(tr("Return to this step")).clicked() { - // Undo consumes point edits and drafts before the document rows shown here - jump = if steps >= 0 { app.session.history_undo_steps(steps as usize) as i64 } else { steps }; + // Point history is consumed before the document rows shown here + jump = if steps >= 0 { + app.session.history_undo_steps(steps as usize) as i64 + } else { + -(app.session.history_redo_steps((-steps) as usize) as i64) + }; } } }); diff --git a/crates/ui-egui/tests/it/history_panel.rs b/crates/ui-egui/tests/it/history_panel.rs index 6a1988b3..7103161b 100644 --- a/crates/ui-egui/tests/it/history_panel.rs +++ b/crates/ui-egui/tests/it/history_panel.rs @@ -97,6 +97,50 @@ fn history_jump_accounts_for_stored_point_edits_without_changing_single_steps() assert!(harness.state().session.tool.path.points.is_empty()); } +/// Incomplete filled curves keep point redo separate from the document redo rows +#[test] +fn history_redo_jump_accounts_for_point_steps_without_changing_single_steps() { + let mut session = texturecraft_engine::sample_session(256, 64).unwrap(); + let layer = session.selected_layer().unwrap(); + let report = + execute(&mut session, "tool.path", &json!({"uvPoints": [[0.2, 0.5], [0.5, 0.3], [0.8, 0.5]], "closed": true, "fill": true, "commit": true})).unwrap(); + for name in ["Step A", "Step B", "Step C"] { + execute(&mut session, "layer.rename", &json!({"name": name})).unwrap(); + } + let done = session.history_labels().len(); + execute(&mut session, "edit.undo", &json!({"steps": 3})).unwrap(); + execute(&mut session, "path.edit", &json!({"effect": report["committed"]["effect"], "index": 0})).unwrap(); + let original = session.tool.path.points.clone(); + + // Partial filled shapes do not repaint; their undo/redo leaves document redo available + for points in [json!([[0.2, 0.5], [0.8, 0.5]]), json!([[0.2, 0.5]]), json!([[0.2, 0.5], [0.8, 0.5]])] { + session.path_checkpoint(); + execute(&mut session, "tool.path", &json!({"uvPoints": points})).unwrap(); + } + for _ in 0..3 { + session.undo().unwrap(); + } + assert_eq!(session.redo_labels().len(), 3); + let mut harness = history_harness(session); + + harness.get_by_label(&format!("{} Redo", egui_phosphor::regular::ARROW_CLOCKWISE)).click(); + harness.run_steps(3); + assert_eq!(harness.state().session.tool.path.points.len(), 2); + assert_eq!(harness.state().session.history_labels().len(), done - 3); + harness.get_by_label(&format!("{} Undo", egui_phosphor::regular::ARROW_COUNTER_CLOCKWISE)).click(); + harness.run_steps(3); + assert_eq!(harness.state().session.tool.path.points, original); + assert_eq!(harness.state().session.history_labels().len(), done - 3); + + harness.get_all_by_label("Rename layer (undone)").last().unwrap().click(); + harness.run_steps(3); + + assert_eq!(harness.state().session.doc.project.layer(layer).unwrap().name, "Step C"); + assert_eq!(harness.state().session.history_labels().len(), done); + assert!(harness.state().session.redo_labels().is_empty()); + assert!(harness.state().session.tool.path.points.is_empty()); +} + /// Returning to the current document row cancels a draft without undoing a document step #[test] fn clicking_the_current_history_row_cancels_a_draft() { diff --git a/crates/ui-egui/tests/it/path_in_view.rs b/crates/ui-egui/tests/it/path_in_view.rs index 8604ced8..819a5468 100644 --- a/crates/ui-egui/tests/it/path_in_view.rs +++ b/crates/ui-egui/tests/it/path_in_view.rs @@ -144,6 +144,32 @@ fn clicking_an_applied_path_edits_it_and_dragging_a_point_changes_it() { assert_eq!(h.state().session.history_labels().len(), steps + 1, "the edit is one step"); } +#[test] +fn clicking_the_2d_view_preserves_a_stored_3d_path_being_edited() { + let mut session = + texturecraft_engine::Session::new_project("t", texturecraft_engine::geom::primitives::sphere(1.0, 24, 12), "builtin:test", None, 128).unwrap(); + session.camera.yaw = 0.0; + session.camera.pitch = 0.0; + session.update(); + let report = execute(&mut session, "tool.path", &json!({"points": [[140, 210], [260, 210]], "viewport": [400, 400], "commit": true})).unwrap(); + execute(&mut session, "path.edit", &json!({"effect": report["committed"]["effect"], "index": 0})).unwrap(); + let before = session.doc.clone(); + let path = session.tool.path.clone(); + let history = session.history_labels(); + let mut harness = Harness::builder().with_size(egui::vec2(1600.0, 960.0)).build_eframe(|context| TextureCraftApp::new(context, session)); + harness.state_mut().ui.layout = ViewLayout::Split; + harness.run_steps(4); + let view_3d = harness.state().viewport_rect; + let view_2d_center = pos2(view_3d.right() + view_3d.width() * 0.5, view_3d.center().y); + + click(&mut harness, view_2d_center); + + assert_eq!(harness.state().session.tool.path, path); + assert_eq!(harness.state().session.doc.project, before.project); + assert_eq!(harness.state().session.doc.pixels.layers, before.pixels.layers); + assert_eq!(harness.state().session.history_labels(), history); +} + #[test] fn clicking_the_curve_inserts_a_point_and_backspace_removes_the_selected_one() { let mut h = harness(); From 1c5ff6e5c3a47959116bc295cfb71c4569b49448 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Wed, 11 Nov 2026 00:30:36 -0500 Subject: [PATCH 61/64] Restore configurable project resource limits --- apps/texturecraft/src/main.rs | 33 ++- crates/formats/README.md | 23 +- crates/formats/src/lib.rs | 9 +- crates/formats/src/project_file/entries.rs | 152 ++++++---- .../formats/src/project_file/load_budget.rs | 68 +++++ .../src/project_file/metadata_reader.rs | 81 ++++++ crates/formats/src/project_file/mod.rs | 115 ++++++-- .../src/project_file/project_open_limit.rs | 41 +++ crates/formats/src/project_file/tests.rs | 261 ++++++++++++++++++ crates/ui-egui/src/control.rs | 2 + crates/ui-egui/src/i18n/ar.rs | 5 + crates/ui-egui/src/i18n/de.rs | 5 + crates/ui-egui/src/i18n/es.rs | 5 + crates/ui-egui/src/i18n/fr.rs | 5 + crates/ui-egui/src/i18n/it.rs | 5 + crates/ui-egui/src/i18n/ja.rs | 5 + crates/ui-egui/src/i18n/ko.rs | 5 + crates/ui-egui/src/i18n/pt_br.rs | 5 + crates/ui-egui/src/i18n/zh_hans.rs | 2 + crates/ui-egui/src/lib.rs | 11 +- crates/ui-egui/src/state.rs | 16 +- crates/ui-egui/src/windows.rs | 54 +++- crates/ui-egui/tests/project_limits.rs | 55 ++++ docs/control-protocol.md | 9 + 24 files changed, 875 insertions(+), 97 deletions(-) create mode 100644 crates/formats/src/project_file/load_budget.rs create mode 100644 crates/formats/src/project_file/metadata_reader.rs create mode 100644 crates/formats/src/project_file/project_open_limit.rs create mode 100644 crates/ui-egui/tests/project_limits.rs diff --git a/apps/texturecraft/src/main.rs b/apps/texturecraft/src/main.rs index 4965c438..2deac956 100644 --- a/apps/texturecraft/src/main.rs +++ b/apps/texturecraft/src/main.rs @@ -121,16 +121,16 @@ fn set_taskbar_icon(w: &winit::window::Window) { } } -/// Settings › Interface › System title bar, read before the window opens from `ui.json`, else as earlier builds saved it; missing or unreadable: off -fn saved_system_title_bar(ui_file: Option<&std::path::Path>, persistence_path: Option<&std::path::Path>) -> bool { +/// Preferences needed before opening the initial project or window, with legacy storage fallback. +fn saved_prefs(ui_file: Option<&std::path::Path>, persistence_path: Option<&std::path::Path>) -> texturecraft_ui_egui::state::Prefs { if let Some(ui) = ui_file.and_then(ui_state_store::read) { - return ui.prefs.system_title_bar; + return ui.prefs; } let file = persistence_path.map(std::path::Path::to_path_buf).or_else(|| eframe::storage_dir(APP_NAME).map(|folder| folder.join("app.ron"))); let saved = file.and_then(|file| std::fs::read_to_string(file).ok()); let entries = saved.and_then(|text| ron::from_str::>(&text).ok()); - entries.and_then(|entries| ron::from_str::(entries.get("ui")?).ok()).is_some_and(|ui| ui.prefs.system_title_bar) + entries.and_then(|entries| ron::from_str::(entries.get("ui")?).ok()).map(|ui| ui.prefs).unwrap_or_default() } /// The app with the window chrome that needs the native window: the Windows borderless guard, and @@ -197,7 +197,6 @@ fn main() { fatal(&format!("internal error: {info}"), std::thread::current().name() == Some("main")); prev(info); })); - let session = initial_session(&args); // Scripted runs (agents, films, tests) set TEXTURECRAFT_NO_PREFS to keep the user's saved settings untouched: state goes to throwaway files let persistence_path = std::env::var_os("TEXTURECRAFT_NO_PREFS").map(|_| std::env::temp_dir().join(format!("texturecraft-noprefs-{}.ron", std::process::id()))); @@ -206,7 +205,10 @@ fn main() { if let Some(file) = &ui_file { let _ = ui_state_store::FILE.set(file.clone()); } - let title_bar = TitleBar::decide(saved_system_title_bar(ui_file.as_deref(), persistence_path.as_deref())); + let prefs = saved_prefs(ui_file.as_deref(), persistence_path.as_deref()); + prefs.apply_resource_limits(); + let session = initial_session(&args); + let title_bar = TitleBar::decide(prefs.system_title_bar); let mut viewport = egui::ViewportBuilder::default().with_title(APP_NAME).with_inner_size(DEFAULT_SIZE).with_min_inner_size(MIN_SIZE); if let Some(i) = icon() { viewport = viewport.with_icon(i); @@ -331,27 +333,36 @@ mod tests { } #[test] - fn the_system_title_bar_setting_is_read_from_ui_json_else_as_earlier_builds_saved_it() { + fn startup_preferences_use_ui_json_then_legacy_storage_then_defaults() { let ron_path = std::env::temp_dir().join(format!("texturecraft-titlebar-test-{}.ron", std::process::id())); let json_path = ron_path.with_extension("json"); for on in [false, true] { let mut ui = UiState::default(); ui.prefs.system_title_bar = on; + ui.prefs.project_open_limit_gib = 16; + // Written as eframe writes it: a pretty RON map of RON strings let kv = std::collections::HashMap::from([("ui".to_string(), ron::to_string(&ui).unwrap())]); std::fs::write(&ron_path, ron::Options::default().to_string_pretty(&kv, Default::default()).unwrap()).unwrap(); - assert_eq!(saved_system_title_bar(None, Some(&ron_path)), on); + + let legacy = saved_prefs(None, Some(&ron_path)); + assert_eq!(legacy.system_title_bar, on); + assert_eq!(legacy.project_open_limit_gib, 16); ui.prefs.system_title_bar = !on; + ui.prefs.project_open_limit_gib = 32; std::fs::write(&json_path, serde_json::to_vec(&ui).unwrap()).unwrap(); - assert_eq!(saved_system_title_bar(Some(&json_path), Some(&ron_path)), !on, "ui.json comes first"); + + let current = saved_prefs(Some(&json_path), Some(&ron_path)); + assert_eq!(current.system_title_bar, !on, "ui.json comes first"); + assert_eq!(current.project_open_limit_gib, 32); } std::fs::write(&json_path, "not json").unwrap(); std::fs::write(&ron_path, "not ron").unwrap(); - assert!(!saved_system_title_bar(Some(&json_path), Some(&ron_path))); + assert_eq!(saved_prefs(Some(&json_path), Some(&ron_path)), texturecraft_ui_egui::state::Prefs::default()); std::fs::remove_file(&json_path).unwrap(); std::fs::remove_file(&ron_path).unwrap(); - assert!(!saved_system_title_bar(Some(&json_path), Some(&ron_path))); + assert_eq!(saved_prefs(Some(&json_path), Some(&ron_path)), texturecraft_ui_egui::state::Prefs::default()); } } diff --git a/crates/formats/README.md b/crates/formats/README.md index 4a53380a..9c0580fe 100644 --- a/crates/formats/README.md +++ b/crates/formats/README.md @@ -128,6 +128,8 @@ pub fn save_project_bytes(pf: &ProjectFile) -> Result>; pub fn load_project_bytes(bytes: &[u8]) -> Result; pub fn save_project(path: &Path, pf: &ProjectFile) -> Result<()>; // native, atomic pub fn load_project(path: &Path) -> Result; // native +pub fn set_project_open_limit_gib(limit_gib: u32); // subsequent loads, minimum 1 GiB +pub fn project_open_limit_gib() -> u32; ``` `.tcraft` layout (zip, deflate): @@ -152,8 +154,25 @@ maps retain their working atlas layout. Loading runs `Project::validate`, refuses a newer `format_version` (`FormatError::NewerVersion`), checks every tile against its texture set's resolution and component count, rejects repeated or -out-of-range tiles and trailing data, drops pixels of layers that are in no stack. Single resources -and meshes have size limits; the project as a whole has none. +out-of-range tiles and trailing data, and drops pixels of layers that are in no stack. Total +decompressed project data is limited to 8 GiB by default. Settings › Project › Max project size on +open changes this limit, in GiB, independently of the save CPU and RAM preferences. Each load keeps +the limit it started with; individual resource, mesh, image and entry-count limits still apply. +The limit counts file data, including binary headers and tile coordinates, rather than peak process +memory. Saves and autosaves are not refused by this open limit; raise it to reopen a larger project. + +Opening checks the sum of all declared ZIP payload sizes before decompression, including unknown +entries, and checks actual reads against the same limit independently. Overlapping ZIP entries are +rejected. ZIP indexing is restricted to the final 32 MiB with a 64 MiB read allowance before the +100,000-entry limit can be checked. Baked-map dimensions must agree with the entry size; float data +is read in bounded chunks with fallible allocation. Nested archives are not recursively extracted +by the project reader. Subsequent image and mesh decoding has separate format-specific limits; +the project-open limit is not a combined budget for those decoded assets or the application's heap. + +Native saves compress entries in parallel within the configured CPU allowance and an estimated +in-flight byte budget. Stored resources and entries larger than that budget stream directly into +the destination without a whole-entry temporary buffer. The save RAM percentage is an estimate, +excluding compressor, allocator and project-snapshot overhead; it is not a peak process memory cap. Unreadable bake settings fall back to defaults field by field while readable settings and project content are retained. Legacy baked-map filenames remain readable; unsupported baked-map types are diff --git a/crates/formats/src/lib.rs b/crates/formats/src/lib.rs index 15df21f4..6e57432e 100644 --- a/crates/formats/src/lib.rs +++ b/crates/formats/src/lib.rs @@ -47,14 +47,19 @@ pub use mesh_import::{HighPolyMesh, ImportedMesh, MeshFile, MeshReport, import_h #[cfg(not(target_arch = "wasm32"))] pub use presets::load_preset; pub use presets::{builtin_preset, builtin_presets, preset_from_json, preset_to_json}; -pub use project_file::{BakePaintData, ProjectFile, load_project_bytes, sanitize_resource_name, save_project_bytes}; +pub use project_file::{ + BakePaintData, DEFAULT_PROJECT_OPEN_LIMIT_GIB, ProjectFile, load_project_bytes, project_open_limit_gib, sanitize_resource_name, save_project_bytes, + set_project_open_limit_gib, +}; #[cfg(not(target_arch = "wasm32"))] pub use export::write_files; #[cfg(not(target_arch = "wasm32"))] pub use mesh_import::{import_mesh, read_mesh_file}; #[cfg(not(target_arch = "wasm32"))] -pub use project_file::{DEFAULT_RAM_PERCENT, DEFAULT_RESERVED_CORES, load_project, save_project, set_save_resources}; +pub use project_file::{ + DEFAULT_RAM_PERCENT, DEFAULT_RESERVED_CORES, available_save_resources, load_project, save_project, save_ram_budget, set_save_resources, +}; #[derive(Debug, thiserror::Error)] pub enum FormatError { diff --git a/crates/formats/src/project_file/entries.rs b/crates/formats/src/project_file/entries.rs index 8bdd8906..7e0238e0 100644 --- a/crates/formats/src/project_file/entries.rs +++ b/crates/formats/src/project_file/entries.rs @@ -7,9 +7,9 @@ //! [`ZipWriter::raw_copy_file`]. The compressed bytes of every entry and the entry order are //! therefore the same as in a serial save. //! -//! Memory stays bounded: a worker only starts an entry while the entries started but not yet written -//! have an estimated compressed size under the RAM share the user allows (a single entry larger than -//! that runs alone), and entry bodies stream into the compressor instead of building a raw copy first. +//! Workers share an estimated byte budget for entries started but not yet written. Stored entries +//! and entries larger than that budget stream directly into the destination, without a whole-entry +//! buffer. The estimate excludes allocator and compressor overhead; it is not a process memory cap. use std::io::{Seek, Write}; @@ -25,7 +25,7 @@ pub(super) type Body<'a> = Box std::io::Result<()> pub(super) struct Entry<'a> { pub name: String, pub options: SimpleFileOptions, - /// Upper bound of the compressed size in bytes (the uncompressed size is a safe choice). + /// Estimated entry size in bytes, based on its uncompressed payload. #[cfg_attr(target_arch = "wasm32", allow(dead_code))] pub weight: u64, pub body: Body<'a>, @@ -69,27 +69,39 @@ mod limits { pub use limits::{DEFAULT_RAM_PERCENT, DEFAULT_RESERVED_CORES}; /// Set what saves may use: cores left to the UI (any number; at least one worker always runs) and -/// the percentage (1 to 100) of the available RAM that entries in flight may hold. +/// the percentage (1 to 100) of available RAM used as the estimated in-flight entry budget. #[cfg(not(target_arch = "wasm32"))] pub fn set_save_resources(reserved_cores: usize, ram_percent: u8) { limits::set(reserved_cores, ram_percent); } +/// Logical CPUs and currently available RAM in bytes, using the same readings as project saves. +#[cfg(not(target_arch = "wasm32"))] +pub fn available_save_resources() -> (usize, u64) { + let cores = std::thread::available_parallelism().map_or(1, usize::from); + (cores, limits::available_ram()) +} + +/// Estimated in-flight entry budget, shared by the save planner and the Settings readout. +#[cfg(not(target_arch = "wasm32"))] +pub fn save_ram_budget(available_ram_bytes: u64, ram_percent: u8) -> u64 { + u64::try_from(u128::from(available_ram_bytes) * u128::from(ram_percent.clamp(1, 100)) / 100).unwrap_or(u64::MAX) +} + /// Worker threads and in-flight byte budget for a save of `entries` entries. #[cfg(not(target_arch = "wasm32"))] pub(super) fn plan(cpus: usize, reserved_cores: usize, entries: usize, available_ram: u64, ram_percent: u8) -> (usize, u64) { let workers = cpus.saturating_sub(reserved_cores).max(1).min(entries); - let budget = u64::try_from(u128::from(available_ram) * u128::from(ram_percent.clamp(1, 100)) / 100).unwrap_or(u64::MAX); - (workers, budget) + (workers, save_ram_budget(available_ram, ram_percent)) } /// Write `entries` in order: in parallel where threads exist, else one after the other. pub(super) fn write_entries(zip: &mut ZipWriter, entries: Vec>) -> Result<()> { #[cfg(not(target_arch = "wasm32"))] { - let cpus = std::thread::available_parallelism().map_or(1, usize::from); - let (reserved, percent) = limits::get(); - let (workers, budget) = plan(cpus, reserved, entries.len(), limits::available_ram(), percent); + let (cores, available_ram_bytes) = available_save_resources(); + let (reserved_cores, ram_percent) = limits::get(); + let (workers, budget) = plan(cores, reserved_cores, entries.len(), available_ram_bytes, ram_percent); if workers > 1 { return parallel::write(zip, entries, workers, budget); } @@ -113,7 +125,7 @@ pub(super) mod parallel { use std::panic::{AssertUnwindSafe, catch_unwind}; use std::sync::{Condvar, Mutex, MutexGuard}; - use zip::{ZipArchive, ZipWriter}; + use zip::{CompressionMethod, ZipArchive, ZipWriter}; use super::Entry; use crate::project_file::zip_err; @@ -148,31 +160,33 @@ pub(super) mod parallel { fn worker(slots: &[Mutex>>], weights: &[u64], budget: u64, state: &Mutex, cv: &Condvar) { loop { - let i = { - let mut st = lock(state); + let entry_index = { + let mut state_guard = lock(state); loop { - if st.stop || st.next >= slots.len() { + if state_guard.stop || state_guard.next >= slots.len() { return; } - let w = weights.get(st.next).copied().unwrap_or(0); - // The first entry in line always starts, however large. - if st.in_flight == 0 || st.in_flight.saturating_add(w) <= budget { - let i = st.next; - st.next += 1; - st.in_flight = st.in_flight.saturating_add(w); - break i; + + let weight = weights.get(state_guard.next).copied().unwrap_or(0); + + // Oversized entries stream separately, so every queued weight fits the budget + if state_guard.in_flight <= budget.saturating_sub(weight) { + let entry_index = state_guard.next; + state_guard.next += 1; + state_guard.in_flight = state_guard.in_flight.saturating_add(weight); + break entry_index; } - st = wait(cv, st); + state_guard = wait(cv, state_guard); } }; - let entry = slots.get(i).and_then(|s| lock(s).take()); - let res = match entry { - Some(e) => { - catch_unwind(AssertUnwindSafe(|| compress(e))).unwrap_or_else(|_| Err(FormatError::Invalid("compressing a project entry failed".into()))) - } + let entry = slots.get(entry_index).and_then(|slot| lock(slot).take()); + let result = match entry { + Some(entry) => catch_unwind(AssertUnwindSafe(|| compress(entry))) + .unwrap_or_else(|_| Err(FormatError::Invalid("compressing a project entry failed".into()))), None => Err(FormatError::Invalid("project entry missing".into())), }; - lock(state).ready.insert(i, res); + + lock(state).ready.insert(entry_index, result); cv.notify_all(); } } @@ -184,53 +198,97 @@ pub(super) mod parallel { zip.raw_copy_file(f).map_err(zip_err) } + fn streams_directly(entry: &Entry<'_>, budget: u64) -> bool { + let stored_options = entry.options.compression_method(CompressionMethod::Stored); + entry.options == stored_options || entry.weight > budget + } + pub(in crate::project_file) fn write(zip: &mut ZipWriter, entries: Vec>, workers: usize, budget: u64) -> Result<()> { - let weights: Vec = entries.iter().map(|e| e.weight).collect(); - let slots: Vec>>> = entries.into_iter().map(|e| Mutex::new(Some(e))).collect(); + if workers == 0 { + return super::write_serial(zip, entries); + } + + let mut remaining = entries.into_iter().peekable(); + while let Some(entry) = remaining.next() { + // Storing bytes gains nothing from a worker; oversized entries must not get a whole-entry buffer + if streams_directly(&entry, budget) { + zip.start_file(entry.name, entry.options).map_err(zip_err)?; + (entry.body)(zip)?; + continue; + } + + let mut batch = vec![entry]; + while remaining.peek().is_some_and(|entry| !streams_directly(entry, budget)) { + if let Some(entry) = remaining.next() { + batch.push(entry); + } + } + + // Finish the workers before direct compression, keeping the CPU allowance shared + write_buffered(zip, batch, workers, budget)?; + } + + Ok(()) + } + + fn write_buffered(zip: &mut ZipWriter, entries: Vec>, workers: usize, budget: u64) -> Result<()> { + if entries.len() == 1 { + return super::write_serial(zip, entries); + } + + let weights: Vec = entries.iter().map(|entry| entry.weight).collect(); + let slots: Vec>>> = entries.into_iter().map(|entry| Mutex::new(Some(entry))).collect(); let state = Mutex::new(State { next: 0, in_flight: 0, ready: BTreeMap::new(), stop: false }); let cv = Condvar::new(); - std::thread::scope(|s| { + std::thread::scope(|scope| { let mut started = 0; - for _ in 0..workers { - // Thread creation can fail (process limits); the workers that did start drain the queue. - if std::thread::Builder::new().spawn_scoped(s, || worker(&slots, &weights, budget, &state, &cv)).is_ok() { + for _ in 0..workers.min(slots.len()) { + // If thread creation fails, the workers already started drain the queue + if std::thread::Builder::new().spawn_scoped(scope, || worker(&slots, &weights, budget, &state, &cv)).is_ok() { started += 1; } } - let res = (|| -> Result<()> { - for (i, w) in weights.iter().enumerate() { + + let result = (|| -> Result<()> { + for (entry_index, weight) in weights.iter().enumerate() { if started == 0 { - // No thread at all: stream the entry into the file like the serial writer does. - let entry = slots.get(i).and_then(|s| lock(s).take()).ok_or_else(|| FormatError::Invalid("project entry missing".into()))?; + // If no workers started, stream directly into the destination + let entry = + slots.get(entry_index).and_then(|slot| lock(slot).take()).ok_or_else(|| FormatError::Invalid("project entry missing".into()))?; zip.start_file(entry.name, entry.options).map_err(zip_err)?; (entry.body)(zip)?; continue; } + let done = { - let mut st = lock(&state); + let mut state_guard = lock(&state); loop { - if let Some(r) = st.ready.remove(&i) { - break r; + if let Some(result) = state_guard.ready.remove(&entry_index) { + break result; } - st = wait(&cv, st); + state_guard = wait(&cv, state_guard); } }; let copied = done.and_then(|bytes| copy_entry(zip, bytes)); - // Release the entry's share only once its bytes are gone. + + // Release the entry's share only once its bytes are gone { - let mut st = lock(&state); - st.in_flight = st.in_flight.saturating_sub(*w); + let mut state_guard = lock(&state); + state_guard.in_flight = state_guard.in_flight.saturating_sub(*weight); } cv.notify_all(); copied?; } + Ok(()) })(); - if res.is_err() { + + if result.is_err() { lock(&state).stop = true; cv.notify_all(); } - res + + result }) } } diff --git a/crates/formats/src/project_file/load_budget.rs b/crates/formats/src/project_file/load_budget.rs new file mode 100644 index 00000000..284c4d64 --- /dev/null +++ b/crates/formats/src/project_file/load_budget.rs @@ -0,0 +1,68 @@ +/// Decompressed bytes accepted by one project load, fixed when the load starts. +pub(super) struct LoadBudget { + limit_bytes: u64, + used_bytes: u64, +} + +impl LoadBudget { + pub(super) fn new(limit_bytes: u64) -> Self { + Self { limit_bytes, used_bytes: 0 } + } + + pub(super) fn remaining(&self) -> u64 { + self.limit_bytes - self.used_bytes + } + + /// Reserve bytes before retaining decoded data so entries share one allocation budget. + pub(super) fn take(&mut self, bytes: u64) -> Result<(), String> { + if bytes > self.remaining() { + return Err(format!( + "project file decompresses to more than {} bytes ({:.2} GiB); increase Max project size on open in Settings > Project to open larger files", + self.limit_bytes, + self.limit_bytes as f64 / (1u64 << 30) as f64, + )); + } + + self.used_bytes += bytes; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::LoadBudget; + + #[test] + fn entries_share_the_limit_and_the_exact_boundary_is_allowed() { + let mut budget = LoadBudget::new(10); + + budget.take(4).unwrap(); + budget.take(6).unwrap(); + let error = budget.take(1).unwrap_err(); + + assert_eq!(budget.remaining(), 0); + assert!(error.contains("10 bytes"), "{error}"); + assert!(error.contains("Settings > Project"), "{error}"); + } + + #[test] + fn a_rejected_entry_does_not_consume_the_remaining_budget() { + let mut budget = LoadBudget::new(10); + budget.take(4).unwrap(); + + assert!(budget.take(7).is_err()); + + assert_eq!(budget.remaining(), 6); + assert!(budget.take(6).is_ok()); + } + + #[test] + fn accounting_cannot_wrap_at_the_integer_boundary() { + let mut budget = LoadBudget::new(u64::MAX); + budget.take(u64::MAX).unwrap(); + + assert!(budget.take(1).is_err()); + assert!(budget.take(0).is_ok()); + assert_eq!(budget.remaining(), 0); + } +} diff --git a/crates/formats/src/project_file/metadata_reader.rs b/crates/formats/src/project_file/metadata_reader.rs new file mode 100644 index 00000000..7e82825c --- /dev/null +++ b/crates/formats/src/project_file/metadata_reader.rs @@ -0,0 +1,81 @@ +use std::cell::Cell; +use std::io::{self, Read, Seek, SeekFrom}; + +/// Restrict ZIP indexing to a bounded tail and read allowance before enabling payload access. +pub(super) struct MetadataReader<'a, R> { + reader: R, + metadata_only: &'a Cell, + metadata_start: u64, + remaining_bytes: u64, + position: u64, +} + +impl<'a, R: Read + Seek> MetadataReader<'a, R> { + pub(super) fn new(mut reader: R, metadata_only: &'a Cell, metadata_bytes: u64) -> io::Result { + let end = reader.seek(SeekFrom::End(0))?; + Ok(Self { reader, metadata_only, metadata_start: end.saturating_sub(metadata_bytes), remaining_bytes: metadata_bytes.saturating_mul(2), position: end }) + } +} + +impl Read for MetadataReader<'_, R> { + fn read(&mut self, bytes: &mut [u8]) -> io::Result { + if bytes.is_empty() { + return Ok(0); + } + + let metadata_only = self.metadata_only.get(); + if metadata_only && (self.position < self.metadata_start || self.remaining_bytes == 0) { + return Err(io::Error::new(io::ErrorKind::InvalidData, "project ZIP metadata exceeds the indexing limit")); + } + + let length = if metadata_only { bytes.len().min(usize::try_from(self.remaining_bytes).unwrap_or(usize::MAX)) } else { bytes.len() }; + let read = self.reader.read(bytes.get_mut(..length).unwrap_or_default())?; + self.position = self.position.saturating_add(read as u64); + if metadata_only { + self.remaining_bytes -= read as u64; + } + + Ok(read) + } +} + +impl Seek for MetadataReader<'_, R> { + fn seek(&mut self, position: SeekFrom) -> io::Result { + self.position = self.reader.seek(position)?; + Ok(self.position) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::io::Cursor; + + #[test] + fn indexing_cannot_read_payloads_outside_the_metadata_window() { + let metadata_only = Cell::new(true); + let mut reader = MetadataReader::new(Cursor::new(vec![7; 100]), &metadata_only, 8).unwrap(); + reader.seek(SeekFrom::Start(91)).unwrap(); + + assert!(reader.read(&mut [0; 1]).is_err()); + reader.seek(SeekFrom::Start(92)).unwrap(); + reader.read_exact(&mut [0; 8]).unwrap(); + + metadata_only.set(false); + reader.seek(SeekFrom::Start(0)).unwrap(); + reader.read_exact(&mut [0; 100]).unwrap(); + } + + #[test] + fn repeated_metadata_scans_share_one_read_allowance() { + let metadata_only = Cell::new(true); + let mut reader = MetadataReader::new(Cursor::new(vec![7; 8]), &metadata_only, 8).unwrap(); + for _ in 0..2 { + reader.seek(SeekFrom::Start(0)).unwrap(); + reader.read_exact(&mut [0; 8]).unwrap(); + } + reader.seek(SeekFrom::Start(0)).unwrap(); + + assert!(reader.read(&mut [0; 1]).is_err()); + } +} diff --git a/crates/formats/src/project_file/mod.rs b/crates/formats/src/project_file/mod.rs index dd10cb9d..8390220a 100644 --- a/crates/formats/src/project_file/mod.rs +++ b/crates/formats/src/project_file/mod.rs @@ -18,6 +18,7 @@ //! count of 0, followed by `width × height × components` f32 LE. Pixels of a UV-tiled texture //! set cover its whole atlas (`resolution` per tile, see `TileGrid`). +use std::cell::Cell; use std::collections::{BTreeMap, HashSet}; use std::io::{Cursor, Read, Seek, Write}; use std::sync::Arc; @@ -29,20 +30,29 @@ use zip::write::SimpleFileOptions; use zip::{CompressionMethod, ZipArchive, ZipWriter}; use self::entries::Entry; +use self::load_budget::LoadBudget; +use self::metadata_reader::MetadataReader; use crate::{FormatError, MAX_IMAGE_SIZE, Result, malformed}; mod entries; +mod load_budget; +mod metadata_reader; +mod project_open_limit; #[cfg(not(target_arch = "wasm32"))] -pub use entries::{DEFAULT_RAM_PERCENT, DEFAULT_RESERVED_CORES, set_save_resources}; +pub use entries::{DEFAULT_RAM_PERCENT, DEFAULT_RESERVED_CORES, available_save_resources, save_ram_budget, set_save_resources}; +pub use project_open_limit::{DEFAULT_PROJECT_OPEN_LIMIT_GIB, project_open_limit_gib, set_project_open_limit_gib}; const KIND: &str = "project file"; const MAGIC: &[u8; 4] = b"TCTX"; /// Version of the `.bin` layout. const BIN_VERSION: u32 = 1; +const BIN_HEADER_BYTES: usize = 24; const MAX_JSON: u64 = 256 << 20; const MAX_THUMBNAIL: u64 = 64 << 20; const MAX_RESOURCE: u64 = 512 << 20; const MAX_ENTRIES: usize = 100_000; +/// Bound ZIP index parsing before the archive exposes its entry count. +const MAX_ZIP_METADATA_BYTES: u64 = 32 << 20; /// Largest image (texels) of a texture set or baked map: UV-tiled sets hold several tiles. const MAX_TEXELS: u64 = 1 << 28; @@ -280,15 +290,37 @@ pub fn load_project(path: &std::path::Path) -> Result { crate::guard(KIND, || load(std::io::BufReader::new(file))) } -fn read_all(r: &mut impl Read, cap: u64, what: &str) -> Result> { +fn read_all(reader: &mut impl Read, cap: u64, budget: &mut LoadBudget, what: &str) -> Result> { let mut out = Vec::new(); - r.take(cap.saturating_add(1)).read_to_end(&mut out).map_err(|e| malformed(KIND, format!("{what}: {e}")))?; + + // Read at most one byte beyond either limit to detect overflow without a full entry allocation + let read_limit = cap.min(budget.remaining()).saturating_add(1); + reader.take(read_limit).read_to_end(&mut out).map_err(|e| malformed(KIND, format!("{what}: {e}")))?; if out.len() as u64 > cap { return Err(FormatError::TooLarge(format!("{what} is larger than {cap} bytes"))); } + + budget.take(out.len() as u64).map_err(FormatError::TooLarge)?; Ok(out) } +/// Decode bounded chunks so a false header cannot allocate an entire missing map. +fn read_f32s(reader: &mut impl Read, count: usize, what: &str) -> Result> { + let mut values = Vec::new(); + let mut bytes = vec![0u8; BAKED_CHUNK.min(count) * 4]; + let mut remaining = count; + while remaining > 0 { + let chunk_values = BAKED_CHUNK.min(remaining); + let chunk = bytes.get_mut(..chunk_values * 4).ok_or_else(|| malformed(KIND, format!("{what}: invalid float chunk")))?; + read_exact(reader, chunk, what)?; + values.try_reserve(chunk_values).map_err(|_| FormatError::TooLarge(format!("{what}: not enough memory for {count} values")))?; + values.extend(chunk.as_chunks::<4>().0.iter().map(|bytes| f32::from_le_bytes(*bytes))); + remaining -= chunk_values; + } + + Ok(values) +} + fn read_exact(r: &mut impl Read, buf: &mut [u8], what: &str) -> Result<()> { r.read_exact(buf).map_err(|e| malformed(KIND, format!("{what}: {e}"))) } @@ -299,7 +331,7 @@ fn u32_at(b: &[u8], i: usize) -> u32 { /// Read and check a `.bin` header: returns (width, height, comps, count). fn read_header(r: &mut impl Read, what: &str) -> Result<(u32, u32, usize, usize)> { - let mut h = [0u8; 24]; + let mut h = [0u8; BIN_HEADER_BYTES]; read_exact(r, &mut h, what)?; if h.get(..4) != Some(MAGIC.as_slice()) { return Err(malformed(KIND, format!("{what}: bad magic"))); @@ -321,7 +353,8 @@ fn expect_end(r: &mut impl Read, what: &str) -> Result<()> { } } -fn read_tiles(reader: &mut impl Read, size: (u32, u32), components: usize, what: &str) -> Result { +fn read_tiles(reader: &mut impl Read, size: (u32, u32), components: usize, budget: &mut LoadBudget, what: &str) -> Result { + budget.take(BIN_HEADER_BYTES as u64).map_err(FormatError::TooLarge)?; let (width, height, stored_components, count) = read_header(reader, what)?; if (width, height) != size || stored_components != components { return Err(malformed( @@ -338,6 +371,7 @@ fn read_tiles(reader: &mut impl Read, size: (u32, u32), components: usize, what: let mut bytes = vec![0u8; TILE_AREA * components * 2]; let mut position_bytes = [0u8; 8]; for _ in 0..count { + budget.take((position_bytes.len() + bytes.len()) as u64).map_err(FormatError::TooLarge)?; read_exact(reader, &mut position_bytes, what)?; let (tx, ty) = (u32_at(&position_bytes, 0), u32_at(&position_bytes, 1)); if tx >= image.tiles_x() || ty >= image.tiles_y() || image.is_allocated(tx, ty) { @@ -355,18 +389,25 @@ fn read_tiles(reader: &mut impl Read, size: (u32, u32), components: usize, what: } /// A baked map: (width, height, data). -fn read_baked(reader: &mut impl Read, components: usize, what: &str) -> Result<(u32, u32, Vec)> { +fn read_baked(reader: &mut impl Read, declared_bytes: u64, components: usize, budget: &mut LoadBudget, what: &str) -> Result<(u32, u32, Vec)> { + budget.take(BIN_HEADER_BYTES as u64).map_err(FormatError::TooLarge)?; let (width, height, stored_components, _) = read_header(reader, what)?; if width == 0 || height == 0 || u64::from(width) * u64::from(height) > MAX_TEXELS || stored_components != components { return Err(malformed(KIND, format!("{what}: bad size {width}×{height}×{stored_components}"))); } - let value_count = (width as usize) * (height as usize) * components; - let mut bytes = vec![0u8; value_count * 4]; - read_exact(reader, &mut bytes, what)?; + let value_count = u64::from(width) * u64::from(height) * components as u64; + let payload_bytes = value_count * 4; + if declared_bytes != BIN_HEADER_BYTES as u64 + payload_bytes { + return Err(malformed(KIND, format!("{what}: {declared_bytes} bytes for a {width}×{height}×{components} map"))); + } + + budget.take(payload_bytes).map_err(FormatError::TooLarge)?; + let value_count = usize::try_from(value_count).map_err(|_| FormatError::TooLarge(format!("{what}: too many values for this platform")))?; + let data = read_f32s(reader, value_count, what)?; expect_end(reader, what)?; - Ok((width, height, bytes.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect())) + Ok((width, height, data)) } /// Texture set holding a paint layer, a content effect or a mask effect id. @@ -376,12 +417,45 @@ fn texture_set_of(project: &Project, id: LayerId) -> Option { } fn load(reader: R) -> Result { - let mut zip = ZipArchive::new(reader).map_err(zip_err)?; + let limit_bytes = u64::from(project_open_limit_gib()) << 30; + load_with_budget(reader, LoadBudget::new(limit_bytes)) +} + +fn check_archive(zip: &mut ZipArchive, limit_bytes: u64) -> Result<()> { if zip.len() > MAX_ENTRIES { return Err(FormatError::TooLarge(format!("project file has more than {MAX_ENTRIES} entries"))); } - let json = read_all(&mut zip.by_name("project.json").map_err(zip_err)?, MAX_JSON, "project.json")?; + // Count every declared payload, including ignored entries, before any decompression + let mut declared_budget = LoadBudget::new(limit_bytes); + for index in 0..zip.len() { + let entry = zip.by_index_raw(index).map_err(zip_err)?; + declared_budget.take(entry.size()).map_err(FormatError::TooLarge)?; + } + + // Shared compressed ranges can amplify one payload into many apparent files + if zip.has_overlapping_entries().map_err(zip_err)? { + return Err(malformed(KIND, "overlapping ZIP entries are not supported")); + } + + Ok(()) +} + +fn open_archive<'a, R: Read + Seek>(reader: R, metadata_only: &'a Cell, metadata_bytes: u64) -> Result>> { + let reader = MetadataReader::new(reader, metadata_only, metadata_bytes)?; + // Project archives start at byte zero; avoid scanning payloads to guess an embedded ZIP offset + let config = zip::read::Config { archive_offset: zip::read::ArchiveOffset::Known(0) }; + let archive = ZipArchive::with_config(config, reader).map_err(zip_err)?; + metadata_only.set(false); + Ok(archive) +} + +fn load_with_budget(reader: R, mut budget: LoadBudget) -> Result { + let metadata_only = Cell::new(true); + let mut zip = open_archive(reader, &metadata_only, MAX_ZIP_METADATA_BYTES)?; + check_archive(&mut zip, budget.remaining())?; + + let json = read_all(&mut zip.by_name("project.json").map_err(zip_err)?, MAX_JSON, &mut budget, "project.json")?; #[derive(serde::Deserialize)] struct Version { format_version: u32, @@ -413,23 +487,24 @@ fn load(reader: R) -> Result { for i in 0..zip.len() { let mut f = zip.by_index(i).map_err(zip_err)?; + let declared_bytes = f.size(); let name = f.name().map_err(zip_err)?.into_owned(); let size_of = |id: LayerId| texture_set_of(&pf.project, id).and_then(|ts| pf.project.texture_sets.get(ts)).map(|t| t.size()); if name == "thumbnail.png" { - pf.thumbnail = Some(read_all(&mut f, MAX_THUMBNAIL, &name)?); + pf.thumbnail = Some(read_all(&mut f, MAX_THUMBNAIL, &mut budget, &name)?); } else if let Some(res_name) = name.strip_prefix("resources/") { if res_name.is_empty() || sanitize_resource_name(res_name) != res_name { return Err(malformed(KIND, format!("bad resource name {name}"))); } - let bytes = read_all(&mut f, MAX_RESOURCE, &name)?; + let bytes = read_all(&mut f, MAX_RESOURCE, &mut budget, &name)?; pf.resources.insert(res_name.to_string(), bytes); } else if let Some((dir, file)) = name.split_once('/').filter(|(d, _)| *d == "highpoly" || *d == "cage") { if file.is_empty() || sanitize_resource_name(file) != file { return Err(malformed(KIND, format!("bad mesh name {name}"))); } - let entry = (file.to_string(), read_all(&mut f, crate::mesh_import::MAX_MESH_FILE_BYTES, &name)?); + let entry = (file.to_string(), read_all(&mut f, crate::mesh_import::MAX_MESH_FILE_BYTES, &mut budget, &name)?); match dir { "cage" => pf.cage = Some(entry), _ => pf.high_poly.push(entry), @@ -446,10 +521,10 @@ fn load(reader: R) -> Result { "skew" => BakePaintTarget::Skew, _ => return Err(malformed(KIND, format!("unknown bake paint target in {name}"))), }; - let (width, height, values) = read_baked(&mut f, 1, &name)?; + let (width, height, values) = read_baked(&mut f, declared_bytes, 1, &mut budget, &name)?; pf.bake_paint.insert((texture_set, target), BakePaintData { width, height, values }); } else if let Some(ext) = name.strip_prefix("mesh.").filter(|e| !e.contains('/')) { - let bytes = read_all(&mut f, crate::mesh_import::MAX_MESH_FILE_BYTES, &name)?; + let bytes = read_all(&mut f, crate::mesh_import::MAX_MESH_FILE_BYTES, &mut budget, &name)?; pf.mesh = Some((ext.to_string(), bytes)); } else if let Some(rest) = name.strip_prefix("pixels/layer_").and_then(|r| r.strip_suffix(".bin")) { let (id, chan) = rest.split_once('_').ok_or_else(|| malformed(KIND, format!("bad entry name {name}")))?; @@ -458,13 +533,13 @@ fn load(reader: R) -> Result { // Drop pixels of layers that are no longer in any stack let Some(size) = size_of(id) else { continue }; - let img = read_tiles(&mut f, size, c.components() + 1, &name)?; + let img = read_tiles(&mut f, size, c.components() + 1, &mut budget, &name)?; pf.pixels.layers.insert((id, c), img); } else if let Some(rest) = name.strip_prefix("pixels/mask_").and_then(|r| r.strip_suffix(".bin")) { let id = LayerId(rest.parse().map_err(|_| malformed(KIND, format!("bad entry name {name}")))?); let Some(size) = size_of(id) else { continue }; - let img = read_tiles(&mut f, size, 2, &name)?; + let img = read_tiles(&mut f, size, 2, &mut budget, &name)?; pf.pixels.masks.insert(id, img); } else if let Some(rest) = name.strip_prefix("baked/").and_then(|r| r.strip_suffix(".bin")) { let (ts, map) = rest.split_once('_').ok_or_else(|| malformed(KIND, format!("bad entry name {name}")))?; @@ -478,7 +553,7 @@ fn load(reader: R) -> Result { continue; } - let (res, height, data) = read_baked(&mut f, m.components(), &name)?; + let (res, height, data) = read_baked(&mut f, declared_bytes, m.components(), &mut budget, &name)?; let maps = pf.baked.entry(ts).or_default(); if maps.maps.is_empty() { maps.resolution = res; diff --git a/crates/formats/src/project_file/project_open_limit.rs b/crates/formats/src/project_file/project_open_limit.rs new file mode 100644 index 00000000..3926da27 --- /dev/null +++ b/crates/formats/src/project_file/project_open_limit.rs @@ -0,0 +1,41 @@ +use std::sync::atomic::{AtomicU32, Ordering}; + +/// Default maximum decompressed project size, in GiB. +pub const DEFAULT_PROJECT_OPEN_LIMIT_GIB: u32 = 8; + +static PROJECT_OPEN_LIMIT_GIB: AtomicU32 = AtomicU32::new(DEFAULT_PROJECT_OPEN_LIMIT_GIB); + +/// Set the limit for subsequent project loads, in GiB; zero is clamped to one GiB. +/// An in-progress load keeps the limit it started with. Individual entry limits still apply. +pub fn set_project_open_limit_gib(limit_gib: u32) { + PROJECT_OPEN_LIMIT_GIB.store(limit_gib.max(1), Ordering::Relaxed); +} + +/// Maximum decompressed project size accepted by subsequent loads, in GiB. +pub fn project_open_limit_gib() -> u32 { + PROJECT_OPEN_LIMIT_GIB.load(Ordering::Relaxed) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::project_file::load_budget::LoadBudget; + + #[test] + fn preferences_apply_to_new_loads_in_gib_without_disabling_existing_guards() { + set_project_open_limit_gib(8); + let mut active_load = LoadBudget::new(u64::from(project_open_limit_gib()) << 30); + + set_project_open_limit_gib(16); + let mut next_load = LoadBudget::new(u64::from(project_open_limit_gib()) << 30); + + assert!(active_load.take(9 << 30).is_err()); + assert!(next_load.take(9 << 30).is_ok()); + + set_project_open_limit_gib(0); + assert_eq!(project_open_limit_gib(), 1); + set_project_open_limit_gib(u32::MAX); + assert_eq!(u64::from(project_open_limit_gib()) << 30, 4_611_686_017_353_646_080); + set_project_open_limit_gib(DEFAULT_PROJECT_OPEN_LIMIT_GIB); + } +} diff --git a/crates/formats/src/project_file/tests.rs b/crates/formats/src/project_file/tests.rs index c0870f01..93a58a9a 100644 --- a/crates/formats/src/project_file/tests.rs +++ b/crates/formats/src/project_file/tests.rs @@ -272,6 +272,7 @@ fn serial_bytes(pf: &ProjectFile) -> Vec { zip.finish().unwrap().into_inner() } +#[cfg(not(target_arch = "wasm32"))] fn parallel_bytes(pf: &ProjectFile, workers: usize, budget: u64) -> Vec { let mut zip = ZipWriter::new(Cursor::new(Vec::new())); entries::parallel::write(&mut zip, entries(pf).unwrap(), workers, budget).unwrap(); @@ -536,6 +537,73 @@ fn a_late_failing_entry_after_good_ones_is_its_own_error() { } } +#[cfg(not(target_arch = "wasm32"))] +fn assert_entry_streams_to_destination(method: CompressionMethod, budget: u64) { + use std::sync::atomic::{AtomicBool, Ordering}; + + let path = std::env::temp_dir().join(format!("texturecraft-entry-streaming-{}-{method:?}.zip", std::process::id())); + let destination = std::fs::File::create(&path).unwrap(); + let observed_destination = destination.try_clone().unwrap(); + let reached_destination = AtomicBool::new(false); + let mut random = 12345u32; + let payload: Vec = (0..131_072) + .map(|_| { + random ^= random << 13; + random ^= random >> 17; + random ^= random << 5; + random as u8 + }) + .collect(); + let compressed = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated); + let mut list: Vec> = (0..2) + .map(|index| Entry { name: format!("before{index}"), options: compressed, weight: 128, body: Box::new(|writer| writer.write_all(&[7; 128])) }) + .collect(); + list.push(Entry { + name: "target".into(), + options: SimpleFileOptions::default().compression_method(method), + weight: payload.len() as u64, + body: Box::new(|writer| { + let before_bytes = observed_destination.metadata()?.len(); + writer.write_all(&payload)?; + writer.flush()?; + reached_destination.store(observed_destination.metadata()?.len() > before_bytes, Ordering::Relaxed); + Ok(()) + }), + }); + list.push(Entry { name: "after".into(), options: compressed, weight: 128, body: Box::new(|writer| writer.write_all(&[9; 128])) }); + let mut writer = ZipWriter::new(destination); + + let result = entries::parallel::write(&mut writer, list, 4, budget); + drop(writer.finish().unwrap()); + drop(observed_destination); + let bytes = std::fs::read(&path).unwrap(); + std::fs::remove_file(&path).unwrap(); + + result.unwrap(); + assert!(reached_destination.load(Ordering::Relaxed), "{method:?} was buffered instead of streamed"); + let mut archive = ZipArchive::new(Cursor::new(bytes)).unwrap(); + let names: Vec<_> = (0..archive.len()).map(|index| archive.by_index(index).unwrap().name().unwrap().into_owned()).collect(); + assert_eq!(names, ["before0", "before1", "target", "after"]); + let mut actual = Vec::new(); + archive.by_name("target").unwrap().read_to_end(&mut actual).unwrap(); + assert_eq!(actual, payload); + let mut after = Vec::new(); + archive.by_name("after").unwrap().read_to_end(&mut after).unwrap(); + assert_eq!(after, [9; 128]); +} + +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn stored_entries_reach_the_destination_during_their_body() { + assert_entry_streams_to_destination(CompressionMethod::Stored, 1 << 20); +} + +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn over_budget_entries_reach_the_destination_during_their_body() { + assert_entry_streams_to_destination(CompressionMethod::Deflated, 4096); +} + #[test] fn recovery_skips_unsupported_baked_map_entries() { let expected = sample().pf; @@ -597,3 +665,196 @@ fn recovery_does_not_accept_unrelated_json_errors() { let error = load_project_bytes(&bytes).unwrap_err(); assert!(error.to_string().contains("duplicate field"), "{error}"); } + +#[test] +fn project_open_limit_counts_every_loaded_entry_kind() { + let paint = sample().paint; + let baked = [header(16, 16, 1, 0), vec![0; 16 * 16 * 4]].concat(); + let entries = [ + ("resources/test.bin".to_string(), vec![1; 1024]), + ("mesh.obj".to_string(), vec![2; 1024]), + ("highpoly/test.obj".to_string(), vec![3; 1024]), + ("cage/test.obj".to_string(), vec![4; 1024]), + ("thumbnail.png".to_string(), vec![5; 1024]), + (format!("pixels/layer_{}_baseColor.bin", paint.0), tile_bin(128, 4, &[(0, 0)])), + (format!("pixels/mask_{}.bin", paint.0), tile_bin(128, 2, &[(0, 0)])), + ("baked/0_ambientOcclusion.bin".to_string(), baked.clone()), + ("bake_paint/0_skew.bin".to_string(), baked), + ]; + + for (name, data) in entries { + let bytes = zip_with(&[(&name, data)]); + let mut archive = ZipArchive::new(Cursor::new(&bytes)).unwrap(); + let total_bytes: u64 = (0..archive.len()).map(|index| archive.by_index(index).unwrap().size()).sum(); + + let accepted = load_with_budget(Cursor::new(&bytes), LoadBudget::new(total_bytes)).unwrap(); + let error = load_with_budget(Cursor::new(&bytes), LoadBudget::new(total_bytes - 1)).unwrap_err(); + let raised_limit = load_with_budget(Cursor::new(&bytes), LoadBudget::new(total_bytes + 1)).unwrap(); + + assert!(matches!(error, FormatError::TooLarge(_)), "{name}: {error}"); + assert!(error.to_string().contains(&format!("{} bytes", total_bytes - 1)), "{name}: {error}"); + assert_same(&accepted, &raised_limit); + } +} + +#[test] +fn project_open_limit_is_shared_across_the_whole_archive() { + let project = sample().pf; + let bytes = serial_bytes(&project); + let mut archive = ZipArchive::new(Cursor::new(&bytes)).unwrap(); + let total_bytes: u64 = (0..archive.len()).map(|index| archive.by_index(index).unwrap().size()).sum(); + + let accepted = load_with_budget(Cursor::new(&bytes), LoadBudget::new(total_bytes)).unwrap(); + let error = load_with_budget(Cursor::new(&bytes), LoadBudget::new(total_bytes - 1)).unwrap_err(); + + assert_same(&project, &accepted); + assert!(matches!(error, FormatError::TooLarge(_)), "{error}"); +} + +#[test] +fn entry_reads_stop_at_the_smaller_of_the_entry_and_project_limits() { + for (entry_limit, project_limit, expected_read) in [(8, 100, 9), (100, 8, 9)] { + let mut reader = Cursor::new(vec![1; 1000]); + let mut budget = LoadBudget::new(project_limit); + + let error = read_all(&mut reader, entry_limit, &mut budget, "resource").unwrap_err(); + + assert!(matches!(error, FormatError::TooLarge(_)), "{error}"); + assert_eq!(reader.position(), expected_read); + } +} + +#[test] +fn oversized_baked_data_is_rejected_before_reading_its_payload() { + let mut reader = Cursor::new(header(16, 16, 1, 0)); + let mut budget = LoadBudget::new(BIN_HEADER_BYTES as u64 + 16 * 16 * 4 - 1); + + let error = read_baked(&mut reader, BIN_HEADER_BYTES as u64 + 16 * 16 * 4, 1, &mut budget, "baked map").unwrap_err(); + + assert!(matches!(error, FormatError::TooLarge(_)), "the size guard must run before the truncated read: {error}"); + assert_eq!(reader.position(), BIN_HEADER_BYTES as u64); +} + +#[test] +fn archive_preflight_counts_ignored_entries_and_allows_the_exact_limit() { + let mut writer = ZipWriter::new(Cursor::new(Vec::new())); + let options = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated); + for name in ["project.json", "unknown/future-data"] { + writer.start_file(name, options).unwrap(); + writer.write_all(&[0; 16]).unwrap(); + } + let bytes = writer.finish().unwrap().into_inner(); + let mut archive = ZipArchive::new(Cursor::new(bytes)).unwrap(); + + check_archive(&mut archive, 32).unwrap(); + let error = check_archive(&mut archive, 31).unwrap_err(); + + assert!(matches!(error, FormatError::TooLarge(_)), "{error}"); +} + +#[test] +fn overlapping_archive_entries_are_rejected_before_decompression() { + let mut writer = ZipWriter::new(Cursor::new(Vec::new())); + writer.start_file("resource", SimpleFileOptions::default()).unwrap(); + writer.write_all(&[0; 16]).unwrap(); + writer.shallow_copy_file("resource", "copy").unwrap(); + let bytes = writer.finish().unwrap().into_inner(); + let mut archive = ZipArchive::new(Cursor::new(bytes)).unwrap(); + + let error = check_archive(&mut archive, 32).unwrap_err(); + + assert!(error.to_string().contains("overlapping ZIP entries"), "{error}"); +} + +#[test] +fn actual_decompression_is_bounded_even_when_the_declared_size_is_small() { + let mut writer = ZipWriter::new(Cursor::new(Vec::new())); + writer.start_file("resource", SimpleFileOptions::default().compression_method(CompressionMethod::Deflated)).unwrap(); + writer.write_all(&vec![0; 1 << 20]).unwrap(); + let mut bytes = writer.finish().unwrap().into_inner(); + let directory = ZipArchive::new(Cursor::new(&bytes)).unwrap().central_directory_start() as usize; + // The central header stores the uncompressed size at byte 24 + bytes.get_mut(directory + 24..directory + 28).unwrap().copy_from_slice(&1u32.to_le_bytes()); + let mut archive = ZipArchive::new(Cursor::new(bytes)).unwrap(); + check_archive(&mut archive, 1024).unwrap(); + let mut entry = archive.by_index(0).unwrap(); + let mut budget = LoadBudget::new(1024); + + let error = read_all(&mut entry, MAX_RESOURCE, &mut budget, "resource").unwrap_err(); + + assert!( + matches!(error, FormatError::TooLarge(_)) || error.to_string().contains("larger than its declared uncompressed size"), + "actual bytes must be bounded independently of ZIP sizes: {error}" + ); +} + +#[test] +fn baked_dimensions_must_match_the_entry_before_reserving_payload_bytes() { + let mut reader = Cursor::new(header(1024, 1024, 3, 0)); + let mut budget = LoadBudget::new(16 << 20); + + let error = read_baked(&mut reader, BIN_HEADER_BYTES as u64, 3, &mut budget, "baked map").unwrap_err(); + + assert!(error.to_string().contains("24 bytes for a 1024×1024×3 map"), "{error}"); + assert_eq!(budget.remaining(), (16 << 20) - BIN_HEADER_BYTES as u64); + assert_eq!(reader.position(), BIN_HEADER_BYTES as u64); +} + +#[test] +fn streamed_float_chunks_preserve_bits_across_the_chunk_boundary() { + let values: Vec = (0..BAKED_CHUNK + 3).map(|index| (index as u32).wrapping_mul(0x9e3779b9)).collect(); + let bytes: Vec = values.iter().flat_map(|bits| bits.to_le_bytes()).collect(); + let mut reader = Cursor::new(bytes); + + let decoded = read_f32s(&mut reader, values.len(), "baked map").unwrap(); + + assert_eq!(decoded.into_iter().map(f32::to_bits).collect::>(), values); + assert_eq!(reader.position(), (values.len() * 4) as u64); +} + +#[test] +fn archive_indexing_does_not_scan_large_payloads_and_rejects_large_metadata() { + let mut writer = ZipWriter::new(Cursor::new(Vec::new())); + writer.start_file("resource", SimpleFileOptions::default().compression_method(CompressionMethod::Stored)).unwrap(); + writer.write_all(&vec![7; 1 << 20]).unwrap(); + let bytes = writer.finish().unwrap().into_inner(); + let metadata_only = Cell::new(true); + + let mut archive = open_archive(Cursor::new(bytes), &metadata_only, 4096).unwrap(); + let mut first_byte = [0; 1]; + archive.by_index(0).unwrap().read_exact(&mut first_byte).unwrap(); + + assert_eq!(first_byte, [7]); + assert!(!metadata_only.get()); + + let mut writer = ZipWriter::new(Cursor::new(Vec::new())); + writer.start_file("a".repeat(5000), SimpleFileOptions::default()).unwrap(); + writer.write_all(&[7]).unwrap(); + let bytes = writer.finish().unwrap().into_inner(); + let metadata_only = Cell::new(true); + + assert!(open_archive(Cursor::new(bytes), &metadata_only, 4096).is_err()); + assert!(metadata_only.get(), "failed indexing must not enable payload access"); +} + +#[test] +fn zip64_entry_counts_remain_supported_and_bounded() { + for count in [65_536, MAX_ENTRIES + 1] { + let mut writer = ZipWriter::new(Cursor::new(Vec::new())); + for index in 0..count { + writer.start_file(format!("e{index}"), SimpleFileOptions::default().compression_method(CompressionMethod::Stored)).unwrap(); + } + let bytes = writer.finish().unwrap().into_inner(); + let metadata_only = Cell::new(true); + + let mut archive = open_archive(Cursor::new(bytes), &metadata_only, MAX_ZIP_METADATA_BYTES).unwrap(); + let result = check_archive(&mut archive, 0); + + assert_eq!(archive.len(), count); + if count <= MAX_ENTRIES { + result.unwrap(); + } else { + assert!(matches!(result, Err(FormatError::TooLarge(_))), "{result:?}"); + } + } +} diff --git a/crates/ui-egui/src/control.rs b/crates/ui-egui/src/control.rs index 0260d65c..b95788d3 100644 --- a/crates/ui-egui/src/control.rs +++ b/crates/ui-egui/src/control.rs @@ -73,6 +73,7 @@ pub(crate) fn encode_png(w: u32, h: u32, rgba: Vec) -> Option<(u32, u32, Vec } pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, p: &Value) -> Value { + app.ui.prefs.apply_resource_limits(); match method { "ping" => ok(json!("pong")), "ui.resize" => { @@ -178,6 +179,7 @@ pub fn handle(app: &mut TextureCraftApp, ctx: &egui::Context, method: &str, p: & match serde_json::from_value(cur) { Ok(ui) => { app.ui = ui; + app.ui.prefs.apply_resource_limits(); ok(Value::Null) } Err(e) => err(format!("invalid UI state: {e}")), diff --git a/crates/ui-egui/src/i18n/ar.rs b/crates/ui-egui/src/i18n/ar.rs index 68dfa1f7..95373f3d 100644 --- a/crates/ui-egui/src/i18n/ar.rs +++ b/crates/ui-egui/src/i18n/ar.rs @@ -1127,4 +1127,9 @@ pub const TABLE: &[(&str, &str)] = &[ "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", "يستخدم الحفظ الأنوية الأخرى وحدًا أقصى بهذه النسبة من الذاكرة الحرة. يعمل نواة واحدة على الأقل دائمًا.", ), + ("Max project size on open", "الحد الأقصى لحجم المشروع عند الفتح"), + ( + "Maximum decompressed project data. Increase this limit to open larger projects.", + "الحد الأقصى لبيانات المشروع بعد فك الضغط. ارفع هذا الحد لفتح مشاريع أكبر.", + ), ]; diff --git a/crates/ui-egui/src/i18n/de.rs b/crates/ui-egui/src/i18n/de.rs index 08420f40..0f7e7c35 100644 --- a/crates/ui-egui/src/i18n/de.rs +++ b/crates/ui-egui/src/i18n/de.rs @@ -1173,4 +1173,9 @@ pub const TABLE: &[(&str, &str)] = &[ "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", "Das Speichern nutzt die übrigen Kerne und höchstens diesen Anteil des freien RAMs. Mindestens ein Kern arbeitet immer.", ), + ("Max project size on open", "Max. Projektgröße beim Öffnen"), + ( + "Maximum decompressed project data. Increase this limit to open larger projects.", + "Maximale entpackte Projektdaten. Erhöhen Sie diesen Grenzwert, um größere Projekte zu öffnen.", + ), ]; diff --git a/crates/ui-egui/src/i18n/es.rs b/crates/ui-egui/src/i18n/es.rs index f3ce2a5d..b5361801 100644 --- a/crates/ui-egui/src/i18n/es.rs +++ b/crates/ui-egui/src/i18n/es.rs @@ -1164,4 +1164,9 @@ pub const TABLE: &[(&str, &str)] = &[ "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", "Guardar usa los demás núcleos y como máximo esta parte de la RAM libre. Siempre trabaja al menos un núcleo.", ), + ("Max project size on open", "Tamaño máximo al abrir"), + ( + "Maximum decompressed project data. Increase this limit to open larger projects.", + "Máximo de datos descomprimidos del proyecto. Aumenta este límite para abrir proyectos más grandes.", + ), ]; diff --git a/crates/ui-egui/src/i18n/fr.rs b/crates/ui-egui/src/i18n/fr.rs index a19bbaa8..00b8c2af 100644 --- a/crates/ui-egui/src/i18n/fr.rs +++ b/crates/ui-egui/src/i18n/fr.rs @@ -1188,4 +1188,9 @@ pub const TABLE: &[(&str, &str)] = &[ "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", "L'enregistrement utilise les autres cœurs et au plus cette part de la RAM libre. Au moins un cœur travaille toujours.", ), + ("Max project size on open", "Taille max. à l’ouverture"), + ( + "Maximum decompressed project data. Increase this limit to open larger projects.", + "Volume maximal des données décompressées du projet. Augmentez cette limite pour ouvrir des projets plus volumineux.", + ), ]; diff --git a/crates/ui-egui/src/i18n/it.rs b/crates/ui-egui/src/i18n/it.rs index 03dfdd3a..e067cf67 100644 --- a/crates/ui-egui/src/i18n/it.rs +++ b/crates/ui-egui/src/i18n/it.rs @@ -1170,4 +1170,9 @@ pub const TABLE: &[(&str, &str)] = &[ "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", "Il salvataggio usa gli altri core e al massimo questa quota della RAM libera. Almeno un core lavora sempre.", ), + ("Max project size on open", "Dimensione massima all’apertura"), + ( + "Maximum decompressed project data. Increase this limit to open larger projects.", + "Quantità massima di dati decompressi del progetto. Aumenta questo limite per aprire progetti più grandi.", + ), ]; diff --git a/crates/ui-egui/src/i18n/ja.rs b/crates/ui-egui/src/i18n/ja.rs index 2b9c8940..0e60e132 100644 --- a/crates/ui-egui/src/i18n/ja.rs +++ b/crates/ui-egui/src/i18n/ja.rs @@ -1155,4 +1155,9 @@ pub const TABLE: &[(&str, &str)] = &[ "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", "保存は残りのコアと、空きRAMのこの割合までを使います。少なくとも1コアは常に動作します。", ), + ("Max project size on open", "開くプロジェクトの最大サイズ"), + ( + "Maximum decompressed project data. Increase this limit to open larger projects.", + "展開後のプロジェクトデータの上限です。大きなプロジェクトを開くには、この上限を引き上げてください。", + ), ]; diff --git a/crates/ui-egui/src/i18n/ko.rs b/crates/ui-egui/src/i18n/ko.rs index 90428a6a..7f80b6be 100644 --- a/crates/ui-egui/src/i18n/ko.rs +++ b/crates/ui-egui/src/i18n/ko.rs @@ -1140,4 +1140,9 @@ pub const TABLE: &[(&str, &str)] = &[ "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", "저장은 나머지 코어와 여유 RAM의 이 비율까지만 사용합니다. 최소 한 개의 코어는 항상 작동합니다.", ), + ("Max project size on open", "열기 시 최대 프로젝트 크기"), + ( + "Maximum decompressed project data. Increase this limit to open larger projects.", + "압축 해제된 프로젝트 데이터의 최대 크기입니다. 더 큰 프로젝트를 열려면 이 한도를 높이세요.", + ), ]; diff --git a/crates/ui-egui/src/i18n/pt_br.rs b/crates/ui-egui/src/i18n/pt_br.rs index 84e22e38..e5b023af 100644 --- a/crates/ui-egui/src/i18n/pt_br.rs +++ b/crates/ui-egui/src/i18n/pt_br.rs @@ -1158,4 +1158,9 @@ pub const TABLE: &[(&str, &str)] = &[ "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", "Salvar usa os outros núcleos e no máximo esta parte da RAM livre. Pelo menos um núcleo sempre trabalha.", ), + ("Max project size on open", "Tamanho máximo ao abrir"), + ( + "Maximum decompressed project data. Increase this limit to open larger projects.", + "Limite de dados descompactados do projeto. Aumente este limite para abrir projetos maiores.", + ), ]; diff --git a/crates/ui-egui/src/i18n/zh_hans.rs b/crates/ui-egui/src/i18n/zh_hans.rs index cb5bcbed..ef4209e4 100644 --- a/crates/ui-egui/src/i18n/zh_hans.rs +++ b/crates/ui-egui/src/i18n/zh_hans.rs @@ -1086,4 +1086,6 @@ pub const TABLE: &[(&str, &str)] = &[ "Saving uses the other cores and at most this share of the free RAM. At least one core always works.", "保存使用其余核心,并最多占用这一比例的可用内存。至少始终有一个核心工作。", ), + ("Max project size on open", "打开项目的大小上限"), + ("Maximum decompressed project data. Increase this limit to open larger projects.", "解压后项目数据的大小上限。提高此限制以打开更大的项目。"), ]; diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 47e4f5aa..815ba793 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -204,6 +204,7 @@ impl TextureCraftApp { ui }); let next_autosave = ui.prefs.autosave_minutes as f64 * 60.0; + ui.prefs.apply_resource_limits(); let mut app = TextureCraftApp { camera_glide: None, @@ -274,7 +275,9 @@ impl TextureCraftApp { /// Run an engine command, reporting errors as toasts. Returns the result on success. pub fn run(&mut self, id: &str, params: Value) -> Option { - // Going to a saved camera glides there; the control channel and CLI jump straight away. + self.ui.prefs.apply_resource_limits(); + + // Going to a saved camera glides there; the control channel and CLI jump straight away let glide_from = (id.starts_with("camera.select") || id.starts_with("camera.bookmark")).then_some(self.session.camera); match texturecraft_engine::execute(&mut self.session, id, ¶ms) { Ok(v) => { @@ -658,6 +661,7 @@ impl eframe::App for TextureCraftApp { self.styled = Some(style); } self.step_camera_glide(ctx); + self.ui.prefs.apply_resource_limits(); control::poll(self, ctx); #[cfg(not(target_arch = "wasm32"))] self.run_file_dialog_answers(); @@ -680,10 +684,7 @@ impl eframe::App for TextureCraftApp { ctx.set_zoom_factor(scale); } #[cfg(not(target_arch = "wasm32"))] - { - texturecraft_engine::formats::set_save_resources(self.ui.prefs.reserved_cores as usize, self.ui.prefs.save_ram_percent); - self.autosave(now); - } + self.autosave(now); i18n::set_language(&self.ui.prefs.language); #[cfg(target_arch = "wasm32")] { diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rs index a04ed92e..e52a2907 100644 --- a/crates/ui-egui/src/state.rs +++ b/crates/ui-egui/src/state.rs @@ -118,9 +118,11 @@ pub struct Prefs { /// Where autosaves, smart materials, presets, templates and layouts go (desktop; read at /// startup). Empty or relative: `Documents/TextureCraft`. pub data_folder: String, - /// Cores a project save leaves to the UI; it compresses on the others (desktop). Any number: - /// at least one worker always runs. + /// Cores a project save leaves to the UI; Settings bounds this to the available logical CPUs + /// (desktop). At least one save worker always runs. pub reserved_cores: u32, + /// Maximum decompressed project size accepted on open, in GiB (at least one). + pub project_open_limit_gib: u32, /// Percent of the free RAM a project save may hold at once (desktop; 1 to 100). pub save_ram_percent: u8, } @@ -138,11 +140,21 @@ impl Default for Prefs { start_window: true, data_folder: String::new(), reserved_cores: 1, + project_open_limit_gib: texturecraft_engine::formats::DEFAULT_PROJECT_OPEN_LIMIT_GIB, save_ram_percent: 50, } } } +impl Prefs { + /// Apply resource preferences before commands or file workers can start. + pub fn apply_resource_limits(&self) { + texturecraft_engine::formats::set_project_open_limit_gib(self.project_open_limit_gib); + #[cfg(not(target_arch = "wasm32"))] + texturecraft_engine::formats::set_save_resources(self.reserved_cores as usize, self.save_ram_percent); + } +} + #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct NewProject { pub mesh: String, diff --git a/crates/ui-egui/src/windows.rs b/crates/ui-egui/src/windows.rs index eb2de8a3..c8448913 100644 --- a/crates/ui-egui/src/windows.rs +++ b/crates/ui-egui/src/windows.rs @@ -576,6 +576,25 @@ fn new_project(app: &mut TextureCraftApp, ctx: &egui::Context) { } } +#[cfg(not(target_arch = "wasm32"))] +fn settings_resources(ctx: &egui::Context) -> (u32, u64) { + let id = egui::Id::unique("settings_resources"); + let now = ctx.input(|input| input.time); + ctx.request_repaint_after(std::time::Duration::from_secs(1)); + + // Query the operating system once a second while Settings is open, rather than every frame + if let Some((sampled_at, cores, available_ram_bytes)) = ctx.data(|data| data.get_temp::<(f64, u32, u64)>(id)) + && (0.0..1.0).contains(&(now - sampled_at)) + { + return (cores, available_ram_bytes); + } + + let (cores, available_ram_bytes) = texturecraft_engine::formats::available_save_resources(); + let cores = u32::try_from(cores).unwrap_or(u32::MAX); + ctx.data_mut(|data| data.insert_temp(id, (now, cores, available_ram_bytes))); + (cores, available_ram_bytes) +} + fn settings(app: &mut TextureCraftApp, ctx: &egui::Context) { let tk = Tokens::get(ctx); let mut open = app.ui.windows.settings; @@ -657,20 +676,39 @@ fn settings(app: &mut TextureCraftApp, ctx: &egui::Context) { ui.end_row(); }); ui.add_space(8.0); + ui.label(caption(tr("Project"))); #[cfg(not(target_arch = "wasm32"))] - { - ui.label(caption(tr("Project"))); - form("settings_project").show(ui, |ui| { + let (available_cores, available_ram_bytes) = settings_resources(ctx); + form("settings_project").show(ui, |ui| { + #[cfg(not(target_arch = "wasm32"))] + { ui.label(tr("Autosave every")); ui.add(egui::DragValue::new(&mut p.autosave_minutes).range(0..=120).suffix(format!(" {}", tr("min")))); ui.end_row(); - ui.label(tr("Cores kept for the UI")); - ui.add(egui::DragValue::new(&mut p.reserved_cores).range(0..=1024)); + let label = ui.label(tr("Cores kept for the UI")); + ui.add(egui::DragValue::new(&mut p.reserved_cores).range(0..=available_cores)).labelled_by(label.id); ui.end_row(); - ui.label(tr("Max RAM while saving")); - ui.add(egui::DragValue::new(&mut p.save_ram_percent).range(1..=100).suffix(" %")); + } + + let label = ui.label(tr("Max project size on open")); + ui.add(egui::DragValue::new(&mut p.project_open_limit_gib).range(1..=u32::MAX).suffix(" GiB")) + .labelled_by(label.id) + .on_hover_text(tr("Maximum decompressed project data. Increase this limit to open larger projects.")); + ui.end_row(); + + #[cfg(not(target_arch = "wasm32"))] + { + let label = ui.label(tr("Max RAM while saving")); + ui.horizontal(|ui| { + ui.add(egui::DragValue::new(&mut p.save_ram_percent).range(1..=100).suffix(" %")).labelled_by(label.id); + let budget_bytes = texturecraft_engine::formats::save_ram_budget(available_ram_bytes, p.save_ram_percent); + ui.label(format!("≈ {:.2} GiB", budget_bytes as f64 / (1_u64 << 30) as f64)); + }); ui.end_row(); - }); + } + }); + #[cfg(not(target_arch = "wasm32"))] + { ui.label(RichText::new(tr("Saving uses the other cores and at most this share of the free RAM. At least one core always works.")).small().color(tk.text_dim)); ui.label( RichText::new(trf("0 turns autosave off. Copies go to {folder}", &[("folder", &crate::user_dir("autosave").display())])) diff --git a/crates/ui-egui/tests/project_limits.rs b/crates/ui-egui/tests/project_limits.rs new file mode 100644 index 00000000..7363a5dd --- /dev/null +++ b/crates/ui-egui/tests/project_limits.rs @@ -0,0 +1,55 @@ +use eframe::App as _; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use texturecraft_engine::{Session, formats, geom}; +use texturecraft_ui_egui::{TextureCraftApp, UiState, control, state::Prefs}; + +#[path = "../src/ui_state_store/memory_storage.rs"] +mod memory_storage; +use memory_storage::MemoryStorage; + +#[test] +fn resource_settings_follow_hardware_persist_and_apply_before_control_requests() { + let legacy: Prefs = serde_json::from_str("{}").unwrap(); + assert_eq!(legacy.project_open_limit_gib, 8); + let mut state = UiState::default(); + state.prefs.language = "en".into(); + state.prefs.project_open_limit_gib = 16; + state.prefs.reserved_cores = u32::MAX; + state.windows.settings = true; + let mut storage = MemoryStorage::default(); + storage.values.insert("ui.json".into(), serde_json::to_string(&state).unwrap()); + let session = Session::new_project("Limits", geom::primitives::plane(2.0, 1), "builtin:plane", None, 128).unwrap(); + let available_cores = u32::try_from(std::thread::available_parallelism().unwrap().get()).unwrap(); + let mut harness = + Harness::builder().with_size(egui::vec2(1200.0, 900.0)).with_step_dt(1.0 / 60.0).with_accessibility_check(false).build_eframe(|context| { + context.egui_ctx.data_mut(|data| data.insert_temp(egui::Id::unique("settings_resources"), (0.0_f64, available_cores, 16_u64 << 30))); + let mut creation = eframe::CreationContext::_new_kittest(context.egui_ctx.clone()); + creation.storage = Some(&storage); + TextureCraftApp::new(&creation, session) + }); + + assert_eq!(formats::project_open_limit_gib(), 16, "saved preferences apply during startup"); + harness.run_steps(3); + assert_eq!(harness.state().ui.prefs.reserved_cores, available_cores, "preferences from a larger machine are clamped"); + harness.get_by_role_and_label(egui::Role::SpinButton, "Cores kept for the UI").set_value_accesskit(f64::from(u32::MAX)); + harness.run_steps(3); + assert_eq!(harness.state().ui.prefs.reserved_cores, available_cores, "editing cannot exceed this machine's CPU count"); + assert!(harness.query_by_label("≈ 8.00 GiB").is_some(), "50% of 16 GiB is shown beside the percentage"); + harness.get_by_role_and_label(egui::Role::SpinButton, "Max RAM while saving").set_value_accesskit(25.0); + harness.run_steps(3); + assert!(harness.query_by_label("≈ 4.00 GiB").is_some(), "the byte estimate follows the edited percentage"); + + harness.get_by_role_and_label(egui::Role::SpinButton, "Max project size on open").set_value_accesskit(24.0); + harness.run_steps(3); + assert_eq!(formats::project_open_limit_gib(), 24, "the input field applies the edited value"); + + let context = egui::Context::default(); + let reply = control::handle(harness.state_mut(), &context, "ui.set", &serde_json::json!({"prefs": {"project_open_limit_gib": 32}})); + + assert_eq!(reply["ok"], true, "{reply}"); + assert_eq!(formats::project_open_limit_gib(), 32, "no frame is needed before the next command"); + harness.state_mut().save(&mut storage); + let restored: UiState = serde_json::from_str(&storage.values["ui.json"]).unwrap(); + assert_eq!(restored.prefs.project_open_limit_gib, 32); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index c02a7617..f255a509 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -182,6 +182,15 @@ call("auth", {"token": token}) print(call("command.run", {"id": "layer.add.fill", "params": {"color": [0.8, 0.1, 0.1]}})) ``` +The UI's `prefs.project_open_limit_gib` sets the maximum decompressed project data accepted on open +(default 8 GiB, minimum 1 GiB). Set it with `ui.set {"prefs":{"project_open_limit_gib":16}}`; +it takes effect before the next control request, without waiting for a frame, and persists with +the UI preferences. Individual entry limits still apply. This controls opening only, independently +of `prefs.reserved_cores` and `prefs.save_ram_percent` for saving. +Settings bounds the reserved-core input to the available logical CPU count and shows the estimated +save budget in GiB beside the RAM percentage. The readout refreshes once a second from currently +available RAM; a save calculates its budget when it starts. + ## MCP server `texturecraft-cli mcp` speaks MCP on stdin/stdout (stdout carries only protocol messages). From 63043aa99edf03a8eec02bc8d5894499375550c8 Mon Sep 17 00:00:00 2001 From: chasse20 Date: Wed, 11 Nov 2026 00:34:26 -0500 Subject: [PATCH 62/64] Fix GPU test setup and rendering cache lifetimes --- Cargo.lock | 1 + crates/render/src/gpu_trace.rs | 60 ++++++++++++++++----- crates/ui-egui/Cargo.toml | 2 + crates/ui-egui/src/render_mode.rs | 18 +++++-- crates/ui-egui/src/render_mode/tests.rs | 70 +++++++++++++++++++++++-- crates/ui-egui/tests/ui_snapshots.rs | 1 + 6 files changed, 130 insertions(+), 22 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 384c4457..9846b729 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4421,6 +4421,7 @@ dependencies = [ "image", "js-sys", "log", + "pollster 0.4.0", "rayon", "rfd", "serde", diff --git a/crates/render/src/gpu_trace.rs b/crates/render/src/gpu_trace.rs index fe423795..601e097e 100644 --- a/crates/render/src/gpu_trace.rs +++ b/crates/render/src/gpu_trace.rs @@ -507,20 +507,26 @@ impl GpuTracer { Ok(true) } - /// Start over at `width × height` (the accumulation buffers are cleared or reallocated). + /// Start over at `width × height`, keeping the active render intact if allocation fails. pub fn reset(&mut self, device: &wgpu::Device, encoder: &mut wgpu::CommandEncoder, width: u32, height: u32) -> Result<(), String> { let (width, height) = (width.clamp(1, 8192), height.clamp(1, 8192)); - self.samples = 0; + let bytes = u64::from(width) * u64::from(height) * 16; + let limits = device.limits(); + + // Reject unsupported sizes before invalidating the displayed render + if bytes > limits.max_storage_buffer_binding_size.min(limits.max_buffer_size) { + return Err(format!("a {width}×{height} render exceeds this GPU's buffer limit")); + } + if let Some(accumulation) = self.acc.as_ref().filter(|accumulation| (accumulation.width, accumulation.height) == (width, height)) { for buffer in &accumulation.acc { encoder.clear_buffer(buffer, 0, None); } + self.samples = 0; return Ok(()); } - self.bind = None; - // Reused buffers must not retain samples from the previous view if let Some(spare) = self.spare_acc.take_if(|accumulation| (accumulation.width, accumulation.height) == (width, height)) { for buffer in spare.acc.iter().chain(&spare.illum) { @@ -528,15 +534,13 @@ impl GpuTracer { } self.spare_acc = self.acc.replace(spare); + self.bind = None; + self.samples = 0; return Ok(()); } - self.spare_acc = self.acc.take(); - let bytes = u64::from(width) * u64::from(height) * 16; - let limits = device.limits(); - if bytes > limits.max_storage_buffer_binding_size.min(limits.max_buffer_size) { - return Err(format!("a {width}×{height} render exceeds this GPU's buffer limit")); - } + // Retire the obsolete spare before allocating, but keep the active render until success + self.spare_acc = None; let create_buffer = |label| { device.create_buffer(&wgpu::BufferDescriptor { @@ -546,12 +550,15 @@ impl GpuTracer { mapped_at_creation: false, }) }; - self.acc = Some(scoped(device, "GPU path tracing: accumulation buffers", || Accum { + let accumulation = scoped(device, "GPU path tracing: accumulation buffers", || Accum { width, height, acc: ["tc_acc_hit", "tc_acc_albedo", "tc_acc_normal", "tc_acc_env"].map(create_buffer), illum: ["tc_illum_a", "tc_illum_b"].map(create_buffer), - })?); + })?; + self.spare_acc = self.acc.replace(accumulation); + self.bind = None; + self.samples = 0; #[cfg(test)] { self.acc_allocations += 1; @@ -831,6 +838,7 @@ mod tests { read_buffer(h, &t.acc.as_ref().unwrap().acc[0]) } + /// Read a completed buffer to check its contents across resets and reuse. fn read_buffer(headless: &Headless, buffer: &wgpu::Buffer) -> Vec<[f32; 4]> { let bytes = buffer.size(); let staging = headless.device.create_buffer(&wgpu::BufferDescriptor { @@ -848,6 +856,7 @@ mod tests { bytemuck::cast_slice(&staging.slice(..).get_mapped_range().unwrap()).to_vec() } + /// Two cached sizes reuse cleared buffers, and leaving Rendering mode releases both. #[test] fn switching_between_two_sizes_reuses_the_accumulation_buffers() { let Some((headless, mut tracer)) = gpu() else { return }; @@ -880,6 +889,33 @@ mod tests { assert!(tracer.acc.is_none() && tracer.spare_acc.is_none(), "leaving Rendering mode frees both sizes"); } + /// Rejecting an oversized render preserves the image and lets tracing continue. + #[test] + fn failed_reset_retains_the_active_render() { + let Some((mut headless, mut tracer)) = gpu() else { return }; + let scene = sphere_scene(&mut headless, crate::ibl::environment("Studio Soft", 32), &WHITE); + let camera = camera(); + let settings = TraceSettings::default(); + let display = TraceDisplay::from_display(&Default::default()); + tracer.render(&headless.device, &headless.queue, &headless.renderer, &scene, &camera, &settings, &display, [32, 24], 2).unwrap(); + let before = accumulation(&headless, &tracer); + + let mut encoder = headless.device.create_command_encoder(&Default::default()); + let error = tracer.reset(&headless.device, &mut encoder, 8192, 8192).unwrap_err(); + + assert!(error.contains("exceeds this GPU's buffer limit")); + assert!(tracer.acc.is_some(), "a rejected resize must keep the active buffers"); + assert!(tracer.bind.is_some(), "a rejected resize must keep the active bindings"); + assert_eq!(tracer.samples(), 2, "a rejected resize must keep the accumulated samples"); + assert_eq!(accumulation(&headless, &tracer), before); + assert!(tracer.pass(&headless.device, &headless.queue, &mut encoder, &camera, &settings, 1)); + let output = GpuTracer::output_texture(&headless.device, 32, 24); + assert!(tracer.resolve(&headless.device, &headless.queue, &mut encoder, &display, &output.create_view(&Default::default()))); + headless.queue.submit([encoder.finish()]); + assert!(crate::readback::Readback::blocking(&headless.device, &headless.queue, &output).is_some()); + assert_eq!(tracer.samples(), 3); + } + const WHITE: [(Channel, [f32; 3]); 3] = [(Channel::BaseColor, [1.0; 3]), (Channel::Metallic, [0.0; 3]), (Channel::Roughness, [0.5; 3])]; #[test] diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index fdc45c70..46f84fd7 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -55,4 +55,6 @@ web-sys = { version = "0.3", features = ["Window", "Document", "HtmlElement", "H eframe = { workspace = true, features = ["x11"] } # Offscreen pictures of the whole window (tests/ui_snapshots.rs). egui_kittest = { version = "0.37", features = ["wgpu", "eframe"] } +# Fallible setup of the exact GPU device used by rendering regression tests. +pollster = "0.4" image = { workspace = true } diff --git a/crates/ui-egui/src/render_mode.rs b/crates/ui-egui/src/render_mode.rs index fd4ffd0d..cef71ed1 100644 --- a/crates/ui-egui/src/render_mode.rs +++ b/crates/ui-egui/src/render_mode.rs @@ -14,6 +14,7 @@ use std::sync::{Mutex, PoisonError}; use eframe::egui_wgpu::{self, CallbackResources, CallbackTrait, ScreenDescriptor}; use egui::{Color32, ColorImage, Rect, RichText, TextureHandle, TextureOptions, Ui, vec2}; +use texturecraft_engine::compose::ImageRes; use texturecraft_engine::geom::{Bvh, Mesh, OrbitCamera}; use texturecraft_render::displace::trace_geometry; use texturecraft_render::gpu_trace::GpuTracer; @@ -248,9 +249,8 @@ pub struct RenderView { env: Mutex)>>, } -/// What a traced environment is built from: the display's environment name and the identity of -/// its imported image (0: none). -type EnvKey = (String, usize); +/// The display's environment name and its retained imported image (None: built-in). +type EnvKey = (String, Option>); /// Viewport resolution of a CPU render (the web renders at half size: it has one thread). fn render_size(rect: Rect) -> (u32, u32) { @@ -287,12 +287,19 @@ fn trace_scene(app: &TextureCraftApp) -> TraceScene { }; drop(cached); - let env_key: EnvKey = (display.environment.clone(), env_image.map_or(0, |image| Arc::as_ptr(image) as usize)); let mut env_cached = app.render.env.lock().unwrap_or_else(PoisonError::into_inner); + let same_image = |source: &Option>| match (source, env_image) { + (Some(cached), Some(current)) => Arc::ptr_eq(cached, current), + (None, None) => true, + _ => false, + }; let env = match env_cached.as_ref() { - Some((cached_key, environment)) if *cached_key == env_key => environment.clone(), + Some(((name, source), environment)) if *name == display.environment && same_image(source) => environment.clone(), _ => { let environment = Arc::new(TraceScene::display_env(display, env_image.map(|image| image.as_ref()))); + + // Retaining the source prevents a later image from reusing its cached identity + let env_key = (display.environment.clone(), env_image.cloned()); *env_cached = Some((env_key, environment.clone())); environment } @@ -711,6 +718,7 @@ impl TraceCallback { } impl CallbackTrait for TraceCallback { + /// Submit tracing work and report its samples or failure to the next UI frame. fn prepare( &self, device: &wgpu::Device, diff --git a/crates/ui-egui/src/render_mode/tests.rs b/crates/ui-egui/src/render_mode/tests.rs index 2ae14be2..247acd98 100644 --- a/crates/ui-egui/src/render_mode/tests.rs +++ b/crates/ui-egui/src/render_mode/tests.rs @@ -9,6 +9,7 @@ use super::{ use texturecraft_engine::Session; use texturecraft_engine::geom::primitives; +/// A small, fully composed sphere avoids unrelated texture-loading transitions. fn session() -> Session { let mut session = Session::new_project("t", primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap(); session.update(); @@ -16,6 +17,7 @@ fn session() -> Session { session } +/// Bump-strength edits invalidate GPU scene data even without displaced geometry. #[test] fn height_strength_changes_restart_the_gpu_scene_without_displacement() { let mut session = session(); @@ -28,19 +30,67 @@ fn height_strength_changes_restart_the_gpu_scene_without_displacement() { assert_ne!(gpu_scene_key(&session), before, "the GPU shader must receive the new bump strength"); } +/// Keeping an imported image alive prevents its cached identity from being reused for another image. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn environment_cache_retains_source_identity_until_replaced() { + use std::sync::Arc; + use texturecraft_engine::compose::ImageRes; + + // The harness draws once; parallel translation tests must not change its language mid-frame + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); + let mut app = egui_kittest::Harness::builder().build_eframe(|context| crate::TextureCraftApp::new(context, session())).into_state(); + app.session.doc.project.display.environment = "resource:environment".into(); + let source = Arc::new(ImageRes { width: 2, height: 1, rgba: vec![[1.0, 0.0, 0.0, 1.0]; 2], srgb: false }); + let original_source = Arc::downgrade(&source); + app.session.images.insert("environment".into(), source); + let first = super::trace_scene(&app).env; + assert!(Arc::ptr_eq(&first, &super::trace_scene(&app).env), "unchanged images reuse the decoded environment"); + + let replacement = Arc::new(ImageRes { width: 2, height: 1, rgba: vec![[0.0, 1.0, 0.0, 1.0]; 2], srgb: false }); + app.session.images.insert("environment".into(), replacement.clone()); + + assert!(original_source.upgrade().is_some(), "the cache must retain its source so its address cannot be reused"); + let second = super::trace_scene(&app).env; + assert!(!Arc::ptr_eq(&first, &second)); + assert_ne!(first.data, second.data, "replacing the image changes the lighting"); + assert!(Arc::ptr_eq(&second, &super::trace_scene(&app).env)); + assert!(original_source.upgrade().is_none(), "replacing the cache releases the previous source"); + + app.session.images.insert("renamed".into(), replacement); + app.session.doc.project.display.environment = "resource:renamed".into(); + assert!(!Arc::ptr_eq(&second, &super::trace_scene(&app).env), "the environment name is also part of the key"); +} + +/// Create one harness device, skipping unavailable or non-compute backends. #[cfg(not(target_arch = "wasm32"))] fn gpu_app() -> Option { - match texturecraft_render::headless::Headless::new() { - Ok(headless) if super::GpuTracer::supported(&headless.device) => {} - _ => { - eprintln!("skipping: no compute-capable GPU adapter"); + use eframe::egui_wgpu::{RenderState, RendererOptions, WgpuConfiguration}; + use egui_kittest::wgpu::{WgpuTestRenderer, default_wgpu_setup}; + + let setup = default_wgpu_setup(); + let instance = pollster::block_on(setup.new_instance()); + let configuration = WgpuConfiguration { wgpu_setup: setup, ..Default::default() }; + let render_state = match pollster::block_on(RenderState::create(&configuration, &instance, None, RendererOptions::PREDICTABLE)) { + Ok(render_state) => render_state, + Err(error) => { + eprintln!("skipping: could not create the harness GPU device: {error}"); return None; } + }; + + let adapter = render_state.adapter.get_info(); + if !super::GpuTracer::supported(&render_state.device) { + eprintln!("skipping: harness adapter {} ({:?}) cannot run the GPU tracer", adapter.name, adapter.backend); + return None; } + eprintln!("GPU lifecycle test adapter: {} ({:?})", adapter.name, adapter.backend); + // The harness draws once; parallel translation tests must not change its language mid-frame + let _language = crate::i18n::TEST_LANGUAGE.lock().unwrap_or_else(std::sync::PoisonError::into_inner); let mut app = egui_kittest::Harness::builder() .with_size(egui::vec2(800.0, 600.0)) - .wgpu() + .renderer(WgpuTestRenderer::from_render_state(render_state)) .build_eframe(|context| crate::TextureCraftApp::new(context, session())) .into_state(); app.session.update(); @@ -51,6 +101,7 @@ fn gpu_app() -> Option { Some(app) } +/// Build a GPU rendering frame at a controlled time without executing its callback. #[cfg(not(target_arch = "wasm32"))] fn draw_gpu(app: &mut crate::TextureCraftApp, context: &egui::Context, time: f64) -> egui::FullOutput { context.run_ui(egui::RawInput { time: Some(time), ..Default::default() }, |ui| { @@ -58,6 +109,7 @@ fn draw_gpu(app: &mut crate::TextureCraftApp, context: &egui::Context, time: f64 }) } +/// A first completed callback must survive a slow frame's switch to full resolution. #[cfg(not(target_arch = "wasm32"))] #[test] fn settling_after_the_first_gpu_frame_keeps_its_image() { @@ -80,6 +132,7 @@ fn settling_after_the_first_gpu_frame_keeps_its_image() { assert_eq!(view.held, Some(previous_texture)); } +/// A finished low-sample render must wake again to release its retained preview. #[cfg(not(target_arch = "wasm32"))] #[test] fn a_low_sample_limit_schedules_the_held_image_timeout() { @@ -159,6 +212,7 @@ fn a_moving_camera_traces_smaller_and_a_still_one_at_full_size() { assert_eq!(traced_size((20, 400), true), (16, 200)); } +/// Camera changes and unfinished uploads keep the preview small until activity settles. #[test] fn motion_starts_on_a_camera_change_and_settles_after_a_moment() { let mut motion = Motion::default(); @@ -176,6 +230,7 @@ fn motion_starts_on_a_camera_change_and_settles_after_a_moment() { assert!(!motion.moving(&camera, 5.0 + MOTION_SETTLE_S * 1.5, false)); } +/// Either sufficient samples or the deadline replaces the retained preview. #[test] fn the_soft_image_stays_until_the_full_size_render_has_samples_or_time_runs_out() { assert!(holds_previous(0, 0.0)); @@ -184,6 +239,7 @@ fn the_soft_image_stays_until_the_full_size_render_has_samples_or_time_runs_out( assert!(!holds_previous(0, SETTLE_HOLD_MAX_S), "a slow GPU: don't hold it forever"); } +/// Sampling grows gradually, holds through jitter and cuts promptly on overload. #[test] fn samples_per_frame_grow_slowly_hold_in_between_and_drop_fast() { let (floor, free) = (1.0 / 144.0, SPP_GROW_PAUSE_FRAMES); @@ -251,6 +307,7 @@ fn a_few_very_quick_frames_do_not_collapse_the_samples_per_frame() { assert!(spp >= 4, "12 ms frames after 3 ms ones are fine: {spp}"); } +/// Invalid timings are ignored and old timings expire within the bounded window. #[test] fn the_frame_floor_is_the_quickest_recent_frame_within_range() { let mut floor = FrameFloor::default(); @@ -267,6 +324,7 @@ fn the_frame_floor_is_the_quickest_recent_frame_within_range() { assert_eq!(floor.push(0.2), FLOOR_RANGE_S.1, "only recent frames count, and at most 1/30 s"); } +/// Resolution changes preserve approximate tracing work within the sample limits. #[test] fn samples_per_frame_follow_the_pixel_count_when_the_size_changes() { assert_eq!(rescale_spp(12, (500, 400), (1000, 800)), 3, "four times the pixels: a quarter of the samples"); @@ -275,6 +333,7 @@ fn samples_per_frame_follow_the_pixel_count_when_the_size_changes() { assert_eq!(rescale_spp(16, (100, 100), (10, 10)), MAX_SPP, "never above the cap"); } +/// Loading throttles texture synchronization without delaying the first or settled update. #[test] fn loading_textures_are_taken_in_at_a_limited_rate() { assert!(take_in_textures(false, 1.0, 1.0), "not loading: every frame"); @@ -283,6 +342,7 @@ fn loading_textures_are_taken_in_at_a_limited_rate() { assert!(take_in_textures(true, 0.0, f64::MIN), "the first frame always"); } +/// The placeholder appears only before the first image has been traced. #[test] fn nothing_traced_yet_shows_the_placeholder() { assert!(!show_image(false, 0)); diff --git a/crates/ui-egui/tests/ui_snapshots.rs b/crates/ui-egui/tests/ui_snapshots.rs index 61593bc9..4ca66c96 100644 --- a/crates/ui-egui/tests/ui_snapshots.rs +++ b/crates/ui-egui/tests/ui_snapshots.rs @@ -28,6 +28,7 @@ fn save(h: &mut Harness<'_, TextureCraftApp>, dir: &Path, name: &str) { eprintln!("wrote {}", path.display()); } +/// Capture the moving preview and settled render after submitting real GPU callbacks. #[test] #[ignore] fn rendering_mode_snapshots() { From 21856d778347e13857f65c8f1107170797bd070f Mon Sep 17 00:00:00 2001 From: test-bit-sys Date: Wed, 11 Nov 2026 08:57:31 +0100 Subject: [PATCH 63/64] fix(formats): preserve existing OBJ UVs when only some objects lack UVs (#286) (#394) Previously, if any object in an OBJ mesh lacked texture coordinates, all UVs across all objects were discarded and replaced with a full automatic unwrap. Skip empty models without indices, preserve existing UVs on textured objects while assigning default UVs to untextured helper/sub-objects, and report a warning without forcing a full mesh unwrap. --- crates/formats/src/mesh_import/obj.rs | 20 ++++++++++-------- crates/formats/src/mesh_import/tests.rs | 27 +++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 8 deletions(-) diff --git a/crates/formats/src/mesh_import/obj.rs b/crates/formats/src/mesh_import/obj.rs index 44277208..2f284704 100644 --- a/crates/formats/src/mesh_import/obj.rs +++ b/crates/formats/src/mesh_import/obj.rs @@ -36,10 +36,14 @@ fn read_inner(bytes: &[u8]) -> Result { let materials = materials.unwrap_or_default(); let mut raw = RawMesh::default(); - let (mut normals, mut uvs, mut colors) = (Some(Vec::new()), Some(Vec::new()), Vec::new()); + let any_uvs = models.iter().any(|m| !m.mesh.indices.is_empty() && m.mesh.texcoords.len() == (m.mesh.positions.len() / 3) * 2); + let (mut normals, mut uvs, mut colors) = (Some(Vec::new()), any_uvs.then(Vec::new), Vec::new()); let mut partial_uvs = false; for model in &models { let mesh = &model.mesh; + if mesh.indices.is_empty() { + continue; + } let vertex_count = mesh.positions.len() / 3; check_vertices(raw.positions.len().saturating_add(vertex_count))?; @@ -56,14 +60,14 @@ fn read_inner(bytes: &[u8]) -> Result { } else { normals = None; } - if mesh.texcoords.len() == vertex_count * 2 { - if let Some(v) = &mut uvs { + if let Some(v) = &mut uvs { + if mesh.texcoords.len() == vertex_count * 2 { // OBJ UVs have their origin bottom-left v.extend(mesh.texcoords.as_chunks::<2>().0.iter().map(|t| Vec2::new(t[0], 1.0 - t[1]))); + } else { + v.extend(std::iter::repeat_n(Vec2::ZERO, vertex_count)); + partial_uvs = true; } - } else { - partial_uvs |= vertex_count > 0 && !mesh.indices.is_empty(); - uvs = None; } // `v x y z r g b`: objects without colors are white @@ -94,8 +98,8 @@ fn read_inner(bytes: &[u8]) -> Result { } } - if partial_uvs && models.iter().any(|model| !model.mesh.texcoords.is_empty()) { - raw.warnings.push("some objects have no UVs; the whole mesh was unwrapped automatically".into()); + if partial_uvs { + raw.warnings.push("some objects have no UVs; default UVs were assigned".into()); } raw.normals = normals; diff --git a/crates/formats/src/mesh_import/tests.rs b/crates/formats/src/mesh_import/tests.rs index fd45cc87..e55f8eae 100644 --- a/crates/formats/src/mesh_import/tests.rs +++ b/crates/formats/src/mesh_import/tests.rs @@ -235,6 +235,33 @@ fn obj_without_uvs_or_normals_is_completed() { assert!(n0.len() > 1 && n0.iter().all(|n| (*n - n0[0]).length() < 1e-5)); } +#[test] +fn obj_with_some_objects_having_uvs_preserves_uvs_without_full_unwrap() { + let obj = "o Body +v 0 0 0 +v 1 0 0 +v 1 1 0 +vt 0 0 +vt 1 0 +vt 1 1 +f 1/1 2/2 3/3 +o Helper +v 2 0 0 +v 3 0 0 +v 3 1 0 +f 4 5 6 +"; + let im = import_mesh_bytes("character.obj", obj.as_bytes()).unwrap(); + assert!(!im.report.uvs_generated); + assert_eq!(im.mesh.uvs[0], Vec2::new(0.0, 1.0)); + assert_eq!(im.mesh.uvs[1], Vec2::new(1.0, 1.0)); + assert_eq!(im.mesh.uvs[2], Vec2::new(1.0, 0.0)); + assert_eq!(im.mesh.uvs[3], Vec2::ZERO); + assert_eq!(im.mesh.uvs[4], Vec2::ZERO); + assert_eq!(im.mesh.uvs[5], Vec2::ZERO); + assert!(im.report.warnings.iter().any(|w| w.contains("some objects have no UVs"))); +} + #[test] fn polygons_keep_their_edges_for_the_wireframe() { // An OBJ quad and pentagon (with UVs, so no unwrap splits them), a triangle, and a PLY quad. From 9e96367d0c0519ce9f5c796815303c44aad46501 Mon Sep 17 00:00:00 2001 From: FredApps <153173854+FredApps@users.noreply.github.com> Date: Wed, 11 Nov 2026 16:52:41 +0100 Subject: [PATCH 64/64] Release: TextureCraft v0.6.0 (#420) --- Cargo.lock | 30 +++++++++++++++--------------- Cargo.toml | 2 +- 2 files changed, 16 insertions(+), 16 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 94579b6f..19c65129 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4259,7 +4259,7 @@ dependencies = [ [[package]] name = "texturecraft" -version = "0.3.1" +version = "0.6.0" dependencies = [ "craft-menu", "craft-update", @@ -4280,7 +4280,7 @@ dependencies = [ [[package]] name = "texturecraft-automation" -version = "0.3.1" +version = "0.6.0" dependencies = [ "base64 0.22.1", "cap-std", @@ -4301,7 +4301,7 @@ dependencies = [ [[package]] name = "texturecraft-bake" -version = "0.3.1" +version = "0.6.0" dependencies = [ "bytemuck", "rayon", @@ -4313,7 +4313,7 @@ dependencies = [ [[package]] name = "texturecraft-cli" -version = "0.3.1" +version = "0.6.0" dependencies = [ "image", "serde_json", @@ -4325,7 +4325,7 @@ dependencies = [ [[package]] name = "texturecraft-compose" -version = "0.3.1" +version = "0.6.0" dependencies = [ "half", "rayon", @@ -4336,7 +4336,7 @@ dependencies = [ [[package]] name = "texturecraft-core" -version = "0.3.1" +version = "0.6.0" dependencies = [ "serde", "serde_json", @@ -4345,7 +4345,7 @@ dependencies = [ [[package]] name = "texturecraft-engine" -version = "0.3.1" +version = "0.6.0" dependencies = [ "epaint_default_fonts", "image", @@ -4365,7 +4365,7 @@ dependencies = [ [[package]] name = "texturecraft-formats" -version = "0.3.1" +version = "0.6.0" dependencies = [ "base64 0.22.1", "exr", @@ -4390,7 +4390,7 @@ dependencies = [ [[package]] name = "texturecraft-geom" -version = "0.3.1" +version = "0.6.0" dependencies = [ "glam 0.30.10", "mikktspace", @@ -4401,7 +4401,7 @@ dependencies = [ [[package]] name = "texturecraft-paint" -version = "0.3.1" +version = "0.6.0" dependencies = [ "epaint_default_fonts", "harfrust", @@ -4416,7 +4416,7 @@ dependencies = [ [[package]] name = "texturecraft-render" -version = "0.3.1" +version = "0.6.0" dependencies = [ "bytemuck", "half", @@ -4435,11 +4435,11 @@ dependencies = [ [[package]] name = "texturecraft-texel" -version = "0.3.1" +version = "0.6.0" [[package]] name = "texturecraft-ui-egui" -version = "0.3.1" +version = "0.6.0" dependencies = [ "base64 0.22.1", "craft-dialogs", @@ -4473,7 +4473,7 @@ dependencies = [ [[package]] name = "texturecraft-web" -version = "0.3.1" +version = "0.6.0" dependencies = [ "eframe", "js-sys", @@ -5865,7 +5865,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" [[package]] name = "xtask" -version = "0.3.1" +version = "0.6.0" dependencies = [ "serde_json", ] diff --git a/Cargo.toml b/Cargo.toml index 29de448b..b67d119b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,7 +5,7 @@ exclude = ["vendor"] default-members = ["crates/core", "crates/texel", "crates/geom", "crates/compose", "crates/bake", "crates/formats", "crates/paint", "crates/engine", "crates/render", "crates/automation", "crates/ui-egui", "apps/texturecraft", "apps/texturecraft-cli", "xtask"] [workspace.package] -version = "0.3.1" +version = "0.6.0" edition = "2024" license = "MIT OR Apache-2.0" rust-version = "1.95"